Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
args = parser.parse_args()
file_type = None
filename = args.file[0]
error = ''
try:
fe = pefile.PE(filename)
file_type = 'PE'
except Exception as e:
error = str(e)
pass
if not file_type:
try:
fe = macholib.MachO.MachO(filename)
file_type = 'MACHO'
except Exception:
error = str(e)
pass
if not file_type:
sys.stderr.write("[*] Error with %s - not a PE or Mach-O\n" % sys.argv[1])
sys.exit(1)
if file_type == 'PE':
try:
if args.sig_title and len(args.sig_title) > 0:
print "[%s]" %(args.sig_title)
if args.linker:
print
print 'MachO Headers Eraser'
print
print 'This script may cause some unpredictable issues, try delete things in the safe list if your program doesn\'t work after patched.'
print
print '[+]Checking if patched'
rawFile = open(executableName, 'r')
rawFile.seek(-4, 2)
if cmp(rawFile.read(),'BOOM') == 0:
print '#Error: Executable has been patched'
exit()
print '[+]Making backup'
os.system('cp %s %s_bak' % (executableName, executableName))
print '[+]Reading raw executable'
machoHeader = MachO.MachO(executableName)
print '[+]%s readed' % machoHeader.filename
for header in machoHeader.headers:
eraseLoadCommandInHeader(header)
print '[+]Generating new executable'
spliceHeadersAndRawStuff(machoHeader, executableName)
print '[+]New executable generated'
print '[+]Overwriting raw executable'
os.system('mv %s_tmp %s' % (executableName, executableName))
#Insert SYMTAB Operations Here
pathname = os.path.dirname(sys.argv[0])
Command= pathname+'/SymbolCleaner '+executableName+" "+str(SYMTAB["symoff"])+" "+str(SYMTAB["nsyms"])+" 0 0 "+executableName+"NoSymbol"+" 32"
system(str(Command))
# appropriate for the system
for name in names:
location = ctypes.util.find_library(name)
if location:
try:
cairoLib = ctypes.CDLL(location)
return
except:
pass
# If the above didn't find it on OS X then we still have a
# trick up our sleeve...
if 'wxMac' in wx.PlatformInfo:
# look at the libs linked to by the pycairo extension module
import macholib.MachO
m = macholib.MachO.MachO(cairo._cairo.__file__)
for h in m.headers:
for idx, name, path in h.walkRelocatables():
if 'libcairo' in path:
try:
cairoLib = ctypes.CDLL(path)
return
except:
pass
if not cairoLib:
raise RuntimeError, "Unable to find the Cairo shared library"
def check_architectures(app):
'''
info检查是否支持64位
demo:armv7, arm64, armv7s
'''
from macholib import MachO, mach_o
m = MachO.MachO(app)
arcs = []
for header in m.headers:
cpu_type = header.header.cputype
cpu_subtype = header.header.cpusubtype
arch = str(mach_o.CPU_TYPE_NAMES.get(cpu_type, cpu_type)).lower()
if cpu_type == 12:
if cpu_subtype == 0:
arch = 'armall'
elif cpu_subtype == 5:
arch = 'armv4t'
elif cpu_subtype == 6:
arch = 'armv6'
elif cpu_subtype == 7:
arch = 'armv5tej'
elif cpu_subtype == 8:
arch = 'arm_xscale'
import macholib.MachO
MH_EXECUTE = 2
f = open(self.installPath + "/data/misc/machotemplate", 'rb')
macho = macholib.MachO.MachO(f.name)
if int(macho.headers[0].header.filetype) != MH_EXECUTE:
print helpers.color("[!] Macho binary template is not the correct filetype")
return ""
cmds = macho.headers[0].commands
for cmd in cmds:
count = 0
if int(cmd[count].cmd) == macholib.MachO.LC_SEGMENT_64:
count += 1
if cmd[count].segname.strip('\x00') == '__TEXT' and cmd[count].nsects > 0:
count += 1
for section in cmd[count]:
if section.sectname.strip('\x00') == '__cstring':
offset = int(section.offset)
placeHolderSz = int(section.size) - 13
template = f.read()
f.close()
if placeHolderSz and offset:
launcher = launcherCode + "\x00" * (placeHolderSz - len(launcherCode))
patchedMachO = template[:offset]+launcher+template[(offset+len(launcher)):]
def get_load_command_human_name(cmd):
""" return string name of LC_LOAD_DYLIB => "load_dylib"
"" if not found
"""
retval = ""
if cmd in macho.LC_REGISTRY:
retval = macho.LC_REGISTRY[cmd].__name__
retval = retval.replace("_command","")
return retval
import sys
import macholib
from macholib import MachO as macho
from collections import namedtuple
import re
# some fixups in macholib that are required for kext support
macholib.mach_o.MH_KEXT_BUNDLE = 0xB
macholib.mach_o.MH_FILETYPE_NAMES[macholib.mach_o.MH_KEXT_BUNDLE] = "kext bundle"
macholib.mach_o.MH_FILETYPE_SHORTNAMES[macholib.mach_o.MH_KEXT_BUNDLE] = "kext"
_old_MachOHeader_load = macho.MachOHeader.load
def new_load(s, fh):
try:
_old_MachOHeader_load(s, fh)
except ValueError as e:
if str(e.message).find('total_size > low_offset') >= 0:
pass
else:
raise
except Exception as e:
raise
macho.MachOHeader.load = new_load
class MemFile(object):
def __init__(self, memory, size):
self._start = 0
self._readp = 0
def processMachoBinary(filename):
outDict = dict()
outDict['result'] = False
setOfArchDigests = SetOfArchitectureDigest()
archDigestIdx = 0
parsedMacho = macholib.MachO.MachO(filename)
for header in parsedMacho.headers :
arch_digest = ArchitectureDigest()
lc_segment = LC_SEGMENT
arch_digest.setComponentByName('cpuType', CPUType(header.header.cputype))
arch_digest.setComponentByName('cpuSubType', CPUSubType(header.header.cpusubtype))
if header.header.cputype == 0x1000007:
lc_segment = LC_SEGMENT_64
segment_commands = list(filter(lambda x: x[0].cmd == lc_segment, header.commands))
text_segment_commands = list(filter(lambda x: x[1].segname.decode("utf-8").startswith("__TEXT"), segment_commands))
def __init__(self, arch, path, baseAddr):
self.arch = arch
self.path = path
self.baseAddr = baseAddr
self.defaultBaseAddr = 0
self.macho = None
self.sections = {}
self.symbols = {}
fullPath = os.path.join(self.arch.root, path)
macho = MachO.MachO(fullPath)
for h in macho.headers:
if h.header.cputype == self.arch.cpuType:
self.macho = h
# find the endAddr
endAddr = 0
for c in self.macho.commands:
if c[0].cmd == MachO.LC_SEGMENT or c[0].cmd == MachO.LC_SEGMENT_64:
if c[1].segname.strip("\0") == "__TEXT":
self.defaultBaseAddr = c[1].vmaddr
if (c[1].vmaddr+c[1].vmsize) > endAddr:
endAddr = c[1].vmaddr+c[1].vmsize
if c[1].maxprot & 0x4: # VM_PROT_EXECUTE
# add all the sections
for section in c[2]:
self.sections[section.addr] = section
self.endAddr = self.baseAddr+endAddr
def rewrite_tkinter_load_commands(tkinter_path):
print("rewrite_tk", tkinter_path)
m = macholib.MachO.MachO(tkinter_path)
tcl_path = None
tk_path = None
rewrite_map = {}
for header in m.headers:
for idx, name, other in header.walkRelocatables():
if other.endswith('/Tk'):
if tk_path is not None and other != tk_path:
raise DistutilsPlatformError('_tkinter is linked to different Tk paths')
tk_path = other
elif other.endswith('/Tcl'):
if tcl_path is not None and other != tcl_path:
raise DistutilsPlatformError('_tkinter is linked to different Tcl paths')
tcl_path = other