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
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Unsafe WebView fetch of local user input

Building an HTML document from text that the user typed (for example the `text` of a `UITextField`, or the replacement string passed to a `UITextFieldDelegate`) and loading it with `UIWebView.loadHTMLString`, `WKWebView.loadHTMLString` or the `load(_:mimeType:...:baseURL:)` methods lets the input inject markup and script. If the `baseURL` is `nil` or also comes from the input, injected script may also be able to read local data.

The standard `swift/unsafe-webview-fetch` query only considers remote flow sources, so it does not report these cases. This query reports the same sinks when the data comes from local user input.

## Recommendation

HTML-encode user input before adding it to an HTML document, or set it through a safe API (for example, assign it as text content from JavaScript). Always pass a safe `baseURL` such as `about:blank` and prefer `WKWebView` to `UIWebView`.

## Example

The following code loads text typed by the user straight into a WebView without restricting the base URL:

```swift
let webText = "Welcome! \(textField.text ?? "")"
webview.loadHTMLString(webText, baseURL: nil) // BAD
```

Encode the input and use a safe base URL instead:

```swift
let webText = "Welcome! \(htmlEscape(textField.text ?? ""))"
webview.loadHTMLString(webText, baseURL: URL(string: "about:blank")) // GOOD
```

## References

- OWASP: [Cross Site Scripting Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).
- Apple Developer Documentation: [WKWebView.loadHTMLString(_:baseURL:)](https://developer.apple.com/documentation/webkit/wkwebview/1415004-loadhtmlstring).
- Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).
- Common Weakness Enumeration: [CWE-95](https://cwe.mitre.org/data/definitions/95.html).
- Common Weakness Enumeration: [CWE-749](https://cwe.mitre.org/data/definitions/749.html).
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* @name Unsafe WebView fetch of local user input
* @description Loading HTML built from local user input (such as text typed into a
* `UITextField`) into a WebView without restricting the base URL may enable
* cross-site scripting or give injected script access to local data.
* @kind path-problem
* @problem.severity warning
* @security-severity 6.1
* @precision medium
* @id swift/custom/unsafe-webview-fetch-local-input
* @tags security
* external/cwe/cwe-079
* external/cwe/cwe-095
* external/cwe/cwe-749
*/

import swift
import UnsafeWebViewFetchLocalInput
import UnsafeWebViewFetchLocalInputFlow::PathGraph

from
UnsafeWebViewFetchLocalInputFlow::PathNode sourceNode,
UnsafeWebViewFetchLocalInputFlow::PathNode sinkNode, UnsafeWebViewFetchSink sink, string message
where
UnsafeWebViewFetchLocalInputFlow::flowPath(sourceNode, sinkNode) and
sink = sinkNode.getNode() and
unsafeWebViewFetchLocalInput(sink, message)
select sink, sourceNode, sinkNode, message
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
* Provides a taint-tracking configuration for reasoning about local user input
* (for example text typed into a `UITextField`) that is loaded into a WebView.
*
* This complements the standard `swift/unsafe-webview-fetch` query, which only
* considers remote flow sources.
*/

import swift
import codeql.swift.dataflow.DataFlow
import codeql.swift.dataflow.TaintTracking
import codeql.swift.dataflow.FlowSources
import codeql.swift.security.UnsafeWebViewFetchExtensions

/**
* A taint configuration from local user input to WebView fetch sinks (and
* `baseURL` arguments).
*/
module UnsafeWebViewFetchLocalInputConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node node) { node instanceof LocalFlowSource }

predicate isSink(DataFlow::Node node) {
exists(UnsafeWebViewFetchSink sink |
node = sink or
node.asExpr() = sink.getBaseUrl()
)
}

predicate isBarrier(DataFlow::Node barrier) { barrier instanceof UnsafeWebViewFetchBarrier }

predicate isAdditionalFlowStep(DataFlow::Node nodeFrom, DataFlow::Node nodeTo) {
any(UnsafeWebViewFetchAdditionalFlowStep s).step(nodeFrom, nodeTo)
}
}

/**
* Taint flow from local user input to WebView fetch sinks (and `baseURL` arguments).
*/
module UnsafeWebViewFetchLocalInputFlow = TaintTracking::Global<UnsafeWebViewFetchLocalInputConfig>;

/**
* Holds if `sink` receives local user input and is unsafe because of its
* `baseURL` argument, as described by `message`.
*/
predicate unsafeWebViewFetchLocalInput(UnsafeWebViewFetchSink sink, string message) {
UnsafeWebViewFetchLocalInputFlow::flowTo(sink) and
(
// no base URL
not exists(sink.getBaseUrl()) and
message = "Local user input is used in a WebView fetch."
or
// base URL is nil
sink.getBaseUrl() instanceof NilLiteralExpr and
message = "Local user input is used in a WebView fetch without restricting the base URL."
or
// base URL is also tainted
UnsafeWebViewFetchLocalInputFlow::flowToExpr(sink.getBaseUrl()) and
message = "Local user input is used in a WebView fetch with a tainted base URL."
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
category: newQuery
---

- Added a custom `swift/custom/unsafe-webview-fetch-local-input` query that complements `swift/unsafe-webview-fetch` by reporting local user input (such as `UITextField.text` or `UITextFieldDelegate` replacement strings) that is loaded into a `UIWebView` or `WKWebView` without a safe base URL. The standard query only considers remote flow sources, and Swift has no threat-model setting to enable local sources.
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
Comment thread
felickz marked this conversation as resolved.
Resolved
version: 0.0.2
library: false
dependencies:
codeql/swift-all: "*"
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import swift
import UnsafeWebViewFetchLocalInput.UnsafeWebViewFetchLocalInput
import utils.test.InlineExpectationsTest

module UnsafeWebViewFetchLocalInputTest implements TestSig {
string getARelevantTag() { result = "unsafeWebViewFetchLocalInput" }

predicate hasActualResult(Location location, string element, string tag, string value) {
exists(UnsafeWebViewFetchSink sink |
unsafeWebViewFetchLocalInput(sink, _) and
location = sink.getLocation() and
element = sink.toString() and
tag = "unsafeWebViewFetchLocalInput" and
value = ""
)
}
}

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

class NSObject { }

struct _NSRange { }

typealias NSRange = _NSRange

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

extension String {
init(contentsOf: URL) throws {
self.init("")
}
}

class WKNavigation : NSObject { }

class UIResponder : NSObject { }

class UIView : UIResponder { }

class UIControl : UIView { }

class UIViewController : UIResponder { }

class UITextField : UIControl {
var text: String? {
get { nil }
set { }
}

var placeholder: String? {
get { nil }
set { }
}
}

protocol UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
}

class UIWebView : UIView {
func loadHTMLString(_ string: String, baseURL: URL?) {} // deprecated
}

class WKWebView : UIView {
func loadHTMLString(_ string: String, baseURL: URL?) -> WKNavigation? {
return WKNavigation()
}
}

// --- tests ---

// Reduced from the iGoat-Swift XSS exercise.
class CrossSiteScriptingExerciseVC : UIViewController {
var webview: UIWebView!
var textField: UITextField!

func loadItemPressed() {
let webText = "Welcome to XSS Exercise !!! \n Here is UIWebView ! \(textField.text ?? "")"
webview.loadHTMLString(webText, baseURL: nil) // $ unsafeWebViewFetchLocalInput
}
}

class WKWebViewExerciseVC : UIViewController {
var webview: WKWebView!
var textField: UITextField!

func concatenated() {
let html = "<html><body>" + (textField.text ?? "") + "</body></html>"
_ = webview.loadHTMLString(html, baseURL: nil) // $ unsafeWebViewFetchLocalInput
}

func taintedBaseUrl() {
let text = textField.text ?? ""
_ = webview.loadHTMLString("<p>\(text)</p>", baseURL: URL(string: text)) // $ unsafeWebViewFetchLocalInput
}

func safeBaseUrl() {
let text = textField.text ?? ""
_ = webview.loadHTMLString("<p>\(text)</p>", baseURL: URL(string: "about:blank")) // GOOD: a safe baseURL is specified
}

func constantHtml() {
_ = webview.loadHTMLString("<p>Hello</p>", baseURL: nil) // GOOD: the HTML is constant
}

func placeholderIsNotUserInput() {
let html = "<p>\(textField.placeholder ?? "")</p>"
_ = webview.loadHTMLString(html, baseURL: nil) // GOOD: the placeholder is set by the app, not typed by the user
}

func remoteInputIsCoveredByStandardQuery() {
let html = try! String(contentsOf: URL(string: "http://example.com/")!)
_ = webview.loadHTMLString(html, baseURL: nil) // GOOD: remote input is reported by swift/unsafe-webview-fetch instead
}
}

class MyTextFieldDelegate : UITextFieldDelegate {
var webview: UIWebView!

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
webview.loadHTMLString("<p>\(string)</p>", baseURL: nil) // $ unsafeWebViewFetchLocalInput
return true
}
}
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.2
dependencies:
languages-swift-custom-src: ${workspace}
extractor: swift
4 changes: 2 additions & 2 deletions scripts/install-codeql-packs.sh
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Install CodeQL packs for all packs discovered in the CodeQL workspace.
OPTIONS:
--language <lang> Install packs only for the specified language
Valid values: actions, cpp, csharp, go, java, javascript,
python, ruby
python, ruby, swift
-h, --help Show this help message

By default, the script installs packs for all languages in the workspace.
Expand Down Expand Up @@ -44,7 +44,7 @@ while [[ $# -gt 0 ]]; do
done

## Validate language if provided
VALID_LANGUAGES=("actions" "cpp" "csharp" "go" "java" "javascript" "python" "ruby")
VALID_LANGUAGES=("actions" "cpp" "csharp" "go" "java" "javascript" "python" "ruby" "swift")
if [[ -n "${LANGUAGE}" ]]; then
LANGUAGE_VALID=false
for valid_lang in "${VALID_LANGUAGES[@]}"; do
Expand Down
Loading