forked from Blendman974/faceclaw
58 lines
2.1 KiB
Python
58 lines
2.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Check ELF64 LOAD/RELRO alignment in an APK; pair with zipalign -c -P 16 4."""
|
|
import argparse
|
|
import struct
|
|
import zipfile
|
|
|
|
PAGE = 16384
|
|
|
|
|
|
def alignment_errors(data):
|
|
if len(data) < 64 or data[:4] != b"\x7fELF" or data[4] != 2 or data[5] not in (1, 2):
|
|
return ["expected an ELF64 library"]
|
|
endian = "<" if data[5] == 1 else ">"
|
|
offset = struct.unpack_from(endian + "Q", data, 32)[0]
|
|
size, count = struct.unpack_from(endian + "HH", data, 54)
|
|
if size < 56 or offset + size * count > len(data):
|
|
return ["invalid program headers"]
|
|
headers = [struct.unpack_from(endian + "IIQQQQQQ", data, offset + i * size) for i in range(count)]
|
|
errors = []
|
|
loads = [h for h in headers if h[0] == 1]
|
|
if not loads:
|
|
errors.append("no LOAD segments")
|
|
for h in loads:
|
|
if h[7] < PAGE or h[7] % PAGE or (h[3] - h[2]) % PAGE:
|
|
errors.append(f"LOAD alignment {h[7]} is incompatible with 16 KiB pages")
|
|
for h in headers:
|
|
if h[0] != 0x6474E552:
|
|
continue
|
|
end = h[3] + h[6]
|
|
# A RELRO ending within a writable LOAD may protect unrelated writable
|
|
# data on a 16 KiB device. A separate LOAD after RELRO is also safe.
|
|
if end % PAGE and any(p[1] & 2 and p[3] <= h[3] and end < p[3] + p[6] for p in loads):
|
|
errors.append("RELRO ends inside writable LOAD without 16 KiB alignment")
|
|
return errors
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("apk")
|
|
args = parser.parse_args()
|
|
checked = 0
|
|
failed = False
|
|
with zipfile.ZipFile(args.apk) as archive:
|
|
for name in archive.namelist():
|
|
if not name.startswith(("lib/arm64-v8a/", "lib/x86_64/")) or not name.endswith(".so"):
|
|
continue
|
|
checked += 1
|
|
errors = alignment_errors(archive.read(name))
|
|
failed |= bool(errors)
|
|
print(f"{'FAIL' if errors else 'OK'} {name}" + (": " + "; ".join(errors) if errors else ""))
|
|
if not checked:
|
|
parser.error("no 64-bit native libraries found")
|
|
return int(failed)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|