Coverage for /var/devmt/py/utils4_1.6.0/utils4/cutils.py: 100%

12 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-11-13 09:50 +0000

1#!/usr/bin/env python 

2# -*- coding: utf-8 -*- 

3r""" 

4:Purpose: This module provides easy-access wrappers for C-based 

5 utilities. 

6 

7:Platform: Linux/Windows | Python 3.7+ 

8:Developer: J Berendt 

9:Email: development@s3dev.uk 

10 

11:Comments: n/a 

12 

13:Example: 

14 

15 Example for wiping a password from memory:: 

16 

17 >>> from utils4 import cutils 

18 

19 >>> pwd = 'B0bsP@$$word&' 

20 >>> _ = cutils.memset(pwd, 0) 

21 >>> pwd 

22 '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 

23 

24""" 

25 

26import ctypes 

27import gc 

28from utils4.reporterror import reporterror 

29 

30 

31def memset(obj: object, fill: int=0) -> bool: 

32 """Fill the memory address block occupied by ``obj`` with ``repl``. 

33 

34 Args: 

35 obj (object): Object to be overwritten, usually a string, can be an 

36 int. *Not* to be used with complex objects, such as lists, dicts, 

37 etc. 

38 fill (int, optional): Value to be filled. Defaults to 0. 

39 

40 Per the ``ctypes.memset`` documentation: 

41 

42 "Same as the standard C memset library function: fills the memory 

43 block at address dst with count bytes of value c. dst must be an 

44 integer specifying an address, or a ctypes instance." 

45 

46 This function is a soft wrapper around the ``ctypes.memset`` function and 

47 provides a boolean return value, enabling the caller to test the success 

48 of the operation. 

49 

50 Additionally, the reference to the ``obj`` object is manually deleted and 

51 a garbage collection call is made. 

52 

53 Returns: 

54 bool: True if the operation succeeds, otherwise False. An operation 

55 is deemed successful if the return value from ``ctypes.memset`` is 

56 equal to the original memory address of ``obj``. 

57 

58 """ 

59 try: 

60 ovh = type(obj)().__sizeof__() - 1 

61 loc = id(obj) + ovh 

62 size = obj.__sizeof__() - ovh 

63 id_ = ctypes.memset(loc, fill, size) 

64 del obj 

65 gc.collect() 

66 except Exception as err: 

67 reporterror(err) 

68 return loc == id_