Swift Unrestricted WebView HTML Loading

Unrestricted WebView HTML loading

Description

Loading untrusted HTML into WKWebView or UIWebView can expose data through scripts or resource requests. baseURL determines how relative URLs are resolved, so set it explicitly instead of relying on nil or an attacker-controlled value. Actual local-file access depends on the WebView type and configuration.

Potential impact

  • WebView-based cross-site scripting
  • Increased risk of access to local files or application data
  • Data exfiltration to attacker-controlled URLs

Remediation

  1. When loading HTML strings, set baseURL to about:blank or an appropriate application-controlled URL.
  2. Isolate untrusted HTML across trust boundaries and sanitize it or render it through a suitable template when needed.
  3. If local-file access is necessary, use WebKit APIs with the narrowest required access scope.

Examples

Before

swift
webView.loadHTMLString(html, baseURL: nil)

After

swift
import WebKit

func loadTrustedContent(in webView: WKWebView) {
    let trustedHTML = "<p>Content generated by the application</p>"
    webView.loadHTMLString(
        trustedHTML,
        baseURL: URL(string: "about:blank"))
}

Explanation:

  • Before: The HTML is not established as trusted, and no base for relative URLs is specified. nil alone does not establish that local-file access is granted.
  • After: Application-generated, trusted HTML uses an explicit base URL. Setting about:blank does not sanitize scripts or absolute URLs in user-controlled HTML; external HTML still needs appropriate sanitization and WebView policy restrictions.

References