Skip to content

Unified: Add unsafe unpacking query - #23315

Open
geoffw0 wants to merge 21 commits into
github:mainfrom
geoffw0:unifiedpacking
Open

geoffw0 wants to merge 21 commits into
github:mainfrom
geoffw0:unifiedpacking

Conversation

@geoffw0

@geoffw0 geoffw0 commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Port original Swift unsafe unpacking query (swift/unsafe-unpacking) to unified Swift as unified/swift/unsafe-unpacking. Initial port by Copilot + GPT-6.1 Sol High effort. I had to do some cleanup afterwards, much of which was because the original query was in experimental and was in need of a bit of cleanup anyway.

We could do with improving this query to understand what version of the zip library is being used. This is particularly true for the ZipFoundation library, the latest version of which I think may actually have been made safe. I’ve removed explicit mentions of that particular library from the .qhelp and examples, so as to not cause confusion, though it's still modelled for now. The core advice to "Use an up-to-date archive library that validates entry paths and symlink targets" stands.

We need a docs team review of the .qhelp for this one.

I’ll start a DCA run as well.

geoffw0 and others added 16 commits December 1, 2026 09:45
Copy the original Swift query, help, referenced samples and query-specific tests byte-for-byte as the baseline for the unified Swift port. Adaptations follow separately.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Inline the data flow configuration and query-specific models from the original Swift libraries without API or behavior changes, preserving their declarations and provenance for review.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Reuse the existing source and unsafe-unpack sink models and propagate downloaded Data into the written path's post-update value. The original two inline alert expectations and source expectation pass. Numeric barriers remain a TODO until the necessary type information is available.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Check that trusted data written to an archive and a separate trusted archive extracted into a downloaded path do not trigger alerts. Both original detections remain unchanged; the learned baseline also passes without --learn.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Use the correct ZipArchive module name, describe the version-dependent risks, and fix the free-function example's invalid self reference. Validate help generation, XML and all sample references; the external Ostorlab reference was also verified.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Add an unsafe-unpacking regression where remote Data is stored before write(to:options:). Record the currently missing source and two alerts, and check that extraction before the write remains unflagged.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Replace unsafe-unpacking's constructor-specific flow step with a Data.write(to:options?:) receiver-to-destination summary. The output represents the path after the write, allowing stored Data and explicit writing options while preserving the original alerts and safe cases.

UnsafeUnpack, PathInjection and CleartextLogging tests pass without learning; only the two intended stored-download alerts are added.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@geoffw0
geoffw0 requested a review from a team as a code owner December 1, 2026 14:51
@geoffw0 geoffw0 added no-change-note-required This PR does not need a change note ready-for-doc-review This PR requires and is ready for review from the GitHub docs team. Unified labels Dec 1, 2026
Copilot AI adaptive review requested due to automatic review settings December 1, 2026 14:51
@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

QHelp previews:

unified/ql/src/queries/security/CWE-022/UnsafeUnpack.qhelp

Arbitrary file write during a zip extraction from a user controlled source

Extracting a malicious ZIP archive can allow an attacker to write files outside the intended extraction directory. This can happen if the extraction code does not validate entry paths or allows symlinks to point outside the directory. An attacker could overwrite sensitive user data or, in some cases, execute code by overwriting an application's shared object file.

Recommendation

Use an up-to-date archive library that validates entry paths and symlink targets, such as ZipArchive. Keep these validation checks enabled.

Example

The following example uses Zip.unzipFile() to extract a ZIP archive from a remote source. Version 2.1.2 of Zip does not validate archive entry paths, making it vulnerable to path traversal.

import Foundation
import Zip

func unzipFile(at sourcePath: String, to destinationPath: String) {
    do {
        let remoteURL = URL(string: "https://example.com/")!
        let source  = URL(fileURLWithPath: sourcePath)
        let destination = URL(fileURLWithPath: destinationPath)

        // Malicious zip is downloaded
        try Data(contentsOf: remoteURL).write(to: source)

        let fileManager = FileManager()
        // Malicious zip is unpacked; Zip 2.1.2 does not validate archive entry paths
        try Zip.unzipFile(source, destination: destination, overwrite: true, password: nil)
    }
}

The following example uses ZipArchive to extract an archive. Up-to-date versions of ZipArchive validate entry paths and symlink targets.

import Foundation
import ZipArchive

func unzipFile(at sourcePath: String, to destinationPath: String) {
    do {
        let remoteURL = URL(string: "https://example.com/")!
        let source  = URL(fileURLWithPath: sourcePath)

        // Malicious zip is downloaded
        try Data(contentsOf: remoteURL).write(to: source)

        // ZipArchive validates paths and symlinks
        try SSZipArchive.unzipFile(atPath: sourcePath, toDestination: destinationPath, delegate: nil)
    }
}

References

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

The taint changes introduce false-positive path alerts and miss unsafe archive extractions, while unmatched braces undermine the regression fixtures.

5 open issues
What changed in this PR

Ports Swift’s unsafe archive-unpacking query to unified Swift, detecting flows from remote data to potentially unsafe archive-extraction APIs.

Changes:

  • Adds unified/swift/unsafe-unpacking with query help and vulnerable/safe examples.
  • Adds taint propagation from written data to archive URLs.
  • Adds regression cases for downloaded, trusted, unrelated, and stored archives.
File Description
unified/​ql/​test/​query-tests/​security/​CWE-022/​UnsafeUnpack/​UnsafeUnpack.swift Adds archive-extraction regression cases.
unified/​ql/​test/​query-tests/​security/​CWE-022/​UnsafeUnpack/​UnsafeUnpack.qlref Connects the query to inline-expectation testing.
unified/​ql/​test/​query-tests/​security/​CWE-022/​UnsafeUnpack/​UnsafeUnpack.expected Records expected alerts and flow paths.
unified/​ql/​src/​queries/​security/​CWE-022/​UnsafeUnpackGood.swift Demonstrates extraction using ZipArchive.
unified/​ql/​src/​queries/​security/​CWE-022/​UnsafeUnpackBad.swift Demonstrates vulnerable extraction using Zip.
unified/​ql/​src/​queries/​security/​CWE-022/​UnsafeUnpack.ql Implements the unified Swift path query.
unified/​ql/​src/​queries/​security/​CWE-022/​UnsafeUnpack.qhelp Explains risks, recommendations, and examples.
unified/​ql/​lib/​ext/​legacy-swift.model.json Adds the Data.write(to:options:) taint summary.

Review effort: Max (adaptive)

["", "Data", true, "append(_:count:)", "", "", "Argument[0]", "Argument[self]", "taint", "manual"],
["", "Data", true, "insert(contentsOf:at:)", "", "", "Argument[contentsOf:]", "Argument[self]", "taint", "manual"],
["", "Data", true, "replaceSubrange(_:with:)", "", "", "Argument[with:]", "Argument[self]", "taint", "manual"],
["", "Data", true, "write(to:options?:)", "", "", "Argument[self]", "Argument[to:]", "taint", "manual"],
["", "Data", true, "append(_:count:)", "", "", "Argument[0]", "Argument[self]", "taint", "manual"],
["", "Data", true, "insert(contentsOf:at:)", "", "", "Argument[contentsOf:]", "Argument[self]", "taint", "manual"],
["", "Data", true, "replaceSubrange(_:with:)", "", "", "Argument[with:]", "Argument[self]", "taint", "manual"],
["", "Data", true, "write(to:options?:)", "", "", "Argument[self]", "Argument[to:]", "taint", "manual"],

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think I need to put this into my own words... the issue seems to be that we're conflating direct taint and indirect taint, e.g.

let remoteURL = URL(string: "https://example.com/")!
let remoteData = Data(contentsOf: remoteURL) // `remoteData` directly contains tainted data
let source  = URL(fileURLWithPath: sourcePath) // `source` points to a file
try remoteData.write(to: source) // `source` now points to a file that contains tainted data
...
try Zip.unzipFile(source, ...) // ... and we need to know that here

One solution is to permit taint of both kinds to intermix, as we are doing now, but probably restrict the taint steps that do this to only this query (to avoid false positives in other queries like Copilot suggests). That's not very clean, but it's probably the smallest change that satisfies that concern.

An ideal solution might be to distinguish direct from indirect taint much like we do with C++ pointers. Even this will only detect cases where we've written tainted data to the file, not other situations where we should not trust the contents of a file (for example it being read from a shared directory).

A third possibility that comes to mind is to split the flow for this query into two stages, one for taint from the remote source -> file writes (i.e. to determine untrusted files) and one for data flow from the written file name -> the unzip. I'm currently leaning towards this third solution as I think it covers all the patterns we're interested in, and gives us space to expand what we mean by an "untrusted file" at a later date. I've thought about the concept of a "path tracking" library before, I think it has uses beyond this query so we should aim for re-usable code.

I'm very much open to opinions on this right now.

* A taint configuration for tainted data that reaches an unsafe unpack sink.
*/
module UnsafeUnpackConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node node) { Models::isSource(node, "remote") }
@geoffw0

geoffw0 commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

TODO:

sophietheking
sophietheking previously approved these changes Dec 4, 2026

@sophietheking sophietheking left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@geoffw0 I left some comments to make it easier to follow by breaking up long sentences. 🙏

Co-authored-by: Sophie <29382425+sophietheking@users.noreply.github.com>
@geoffw0

geoffw0 commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

@sophietheking thanks for your readability suggestions. I've accepted all of them. :)

This branch has not been deployed

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

Labels

documentation no-change-note-required This PR does not need a change note ready-for-doc-review This PR requires and is ready for review from the GitHub docs team. Unified

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants