Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/codeql-qlt-unit-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ jobs:
# The `ql` language (i.e. ql for ql) is always a special case.
# The `actions` language is currently not supported by `qlt` but is supported by `codeql`.
# TODO: Implement support for `actions` language in `qlt`
if [[ "$lang" == "ql" || "$lang" == "actions" ]]; then
# The `swift` extractor only runs on macOS, so Swift tests cannot be extracted on this Linux runner.
if [[ "$lang" == "ql" || "$lang" == "actions" || "$lang" == "swift" ]]; then
echo "⚠️ qlt unit testing is not currently supported for language: $lang"
continue
fi
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* @name Uncontrolled data used in path expression (extended deep link models)
* @description Accessing paths influenced by users can allow an attacker to access unexpected resources.
* This variant of `swift/path-injection` adds models for parsing custom URL scheme
* (deep link) query parameters and for deep links stored on view controllers.
* @kind path-problem
* @problem.severity error
* @security-severity 7.5
* @precision high
* @id swift/path-injection-extended
* @tags security
* external/cwe/cwe-022
* external/cwe/cwe-023
* external/cwe/cwe-036
* external/cwe/cwe-073
* external/cwe/cwe-099
*/

import swift
import codeql.swift.dataflow.DataFlow
import codeql.swift.security.PathInjectionQuery
import PathInjectionModels
import PathInjectionFlow::PathGraph

from PathInjectionFlow::PathNode source, PathInjectionFlow::PathNode sink
where PathInjectionFlow::flowPath(source, sink)
select sink.getNode(), source, sink, "This path depends on a $@.", source.getNode(),
"user-provided value"
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* Provides additional models used by `swift/path-injection-extended` to track
* custom URL scheme (deep link) data into file system paths.
*
* Swift does not support data extension (`.model.yml`) files, so these models
* are written in QL using the `SummaryModelCsv` and `TaintInheritingContent`
* extension points of `codeql/swift-all`. They only take effect in queries that
* import this module.
*/

import swift
private import codeql.swift.dataflow.DataFlow
private import codeql.swift.dataflow.ExternalFlow
private import codeql.swift.dataflow.FlowSteps
private import codeql.swift.security.PathInjectionExtensions

/**
* A model for `URLComponents` / `NSURLComponents` and `Sequence` members that
* permit taint flow when parsing query parameters out of a URL.
*/
private class UrlComponentsSummaries extends SummaryModelCsv {
override predicate row(string row) {
row =
[
";URLComponents;true;init(url:resolvingAgainstBaseURL:);;;Argument[0];ReturnValue.OptionalSome;taint",
";URLComponents;true;init(string:);;;Argument[0];ReturnValue.OptionalSome;taint",
";NSURLComponents;true;init(url:resolvingAgainstBaseURL:);;;Argument[0];ReturnValue.OptionalSome;taint",
";NSURLComponents;true;init(string:);;;Argument[0];ReturnValue.OptionalSome;taint",
";Sequence;true;first(where:);;;Argument[-1];ReturnValue;taint"
]
}
}

/**
* A content implying that, if a `URLComponents`, `NSURLComponents`,
* `URLQueryItem` or `NSURLQueryItem` is tainted, then all its fields (for
* example `queryItems`, `path`, `name` and `value`) are tainted.
*/
private class UrlComponentsFieldsInheritTaint extends TaintInheritingContent,
DataFlow::Content::FieldContent
{
UrlComponentsFieldsInheritTaint() {
this.getField().getEnclosingDecl().asNominalTypeDecl().getFullName() =
["URLComponents", "NSURLComponents", "URLQueryItem", "NSURLQueryItem"]
}
}

/** Holds if `f` is a stored property of a `UIViewController` subclass. */
private predicate isViewControllerProperty(FieldDecl f) {
f.getEnclosingDecl().asNominalTypeDecl().getABaseTypeDecl*().getFullName() = "UIViewController"
}

/**
* A flow step from a value assigned to a stored property of a
* `UIViewController` subclass to reads of that property through `self`.
*
* View controllers commonly store a deep link in a property and handle it later
* in a lifecycle method such as `viewDidAppear(_:)`, which is invoked by UIKit
* rather than by application code, so standard data flow does not connect the
* write to the read.
*/
private class ViewControllerStoredPropertyStep extends PathInjectionAdditionalFlowStep {
override predicate step(DataFlow::Node node1, DataFlow::Node node2) {
exists(FieldDecl f, AssignExpr assign, MemberRefExpr read |
isViewControllerProperty(f) and
assign.getDest().(MemberRefExpr).getMember() = f and
node1.asExpr() = assign.getSource() and
read.getMember() = f and
not read = any(AssignExpr a).getDest() and
read.getBase().(DeclRefExpr).getDecl() = any(Callable c).getSelfParam() and
node2.asExpr() = read
)
}
}
5 changes: 5 additions & 0 deletions languages/swift/custom/src/qlpack.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
name: languages-swift-custom-src
version: 0.0.1
library: false
dependencies:
codeql/swift-all: "*"
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import swift
import codeql.swift.dataflow.DataFlow
import codeql.swift.security.PathInjectionQuery
import PathInjectionExtended.PathInjectionModels
import utils.test.InlineExpectationsTest

module PathInjectionExtendedTest implements TestSig {
string getARelevantTag() { result = "hasPathInjection" }

predicate hasActualResult(Location location, string element, string tag, string value) {
exists(DataFlow::Node sink |
PathInjectionFlow::flowTo(sink) and
location = sink.getLocation() and
location.getFile().getBaseName() != "" and
element = sink.toString() and
tag = "hasPathInjection" and
value = ""
)
}
}

import MakeTest<PathInjectionExtendedTest>
159 changes: 159 additions & 0 deletions languages/swift/custom/test/PathInjectionExtended/deeplink.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
// --- stubs ---

struct URL {
init?(string: String) {}

var lastPathComponent: String { get { return "" } }

func appendingPathComponent(_ pathComponent: String) -> URL { return self }
}

struct URLQueryItem {
var name: String
var value: String?
}

struct URLComponents {
init?(url: URL, resolvingAgainstBaseURL resolve: Bool) {}

var queryItems: [URLQueryItem]? { get { return nil } set {} }
}

class NSURLComponents {
init?(url: URL, resolvingAgainstBaseURL resolve: Bool) {}

var queryItems: [URLQueryItem]? { get { return nil } set {} }
}

class Data {
struct Base64DecodingOptions : OptionSet { let rawValue: Int }
struct WritingOptions : OptionSet { let rawValue: Int }

init?(base64Encoded base64String: String, options: Data.Base64DecodingOptions = []) {}

func write(to: URL, options: Data.WritingOptions = []) {}
}

class FileManager {
enum SearchPathDirectory : UInt { case documentDirectory }
struct SearchPathDomainMask : OptionSet {
let rawValue: UInt
static let userDomainMask = SearchPathDomainMask(rawValue: 1)
}

static let `default` = FileManager()

func urls(for directory: FileManager.SearchPathDirectory, in domainMask: FileManager.SearchPathDomainMask) -> [URL] { return [] }
}

class UIApplication {
struct OpenURLOptionsKey : Hashable {
static func == (lhs: OpenURLOptionsKey, rhs: OpenURLOptionsKey) -> Bool {
return true;
}

func hash(into hasher: inout Hasher) {}
}
struct LaunchOptionsKey: Hashable {
init(rawValue: String) {}
public static let url: UIApplication.LaunchOptionsKey = UIApplication.LaunchOptionsKey(rawValue: "")
func hash(into hasher: inout Hasher) {}
}
}

protocol UIApplicationDelegate {
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?) -> Bool
}

class UIViewController {
func viewDidAppear(_ animated: Bool) {}
}

// --- app helpers ---

extension FileManager {
class func documentsUrlForFile(withName name: String) -> URL {
let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
return documents.appendingPathComponent(name)
}
}

// --- tests ---

class AppDelegate: UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?) -> Bool {
let mainViewController = MainViewController()
let deeplink = launchOptions?[.url] as? URL
mainViewController.set(deeplink: deeplink)

let safeViewController = SafeViewController()
safeViewController.set(fileName: "report.bin")
return true
}

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
if let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
let name = components.queryItems?.first(where: { $0.name == "name" })?.value,
let data = Data(base64Encoded: "") {
data.write(to: FileManager.documentsUrlForFile(withName: name)) // $ hasPathInjection
data.write(to: FileManager.documentsUrlForFile(withName: "export.bin")) // safe: fixed file name
}
return true
}
}

// The deep link is stored on the view controller and handled later in a UIKit
// lifecycle method (`viewDidAppear(_:)`) that is not called from app code.
class MainViewController: UIViewController {
private var deeplink: URL?

func set(deeplink: URL?) {
self.deeplink = deeplink
}

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

if let deeplink = deeplink {
handleDeeplink(deeplink)
}
}

private func handleDeeplink(_ url: URL) {
let route = url.lastPathComponent
if route == "save",
let dataParam = getQueryParameter(url, "data"),
let data = Data(base64Encoded: dataParam),
let name = getQueryParameter(url, "name") {
data.write(to: FileManager.documentsUrlForFile(withName: name)) // $ hasPathInjection
data.write(to: FileManager.documentsUrlForFile(withName: "export.bin")) // safe: fixed file name
}
}

func getQueryParameter(_ url: URL, _ name: String) -> String? {
if let components = NSURLComponents(url: url, resolvingAgainstBaseURL: true), let params = components.queryItems {
if let value = params.first(where: { $0.name == name })?.value {
return value
}
}
return nil
}
}

// The stored property is only ever assigned constant values.
class SafeViewController: UIViewController {
private var fileName: String = "default.bin"

func set(fileName: String) {
self.fileName = fileName
}

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

if let data = Data(base64Encoded: "") {
data.write(to: FileManager.documentsUrlForFile(withName: fileName)) // safe: constant file name
}
}
}
5 changes: 5 additions & 0 deletions languages/swift/custom/test/qlpack.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
name: languages-swift-custom-test
version: 0.0.1
dependencies:
languages-swift-custom-src: ${workspace}
extractor: swift
Loading