diff --git a/unified/ql/lib/ext/legacy-swift.model.json b/unified/ql/lib/ext/legacy-swift.model.json index c8260c926b96..6fc4e0db15b0 100644 --- a/unified/ql/lib/ext/legacy-swift.model.json +++ b/unified/ql/lib/ext/legacy-swift.model.json @@ -32,7 +32,7 @@ ["", "UITextInput", true, "text(in:)", "", "", "ReturnValue", "local", "manual"], ["", "UITextInput", true, "shouldChangeText(in:replacementText:)", "", "", "Parameter[replacementText:]", "local", "manual"], ["", "NSData", true, "init(contentsOf:)", "", "", "ReturnValue", "remote", "manual"], - ["", "NSData", true, "init(contentsOf:options:)", "", "", "ReturnValue", "remote", "manual"], + ["", "NSData", true, "init(contentsOf:options?:)", "", "", "ReturnValue", "remote", "manual"], ["", "NSString", true, "length", "", "", "", "nsstring-length", "manual"], ["", "NSString", true, "init(contentsOf:)", "", "", "ReturnValue", "remote", "manual"], ["", "NSString", true, "init(contentsOfFile:)", "", "", "ReturnValue", "local", "manual"], @@ -43,7 +43,7 @@ ["", "NSString", true, "init(contentsOf:usedEncoding:)", "", "", "ReturnValue", "remote", "manual"], ["", "NSString", true, "init(contentsOfFile:usedEncoding:)", "", "", "ReturnValue", "local", "manual"], ["", "FileManager", true, "contents(atPath:)", "", "", "ReturnValue", "local", "manual"], - ["", "Data", true, "init(contentsOf:options:)", "", "", "ReturnValue", "remote", "manual"], + ["", "Data", true, "init(contentsOf:options?:)", "", "", "ReturnValue", "remote", "manual"], ["", "Data", true, "init(contentsOf:)", "", "", "ReturnValue", "remote", "manual"], ["", "UISceneDelegate", true, "scene(_:continue:)", "", "", "Parameter[continue:]", "remote", "manual"], ["", "UISceneDelegate", true, "scene(_:didUpdate:)", "", "", "Parameter[didUpdate:]", "remote", "manual"], @@ -109,7 +109,7 @@ ["", "", false, "vfprintf(_:_:_:)", "", "", "Argument[1,2]", "log-injection", "manual"], ["", "NSData", true, "init(contentsOf:)", "", "", "Argument[contentsOf:]", "path-injection", "manual"], ["", "NSData", true, "init(contentsOfFile:)", "", "", "Argument[contentsOfFile:]", "path-injection", "manual"], - ["", "NSData", true, "init(contentsOf:options:)", "", "", "Argument[contentsOf:]", "path-injection", "manual"], + ["", "NSData", true, "init(contentsOf:options?:)", "", "", "Argument[contentsOf:]", "path-injection", "manual"], ["", "NSData.Type", true, "dataWithContentsOfMappedFile(_:)", "", "", "Argument[0]", "path-injection", "manual"], ["", "NSData", true, "init(contentsOfFile:options:)", "", "", "Argument[contentsOfFile:]", "path-injection", "manual"], ["", "NSData", true, "init(contentsOfMappedFile:)", "", "", "Argument[contentsOfMappedFile:]", "path-injection", "manual"], @@ -163,7 +163,7 @@ ["", "FileManager", true, "subpathsOfDirectory(atPath:)", "", "", "Argument[atPath:]", "path-injection", "manual"], ["", "FileManager", true, "trashItem(at:resultingItemURL:)", "", "", "Argument[at:]", "path-injection", "manual"], ["", "FileManager", true, "unmountVolume(at:options?:completionHandler:)", "", "", "Argument[at:]", "path-injection", "manual"], - ["", "Data", true, "init(contentsOf:options:)", "", "", "Argument[contentsOf:]", "path-injection", "manual"], + ["", "Data", true, "init(contentsOf:options?:)", "", "", "Argument[contentsOf:]", "path-injection", "manual"], ["", "Data", true, "md5()", "", "", "Argument[self]", "weak-hash-input-MD5", "manual"], ["", "Data", true, "sha1()", "", "", "Argument[self]", "weak-hash-input-SHA1", "manual"], ["", "Data", true, "sha2(_:)", "", "", "Argument[self]", "weak-password-hash-input-SHA2", "manual"], @@ -870,7 +870,7 @@ ["", "URL", true, "withUnsafeFileSystemRepresentation(_:)", "", "", "Argument[0].ReturnValue", "ReturnValue", "taint", "manual"], ["", "NSData", true, "init(contentsOf:)", "", "", "Argument[contentsOf:]", "ReturnValue", "taint", "manual"], ["", "NSData", true, "init(contentsOfFile:)", "", "", "Argument[contentsOfFile:]", "ReturnValue", "taint", "manual"], - ["", "NSData", true, "init(contentsOf:options:)", "", "", "Argument[contentsOf:]", "ReturnValue", "taint", "manual"], + ["", "NSData", true, "init(contentsOf:options?:)", "", "", "Argument[contentsOf:]", "ReturnValue", "taint", "manual"], ["", "NSData", true, "init(data:)", "", "", "Argument[data:]", "ReturnValue", "taint", "manual"], ["", "NSData", true, "init(bytes:length:)", "", "", "Argument[bytes:]", "ReturnValue", "taint", "manual"], ["", "NSData", true, "base64EncodedData(options?:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], @@ -983,6 +983,7 @@ ["", "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, "withUnsafeMutableBytes(_:)", "", "", "Argument[self]", "Argument[0].Parameter[0].CollectionElement", "taint", "manual"], ["", "Data", true, "withUnsafeMutableBytes(_:)", "", "", "Argument[self].CollectionElement", "Argument[0].Parameter[0].CollectionElement", "taint", "manual"], ["", "Data", true, "withUnsafeMutableBytes(_:)", "", "", "Argument[0].Parameter[0].CollectionElement", "Argument[self].CollectionElement", "taint", "manual"], @@ -1000,7 +1001,7 @@ ["", "Data", true, "replacing(_:with:subrange:maxReplacements?:)", "", "", "Argument[with:]", "Argument[self]", "taint", "manual"], ["", "Data", true, "trimmingPrefix(while:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "Data", true, "trimmingPrefix(_:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], - ["", "Data", true, "init(contentsOf:options:)", "", "", "Argument[contentsOf:]", "ReturnValue", "taint", "manual"], + ["", "Data", true, "init(contentsOf:options?:)", "", "", "Argument[contentsOf:]", "ReturnValue", "taint", "manual"], ["", "Data", true, "base64EncodedData(options?:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "Data", true, "base64EncodedString(options?:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "Data", true, "init(base64Encoded:options?:)", "", "", "Argument[base64Encoded:]", "ReturnValue", "taint", "manual"], diff --git a/unified/ql/src/queries/security/CWE-022/UnsafeUnpack.qhelp b/unified/ql/src/queries/security/CWE-022/UnsafeUnpack.qhelp new file mode 100644 index 000000000000..8c62389f9576 --- /dev/null +++ b/unified/ql/src/queries/security/CWE-022/UnsafeUnpack.qhelp @@ -0,0 +1,40 @@ + + + + +

+ +Unpacking files from a malicious zip without properly validating that the destination file path +is within the destination directory, or allowing symlinks to point to files outside the extraction directory, +allows an attacker to extract files to arbitrary locations outside the extraction directory. This can +overwrite sensitive user data and, in some cases, can lead to code execution if an +attacker overwrites an application's shared object file. +

+
+ + +

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

+
+ + +

+The following example unpacks a remote zip using Zip.unzipFile(). +Zip 2.1.2 does not validate archive entry paths and is vulnerable to path traversal. +

+ + +

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

+ +
+ + +
  • +Ostorlab: +Zip Packages Exploitation. +
  • +
    +
    diff --git a/unified/ql/src/queries/security/CWE-022/UnsafeUnpack.ql b/unified/ql/src/queries/security/CWE-022/UnsafeUnpack.ql new file mode 100644 index 000000000000..2686e18b6de4 --- /dev/null +++ b/unified/ql/src/queries/security/CWE-022/UnsafeUnpack.ql @@ -0,0 +1,40 @@ +/** + * @name Arbitrary file write during a zip extraction from a user controlled source + * @description Unpacking user controlled zips without validating whether the + * destination file path is within the destination directory can cause files + * outside the destination directory to be overwritten. + * @kind path-problem + * @problem.severity error + * @security-severity 7.5 + * @precision high + * @id unified/swift/unsafe-unpacking + * @tags security + * external/cwe/cwe-022 + */ + +import unified + +/** + * 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") } + + predicate isSink(DataFlow::Node node) { Models::isSink(node, "unsafe-unpack") } + + predicate isBarrier(DataFlow::Node node) { + // TODO: Port numeric barriers from original Swift's UnsafeUnpackExtensions.qll. + none() + } + + predicate observeDiffInformedIncrementalMode() { any() } +} + +module UnsafeUnpackFlow = TaintTracking::Global; + +import UnsafeUnpackFlow::PathGraph + +from UnsafeUnpackFlow::PathNode sourceNode, UnsafeUnpackFlow::PathNode sinkNode +where UnsafeUnpackFlow::flowPath(sourceNode, sinkNode) +select sinkNode.getNode(), sourceNode, sinkNode, + "Unsafe unpacking from a malicious zip retrieved from a remote location." diff --git a/unified/ql/src/queries/security/CWE-022/UnsafeUnpackBad.swift b/unified/ql/src/queries/security/CWE-022/UnsafeUnpackBad.swift new file mode 100644 index 000000000000..3dac40943dde --- /dev/null +++ b/unified/ql/src/queries/security/CWE-022/UnsafeUnpackBad.swift @@ -0,0 +1,17 @@ +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) + } +} diff --git a/unified/ql/src/queries/security/CWE-022/UnsafeUnpackGood.swift b/unified/ql/src/queries/security/CWE-022/UnsafeUnpackGood.swift new file mode 100644 index 000000000000..deb53f7ee469 --- /dev/null +++ b/unified/ql/src/queries/security/CWE-022/UnsafeUnpackGood.swift @@ -0,0 +1,15 @@ +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) + } +} diff --git a/unified/ql/test/query-tests/security/CWE-022/UnsafeUnpack/UnsafeUnpack.expected b/unified/ql/test/query-tests/security/CWE-022/UnsafeUnpack/UnsafeUnpack.expected new file mode 100644 index 000000000000..c112b82171f7 --- /dev/null +++ b/unified/ql/test/query-tests/security/CWE-022/UnsafeUnpack/UnsafeUnpack.expected @@ -0,0 +1,26 @@ +#select +| UnsafeUnpack.swift:65:27:65:32 | source | UnsafeUnpack.swift:61:13:61:39 | Data(...) | UnsafeUnpack.swift:65:27:65:32 | source | Unsafe unpacking from a malicious zip retrieved from a remote location. | +| UnsafeUnpack.swift:93:38:93:43 | source | UnsafeUnpack.swift:89:13:89:39 | Data(...) | UnsafeUnpack.swift:93:38:93:43 | source | Unsafe unpacking from a malicious zip retrieved from a remote location. | +| UnsafeUnpack.swift:134:23:134:29 | archive | UnsafeUnpack.swift:126:16:126:55 | Data(...) | UnsafeUnpack.swift:134:23:134:29 | archive | Unsafe unpacking from a malicious zip retrieved from a remote location. | +edges +| UnsafeUnpack.swift:61:13:61:39 | Data(...) | UnsafeUnpack.swift:61:51:61:56 | [post] source | provenance | | +| UnsafeUnpack.swift:61:51:61:56 | [post] source | UnsafeUnpack.swift:65:27:65:32 | source | provenance | | +| UnsafeUnpack.swift:89:13:89:39 | Data(...) | UnsafeUnpack.swift:89:51:89:56 | [post] source | provenance | | +| UnsafeUnpack.swift:89:51:89:56 | [post] source | UnsafeUnpack.swift:93:38:93:43 | source | provenance | | +| UnsafeUnpack.swift:126:9:126:12 | data | UnsafeUnpack.swift:131:5:131:8 | data | provenance | | +| UnsafeUnpack.swift:126:16:126:55 | Data(...) | UnsafeUnpack.swift:126:9:126:12 | data | provenance | | +| UnsafeUnpack.swift:131:5:131:8 | data | UnsafeUnpack.swift:131:20:131:26 | [post] archive | provenance | | +| UnsafeUnpack.swift:131:20:131:26 | [post] archive | UnsafeUnpack.swift:134:23:134:29 | archive | provenance | | +nodes +| UnsafeUnpack.swift:61:13:61:39 | Data(...) | semmle.label | Data(...) | +| UnsafeUnpack.swift:61:51:61:56 | [post] source | semmle.label | [post] source | +| UnsafeUnpack.swift:65:27:65:32 | source | semmle.label | source | +| UnsafeUnpack.swift:89:13:89:39 | Data(...) | semmle.label | Data(...) | +| UnsafeUnpack.swift:89:51:89:56 | [post] source | semmle.label | [post] source | +| UnsafeUnpack.swift:93:38:93:43 | source | semmle.label | source | +| UnsafeUnpack.swift:126:9:126:12 | data | semmle.label | data | +| UnsafeUnpack.swift:126:16:126:55 | Data(...) | semmle.label | Data(...) | +| UnsafeUnpack.swift:131:5:131:8 | data | semmle.label | data | +| UnsafeUnpack.swift:131:20:131:26 | [post] archive | semmle.label | [post] archive | +| UnsafeUnpack.swift:134:23:134:29 | archive | semmle.label | archive | +subpaths diff --git a/unified/ql/test/query-tests/security/CWE-022/UnsafeUnpack/UnsafeUnpack.qlref b/unified/ql/test/query-tests/security/CWE-022/UnsafeUnpack/UnsafeUnpack.qlref new file mode 100644 index 000000000000..955e45651c88 --- /dev/null +++ b/unified/ql/test/query-tests/security/CWE-022/UnsafeUnpack/UnsafeUnpack.qlref @@ -0,0 +1,3 @@ +query: queries/security/CWE-022/UnsafeUnpack.ql +postprocess: + - utils/test/InlineExpectationsTestQuery.ql diff --git a/unified/ql/test/query-tests/security/CWE-022/UnsafeUnpack/UnsafeUnpack.swift b/unified/ql/test/query-tests/security/CWE-022/UnsafeUnpack/UnsafeUnpack.swift new file mode 100644 index 000000000000..a832906dd410 --- /dev/null +++ b/unified/ql/test/query-tests/security/CWE-022/UnsafeUnpack/UnsafeUnpack.swift @@ -0,0 +1,135 @@ + +// --- stubs --- + +struct URL +{ + init?(string: String) {} + init(fileURLWithPath: String) {} +} + +class Zip { + class func unzipFile(_ zipFilePath: URL, destination: URL, overwrite: Bool, password: String?, progress: ((_ progress: Double) -> ())? = nil, fileOutputHandler: ((_ unzippedFile: URL) -> Void)? = nil) throws {} +} + +class NSObject { +} + +class Progress : NSObject { + +} + +class FileManager : NSObject { + func unzipItem(at sourceURL: URL, to destinationURL: URL, skipCRC32: Bool = false, + progress: Progress? = nil, pathEncoding: String.Encoding? = nil) throws {} +} + +protocol DataProtocol { } +class Data : DataProtocol { + struct ReadingOptions : OptionSet { let rawValue: Int } + struct WritingOptions : OptionSet { let rawValue: Int } + + init(_ elements: S) { count = 0 } + init(contentsOf: URL, options: ReadingOptions = []) { count = 0 } + func write(to: URL, options: Data.WritingOptions = []) {} + + var count: Int +} + +extension String { + + struct Encoding { + var rawValue: UInt + + init(rawValue: UInt) { self.rawValue = rawValue } + + static let ascii = Encoding(rawValue: 1) + } + init(contentsOf url: URL) throws { + self.init("") + } +} + +// --- tests --- + +func testUnsafeUnpackQhelpExample1ZipBad(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) // $ 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) // $ Alert + } +} + +func testUnsafeUnpackQhelpExample2ZipArchiveGood(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) + } +} + +func testUnsafeUnpackZipFoundationBad(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) // $ Source + + let fileManager = FileManager() + // Malicious zip is unpacked; older versions of ZIPFoundation allow symlink path traversal + try fileManager.unzipItem(at:source, to: destination) // $ Alert + } +} + +func testTrustedArchive() throws { + let source = URL(fileURLWithPath: "/trusted.zip") + let destination = URL(fileURLWithPath: "/destination") + + // write known data to `source` + Data([0x50, 0x4b]).write(to: source) + + // unzip known data (safe) + try Zip.unzipFile(source, destination: destination, overwrite: true, password: nil) + try FileManager().unzipItem(at: source, to: destination) +} + +func testUnrelatedArchive() throws { + let remoteURL = URL(string: "https://example.com/")! + let downloadedArchive = URL(fileURLWithPath: "/downloaded.zip") + let trustedArchive = URL(fileURLWithPath: "/trusted.zip") + + // write tainted data to `downloadedArchive` + Data(contentsOf: remoteURL, options: []).write(to: downloadedArchive) + + // unzip `trustedArchive` over `downloadedArchive` (safe) + try Zip.unzipFile(trustedArchive, destination: downloadedArchive, overwrite: true, password: nil) + try FileManager().unzipItem(at: trustedArchive, to: downloadedArchive) +} + +func testStoredDownloadWithExplicitWritingOptions() throws { + let remoteURL = URL(string: "https://example.com/archive.zip")! + let archive = URL(fileURLWithPath: "/downloaded.zip") + let destination = URL(fileURLWithPath: "/destination") + let data = Data(contentsOf: remoteURL, options: []) // $ Source + + try Zip.unzipFile(archive, destination: destination, overwrite: true, password: nil) + + // write previously read tainted data to `archive` + data.write(to: archive, options: []) + + // unzip tainted data + try Zip.unzipFile(archive, destination: destination, overwrite: true, password: nil) // $ Alert +}