Network Protocol Stack

Models a multi-layer network stack (Ethernet, IP, TCP, Application) that targets five vulnerability classes, each with a pattern, a property or both:

Malformed input (CWE-20) shares ipPayloadNonNegative with CWE-190; that property is not violated today.

Run#

Shell
saple analyze examples/network_protocol_stack.spl

The model declares the patterns ipLengthOverflow, fragmentOverflow, synFlood and heapOverflow; all four match. Most of the report is property violations (copyBoundRespected, heapBoundRespected, fragmentBoundRespected, connectionTableBound), one per path on which they fail.

Structure#

Each protocol layer is a separate agent with its own process equations. The layers communicate through a shared schema modelling packet buffers, the connection table, and reassembly state.

Complete model#

examples/network_protocol_stack.spl, as shipped:

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 ;
    }
}
↑ ↓ to moveEnter to openEsc to close