Skip to content

Instantly share code, notes, and snippets.

@ChiChou
Last active March 8, 2023 02:30
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ChiChou/15f0772db25343be0bb7072f15992a4e to your computer and use it in GitHub Desktop.
Save ChiChou/15f0772db25343be0bb7072f15992a4e to your computer and use it in GitHub Desktop.
checksec for iOS executables based on lief
#!/usr/bin/env python3
import struct
import lief
from lief.MachO import LOAD_COMMAND_TYPES, HEADER_FLAGS
def check(filename):
macho = lief.parse(filename)
# check this?
# nx = HEADER_FLAGS.ALLOW_STACK_EXECUTION not in macho.header.flags
# PIE
pie_enabled = HEADER_FLAGS.PIE in macho.header.flags
# restrict segment for anti-debugging
# ptrace looks hard to detect by pure static analytics
restricted_segment = False
for segment in macho.segments:
if segment.name.lower() == '__restrict':
restricted_segment = True
break
imported = macho.imported_functions
# stack canary
canary_enabled = '___stack_chk_fail' in imported and '___stack_chk_guard' in imported
# ARC
arc_enabled = '_objc_release' in imported
# encrypted
cryptid = 0
for cmd in macho.commands:
if cmd.command == LOAD_COMMAND_TYPES.ENCRYPTION_INFO:
buf = bytearray(cmd.data)
cmd, cmdsize, cryptoff, cryptsize, cryptid = struct.unpack('<IIIII', buf)
break
elif cmd.command == LOAD_COMMAND_TYPES.ENCRYPTION_INFO_64:
buf = bytearray(cmd.data)
cmd, cmdsize, cryptoff, cryptsize, cryptid, pad = struct.unpack('<IIIIII', buf)
break
encrypted = bool(cryptid)
result = {
'RESTRICT': restricted_segment,
'CANARY': canary_enabled,
'PIE': pie_enabled,
'ARC': arc_enabled,
'ENCRYPTED': encrypted,
}
for item in result.items():
print('%s: %s' % item)
if __name__ == '__main__':
import sys
try:
path = sys.argv[1]
check(path)
except KeyError:
print('usage: check.py EXECUTABLE')
Copy link

ghost commented Apr 9, 2018

With LIEF 0.8.3, pie_enabled = HEADER_FLAGS.PIE in macho.header.flags should be pie_enabled = HEADER_FLAGS.PIE in macho.header.flags_list (https://lief.quarkslab.com/doc/stable/api/python/macho.html?highlight=header#lief.MachO.Header.flags_list).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment