Created
June 22, 2022 09:35
-
-
Save mikehouse/169689cc347e4802d1dd4c8a17586092 to your computer and use it in GitHub Desktop.
Parse __TEXT __text segment for Mach-O binary in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from macholib.MachO import MachO | |
import os | |
import hashlib | |
# Taken and a bit modified from https://www.programcreek.com/python/example/111986/macholib.MachO.MachO | |
def extract_shellcode(filename): | |
macho_filename = filename | |
fileoffset = 0 | |
shellcodesize = 0 | |
m = MachO(macho_filename) | |
for (load_cmd, cmd, data) in m.headers[0].commands: | |
if data: | |
if hasattr(data[0], "sectname"): | |
sectionName = str(getattr(data[0], 'sectname', '')) | |
if "text" in sectionName: | |
fileoffset=data[0].offset | |
shellcodesize+=data[0].size | |
break | |
with open(macho_filename, 'rb') as f: | |
f.seek(fileoffset, 1) | |
print("read __text section from {} with length {}".format(fileoffset, shellcodesize)) | |
shellcode_bytes = f.read(shellcodesize) | |
h = hashlib.sha256() | |
h.update(shellcode_bytes) | |
print(h.hexdigest()) | |
f.close() | |
path = '../MyApp.app/MyApp' | |
extract_shellcode(path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment