Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(213)

Side by Side Diff: ios/web/web_state/ui/crw_wk_web_view_web_controller.mm

Issue 1230033005: WKWebView: Added cert verification API to web controller. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Addressed review comments Created 5 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2014 The Chromium Authors. All rights reserved. 1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #import "ios/web/web_state/ui/crw_wk_web_view_web_controller.h" 5 #import "ios/web/web_state/ui/crw_wk_web_view_web_controller.h"
6 6
7 #import <WebKit/WebKit.h> 7 #import <WebKit/WebKit.h>
8 8
9 #include "base/ios/ios_util.h" 9 #include "base/ios/ios_util.h"
10 #include "base/ios/weak_nsobject.h" 10 #include "base/ios/weak_nsobject.h"
11 #include "base/json/json_reader.h" 11 #include "base/json/json_reader.h"
12 #include "base/mac/bind_objc_block.h"
12 #import "base/mac/scoped_nsobject.h" 13 #import "base/mac/scoped_nsobject.h"
13 #include "base/macros.h" 14 #include "base/macros.h"
15 #import "base/memory/scoped_ptr.h"
14 #include "base/strings/sys_string_conversions.h" 16 #include "base/strings/sys_string_conversions.h"
15 #include "base/values.h" 17 #include "base/values.h"
16 #import "ios/net/http_response_headers_util.h" 18 #import "ios/net/http_response_headers_util.h"
17 #import "ios/web/crw_network_activity_indicator_manager.h" 19 #import "ios/web/crw_network_activity_indicator_manager.h"
18 #import "ios/web/navigation/crw_session_controller.h" 20 #import "ios/web/navigation/crw_session_controller.h"
19 #include "ios/web/navigation/web_load_params.h" 21 #include "ios/web/navigation/web_load_params.h"
22 #include "ios/web/net/cert_verifier_block_adapter.h"
23 #include "ios/web/public/browser_state.h"
20 #include "ios/web/public/web_client.h" 24 #include "ios/web/public/web_client.h"
25 #include "ios/web/public/web_thread.h"
21 #import "ios/web/public/web_state/js/crw_js_injection_manager.h" 26 #import "ios/web/public/web_state/js/crw_js_injection_manager.h"
22 #import "ios/web/public/web_state/ui/crw_native_content_provider.h" 27 #import "ios/web/public/web_state/ui/crw_native_content_provider.h"
23 #import "ios/web/public/web_state/ui/crw_web_view_content_view.h" 28 #import "ios/web/public/web_state/ui/crw_web_view_content_view.h"
24 #import "ios/web/ui_web_view_util.h" 29 #import "ios/web/ui_web_view_util.h"
25 #include "ios/web/web_state/blocked_popup_info.h" 30 #include "ios/web/web_state/blocked_popup_info.h"
26 #import "ios/web/web_state/error_translation_util.h" 31 #import "ios/web/web_state/error_translation_util.h"
27 #include "ios/web/web_state/frame_info.h" 32 #include "ios/web/web_state/frame_info.h"
28 #import "ios/web/web_state/js/crw_js_window_id_manager.h" 33 #import "ios/web/web_state/js/crw_js_window_id_manager.h"
29 #import "ios/web/web_state/js/page_script_util.h" 34 #import "ios/web/web_state/js/page_script_util.h"
30 #import "ios/web/web_state/ui/crw_web_controller+protected.h" 35 #import "ios/web/web_state/ui/crw_web_controller+protected.h"
31 #import "ios/web/web_state/ui/crw_wk_web_view_crash_detector.h" 36 #import "ios/web/web_state/ui/crw_wk_web_view_crash_detector.h"
32 #import "ios/web/web_state/ui/web_view_js_utils.h" 37 #import "ios/web/web_state/ui/web_view_js_utils.h"
33 #import "ios/web/web_state/ui/wk_web_view_configuration_provider.h" 38 #import "ios/web/web_state/ui/wk_web_view_configuration_provider.h"
34 #import "ios/web/web_state/web_state_impl.h" 39 #import "ios/web/web_state/web_state_impl.h"
35 #import "ios/web/web_state/web_view_internal_creation_util.h" 40 #import "ios/web/web_state/web_view_internal_creation_util.h"
36 #import "ios/web/webui/crw_web_ui_manager.h" 41 #import "ios/web/webui/crw_web_ui_manager.h"
37 #import "net/base/mac/url_conversions.h" 42 #import "net/base/mac/url_conversions.h"
43 #include "net/cert/cert_verify_result.h"
44 #include "net/ssl/ssl_config_service.h"
45 #include "net/url_request/url_request_context.h"
38 46
39 #if !defined(ENABLE_CHROME_NET_STACK_FOR_WKWEBVIEW) 47 #if !defined(ENABLE_CHROME_NET_STACK_FOR_WKWEBVIEW)
40 #include "ios/web/public/cert_store.h" 48 #include "ios/web/public/cert_store.h"
41 #include "ios/web/public/navigation_item.h" 49 #include "ios/web/public/navigation_item.h"
42 #include "ios/web/public/ssl_status.h" 50 #include "ios/web/public/ssl_status.h"
43 #import "ios/web/web_state/wk_web_view_security_util.h" 51 #import "ios/web/web_state/wk_web_view_security_util.h"
44 #include "net/cert/x509_certificate.h" 52 #include "net/cert/x509_certificate.h"
45 #include "net/ssl/ssl_info.h" 53 #include "net/ssl/ssl_info.h"
46 #endif 54 #endif
47 55
48 namespace { 56 namespace {
49 // Extracts Referer value from WKNavigationAction request header. 57 // Extracts Referer value from WKNavigationAction request header.
50 NSString* GetRefererFromNavigationAction(WKNavigationAction* action) { 58 NSString* GetRefererFromNavigationAction(WKNavigationAction* action) {
51 return [action.request valueForHTTPHeaderField:@"Referer"]; 59 return [action.request valueForHTTPHeaderField:@"Referer"];
52 } 60 }
53 61
62 // Returns net::URLRequestContext obtained from the given |webState|.
63 net::URLRequestContext* GetURLRequestContext(web::WebState* webState) {
64 DCHECK(webState);
65 auto contextGetter = webState->GetBrowserState()->GetRequestContext();
Ryan Sleevi 2015/08/06 03:07:09 This is not a valid (Chromium) use of auto See th
Eugene But (OOO till 7-30) 2015/08/07 02:27:20 I used auto to avoid a linebreak. But I'm not very
66 DCHECK(contextGetter);
67 return contextGetter->GetURLRequestContext();
68 }
69
54 NSString* const kScriptMessageName = @"crwebinvoke"; 70 NSString* const kScriptMessageName = @"crwebinvoke";
55 NSString* const kScriptImmediateName = @"crwebinvokeimmediate"; 71 NSString* const kScriptImmediateName = @"crwebinvokeimmediate";
56 72
57 // Utility functions for storing the source of NSErrors received by WKWebViews: 73 // Utility functions for storing the source of NSErrors received by WKWebViews:
58 // - Errors received by |-webView:didFailProvisionalNavigation:withError:| are 74 // - Errors received by |-webView:didFailProvisionalNavigation:withError:| are
59 // recorded using WKWebViewErrorSource::PROVISIONAL_LOAD. These should be 75 // recorded using WKWebViewErrorSource::PROVISIONAL_LOAD. These should be
60 // aborted. 76 // aborted.
61 // - Errors received by |-webView:didFailNavigation:withError:| are recorded 77 // - Errors received by |-webView:didFailNavigation:withError:| are recorded
62 // using WKWebViewsource::NAVIGATION. These errors should not be aborted, as 78 // using WKWebViewsource::NAVIGATION. These errors should not be aborted, as
63 // the WKWebView will automatically retry the load. 79 // the WKWebView will automatically retry the load.
(...skipping 60 matching lines...) Expand 10 before | Expand all | Expand 10 after
124 WKNavigationType _lastNavigationTypeForMainFrame; 140 WKNavigationType _lastNavigationTypeForMainFrame;
125 141
126 // Whether the web page is currently performing window.history.pushState or 142 // Whether the web page is currently performing window.history.pushState or
127 // window.history.replaceState 143 // window.history.replaceState
128 // Set to YES on window.history.willChangeState message. To NO on 144 // Set to YES on window.history.willChangeState message. To NO on
129 // window.history.didPushState or window.history.didReplaceState. 145 // window.history.didPushState or window.history.didReplaceState.
130 BOOL _changingHistoryState; 146 BOOL _changingHistoryState;
131 147
132 // CRWWebUIManager object for loading WebUI pages. 148 // CRWWebUIManager object for loading WebUI pages.
133 base::scoped_nsobject<CRWWebUIManager> _webUIManager; 149 base::scoped_nsobject<CRWWebUIManager> _webUIManager;
150
151 // Backs up property with the same name.
152 scoped_ptr<net::CertVerifierBlockAdapter> _certVerifier;
134 } 153 }
135 154
136 // Response's MIME type of the last known navigation. 155 // Response's MIME type of the last known navigation.
137 @property(nonatomic, copy) NSString* documentMIMEType; 156 @property(nonatomic, copy) NSString* documentMIMEType;
138 157
139 // Dictionary where keys are the names of WKWebView properties and values are 158 // Dictionary where keys are the names of WKWebView properties and values are
140 // selector names which should be called when a corresponding property has 159 // selector names which should be called when a corresponding property has
141 // changed. e.g. @{ @"URL" : @"webViewURLDidChange" } means that 160 // changed. e.g. @{ @"URL" : @"webViewURLDidChange" } means that
142 // -[self webViewURLDidChange] must be called every time when WKWebView.URL is 161 // -[self webViewURLDidChange] must be called every time when WKWebView.URL is
143 // changed. 162 // changed.
144 @property(nonatomic, readonly) NSDictionary* wkWebViewObservers; 163 @property(nonatomic, readonly) NSDictionary* wkWebViewObservers;
145 164
146 // Activity indicator group ID for this web controller. 165 // Activity indicator group ID for this web controller.
147 @property(nonatomic, readonly) NSString* activityIndicatorGroupID; 166 @property(nonatomic, readonly) NSString* activityIndicatorGroupID;
148 167
149 #if !defined(ENABLE_CHROME_NET_STACK_FOR_WKWEBVIEW) 168 #if !defined(ENABLE_CHROME_NET_STACK_FOR_WKWEBVIEW)
150 // Identifier used for storing and retrieving certificates. 169 // Identifier used for storing and retrieving certificates.
151 @property(nonatomic, readonly) int certGroupID; 170 @property(nonatomic, readonly) int certGroupID;
152 #endif // #if !defined(ENABLE_CHROME_NET_STACK_FOR_WKWEBVIEW) 171 #endif // #if !defined(ENABLE_CHROME_NET_STACK_FOR_WKWEBVIEW)
153 172
173 // Cert verification flags. Must be called on IO Thread.
174 @property(nonatomic, readonly) net::CertVerifier::VerifyFlags certVerifyFlags;
175
176 // Cert verification object which wraps net::CertVerifier. Must be called on
177 // IO Thread.
178 @property(nonatomic, readonly) net::CertVerifierBlockAdapter* certVerifier;
179
154 // Returns the WKWebViewConfigurationProvider associated with the web 180 // Returns the WKWebViewConfigurationProvider associated with the web
155 // controller's BrowserState. 181 // controller's BrowserState.
156 - (web::WKWebViewConfigurationProvider&)webViewConfigurationProvider; 182 - (web::WKWebViewConfigurationProvider&)webViewConfigurationProvider;
157 183
158 // Creates a web view with given |config|. No-op if web view is already created. 184 // Creates a web view with given |config|. No-op if web view is already created.
159 - (void)ensureWebViewCreatedWithConfiguration:(WKWebViewConfiguration*)config; 185 - (void)ensureWebViewCreatedWithConfiguration:(WKWebViewConfiguration*)config;
160 186
161 // Returns a new autoreleased web view created with given configuration. 187 // Returns a new autoreleased web view created with given configuration.
162 - (WKWebView*)createWebViewWithConfiguration:(WKWebViewConfiguration*)config; 188 - (WKWebView*)createWebViewWithConfiguration:(WKWebViewConfiguration*)config;
163 189
(...skipping 69 matching lines...) Expand 10 before | Expand all | Expand 10 after
233 // _documentURL, and informs the superclass of the change. 259 // _documentURL, and informs the superclass of the change.
234 - (void)URLDidChangeWithoutDocumentChange:(const GURL&)URL; 260 - (void)URLDidChangeWithoutDocumentChange:(const GURL&)URL;
235 261
236 // Returns new autoreleased instance of WKUserContentController which has 262 // Returns new autoreleased instance of WKUserContentController which has
237 // early page script. 263 // early page script.
238 - (WKUserContentController*)createUserContentController; 264 - (WKUserContentController*)createUserContentController;
239 265
240 // Attempts to handle a script message. Returns YES on success, NO otherwise. 266 // Attempts to handle a script message. Returns YES on success, NO otherwise.
241 - (BOOL)respondToWKScriptMessage:(WKScriptMessage*)scriptMessage; 267 - (BOOL)respondToWKScriptMessage:(WKScriptMessage*)scriptMessage;
242 268
269 // Verifies the given |cert| for the given |host| and calls |block| on
270 // completion. |block| can not be null and will be called asynchronously on the
271 // main thread.
272 - (void)verifyCert:(scoped_refptr<net::X509Certificate>)cert
273 forHost:(NSString*)host
274 completionHandler:(void (^)(net::CertVerifyResult, int))block;
275
243 // Used to decide whether a load that generates errors with the 276 // Used to decide whether a load that generates errors with the
244 // NSURLErrorCancelled code should be cancelled. 277 // NSURLErrorCancelled code should be cancelled.
245 - (BOOL)shouldAbortLoadForCancelledError:(NSError*)error; 278 - (BOOL)shouldAbortLoadForCancelledError:(NSError*)error;
246 279
247 #if !defined(ENABLE_CHROME_NET_STACK_FOR_WKWEBVIEW) 280 #if !defined(ENABLE_CHROME_NET_STACK_FOR_WKWEBVIEW)
248 // Called when WKWebView estimatedProgress has been changed. 281 // Called when WKWebView estimatedProgress has been changed.
249 - (void)webViewEstimatedProgressDidChange; 282 - (void)webViewEstimatedProgressDidChange;
250 283
251 // Called when WKWebView certificateChain or hasOnlySecureContent property has 284 // Called when WKWebView certificateChain or hasOnlySecureContent property has
252 // changed. 285 // changed.
(...skipping 243 matching lines...) Expand 10 before | Expand all | Expand 10 after
496 } 529 }
497 530
498 #if !defined(ENABLE_CHROME_NET_STACK_FOR_WKWEBVIEW) 531 #if !defined(ENABLE_CHROME_NET_STACK_FOR_WKWEBVIEW)
499 - (int)certGroupID { 532 - (int)certGroupID {
500 DCHECK(self.webStateImpl); 533 DCHECK(self.webStateImpl);
501 // Request tracker IDs are used as certificate groups. 534 // Request tracker IDs are used as certificate groups.
502 return self.webStateImpl->GetRequestTracker()->identifier(); 535 return self.webStateImpl->GetRequestTracker()->identifier();
503 } 536 }
504 #endif 537 #endif
505 538
539 - (net::CertVerifier::VerifyFlags)certVerifyFlags {
540 net::URLRequestContext* context = GetURLRequestContext(self.webState);
541 DCHECK(context);
542 net::SSLConfigService* SSLConfigService = context->ssl_config_service();
543 DCHECK(SSLConfigService);
544 net::SSLConfig config;
545 SSLConfigService->GetSSLConfig(&config);
546 return static_cast<net::CertVerifier::VerifyFlags>(
547 config.GetCertVerifyFlags());
548 }
549
550 - (net::CertVerifierBlockAdapter*)certVerifier {
551 if (!_certVerifier) {
Ryan Sleevi 2015/08/06 03:07:09 Why do you lazily create this?
Eugene But (OOO till 7-30) 2015/08/07 02:27:20 I can't create this in -init, because GetURLReques
552 net::URLRequestContext* context = GetURLRequestContext(self.webState);
553 DCHECK(context);
554 _certVerifier.reset(
555 new net::CertVerifierBlockAdapter(context->cert_verifier()));
556 }
557 return _certVerifier.get();
558 }
559
506 - (web::WKWebViewConfigurationProvider&)webViewConfigurationProvider { 560 - (web::WKWebViewConfigurationProvider&)webViewConfigurationProvider {
507 DCHECK(self.webStateImpl); 561 DCHECK(self.webStateImpl);
508 web::BrowserState* browserState = self.webStateImpl->GetBrowserState(); 562 web::BrowserState* browserState = self.webStateImpl->GetBrowserState();
509 return web::WKWebViewConfigurationProvider::FromBrowserState(browserState); 563 return web::WKWebViewConfigurationProvider::FromBrowserState(browserState);
510 } 564 }
511 565
512 - (void)ensureWebViewCreatedWithConfiguration:(WKWebViewConfiguration*)config { 566 - (void)ensureWebViewCreatedWithConfiguration:(WKWebViewConfiguration*)config {
513 if (!_wkWebView) { 567 if (!_wkWebView) {
514 // Use a separate userContentController for each web view. 568 // Use a separate userContentController for each web view.
515 // WKUserContentController does not allow adding multiple script message 569 // WKUserContentController does not allow adding multiple script message
(...skipping 329 matching lines...) Expand 10 before | Expand all | Expand 10 after
845 (*handlers)["window.history.willChangeState"] = 899 (*handlers)["window.history.willChangeState"] =
846 @selector(handleWindowHistoryWillChangeStateMessage:context:); 900 @selector(handleWindowHistoryWillChangeStateMessage:context:);
847 }); 901 });
848 DCHECK(handlers); 902 DCHECK(handlers);
849 auto iter = handlers->find(command); 903 auto iter = handlers->find(command);
850 return iter != handlers->end() 904 return iter != handlers->end()
851 ? iter->second 905 ? iter->second
852 : [super selectorToHandleJavaScriptCommand:command]; 906 : [super selectorToHandleJavaScriptCommand:command];
853 } 907 }
854 908
909 - (void)verifyCert:(scoped_refptr<net::X509Certificate>)cert
910 forHost:(NSString*)host
911 completionHandler:(void (^)(net::CertVerifyResult, int))completionHandler {
912 DCHECK(completionHandler);
913 base::WeakNSObject<CRWWKWebViewWebController> weakSelf(self);
914 web::WebThread::PostTask(web::WebThread::IO, FROM_HERE, base::BindBlock(^{
915 // WeakNSObject does not work across different threads, hence this block
916 // retains self.
917 if ([self isBeingDestroyed]) {
918 completionHandler(net::CertVerifyResult(), net::ERR_FAILED);
919 return;
920 }
921
922 std::string hostname = base::SysNSStringToUTF8(host);
923 net::CertVerifierBlockAdapter::Params params(cert, hostname);
924 params.ocsp_response = ""; // Not provided by iOS API.
925 params.flags = self.certVerifyFlags;
926 params.crl_set = net::SSLConfigService::GetCRLSet().Pass();
927
928 self.certVerifier->Verify(
929 params, ^(net::CertVerifyResult result, int status) {
930 dispatch_async(dispatch_get_main_queue(), ^{
931 completionHandler(result, status);
932 });
933 });
934 }));
935 }
936
855 - (BOOL)shouldAbortLoadForCancelledError:(NSError*)error { 937 - (BOOL)shouldAbortLoadForCancelledError:(NSError*)error {
856 DCHECK_EQ(error.code, NSURLErrorCancelled); 938 DCHECK_EQ(error.code, NSURLErrorCancelled);
857 // Do not abort the load if it is for an app specific URL, as such errors 939 // Do not abort the load if it is for an app specific URL, as such errors
858 // are produced during the app specific URL load process. 940 // are produced during the app specific URL load process.
859 const GURL errorURL = 941 const GURL errorURL =
860 net::GURLWithNSURL(error.userInfo[NSURLErrorFailingURLErrorKey]); 942 net::GURLWithNSURL(error.userInfo[NSURLErrorFailingURLErrorKey]);
861 if (web::GetWebClient()->IsAppSpecificURL(errorURL)) 943 if (web::GetWebClient()->IsAppSpecificURL(errorURL))
862 return NO; 944 return NO;
863 // Don't abort NSURLErrorCancelled errors originating from navigation 945 // Don't abort NSURLErrorCancelled errors originating from navigation
864 // as the WKWebView will automatically retry these loads. 946 // as the WKWebView will automatically retry these loads.
(...skipping 316 matching lines...) Expand 10 before | Expand all | Expand 10 after
1181 withError:(NSError *)error { 1263 withError:(NSError *)error {
1182 [self handleLoadError:WKWebViewErrorWithSource(error, NAVIGATION) 1264 [self handleLoadError:WKWebViewErrorWithSource(error, NAVIGATION)
1183 inMainFrame:YES]; 1265 inMainFrame:YES];
1184 } 1266 }
1185 1267
1186 - (void)webView:(WKWebView *)webView 1268 - (void)webView:(WKWebView *)webView
1187 didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 1269 didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
1188 completionHandler: 1270 completionHandler:
1189 (void (^)(NSURLSessionAuthChallengeDisposition disposition, 1271 (void (^)(NSURLSessionAuthChallengeDisposition disposition,
1190 NSURLCredential *credential))completionHandler { 1272 NSURLCredential *credential))completionHandler {
1191 NOTIMPLEMENTED(); 1273 if (![challenge.protectionSpace.authenticationMethod
1192 completionHandler(NSURLSessionAuthChallengeRejectProtectionSpace, nil); 1274 isEqual:NSURLAuthenticationMethodServerTrust]) {
1275 completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
1276 return;
1277 }
1278
1279 SecTrustRef trust = challenge.protectionSpace.serverTrust;
1280 scoped_refptr<net::X509Certificate> cert = web::CreateCertFromTrust(trust);
1281 [self verifyCert:cert
1282 forHost:challenge.protectionSpace.host
1283 completionHandler:^(net::CertVerifyResult result, int status) {
1284 bool isCertValid = status == net::OK &&
1285 !net::IsCertStatusError(result.cert_status) &&
1286 !net::IsCertStatusMinorError(result.cert_status);
1287 if (isCertValid) {
1288 // Cert is valid.
1289 } else {
1290 // Cert is invalid.
1291 }
1292 NOTIMPLEMENTED();
1293 completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
1294 }];
1193 } 1295 }
1194 1296
1195 - (void)webViewWebContentProcessDidTerminate:(WKWebView*)webView { 1297 - (void)webViewWebContentProcessDidTerminate:(WKWebView*)webView {
1196 [self webViewWebProcessDidCrash]; 1298 [self webViewWebProcessDidCrash];
1197 } 1299 }
1198 1300
1199 #pragma mark WKUIDelegate Methods 1301 #pragma mark WKUIDelegate Methods
1200 1302
1201 - (WKWebView*)webView:(WKWebView*)webView 1303 - (WKWebView*)webView:(WKWebView*)webView
1202 createWebViewWithConfiguration:(WKWebViewConfiguration*)configuration 1304 createWebViewWithConfiguration:(WKWebViewConfiguration*)configuration
(...skipping 78 matching lines...) Expand 10 before | Expand all | Expand 10 after
1281 placeholderText:defaultText 1383 placeholderText:defaultText
1282 requestURL: 1384 requestURL:
1283 net::GURLWithNSURL(frame.request.URL) 1385 net::GURLWithNSURL(frame.request.URL)
1284 completionHandler:completionHandler]; 1386 completionHandler:completionHandler];
1285 } else if (completionHandler) { 1387 } else if (completionHandler) {
1286 completionHandler(nil); 1388 completionHandler(nil);
1287 } 1389 }
1288 } 1390 }
1289 1391
1290 @end 1392 @end
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698