Stack Buffer Overflow (x86-64)

A hand-written SPL model of an x86-64 function whose loop copies user input into a stack frame without a bounds check. (To analyse real assembly instead, see the x86-64 front end.)

Run#

Shell
saple analyze examples/stack_buffer_overflow.spl

The report holds the structural findings stackBufferOverflow and returnAddressOverwrite (both CRITICAL) and violations of the properties noStackOverflow and noFrameOverflow, one per path on which they fail.

Notes#

The model abstracts the instruction chain — push/pop, mov, jmp — into named transitions. Each loop iteration is a recursive behavior equation, and the overflow shows when the symbolic stack-write offset crosses the frame boundary.

Complete model#

examples/stack_buffer_overflow.spl, as shipped:

SPL stack_buffer_overflow.spl
// Stack Buffer Overflow — a hand-written model of an x86-64 copy loop
//
// Demonstrates the SAPLE pipeline on a hand-written model:
//   1. A suspicious instruction chain is picked out
//   2. The chain is modeled as SPL process equations
//   3. Predicate transformers build SMT constraints
//   4. Z3 proves exploitability with a concrete witness
//
// Source chain (x86-64):
//   0x401020: mov rdi, [rsp+0x8]      ; rdi = user input pointer
//   0x401025: call read_input          ; reads into rdi, returns size in rax
//   0x40102a: sub rsp, 0x20           ; allocate 32 bytes on stack
//   0x40102e: xor rcx, rcx            ; rcx = 0 (loop counter)
//   .loop:
//   0x401031: mov dl, [rdi+rcx]       ; read byte from input
//   0x401034: mov [rsp+rcx], dl       ; write byte to stack  ← VULN
//   0x401037: inc rcx
//   0x401039: cmp rcx, rax            ; compare counter with input size
//   0x40103c: jl .loop
//
// The chain is suspicious because [rsp+rcx] can exceed the
// 0x20-byte stack frame when rax (input size from read_input) > 0x20.
// SAPLE proves it with a concrete witness.
//
// What the analysis should find: the patterns stackBufferOverflow and
// returnAddressOverwrite (CRITICAL), and violations of the properties
// noStackOverflow and noFrameOverflow on the paths where they fail.
//
// ═══════════════════════════════════════════════════════════════
// SMT CONSTRAINT GENERATION (what SAPLE produces automatically):
//
// Each action's postcondition becomes a predicate transformer step.
// The chain of transformers composes into a single SMT formula:
//
//   frameBase = rsp_init
//   rsp' = rsp_init - 32        (allocStackFrame)
//   frameSize = 32               (allocStackFrame)
//   rcx₀ = 0                    (zeroCounter)
//   rcxₖ = k                    (after k loop iterations)
//   writeAddrₖ = rsp' + rcxₖ    (loopBodyCopyByte)
//
// Overflow condition:
//   writeAddrₖ >= frameBase
//   ↔ (rsp_init - 32) + k >= rsp_init
//   ↔ k >= 32
//
// Since rcxₖ < rax and rax is unconstrained (havoc from read_input):
//   rax = 33 → k reaches 32 → OVERFLOW (SAT)
//
// Z3 query:
//   (declare-const rsp_init (_ BitVec 64))
//   (declare-const rax (_ BitVec 64))
//   (declare-const k (_ BitVec 64))
//   (assert (bvule k rax))
//   (assert (bvuge k #x20))
//   (check-sat) → SAT
//   (get-model) → rax=0x21, k=0x20
// ═══════════════════════════════════════════════════════════════

type LoopState = { BEFORE_LOOP, IN_LOOP, AFTER_LOOP };

// ─── Actions modeling x86-64 instruction semantics ───
// Each action corresponds to one or more x86 instructions.
// The guard/effect pair IS the predicate transformer for that step.

// mov rdi, [rsp+0x8] — load user input pointer
// PT: E₁ = E₀[inputPtr ↦ rsp + 8]
transition loadInputPtr() {
    guard:  true ;
    effect: inputPtr := rsp + 8 ;
}

// call read_input — external function, returns size in rax
// PT: E₂ = E₁[rax ↦ 48]
// In real use, the input size comes from the program's input.
// Here we use 48 (> 32 byte frame) to demonstrate the overflow.
// The SMT solver would find this automatically; concrete execution
// needs a specific value to walk the loop.
transition callReadInput() {
    guard:  true ;
    effect: rax := 48 ;
}

// sub rsp, 0x20 — allocate 32 bytes of stack frame
// PT: E₃ = E₂[frameBase ↦ rsp]
// (We split the multi-register update into sequential actions)
transition saveFrameBase() {
    guard:  true ;
    effect: frameBase := rsp ;
}

// PT: E₄ = E₃[rsp ↦ rsp - 32, frameSize ↦ 32]
transition allocStackFrame() {
    guard:  true ;
    effect: rsp := rsp - 32 ;
}

// The frame is 32 bytes.
transition setFrameSize() {
    guard:  true ;
    effect: frameSize := 32 ;
}

// xor rcx, rcx — zero the loop counter
// PT: E₅ = E₄[rcx ↦ 0]
transition zeroCounter() {
    guard:  true ;
    effect: rcx := 0 ;
}

// Loop body: mov dl,[rdi+rcx]; mov [rsp+rcx],dl; inc rcx
// PT: E_{k+1} = E_k[writeAddr ↦ rsp + rcx, bytesWritten ↦ rcx + 1, rcx ↦ rcx + 1]
// The loop guard (cmp rcx, rax; jl) becomes the precondition.
// Combined into one action to keep depth manageable for bounded exploration.
transition loopBodyCopyByte() {
    guard:  rcx < rax ;
    effect: writeAddr := rsp + rcx ;
}

// inc rcx — next loop iteration.
transition advanceLoop() {
    guard:  true ;
    effect: rcx := rcx + 1 ;
}

// cmp rcx, rax; jge .exit — loop termination
transition loopExit() {
    guard:  rcx >= rax ;
    effect: loopDone := 1 ;
}

// ─── Agent: the instruction chain as process equations ───
// The behavior equations capture the control flow graph:
//   Start → Setup → CopyLoop → Done
//   CopyLoop = (copy one byte; continue) + (exit loop)

agent StackCopier() {
    attributes {
        state : LoopState = BEFORE_LOOP ;
    }
    process {
        Start    = loadInputPtr() . callReadInput() .
                   saveFrameBase() . allocStackFrame() . setFrameSize() .
                   zeroCounter() . CopyLoop ;

        // Choice operator (+) models the conditional branch:
        //   Left branch:  rcx < rax  → copy byte, advance, loop back
        //   Right branch: rcx >= rax → exit loop
        CopyLoop = loopBodyCopyByte() . advanceLoop() . CopyLoop
                 + loopExit() . Done ;

        Done     = done ;
    }
}

// ─── Environment: register and memory state ───

schema X86State {
    attributes {
        // Registers
        rsp : Int = 1000 ;       // stack pointer (concrete initial for analysis)
        rax : Int = 0 ;          // return value / input size
        rcx : Int = 0 ;          // loop counter
        inputPtr : Int = 0 ;     // rdi — pointer to input

        // Frame tracking
        frameBase : Int = 0 ;    // saved rsp before allocation
        frameSize : Int = 0 ;    // bytes allocated (0x20 = 32)

        // Write tracking
        writeAddr : Int = 0 ;    // last write destination

        // Loop control
        loopDone : Int = 0 ;
    }
    invariants {
        frameSize >= 0 ;
    }
}

// ─── Vulnerability Patterns ───
// These state what is suspected; SAPLE proves or disproves it.

// CWE-121: Stack-based Buffer Overflow
// Detected when: the copy loop writes beyond the allocated stack frame
pattern stackBufferOverflow {
    signature {
        allocStackFrame() .
        zeroCounter() .
        loopBodyCopyByte() . done
    }
    constraints {
        rcx > frameSize
    }
    severity: CRITICAL ;
}

// CWE-121 variant: Return Address Overwrite
// More specific — the write reaches the saved return address
// (frameBase is where the return address lives on x86-64)
pattern returnAddressOverwrite {
    signature {
        saveFrameBase() .
        allocStackFrame() .
        loopBodyCopyByte() . done
    }
    constraints {
        writeAddr >= frameBase && frameBase > 0
    }
    severity: CRITICAL ;
}

// ─── System: defines what SAPLE checks ───

system StackOverflowCheck {
    schema: X86State ;
    agents {
        StackCopier() * 1 ;
    }
    init {
        rsp == 1000 &&
        rax == 0 &&
        rcx == 0 &&
        frameSize == 0 ;
    }
    properties {
        // SAFETY: loop counter (= bytes written) must not exceed frame size
        // This is the SMT property: ∀ reachable states, rcx ≤ frameSize
        // SAPLE disproves it → finds the vulnerability
        // PT chain produces: rcx can reach rax=48 > frameSize=32 → VIOLATION
        noFrameOverflow : rcx <= frameSize || frameSize == 0 ;

        // SAFETY: write address must stay within frame
        // writeAddr = rsp + rcx = (frameBase - 32) + rcx
        // Overflow when: writeAddr >= frameBase ↔ rcx >= 32
        noStackOverflow : writeAddr < frameBase || frameBase == 0 ;

        // STRUCTURAL: loop counter respects input size
        loopBoundRespected : rcx <= rax || loopDone == 1 ;
    }
}
↑ ↓ to moveEnter to openEsc to close