MASTG-BEST-0073: Properly Validate Server Trust in URLSessionDelegate and WKNavigationDelegate
When an iOS app overrides the default certificate validation by implementing URLSessionDelegate.urlSession(_:didReceive:completionHandler:) or WKNavigationDelegate.webView(_:didReceive:completionHandler:), it takes full control of the server trust evaluation. An incorrect implementation that accepts credentials without calling SecTrustEvaluateWithError bypasses certificate chain validation and hostname verification, leaving connections open to Machine-in-the-Middle (MITM) attacks.
See "Performing manual server trust authentication" in the Apple Developer Documentation for more information.
Prefer the Default ATS Trust Evaluation¶
The safest approach is to not implement urlSession(_:didReceive:completionHandler:) or webView(_:didReceive:completionHandler:) at all. When these methods are absent, the URL Loading System and WKWebView perform the full ATS-enforced server trust evaluation automatically. Override these methods only when the app has a specific justified requirement (for example, certificate pinning or connecting to a development server with a self-signed certificate). Even for certificate pinning, prefer Apple's declarative Identity Pinning, which lets you pin CA or leaf public keys directly in the Info.plist under NSPinnedDomains and is enforced automatically by ATS without any custom validation code (see Server Trust Evaluation). If a server presents an otherwise untrusted certificate, fix it server-side rather than weakening or replacing the system's trust evaluation in the app.
Perform Explicit Server Trust Evaluation¶
If you must handle the challenge, always:
- Confirm the challenge is of type
NSURLAuthenticationMethodServerTrust. - Obtain the
serverTrustobject fromchallenge.protectionSpace.serverTrust. - Call
SecTrustEvaluateWithErrorand verify it returnstrue. - Call
completionHandler(.useCredential, URLCredential(trust: serverTrust))only when evaluation succeeds. - Call
completionHandler(.cancelAuthenticationChallenge, nil)on any other challenge type or when evaluation fails.
Tests¶
MASTG-TEST-0396: References to URLSessionDelegate Bypassing Certificate Validation MASTG-TEST-0397: References to WKNavigationDelegate Bypassing Certificate Validation