Skip to content

Instantly share code, notes, and snippets.

@itdaniher
Created January 3, 2018 15:11
Show Gist options
  • Save itdaniher/488798950d33625e991350ee449279ec to your computer and use it in GitHub Desktop.
Save itdaniher/488798950d33625e991350ee449279ec to your computer and use it in GitHub Desktop.
find and print all strings in mapped memory for a given pid
import ctypes
import re
import sys
import glob
import os
c_ptrace = ctypes.CDLL(None).ptrace
c_pid_t = ctypes.c_int32
c_ptrace.argtypes = [ctypes.c_int, c_pid_t, ctypes.c_void_p, ctypes.c_void_p]
def ptrace(attach, pid):
err = c_ptrace(16 + attach ^ 1, pid, 1, 0)
if err != 0: print('ptrace', err)
pid = ''
if len(sys.argv) < 2:
mapss = []
for x in glob.glob('/proc/*/maps'):
if os.access(x, os.R_OK):
try:
if 'deleted' in open(x, 'r').read():
mapss.append(x)
except:
pass
else:
mapss = ['/proc/%s/maps' % sys.argv[-1]]
def dump_mem(pid):
res = ''
pname = open('/proc/' + pid + '/cmdline').read().replace(
'\x00', '').split('/')[-1][0:10]
ptrace(True, int(pid))
maps_file = open("/proc/" + pid + "/maps", 'r')
mem_file = open("/proc/" + pid + "/mem", 'r', 0)
for line in maps_file.readlines(): # for each mapped region
m = re.match(r'([0-9A-Fa-f]+)-([0-9A-Fa-f]+) ([-r])', line)
if (m.group(3) == 'r') and ('[heap]' in line or '[stack]' in line):
start = int(m.group(1), 16)
end = int(m.group(2), 16)
mem_file.seek(start) # seek to region start
chunk = mem_file.read(end - start) # read region contents
res += line + '\n'
#res += ''.join([x for (x,y) in zip(chunk, chunk[1::]) if x!=y]).encode('string_escape')+'\n'*3
res += str(re.findall('[\w.\/]{3,}', chunk))
maps_file.close()
mem_file.close()
ptrace(False, int(pid))
return res
if mapss:
pids = [re.match('/proc/([0-9]+)/maps', x).group(1)
for x in mapss if re.match('/proc/([0-9]+)/maps', x)]
for pid in pids:
results = dump_mem(pid)
print(results)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment