Rules / Swift
SHIELD-SWIFT-013
Path traversal via file read
What it detects
A file is read from a path built with interpolated variable data.
How to fix
Canonicalize the path and confine it to an allowed base directory before reading.
Vulnerable — Shield flags thisReportLoader.swift
import Foundation
func loadReport(named filename: String) throws -> Data {
// filename comes straight from the request
let data = try Data(contentsOf: URL(fileURLWithPath: "/var/reports/\(filename)"))
return data
}
Fixed — scans cleanReportLoader.swift
import Foundation
func loadReport(named filename: String) throws -> Data {
let base = URL(fileURLWithPath: "/var/reports", isDirectory: true)
let target = base.appendingPathComponent(filename).standardizedFileURL
guard target.path.hasPrefix(base.path + "/") else {
throw CocoaError(.fileReadNoPermission)
}
return try Data(contentsOf: target)
}
Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-SWIFT-013, the fixed one does not.