CRITICAL
Rule Definition
In Swift one can inject directly JavaScript code via a string passed to "WKWebView.evaluateJavaScript". This string might be hard-coded (i.e. with a fixed value at compile time) or constructed at run-time. If this construction has a non-local character (e.g. concatenation with string fragments received from outside of the enclosing method), or moreover, it relies on (untrusted) external sources, it can eventually open a means for an attacker to inject malicious code.
Remediation
Ensure the code constructing the string containing the JavaScript code is well encapsulated, and most of all, avoid using untrusted external data if given the case.
Sanitizing the string just before passing to "evaluateJavaScript" can eventually deflect attack attempts.
Violation Code Sample
func evaluate(color: String) {
var webView: WKWebView
// if not resolved, 'color' might potentially be anything
let script = "document.body.style.backgroundColor = `\(color)`;"
webView.evaluateJavaScript(script, completionHandler: nil)
}
Fixed Code Sample
func evaluate() {
var webView: WKWebView
// if not resolved, 'color' might potentially be anything
let script = "document.body.style.backgroundColor = `red`;"
webView.evaluateJavaScript(script, completionHandler: nil)
}
Reference
https://owasp.org/www-project-cheat-sheets/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html
https://developer.apple.com/documentation/webkit/wkwebview/1415017-evaluatejavascript?language=swift
https://developer.apple.com/library/archive/documentation/Security/Conceptual/SecureCodingGuide/OtherHardeningTechniques/OtherHardeningTechniques.html
Related Technologies
Technical Criterion
CWE-79 - Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.