0

I am trying to memset a substring in python file using ctypes.memset

Here is the code I am using:

import ctypes

def memz(string):
    buffsize = len(string)+1
    size = sys.getsizeof(string)
    offset = size - buffsize
    start = string.find('{') -----------> 142
    end = string.find('}') + 1  --------> 167
    location = id(string)
    ctypes.memset(location + offset + start, 0, end-start)

I see that this does not memset the substring, but writes some other part of memory. I suspect I am not passing the correct memory location to ctypes.memset. Do I need to change the format of the location(location + offset + start) that I am passing to ctypes.memset?

PS: The solution is derived from Mark data as sensitive in python. I tried that solution but using the memset from ctypes.CDLL('libc.so.6').memset results in a seg fault. I am using Python2.7.11.

truth_seeker
  • 345
  • 4
  • 14

1 Answers1

1

Your solution works too. I tried running it locally and it cleared the required substring.

str = 'This is a {sample} string'

print(ctypes.string_at(id(str), sys.getsizeof(str)))

buffSize = len(str)+1
size = sys.getsizeof(str)
offset = size - buffSize
start = str.find('{')
end = str.find('}') + 1
location = id(str)

ctypes.memset(location + offset + start, 0, end-start)

print(ctypes.string_at(id(str), sys.getsizeof(str)))

It produces following output

 ���A,�5~��dThis is a {sample} string
 ���A,�5~��dThis is a  string
bhushan
  • 470
  • 3
  • 14
  • Thanks for trying this out. I tried it in my local machine too and it worked, but it does not work as part of a big code where i am using it. – truth_seeker Mar 24 '18 at 00:17
  • Probably you can try different way to calculate the offset from the starting location. you may want to use the `startIndex = ctypes.string_at(id(string), sys.getsizeof(string)).find('{') endIndex = ctypes.string_at(id(string), sys.getsizeof(string)).find('}')` and then use memset `memset( id(string) + startIndex, 0, endIndex-startIndex+1)` – bhushan Mar 24 '18 at 00:26