Examples

Seven complete, commented SPL models in examples/. Each opens below in full and has a walkthrough of what saple analyze reports.

Systems and protocols

Dining Philosophers

Walkthrough
dining_philosophers.splDeadlockLiveness

The classic concurrency benchmark: 5 philosophers, 5 forks. Verifies noDeadlock, mutualExclusion, and progress.

Shell
saple analyze examples/dining_philosophers.spl --verbose
Complete SPL model
SPL dining_philosophers.spl
// Dining Philosophers — Deadlock and Starvation Analysis
//
// Classic concurrency problem modeled in SPL process equations: five
// philosophers sit at a round table with one fork between each pair; a
// philosopher needs both neighbouring forks to eat.
// Demonstrates: parallel composition, guarded choice, deadlock detection,
// behavioral equation recursion, multi-agent interaction via shared resources.
//
// What the analysis should find: the system declares three properties
// (noDeadlock, mutualExclusion, progress) and no patterns; `saple analyze`
// reports no violation ("No vulnerabilities detected.").

// What a philosopher is doing, and whether a fork is on the table.
type PhilState = { THINKING, HUNGRY, EATING };
type ForkState = { FREE, TAKEN };

// ─── Actions ───
// Each transition makes one small state change; a philosopher's meal is a
// sequence of these fine-grained steps.

// A thinking philosopher becomes hungry.
transition getHungry(id : Int) {
    guard:  Philosopher(id).state == THINKING ;
    effect: Philosopher(id).state := HUNGRY ;
}

// A hungry philosopher takes the left fork (fork `id`) if it is free.
transition pickLeft(id : Int) {
    guard:  Philosopher(id).state == HUNGRY &&
          Fork(id).state == FREE ;
    effect: Fork(id).state := TAKEN ;
}

// A hungry philosopher takes the right fork (fork `id + 1`, wrapping) if it is free.
transition pickRight(id : Int) {
    guard:  Philosopher(id).state == HUNGRY &&
          Fork((id + 1) % numPhil).state == FREE ;
    effect: Fork((id + 1) % numPhil).state := TAKEN ;
}

// With both forks taken, the philosopher eats.
transition startEating(id : Int) {
    guard:  Fork(id).state == TAKEN &&
          Fork((id + 1) % numPhil).state == TAKEN ;
    effect: Philosopher(id).state := EATING ;
}

// An eating philosopher puts the left fork back.
transition putLeftFork(id : Int) {
    guard:  Philosopher(id).state == EATING ;
    effect: Fork(id).state := FREE ;
}

// An eating philosopher puts the right fork back.
transition putRightFork(id : Int) {
    guard:  Philosopher(id).state == EATING ;
    effect: Fork((id + 1) % numPhil).state := FREE ;
}

// The meal ends; the philosopher thinks again.
transition finishEating(id : Int) {
    guard:  Philosopher(id).state == EATING ;
    effect: Philosopher(id).state := THINKING ;
}

// ─── Agents ───

// One philosopher; `id` is the seat number.
agent Philosopher(id : Int) {
    attributes {
        state : PhilState = THINKING ;
    }
    process {
        // Cycle: think → hungry → acquire forks → eat → release → repeat
        // Think: get hungry, then try for the forks.
        Think    = getHungry(id) . TryForks ;
        // TryForks: pick the forks up in either order (nondeterministic choice).
        TryForks = pickLeft(id) . pickRight(id) . Eat
                 + pickRight(id) . pickLeft(id) . Eat ;
        // Eat: start eating once both forks are held.
        Eat      = startEating(id) . Release ;
        // Release: put both forks back, stop eating, and think again.
        Release  = putLeftFork(id) . putRightFork(id) . finishEating(id) . Think ;
    }
}

// One fork: a passive resource whose state the philosophers change.
agent Fork(id : Int) {
    attributes {
        state : ForkState = FREE ;
    }
    process {
        // A fork takes no actions of its own.
        Idle = done ;
    }
}

// ─── Environment ───

// Shared state: the number of seats.
schema DiningTable {
    attributes {
        numPhil : Int = 5 ;
    }
    invariants {
        // A table needs at least two philosophers.
        numPhil >= 2 ;
    }
}

// ─── System ───

// Five philosophers and five forks around the table.
system DiningPhilosophers {
    schema: DiningTable ;
    agents {
        Philosopher(i) * 5 ;
        Fork(i) * 5 ;
    }
    init {
        numPhil == 5 ;
    }
    properties {
        // Deadlock freedom: some philosopher can always act
        noDeadlock : exists (i : Int) in [0..numPhil) .
            Philosopher(i).state == THINKING ||
            Philosopher(i).state == EATING ||
            (Philosopher(i).state == HUNGRY &&
             (Fork(i).state == FREE || Fork((i + 1) % numPhil).state == FREE)) ;

        // Mutual exclusion: adjacent philosophers never eat simultaneously
        mutualExclusion : forall (i : Int) in [0..numPhil) .
            !(Philosopher(i).state == EATING &&
              Philosopher((i + 1) % numPhil).state == EATING) ;

        // Progress: at least one philosopher can eventually eat
        progress : exists (i : Int) in [0..numPhil) .
            Philosopher(i).state != HUNGRY ||
            Fork(i).state == FREE ;
    }
}

Cache Coherence (MESI)

Walkthrough
cache_coherence.splData raceStale read

Four-core MESI cache protocol, with patterns for concurrent writes without invalidation and for stale reads of remotely-modified lines. Properties: coherence, exclusiveIsolation, liveness.

Shell
saple analyze examples/cache_coherence.spl --verbose
Complete SPL model
SPL cache_coherence.spl
// MESI Cache Coherence Protocol — Behavioral Equivalence
//
// Models the MESI (Modified/Exclusive/Shared/Invalid) cache coherence
// protocol used in multi-core processors. Demonstrates behavioral
// equivalence checking: the protocol implementation should be
// equivalent to a sequential memory model.
//
// Key SAPLE features: parallel composition of cache agents,
// environment invariants for coherence, behavioral equations
// with guards, and equivalence properties.
//
// What the analysis should find: the dataRace pattern (CRITICAL) matches;
// staleRead does not, and no property is reported violated.

// State of a cache line (MESI) and the operation on the shared bus.
type CacheState = { MODIFIED, EXCLUSIVE, SHARED, INVALID };
type BusOp = { READ, READX, UPGRADE, FLUSH };

// ─── Actions ───
// Decomposed into fine-grained atomic transitions.

// The core reads a valid line: no state change.
transition cpuReadHit(core : Int) {
    guard:  Cache(core).state != INVALID ;
    effect: skip ;
}

// The core reads an invalid line: it is loaded as Shared.
transition cpuReadMiss(core : Int) {
    guard:  Cache(core).state == INVALID ;
    effect: Cache(core).state := SHARED ;
}

// Broadcast a read request on the bus.
transition issueBusRead(addr : Int) {
    guard:  true ;
    effect: busOp := READ ;
}

// The core writes an invalid line: it becomes Modified.
transition cpuWriteInvalid(core : Int, val : Int) {
    guard:  Cache(core).state == INVALID ;
    effect: Cache(core).state := MODIFIED ;
}

// The core writes a Shared line: it becomes Modified.
transition cpuWriteShared(core : Int, val : Int) {
    guard:  Cache(core).state == SHARED ;
    effect: Cache(core).state := MODIFIED ;
}

// The core writes an Exclusive line: it becomes Modified without bus traffic.
transition cpuWriteExclusive(core : Int) {
    guard:  Cache(core).state == EXCLUSIVE ;
    effect: Cache(core).state := MODIFIED ;
}

// Broadcast an upgrade (invalidate the other copies).
transition issueBusUpgrade() {
    guard:  true ;
    effect: busOp := UPGRADE ;
}

// Broadcast a read-for-ownership.
transition issueBusReadX() {
    guard:  true ;
    effect: busOp := READX ;
}

// Snooping another core's write: drop a Shared copy.
transition snoopInvalidate(core : Int) {
    guard:  Cache(core).state == SHARED ;
    effect: Cache(core).state := INVALID ;
}

// Snooping another core's read: write back a Modified line and share it.
transition snoopFlush(core : Int) {
    guard:  Cache(core).state == MODIFIED ;
    effect: Cache(core).state := SHARED ;
}

// Snooping another core's read: an Exclusive line becomes Shared.
transition snoopShareExclusive(core : Int) {
    guard:  Cache(core).state == EXCLUSIVE ;
    effect: Cache(core).state := SHARED ;
}

// Evict a clean (Shared or Exclusive) line.
transition evictClean(core : Int) {
    guard:  Cache(core).state == SHARED || Cache(core).state == EXCLUSIVE ;
    effect: Cache(core).state := INVALID ;
}

// Evict a Modified line (it must be written back).
transition evictDirty(core : Int) {
    guard:  Cache(core).state == MODIFIED ;
    effect: Cache(core).state := INVALID ;
}

// Broadcast a write-back.
transition flushBus() {
    guard:  true ;
    effect: busOp := FLUSH ;
}

// ─── Agents ───

// One core's cache controller.
agent Cache(id : Int) {
    attributes {
        state : CacheState = INVALID ;   // MESI state of the line
        data : Int = 0 ;                 // cached value
        addr : Int = 0 ;                 // cached address
    }
    process {
        // Each cache controller cycles through operations
        Idle    = [state == INVALID] Miss + [state != INVALID] Hit ;
        // Miss: read or write an invalid line, then answer snoops.
        Miss    = cpuReadMiss(id) . issueBusRead(addr) . SnoopReply
                + cpuWriteInvalid(id, data) . issueBusReadX() . SnoopReply ;
        // Hit: read, write, or evict a valid line.
        Hit     = cpuReadHit(id) . Idle
                + cpuWriteShared(id, data) . issueBusUpgrade() . Idle
                + cpuWriteExclusive(id) . Idle
                + evictClean(id) . Idle
                + evictDirty(id) . flushBus() . Idle ;
        // SnoopReply: react to the other cores' bus traffic, or not at all.
        SnoopReply = snoopInvalidate(id) . Idle
                   + snoopFlush(id) . Idle
                   + snoopShareExclusive(id) . Idle
                   + Idle ;
    }
}

// Reference model: sequential memory (for equivalence checking)
agent SequentialMemory() {
    attributes {
        lastWriter : Int = 0 ;
        lastValue : Int = 0 ;
    }
    process {
        // Reads and writes in sequence, one at a time.
        Ready = cpuReadHit(core) . Ready
              + cpuWriteShared(core, val) . Ready
              + done ;
    }
}

// ─── Environment ───

// Shared state: number of cores and the current bus operation.
schema CacheEnv {
    attributes {
        numCores : Int = 4 ;
        busOp : BusOp = FLUSH ;
        busAddr : Int = 0 ;
    }
    invariants {
        // MESI invariant: at most one cache in Modified state
        forall (i : Int) in [0..numCores) .
            forall (j : Int) in [0..numCores) .
                (i != j) =>
                    !(Cache(i).state == MODIFIED && Cache(j).state == MODIFIED) ;

        // If any cache is Exclusive, no other cache has it Shared or Modified
        forall (i : Int) in [0..numCores) .
            Cache(i).state == EXCLUSIVE =>
                forall (j : Int) in [0..numCores) .
                    (i != j) => Cache(j).state == INVALID ;
    }
}

// ─── Vulnerability Patterns ───

// Data race: two cores write without proper invalidation
pattern dataRace {
    signature {
        cpuWriteShared(core1, val1) .
        cpuWriteShared(core2, val2) . done
    }
    constraints { core1 != core2 }
    severity: CRITICAL ;
}

// Stale read: reading from a cache line modified elsewhere
pattern staleRead {
    signature {
        cpuWriteInvalid(writer, val) .
        cpuReadHit(reader) . done
    }
    constraints { writer != reader }
    severity: HIGH ;
}

// ─── System ───

// Four caches, all starting Invalid.
system MESIProtocol {
    schema: CacheEnv ;
    agents {
        Cache(i) * 4 ;
    }
    init {
        numCores == 4 &&
        forall (i : Int) in [0..numCores) .
            Cache(i).state == INVALID ;
    }
    properties {
        // Coherence: no two caches hold Modified simultaneously
        coherence : forall (i : Int) in [0..numCores) .
            forall (j : Int) in [0..numCores) .
                (i != j) =>
                    !(Cache(i).state == MODIFIED &&
                      Cache(j).state == MODIFIED) ;

        // Exclusive isolation: Exclusive implies all others Invalid
        exclusiveIsolation : forall (i : Int) in [0..numCores) .
            Cache(i).state == EXCLUSIVE =>
                forall (j : Int) in [0..numCores) .
                    (i != j) => Cache(j).state == INVALID ;

        // Liveness: Invalid cache can transition to valid state
        liveness : forall (i : Int) in [0..numCores) .
            Cache(i).state == INVALID =>
                Cache(i).state == EXCLUSIVE ||
                Cache(i).state == SHARED ;
    }
}

PoS Consensus

Walkthrough
consensus.splPoSSafety

Multi-node proof-of-stake consensus protocol with validator selection and block creation. Declares one safety property, noDoubleBlock (the block counter stays non-negative).

Shell
saple analyze examples/consensus.spl --verbose
Complete SPL model
SPL consensus.spl
// Proof-of-Stake Consensus Protocol — Full SPL Model
//
// Ten nodes take turns: in each time slot one idle node is selected as the
// validator, a block is created, and the block is sent to the network.
// The model checks that the block counter never becomes negative.
//
// What the analysis should find: nothing. The system declares one property
// (noDoubleBlock) and no patterns; `saple analyze` reports
// "No vulnerabilities detected."

// Lifecycle of a node: idle, currently validating, or blocked.
type NodeState = { IDLE, VALIDATING, BLOCKED };

// ─── Transitions ───

// Pick the validator for a time slot: enabled while some node is idle;
// the node at index `slot` becomes the validator.
transition selectValidator(slot : Int) {
    guard:  exists (i : Int) in [0..numNodes) .
              Node(i).state == IDLE ;
    effect: Node(slot).state := VALIDATING ;
}

// A validator creates the next block: the chain height grows by one.
transition createBlock() {
    guard:  exists (i : Int) in [0..numNodes) . Node(i).isValidator == true ;
    effect: BlockNumber := BlockNumber + 1 ;
}

// A node that created a block broadcasts it; the protocol moves to the next slot.
transition sendBlock() {
    guard:  exists (i : Int) in [0..numNodes) . Node(i).blockCreated > 0 ;
    effect: timeSlot := timeSlot + 1 ;
}

// ─── Agents ───

// One consensus participant.
agent Node(id : Int) {
    attributes {
        isValidator : Bool = false ;     // selected as validator in this slot
        blockCreated : Int = 0 ;         // blocks this node has created
        stake : Real = 100.0 ;           // stake that weighs validator selection
        state : NodeState = IDLE ;       // lifecycle state
        isMalicious : Bool = false ;     // reserved for adversarial variants
    }
    process {
        // B0: be selected as validator for the current slot, or stop.
        B0 = selectValidator(timeSlot) . B1 + done ;
        // B1: create and send a block, then wait for the next slot.
        B1 = createBlock . sendBlock . B0 ;
    }
}

// ─── Environment ───

// Shared protocol state.
schema ConsensusEnv {
    attributes {
        BlockNumber : Int = 0 ;   // height of the chain
        timeSlot : Int = 0 ;      // current slot
        numNodes : Int = 10 ;     // number of participants
    }
    invariants {
        // Counters only grow.
        BlockNumber >= 0 ;
        timeSlot >= 0 ;
    }
}

// ─── System ───

// Ten nodes running the protocol over the shared environment.
system PoSConsensus {
    schema: ConsensusEnv ;
    agents {
        Node(i) * 10 ;
    }
    init {
        numNodes == 10 ;
    }
    properties {
        // The chain height never becomes negative.
        noDoubleBlock : BlockNumber >= 0 ;
    }
}

Token Contract

Walkthrough
token_contract.splReentrancyCWE-190AccessRace

Simplified ERC-20 token. Detects external-call reentrancy, unchecked mint overflow, unauthorized mint, and the approval double-spend race.

Shell
saple analyze examples/token_contract.spl --verbose
Complete SPL model
SPL token_contract.spl
// ERC-20 Token Contract — Vulnerability Pattern Matching
//
// Models a simplified ERC-20 smart contract in SPL to detect
// reentrancy, integer overflow, and unauthorized access patterns.
// Demonstrates: vulnerability patterns with severity, guarded behaviors,
// two-level algebraic matching.
//
// A TokenContract agent serves transfers, approvals and owner-only
// mint/burn; an Attacker agent debits, calls out, and re-enters.
//
// What the analysis should find: all four patterns match — reentrancy and
// unauthorizedMint (CRITICAL), integerOverflow and approvalRace (HIGH).

// Outcome of a transaction.
type TxStatus = { PENDING, COMMITTED, REVERTED };

// ─── Actions ───
// Each action models a single atomic state change.

// Take `amount` from the sender's balance (needs enough funds).
transition debitSender(from : Int, amount : Int) {
    guard:  balances[from] >= amount && amount > 0 ;
    effect: balances[from] -= amount ;
}

// Add `amount` to the receiver's balance.
transition creditReceiver(to : Int, amount : Int) {
    guard:  amount > 0 ;
    effect: balances[to] += amount ;
}

// Set how much `owner` lets a spender take.
transition setAllowance(owner : Int, amount : Int) {
    guard:  amount >= 0 ;
    effect: allowances[owner] := amount ;
}

// Spend from an allowance (needs enough allowance).
transition deductAllowance(owner : Int, amount : Int) {
    guard:  allowances[owner] >= amount ;
    effect: allowances[owner] -= amount ;
}

// Call out to another contract; a callback may now come back in.
transition externalCall(target : Int) {
    guard:  true ;
    effect: callbackPending := true ;
}

// The pending callback returns.
transition resolveCallback() {
    guard:  callbackPending == true ;
    effect: callbackPending := false ;
}

// Owner-only: create new tokens for `to`.
transition mintTokens(to : Int, amount : Int) {
    guard:  caller == owner && amount > 0 ;
    effect: balances[to] += amount ;
}

// Owner-only: grow the total supply by the minted amount.
transition increaseTotalSupply(amount : Int) {
    guard:  caller == owner ;
    effect: totalSupply += amount ;
}

// Owner-only: destroy tokens held by `from`.
transition burnTokens(from : Int, amount : Int) {
    guard:  caller == owner && balances[from] >= amount ;
    effect: balances[from] -= amount ;
}

// Owner-only: shrink the total supply by the burned amount.
transition decreaseTotalSupply(amount : Int) {
    guard:  caller == owner ;
    effect: totalSupply -= amount ;
}

// ─── Agents ───

// The contract: serves user operations, and admin operations for the owner.
agent TokenContract() {
    attributes {
        txStatus : TxStatus = PENDING ;
    }
    process {
        // Normal operation cycle
        // Ready: the owner may run admin operations; anyone may run user operations.
        Ready    = [caller == owner] AdminOps + UserOps ;
        // UserOps: transfer, approve, or transfer on someone's behalf.
        UserOps  = Transfer + Approve + TransferFrom ;
        // Transfer: debit the caller, credit the recipient.
        Transfer = debitSender(caller, amount) . creditReceiver(recipient, amount) . Ready ;
        // Approve: set the caller's allowance.
        Approve  = setAllowance(caller, amount) . Ready ;
        // TransferFrom: spend an allowance, debit the source, credit the recipient.
        TransferFrom = deductAllowance(source, amount) .
                       debitSender(source, amount) .
                       creditReceiver(recipient, amount) . Ready ;
        // AdminOps: mint or burn, keeping the total supply in step.
        AdminOps = mintTokens(recipient, amount) . increaseTotalSupply(amount) . Ready
                 + burnTokens(source, amount) . decreaseTotalSupply(amount) . Ready ;
    }
}

// An adversary that re-enters the contract through the external call.
agent Attacker() {
    attributes {
        reentrancyCount : Int = 0 ;
    }
    process {
        // Reentrancy: trigger external call during transfer, then re-enter
        Attack = debitSender(victim, drainAmount) .
                 externalCall(contractAddr) .
                 ReentrantCallback ;
        // Each callback debits the victim again, or stops.
        ReentrantCallback = resolveCallback() .
                            debitSender(victim, drainAmount) .
                            ReentrantCallback
                          + resolveCallback() . done ;
    }
}

// ─── Environment ───

// Shared contract state.
schema TokenEnv {
    attributes {
        totalSupply : Int = 1000000 ;      // tokens in existence
        callbackPending : Bool = false ;   // an external call has not returned yet
        owner : Int = 0 ;                  // the contract owner
        caller : Int = 0 ;                 // who is calling now
    }
    invariants {
        // The supply never goes negative.
        totalSupply >= 0 ;
    }
}

// ─── Vulnerability Patterns ───

// Reentrancy: external call between balance debit operations
pattern reentrancy {
    signature {
        debitSender(from, amount) .
        externalCall(target) .
        debitSender(from, amount2) . done
    }
    constraints { from == from }
    severity: CRITICAL ;
}

// Integer overflow: mint without bounds check
pattern integerOverflow {
    signature {
        mintTokens(to, amount) . increaseTotalSupply(amount) . done
    }
    constraints { totalSupply + amount < totalSupply }
    severity: HIGH ;
}

// Unauthorized access: mint by non-owner
pattern unauthorizedMint {
    signature {
        mintTokens(to, amount) . done
    }
    constraints { caller != owner }
    severity: CRITICAL ;
}

// Double-spend via approval race
pattern approvalRace {
    signature {
        setAllowance(owner, amount1) .
        deductAllowance(owner, amount2) .
        setAllowance(owner, amount3) . done
    }
    constraints { amount2 > amount1 }
    severity: HIGH ;
}

// ─── System ───

// The contract and one attacker.
system TokenSystem {
    schema: TokenEnv ;
    agents {
        TokenContract() * 1 ;
        Attacker() * 1 ;
    }
    init {
        totalSupply == 1000000 ;
    }
    properties {
        // Conservation: total supply stays non-negative
        supplyConservation : totalSupply >= 0 ;

        // No reentrancy: callback never pending during debit
        noReentrancy : !(callbackPending == true) ;

        // Owner-only minting
        mintAuthorized : totalSupply <= 1000000 || caller == owner ;
    }
}

Security applications

Vulnerable Packet Parser

Walkthrough
vulnerable_server.splCWE-190CWE-787CWE-416

Network packet parser that computes an allocation size, copies data, and frees on error. Integer overflow → undersized buffer → out-of-bounds write → use-after-free in the error path.

Shell
saple analyze examples/vulnerable_server.spl \
  --verbose
Complete SPL model
SPL vulnerable_server.spl
// Vulnerable Network Packet Parser — CWE Vulnerability Detection
//
// Models a simplified network server that parses incoming packets.
// Contains intentional vulnerabilities for SAPLE to detect:
//
//   CWE-190: Integer Overflow
//     - Packet length field (16-bit) multiplied by element size
//       can overflow, causing undersized buffer allocation.
//
//   CWE-787: Out-of-Bounds Write (Buffer Overflow)
//     - memcpy uses the original (large) length, writing past
//       the (small, overflowed) allocated buffer.
//
//   CWE-416: Use-After-Free
//     - Error path frees the buffer but continues to a handler
//       that reads from the freed pointer.
//
// This models the classic pattern:
//   uint16_t count = packet.count;          // attacker-controlled
//   size_t alloc_size = count * sizeof(Item); // integer overflow!
//   char *buf = malloc(alloc_size);         // small allocation
//   memcpy(buf, packet.data, count * sizeof(Item)); // huge copy → overflow
//
// What the analysis should find: the patterns integerOverflow and
// bufferOverflow (CRITICAL) and useAfterFree (HIGH), and a violation of the
// property noIntegerOverflow.

// Lifecycle of the server while it handles one packet.
type ServerState = { IDLE, PARSING, PROCESSING, ERROR, DONE };

// ─── Actions: packet parsing pipeline ───

// Step 1: Receive packet and read the count field (attacker-controlled input)
transition recvPacket(inputCount : Int) {
    guard:  serverState == IDLE ;
    effect: packetCount := inputCount ;
}

// Step 2: Compute allocation size (count * elementSize)
// BUG (CWE-190): If packetCount is large, this overflows
transition computeAllocSize() {
    guard:  serverState == PARSING ;
    effect: allocSize := packetCount * elementSize ;
}

// Step 3: Allocate buffer with the (possibly overflowed) size
transition allocateBuffer() {
    guard:  allocSize >= 0 ;
    effect: bufferSize := allocSize ;
}

// Step 4: Compute copy length from original count (not the overflowed size)
transition computeCopyLen() {
    guard:  bufferSize >= 0 ;
    effect: copyLength := packetCount * elementSize ;
}

// Step 5: Perform the copy
// BUG (CWE-787): copyLength > bufferSize when overflow occurred
transition performCopy() {
    guard:  copyLength >= 0 ;
    effect: bytesWritten := copyLength ;
}

// Step 6: Process the buffer contents
transition processBuffer() {
    guard:  serverState == PROCESSING && bufferFreed == false ;

    effect: serverState := DONE ;
}

// Step 7: Free the buffer
transition freeBuffer() {
    guard:  bufferSize > 0 ;
    effect: bufferFreed := true ;
}

// Step 8: Error handler that touches the buffer
// BUG (CWE-416): Accesses buffer after it was freed
transition errorHandler() {
    guard:  serverState == ERROR ;
    effect: errorBufRead := bufferSize ;
}

// Transition actions (no data effect, just state machine)
transition startParsing() {
    guard:  serverState == IDLE ;
    effect: serverState := PARSING ;
}

// Parsing succeeded: process the packet.
transition startProcessing() {
    guard:  serverState == PARSING ;
    effect: serverState := PROCESSING ;
}

// Parsing failed: take the error path.
transition triggerError() {
    guard:  serverState == PARSING ;
    effect: serverState := ERROR ;
}

// Processing is complete.
transition finishProcessing() {
    guard:  serverState == PROCESSING ;
    effect: serverState := DONE ;
}

// ─── Agent ───

agent PacketParser() {
    attributes {
        state : ServerState = IDLE ;
    }
    process {
        // Normal path: receive → parse → allocate → copy → process → done
        // Error path:  receive → parse → error → free → errorHandler (use-after-free!)
        Start     = recvPacket(inputCount) . startParsing() . Parse ;
        Parse     = computeAllocSize() . allocateBuffer() .
                    computeCopyLen() . performCopy() .
                    startProcessing() . Process
                  + triggerError() . ErrorPath ;
        Process   = processBuffer() . Cleanup ;
        Cleanup   = freeBuffer() . done ;
        ErrorPath = freeBuffer() . errorHandler() . done ;
    }
}

// ─── Environment ───

schema ServerEnv {
    attributes {
        serverState : ServerState = IDLE ;
        packetCount : Int = 0 ;
        elementSize : Int = 64 ;
        allocSize : Int = 0 ;
        bufferSize : Int = 0 ;
        copyLength : Int = 0 ;
        bytesWritten : Int = 0 ;
        bufferFreed : Bool = false ;
        errorBufRead : Int = 0 ;
        maxUint16 : Int = 65535 ;
        maxAllocSize : Int = 4194304 ;
    }
    invariants {
        elementSize > 0 ;
    }
}

// ─── Vulnerability Patterns ───

// CWE-190: Integer Overflow in allocation size computation
// Signature: compute alloc from attacker input, then allocate with result
pattern integerOverflow {
    signature {
        recvPacket(inputCount) .
        computeAllocSize() .
        allocateBuffer() . done
    }
    constraints {
        packetCount * elementSize > maxAllocSize &&
        allocSize < packetCount * elementSize
    }
    severity: CRITICAL ;
}

// CWE-787: Out-of-Bounds Write (buffer overflow via copy)
// Signature: allocate buffer then copy more than allocated
pattern bufferOverflow {
    signature {
        allocateBuffer() .
        computeCopyLen() .
        performCopy() . done
    }
    constraints { copyLength > bufferSize }
    severity: CRITICAL ;
}

// CWE-416: Use-After-Free
// Signature: free buffer then access it
pattern useAfterFree {
    signature {
        freeBuffer() .
        errorHandler() . done
    }
    constraints { bufferFreed == true }
    severity: HIGH ;
}

// ─── System ───

system VulnerableServer {
    schema: ServerEnv ;
    agents {
        PacketParser() * 1 ;
    }
    init {
        serverState == IDLE &&
        packetCount == 0 &&
        bufferFreed == false ;
    }
    properties {
        // SAFETY: Written bytes should never exceed buffer size
        noBufferOverflow : bytesWritten <= bufferSize ;

        // SAFETY: Buffer should not be accessed after free
        noUseAfterFree : bufferFreed == false || errorBufRead == 0 ;

        // SAFETY: Allocation size should not overflow
        noIntegerOverflow : allocSize >= 0 ;
    }
}

Stack Buffer Overflow

Walkthrough
stack_buffer_overflow.splCWE-121CWE-787

x86-64 instruction chain where a loop copies user input into a stack frame without bounds checking. SAPLE finds the overflow and the return-address overwrite.

Shell
saple analyze examples/stack_buffer_overflow.spl \
  --verbose
Complete SPL model
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 ;
    }
}

Network Protocol Stack

Walkthrough
network_protocol_stack.splCWE-190CWE-122CWE-400CWE-787CWE-805

Multi-layer TCP/IP stack (Ethernet → IP → TCP → Application) targeting five vulnerability classes with patterns and properties: IP length overflow, fragment-reassembly overflow, SYN flood, heap overflow, and a copy longer than its buffer.

Shell
saple analyze examples/network_protocol_stack.spl \
  --verbose
Complete SPL model
SPL network_protocol_stack.spl
// Network Protocol Stack — Comprehensive SAPLE Example
//
// Models a TCP/IP stack with 4 protocol layers as separate agents:
//   1. EthernetParser  — frame parsing, MAC validation
//   2. IPProcessor     — header parsing, fragment reassembly
//   3. TCPStateMachine — connection management, state transitions
//   4. AppHandler      — payload copy to heap buffer
//
// Exercises many SPL language features:
//   - Process calculus: prefix (.), choice (+), recursion, done
//   - Value types: Int, enum/Str
//   - Operators: arithmetic, comparison, logical (&&, ||)
//   - Guard/effect conditions as predicate transformers
//   - Patterns with constraints (structural + semantic matching)
//   - Safety properties checked at every step
//   - Multiple agents in a system
//   - Schema with invariants
//
// Targets five vulnerability classes, each by a pattern, a property or both:
//   CWE-190: IP total_length integer overflow     (pattern ipLengthOverflow;
//                                                   property ipPayloadNonNegative)
//   CWE-122: Fragment reassembly buffer overflow   (pattern fragmentOverflow;
//                                                   property fragmentBoundRespected)
//   CWE-400: SYN flood connection table exhaustion (pattern synFlood;
//                                                   property connectionTableBound)
//   CWE-787: Heap buffer overflow on payload copy  (pattern heapOverflow;
//                                                   property heapBoundRespected)
//   CWE-805: Copy longer than the buffer           (property copyBoundRespected)
// Malformed input (CWE-20) shares the property ipPayloadNonNegative with
// CWE-190; that property is not violated today.
//
// What the analysis should find today: the patterns ipLengthOverflow,
// fragmentOverflow, heapOverflow (CRITICAL) and synFlood (HIGH), and
// violations of copyBoundRespected, heapBoundRespected,
// fragmentBoundRespected and connectionTableBound, one per failing path.

// State machines of the four layers and of a connection-table entry.
type FrameState = { WAITING, PARSING, VALIDATED, REJECTED };
type IPState    = { IDLE, PROCESSING, REASSEMBLING, FORWARDING };
type TCPState   = { LISTEN, SYN_RECEIVED, ESTABLISHED, FIN_WAIT, CLOSED };
type ConnState  = { HALF_OPEN, OPEN, CLOSING };

// ─── Environment: shared packet buffer and protocol state ───

schema PacketBuffer {
    attributes {
        // Layer 1: Ethernet
        etherType : Int = 0 ;
        srcMAC : Int = 0 ;
        dstMAC : Int = 0 ;
        macOUI : Int = 0 ;
        frameValid : Int = 0 ;

        // Layer 2: IP
        ipVersion : Int = 4 ;
        ipTotalLength : Int = 0 ;
        ipHeaderLength : Int = 0 ;
        ipPayloadLength : Int = 0 ;
        ipFlags : Int = 0 ;
        fragmentOffset : Int = 0 ;
        fragmentCount : Int = 0 ;
        totalFragmentSize : Int = 0 ;
        maxReassemblyBuffer : Int = 100 ;

        // Layer 3: TCP
        tcpSrcPort : Int = 0 ;
        tcpDstPort : Int = 80 ;
        tcpSeqNum : Int = 0 ;
        tcpAckNum : Int = 0 ;
        connectionCount : Int = 0 ;
        maxConnections : Int = 3 ;
        synRate : Int = 0 ;

        // Layer 4: Application
        payloadSize : Int = 0 ;
        heapPtr : Int = 2000 ;
        heapBase : Int = 2000 ;
        heapEnd : Int = 2008 ;
        bytesCopied : Int = 0 ;
        loopDone : Int = 0 ;
    }
    invariants {
        maxReassemblyBuffer > 0 ;
        maxConnections > 0 ;
        heapEnd > heapBase ;
    }
}

// ─── Layer 1: Ethernet Actions ───

// Parse ethernet frame header — extract EtherType
// PT: E₁ = E₀[etherType ↦ 2048]
transition parseEthernetHeader() {
    guard:  true ;
    effect: etherType := 2048 ;
}

// Set MAC address fields from frame
// PT: E₂ = E₁[srcMAC ↦ 1234567890]
transition setMACFields() {
    guard:  true ;
    effect: srcMAC := 1234567890 ;
}

// Validate EtherType — check for IPv4 (0x0800 = 2048)
// PT: E₃ = E₂[frameValid ↦ 1]
transition validateFrame() {
    guard:  true ;
    effect: frameValid := 1 ;
}

// Accept valid frame — extract OUI from MAC address
transition acceptFrame() {
    guard:  frameValid == 1 ;
    effect: macOUI := srcMAC / 16777216 ;
}

// Reject invalid frame
transition rejectFrame() {
    guard:  frameValid == 0 ;
    effect: frameValid := 0 ;
}

// ─── Layer 2: IP Actions ───

// Parse IP header — set total length
// Concrete value: 150 (valid packet size, gives positive payload)
// PT: E₄ = E₃[ipTotalLength ↦ 150]
transition parseIPHeader() {
    guard:  true ;
    effect: ipTotalLength := 150 ;
}

// Set IP header length
// PT: E₅ = E₄[ipHeaderLength ↦ 20]
transition setIPHeaderLength() {
    guard:  true ;
    effect: ipHeaderLength := 20 ;
}

// Compute payload length
// ipPayloadLength = 150 - 20 = 130 (positive)
// This triggers CWE-122: 130 > maxReassemblyBuffer(100)
// PT: E₆ = E₅[ipPayloadLength ↦ ipTotalLength - ipHeaderLength]
transition computePayloadLength() {
    guard:  true ;
    effect: ipPayloadLength := ipTotalLength - ipHeaderLength ;
}

// Set IP flags — MF (More Fragments) bit
// PT: E₇ = E₆[ipFlags ↦ 1]
transition setIPFlags() {
    guard:  true ;
    effect: ipFlags := 1 ;
}

// Initialize fragment reassembly — set fragment count
transition startReassembly() {
    guard:  fragmentCount == 0 ;
    effect: fragmentCount := 3 ;
}

// Add fragment to reassembly buffer — VULNERABILITY: buffer overflow
// totalFragmentSize accumulates ipPayloadLength (130) per fragment
// After 1 fragment: 130 > maxReassemblyBuffer(100) → CWE-122
// PT: E₈ₖ = E₈ₖ₋₁[totalFragmentSize ↦ totalFragmentSize + ipPayloadLength]
transition reassembleFragment() {
    guard:  fragmentCount > 0 ;
    effect: totalFragmentSize := totalFragmentSize + ipPayloadLength ;
}

// Decrement fragment counter
transition decrementFragments() {
    guard:  true ;
    effect: fragmentCount := fragmentCount - 1 ;
}

// Complete fragment reassembly — pass to TCP
transition completeReassembly() {
    guard:  fragmentCount == 0 ;
    effect: payloadSize := totalFragmentSize ;
}

// ─── Layer 3: TCP Actions ───

// Receive SYN packet — VULNERABILITY: no bound check on connections
// connectionCount increments without limit → CWE-400 (SYN flood)
// Pre: true (accepts any packet — the vulnerability is the lack of guard)
// PT: E₉ = E₈[connectionCount ↦ connectionCount + 1]
transition receiveSYN() {
    guard:  true ;
    effect: connectionCount := connectionCount + 1 ;
}

// Track SYN rate
// PT: E₁₀ = E₉[synRate ↦ synRate + 1]
transition incrementSynRate() {
    guard:  true ;
    effect: synRate := synRate + 1 ;
}

// Send SYN-ACK response — has the bound check that receiveSYN lacks
transition sendSYNACK() {
    guard:  connectionCount <= maxConnections ;
    effect: tcpAckNum := tcpSeqNum + 1 ;
}

// Receive ACK — complete three-way handshake
transition receiveACK() {
    guard:  true ;
    effect: tcpSeqNum := tcpSeqNum + 1 ;
}

// Receive RST — connection reset
transition receiveRST() {
    guard:  true ;
    effect: connectionCount := connectionCount - 1 ;
}

// Set TCP closed state
transition setTCPClosed() {
    guard:  true ;
    effect: synRate := 0 ;
}

// Validate sequence number
transition validateSequence() {
    guard:  true ;
    effect: tcpSeqNum := tcpSeqNum + 1 ;
}

// ─── Layer 4: Application Actions ───

// Receive payload from TCP layer
// Concrete value: payloadSize = 20 (larger than 8-byte heap buffer)
// PT: E₁₁ = E₁₀[payloadSize ↦ 20]
transition receivePayload() {
    guard:  true ;
    effect: payloadSize := 20 ;
}

// Copy one byte to heap buffer — VULNERABILITY: heap overflow
// heapPtr increments past heapEnd (2008) when payloadSize (20) > buffer (8)
// Triggers after 9 iterations: heapPtr = 2009 > heapEnd = 2008
// PT: E₁₂ₖ = E₁₂ₖ₋₁[heapPtr ↦ heapPtr + 1]
transition copyPayloadByte() {
    guard:  bytesCopied < payloadSize ;
    effect: heapPtr := heapPtr + 1 ;
}

// Advance copy counter
// PT: E₁₃ₖ = E₁₂ₖ[bytesCopied ↦ bytesCopied + 1]
transition advanceCopyCounter() {
    guard:  true ;
    effect: bytesCopied := bytesCopied + 1 ;
}

// Finish payload copy
transition finishCopy() {
    guard:  bytesCopied >= payloadSize ;
    effect: loopDone := 1 ;
}

// ─── Agents: one per protocol layer ───
// NOTE: The analyzer enters from the first agent's first equation.
// We use a single NetworkStack agent that chains through all layers
// to ensure the full pipeline is exercised in one execution path.

agent NetworkStack() {
    attributes {
        phase : Int = 0 ;
    }
    process {
        // Layer 1: Ethernet parsing
        Start    = parseEthernetHeader() . setMACFields() . Validate ;
        Validate = validateFrame() . Route ;
        Route    = acceptFrame() . IPStart
                 + rejectFrame() . Done ;

        // Layer 2: IP processing
        IPStart  = parseIPHeader() . setIPHeaderLength() .
                   computePayloadLength() . setIPFlags() . IPRoute ;
        IPRoute  = startReassembly() . Reassemble
                 + TCPStart ;
        Reassemble = reassembleFragment() . decrementFragments() . Reassemble
                   + completeReassembly() . TCPStart ;

        // Layer 3: TCP connection handling
        // Choice: accept SYN (loops back to accept more) or proceed to app
        TCPStart = receiveSYN() . incrementSynRate() .
                   sendSYNACK() . receiveACK() . TCPStart
                 + validateSequence() . AppStart ;

        // Layer 4: Application payload copy
        AppStart = receivePayload() . CopyLoop ;
        CopyLoop = copyPayloadByte() . advanceCopyCounter() . CopyLoop
                 + finishCopy() . Done ;

        Done     = done ;
    }
}

// ─── Vulnerability Patterns ───
// Structural signatures + semantic constraints for two-level matching.
// Level 1: action subsequence match in behavior paths.
// Level 2: constraint evaluation against concrete state.

// CWE-190: Integer Overflow in IP Length Computation
// Detected when ipPayloadLength goes negative (underflow)
pattern ipLengthOverflow {
    signature {
        parseIPHeader() . computePayloadLength() . done
    }
    constraints {
        ipPayloadLength < 0
    }
    severity: CRITICAL ;
}

// CWE-122: Heap-based Buffer Overflow in Fragment Reassembly
// Triggered when accumulated fragment size exceeds reassembly buffer
// ipPayloadLength = 130, after 1 fragment: totalFragmentSize = 130 > 100
pattern fragmentOverflow {
    signature {
        startReassembly() . reassembleFragment() . done
    }
    constraints {
        totalFragmentSize > maxReassemblyBuffer
    }
    severity: CRITICAL ;
}

// CWE-400: SYN Flood / Resource Exhaustion
// Triggered when connection count exceeds table limit
// receiveSYN has no bound check (guard: true), so connectionCount grows unbounded
pattern synFlood {
    signature {
        receiveSYN() . sendSYNACK() . done
    }
    constraints {
        connectionCount > maxConnections
    }
    severity: HIGH ;
}

// CWE-787: Out-of-bounds Write in Payload Copy
// Triggered when heap write pointer exceeds buffer end
// payloadSize=20 > buffer=8, so heapPtr reaches 2009 > heapEnd=2008
pattern heapOverflow {
    signature {
        receivePayload() . copyPayloadByte() . done
    }
    constraints {
        heapPtr >= heapEnd
    }
    severity: CRITICAL ;
}

// ─── System: ties everything together ───

system NetworkStackAnalysis {
    schema: PacketBuffer ;
    agents {
        NetworkStack() * 1 ;
    }
    init {
        connectionCount == 0 &&
        fragmentCount == 0 &&
        bytesCopied == 0 &&
        heapPtr == 2000 ;
    }
    properties {
        // CWE-20/190: IP payload must not be negative
        ipPayloadNonNegative : ipPayloadLength >= 0 || ipTotalLength == 0 ;

        // CWE-122: Fragment total must stay within buffer
        fragmentBoundRespected : totalFragmentSize <= maxReassemblyBuffer || fragmentCount == 0 ;

        // CWE-400: Connection count must not exceed limit
        connectionTableBound : connectionCount <= maxConnections ;

        // CWE-787: Heap pointer must stay within buffer
        heapBoundRespected : heapPtr <= heapEnd || bytesCopied == 0 ;

        // CWE-805: Bytes copied must not exceed buffer capacity
        // Buffer capacity is heapEnd - heapBase = 8 bytes
        copyBoundRespected : bytesCopied <= heapEnd - heapBase ;
    }
}

Rule extraction

Add --extract-rules to any of the above. SAPLE turns each finding into a reusable .spl pattern, cross-validates it through the SMT solver, and stores it under patterns/generated/. On subsequent runs, those rules auto-load and apply to new files.

Shell
saple analyze examples/vulnerable_server.spl \
  --extract-rules --export rules.json \
  --verbose
Learn the SPL language The examples on GitHub
↑ ↓ to moveEnter to openEsc to close