Skip to content

[NEW QUERY] Swift: swift/untrusted-pointer-offset (CWE-125) - #103

Draft
felickz with Copilot wants to merge 4 commits into
mainfrom
copilot/query-create-memory-safety
Draft

felickz with Copilot wants to merge 4 commits into
mainfrom
copilot/query-create-memory-safety

Conversation

Copilot AI commented Oct 16, 2026 •

Copy link
Copy Markdown

📝 Query Information

  • Language: swift
  • Query ID: swift/untrusted-pointer-offset (languages/swift/custom/src/UntrustedPointerOffset/UntrustedPointerOffset.ql)
  • Category: security
  • Severity: error (@security-severity 8.1, @precision medium)
  • CWE/CVE (if applicable): CWE-125, CWE-787, CWE-823

🎯 Description

⚠️ Not yet executed. The Swift extractor in the CodeQL bundle only works on macOS (on Linux it is a stub that exits with incompatible-os). Building it from source in the sandbox also failed because bcr.bazel.build is blocked. UntrustedPointerOffset.expected is intentionally missing rather than written by hand. Before merge, on macOS run cd languages/swift/custom/test && codeql test run --learn -- UntrustedPointerOffset/ and check the results against the inline // $ Alert / // $ Source markers.

Fills the gap where no Swift query covers attacker-controlled offsets used with unsafe pointers. Default setup missed an OVIA deep-link handler that adds a signed offset from the URL to a pointer and also uses it to compute a copy length.

What This Query Detects

The taint source is the stock Swift FlowSource. A sink is any argument that sets the offset, index or length of an unsafe pointer access:

Sink Pointer types
+ / - / += / -= (the non-pointer operand) Unsafe[Mutable][Raw]Pointer, AutoreleasingUnsafeMutablePointer
advanced(by:), load(fromByteOffset:as:), loadUnaligned(fromByteOffset:as:) pointers and buffer pointers
subscript index (buffer pointers are only bounds-checked in debug builds) pointers and buffer pointers
length argument of Data(bytes:count:), Data(bytesNoCopy:count:deallocator:), NSData(bytes[NoCopy]:length:…), Unsafe*BufferPointer(start:count:) n/a

Barriers:

  • Two-sided bounds check. A variable read is safe only if conditions that bound it from below and from above control the read on the matching true/false branch. Comparisons, contains(_:) and ~= all count. One-sided checks still alert, because negative Int offsets are the attack.
  • Clamping: min(max(…)) / max(min(…)).
  • Buffer size reads: .count, .capacity, .startIndex, .endIndex. The size of untrusted data is not an attacker-chosen offset.

New taint models, needed for the URL query-parameter pattern and scoped to this query:

  • URLComponents / NSURLComponents initializers and fields
  • URLQueryItem fields
  • Sequence.first(where:), where taint on the whole collection flows to the returned element

Example Vulnerable Code

if let offsetParam = getQueryParameter(url, "offset"), let offset = Int(offsetParam) {
    let arr = [UInt8](data)
    data = Data(bytes: &data + offset, count: arr.count - offset) // both `offset` uses flagged
}

Example Safe Code

guard offset >= 0, offset < data.count else { return }
_ = buffer.advanced(by: offset)

if let raw = getQueryParameter(url, "index"), let index = Int(raw), (0..<16).contains(index) {
    _ = other[index]
}

_ = other + 4 // constant offset

🧪 Testing

  • Positive test cases included
  • Negative test cases included
  • Edge cases covered
  • All tests pass

UntrustedPointerOffset.swift uses only the standard library plus stubs. It type-checks with swiftc 6.4, and swiftc -dump-ast was used to check how the AST is resolved (for example, &data + offset resolves to Strideable.+ where Self: _Pointer).

Positive cases:

  • the reduced OVIA route
  • advanced(by:), pointer subscript, ptr - i, ptr += i
  • baseAddress! + i used inside a closure

Negative cases:

  • a two-sided if check
  • a two-sided guard check
  • contains used in an if let condition
  • constant offsets

📋 Checklist

  • Query compiles without errors
  • Documentation complete (.md and .qhelp)
  • Metadata properly set (@name, @id, @kind, etc.)
  • Tests validate query behavior
  • No false positives in test cases

Other changes:

  • New languages/swift/custom/{src,test} packs.
  • codeql-qlt-unit-tests.yml now skips swift during language discovery, since ubuntu-latest cannot extract Swift.

Known limitations:

  • The barrier only recognizes checks on the same variable.
  • Checks made through a different alias or an inline expression are not recognized.

🔗 References


Note: This query was developed using Test-Driven Development methodology.

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
Copilot AI changed the title [WIP] Add Swift query for memory safety (CWE-125) [NEW QUERY] Swift: swift/untrusted-pointer-offset (CWE-125) Oct 16, 2026
Copilot AI requested a review from felickz October 16, 2026 15:50
@felickz
felickz requested a balanced review from Copilot October 30, 2026 18:16

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Overbroad sanitization barriers can suppress unsafe pointer-access findings by accepting partial bounds checks, reassigned variables, tainted clamp bounds, and arbitrary size-named properties.

4 open issues
What changed in this PR

Adds swift/untrusted-pointer-offset to the custom CodeQL queries, targeting attacker-controlled offsets, indices, and lengths in unsafe Swift pointer operations.

Changes:

  • Models pointer-operation sinks, URL-derived taint, and bounds-check barriers.
  • Adds Swift source/test packs, query documentation, and positive and negative fixtures.
  • Excludes Swift tests from the Ubuntu workflow; macOS execution and expected results remain pending.
File Description
languages/​swift/​custom/​test/​UntrustedPointerOffset/​UntrustedPointerOffset.swift Adds deep-link, pointer-operation, and bounds-check fixtures.
languages/​swift/​custom/​test/​UntrustedPointerOffset/​UntrustedPointerOffset.qlref Connects fixtures to the query and inline expectations processor.
languages/​swift/​custom/​test/​qlpack.yml Defines the Swift test pack.
languages/​swift/​custom/​src/​UntrustedPointerOffset/​UntrustedPointerOffset.ql Implements taint tracking, pointer sinks, and barriers.
languages/​swift/​custom/​src/​UntrustedPointerOffset/​UntrustedPointerOffset.md Documents risks, recommendations, and examples.
languages/​swift/​custom/​src/​qlpack.yml Defines the Swift query pack.
.github/​workflows/​codeql-qlt-unit-tests.yml Skips Swift tests on the Linux runner.

Review effort: Balanced

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
@felickz

felickz commented Oct 31, 2026

Copy link
Copy Markdown

@copilot A rescan of the synthetic corpus found additional medium and low severity findings that fit this gap. Please re-run your analysis against each finding below, confirm whether the proposed change covers each scenario, and extend it where it does not. Keep each change minimal with a positive and a negative regression test, keep every existing test passing, and do not broaden scope. The same findings are listed in the matching comment on issue #100.

Linked findings

Repo CWE Severity AI scan alert Summary
iGoat-Swift CWE-125 medium https://github.com/codeql-forks-felickz/iGoat-Swift/security/code-scanning/34 Data.aes() always passes keyLength = size_t(kCCKeySizeAES128) (16) to CCCrypt() while the key pointer comes from the caller-supplied `
iGoat-Swift CWE-125 medium https://github.com/codeql-forks-felickz/iGoat-Swift/security/code-scanning/46 String.aesEncrypt(key:iv:options:) / String.aesDecrypt(key:iv:options:) hard-code keyLength = size_t(kCCKeySizeAES128) (16 bytes) whil

Handling

Create a new CodeQL query. No existing query covers these patterns (most findings are gap type query-absent or missing-query). Because coverage of lower-severity patterns can be heuristic, target Community Packs unless precision is shown to be high enough for github/codeql.

Patterns

  • query-absent (2 findings), for example iGoat-Swift iGoat-Swift/iGoat-Swift/Source/Extensions/Data+Extension.swift

Finding details

1. iGoat-Swift iGoat-Swift/iGoat-Swift/Source/Extensions/Data+Extension.swift:11 (CWE-125, medium)
  • AI Scan alert: https://github.com/codeql-forks-felickz/iGoat-Swift/security/code-scanning/34
  • AI Scan message: Data.aes() always passes keyLength = size_t(kCCKeySizeAES128) (16) to CCCrypt() while the key pointer comes from the caller-supplied `
  • Context for the agent: Data+Extension.swift:11 hard-codes keyLength 16 for CCCrypt while the key pointer comes from a caller buffer of unchecked length. CodeQL would need a query relating buffer size to length arguments of unsafe pointer crypto calls.
  • Why CodeQL appears to miss it: query-absent: Fixed-length 16-byte key size passed to CCCrypt with a caller-supplied buffer can cause an out-of-bounds read, matching the memory safety query request.
  • Recommended action from the comparison: write-new-query (classification confidence: medium)
2. iGoat-Swift iGoat-Swift/iGoat-Swift/Source/Extensions/NSString+Extension.swift:10 (CWE-125, medium)
  • AI Scan alert: https://github.com/codeql-forks-felickz/iGoat-Swift/security/code-scanning/46
  • AI Scan message: String.aesEncrypt(key:iv:options:) / String.aesDecrypt(key:iv:options:) hard-code keyLength = size_t(kCCKeySizeAES128) (16 bytes) whil
  • Context for the agent: NSString+Extension.swift:10 hard-codes a 16-byte key length for CCCrypt calls with a caller-supplied key. Same query need as other CCCrypt length mismatch cases.
  • Why CodeQL appears to miss it: query-absent: Same fixed key length versus caller key buffer pattern in String AES helpers.
  • Recommended action from the comparison: write-new-query (classification confidence: medium)

Please continue on this pull request.

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>

Copilot AI commented Oct 31, 2026

Copy link
Copy Markdown
Author

@copilot A rescan of the synthetic corpus found additional medium and low severity findings that fit this gap. Please re-run your analysis against each finding below, confirm whether the proposed chan...

Added a dedicated swift/untrusted-crypto-key-length query in 9b07e55. It covers caller-provided Data keys passed to CCCrypt through withUnsafeBytes or NSData.bytes, with positive and checked/length-derived negative tests. The query compiles and the fixture typechecks; qltest extraction is blocked because Swift extraction requires macOS.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Query Create]: CWE-125 HIGH - Swift: new query for memory safety

3 participants