|
| 1 | +#!/usr/bin/python3 |
| 2 | +import sys |
| 3 | +import re |
| 4 | + |
| 5 | + |
| 6 | +def print_usage(): |
| 7 | + print("Usage: read_write_heap.py pid search_s replace_s") |
| 8 | + exit(1) |
| 9 | + |
| 10 | + |
| 11 | +def read_write_heap(pid, search_s, replace_s, only_writable=True): |
| 12 | + mem_perm = 'rw' if only_writable else 'r-' |
| 13 | + maps_filename = "/proc/{}/maps".format(pid) |
| 14 | + mem_filename = "/proc/{}/mem".format(pid) |
| 15 | + try: |
| 16 | + with open(maps_filename, 'r') as maps_file: |
| 17 | + with open(mem_filename, 'rb+', 0) as mem_file: |
| 18 | + for line in maps_file.readlines(): |
| 19 | + addr_perm = r'([0-9A-Fa-f]+)-([0-9A-Fa-f]+) ([-r][-w])' |
| 20 | + m = re.search(addr_perm, line) |
| 21 | + h = re.search(r'(\[heap\])', line) |
| 22 | + if m.group(3) == mem_perm and h and h.group(0) == "[heap]": |
| 23 | + start_addr = int(m.group(1), 16) |
| 24 | + end_addr = int(m.group(2), 16) |
| 25 | + mem_file.seek(start_addr) |
| 26 | + heap = mem_file.read(end_addr - start_addr) |
| 27 | + pos = heap.find(bytes(search_s, "ASCII")) |
| 28 | + if pos: |
| 29 | + mem_file.seek(start_addr + pos) |
| 30 | + adjusted_str = replace_s.ljust(len(search_s)) |
| 31 | + mem_file.write(bytes(adjusted_str, "ASCII")) |
| 32 | + else: |
| 33 | + print("Couldn't find the %s in the heap", search_s) |
| 34 | + except IOError as e: |
| 35 | + print("[ERROR] Can not open file {}:".format(maps_filename)) |
| 36 | + print(" I/O error({}): {}".format(e.errno, e.strerror)) |
| 37 | + exit(1) |
| 38 | + |
| 39 | + |
| 40 | +try: |
| 41 | + if len(sys.argv) != 4: |
| 42 | + print_usage() |
| 43 | + pid = int(sys.argv[1]) |
| 44 | + search_s = sys.argv[2] |
| 45 | + replace_s = sys.argv[3] |
| 46 | + if (len(search_s) == 0 or len(replace_s) == 0): |
| 47 | + print_usage() |
| 48 | + read_write_heap(pid, search_s, replace_s) |
| 49 | +except Exception as e: |
| 50 | + print_usage() |
0 commit comments