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

Side by Side Diff: webkit/child/site_isolation_policy.cc

Issue 22254005: UMA data collector for cross-site documents(XSD) (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@lkgr
Patch Set: "X-Content-Type-Options: nosniff" rule is added. Created 7 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
(Empty)
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "webkit/child/site_isolation_policy.h"
6
7 #include "base/basictypes.h"
8 #include "base/logging.h"
9 #include "base/metrics/histogram.h"
10 #include "base/strings/string_util.h"
11 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
12 #include "third_party/WebKit/public/platform/WebHTTPHeaderVisitor.h"
13 #include "third_party/WebKit/public/platform/WebString.h"
14 #include "third_party/WebKit/public/platform/WebURL.h"
15 #include "third_party/WebKit/public/platform/WebURLRequest.h"
16 #include "third_party/WebKit/public/platform/WebURLResponse.h"
17 #include "third_party/WebKit/public/web/WebDocument.h"
18 #include "third_party/WebKit/public/web/WebFrame.h"
19 #include "third_party/WebKit/public/web/WebFrameClient.h"
20 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
21
22 using WebKit::WebDocument;
23 using WebKit::WebString;
24 using WebKit::WebURL;
25 using WebKit::WebURLResponse;
26 using WebKit::WebURLRequest;
27
28
29 namespace webkit_glue {
30
31 ResponseMetaData::ResponseMetaData() {}
32
33 void SiteIsolationPolicy::WillSendRequest(
34 unsigned identifier,
35 WebURLRequest::TargetType target_type) {
36 TargetTypeMap* id_target_map = GetIdTargetMap();
37 // When |identifier| already exists in the map, it means that this request has
38 // been redirected to issue another request. We don't overwrite the existing
39 // target_type since it becomes TargetIsSubresource no matter what the
40 // original target_type was.
41 if (!id_target_map->count(identifier))
42 (*id_target_map)[identifier] = target_type;
43 }
44
45 void SiteIsolationPolicy::DidReceiveResponse(WebKit::WebFrame* frame,
46 unsigned identifier,
47 const WebURLResponse& response) {
48 TargetTypeMap* id_target_map = GetIdTargetMap();
49 DCHECK_EQ(id_target_map->count(identifier),1U);
50
51 UMA_HISTOGRAM_COUNTS("SiteIsolation.AllResponses", 1);
52
53 GURL response_url = response.url();
54 WebURLRequest::TargetType target_type = (*id_target_map)[identifier];
55 id_target_map->erase(identifier);
56
57 // See if this is for navigation. If it is, don't block it, under the
58 // assumption that we will put it in an appropriate process.
59 if (IsFrameNavigating(frame)) {
60 return;
61 }
62
63 GURL frame_origin(frame->document().securityOrigin().toString());
64
65 if (!IsBlockableScheme(frame_origin)) {
66 return;
67 }
68
69 if (IsSameSite(frame_origin, response_url)) {
70 return;
71 }
72
73 ResponseMetaData::CanonicalMimeType canonical_mime_type =
74 GetCanonicalMimeType(response);
75
76 if (canonical_mime_type == ResponseMetaData::Others) {
77 return;
78 }
79
80 // Every CORS request should have the Access-Control-Allow-Origin header even
81 // if it is preceded by a pre-flight request. Therefore, if this is a CORS
82 // request, it has this header. response.httpHeaderField() internally uses
83 // case-insensitive matching for the header name.
84 std::string access_control_origin = response.httpHeaderField(
85 WebKit::WebString::fromUTF8("Access-Control-Allow-Origin")).utf8();
86
87 if (IsValidCorsHeaderSet(frame_origin, response_url, access_control_origin)) {
88 return;
89 }
90
91 // Real XSD data collection starts from here.
92 std::string no_sniff = response.httpHeaderField(
93 WebKit::WebString::fromUTF8("X-Content-Type-Options")).utf8();
94
95 ResponseMetaData resp_data;
96 resp_data.frame_origin = frame_origin.spec();
97 resp_data.response_url = response_url;
98 resp_data.request_identifier = identifier;
99 resp_data.target_type = target_type;
100 resp_data.canonical_mime_type = canonical_mime_type;
101 resp_data.http_status_code = response.httpStatusCode();
102 resp_data.no_sniff = (no_sniff == "nosniff");
103
104 UrlResponseMetaDataMap* url_responsedata_map = GetUrlResponseMetaDataMap();
105 IdUrlMap* id_url_map = GetIdUrlMap();
106
107 (*url_responsedata_map)[resp_data.response_url] = resp_data;
108 (*id_url_map)[identifier] = resp_data.response_url;
109 }
110
111 // These macros are defined here so that we prevent code size bloat-up due to
112 // the UMA_HISTOGRAM_* macros. Similar logic is used for recording UMA stats for
113 // different MIME types, but we cannot create a helper function for this since
114 // UMA_HISTOGRAM_* macros do not accept variabls as their bucket names. As a
Charlie Reis 2013/08/13 21:09:03 nit: variables
dsjang 2013/08/13 21:49:52 Done.
115 // solution, macros are used instead to capture the repeated pattern for
116 // recording UMA stats.
117 // TODO(dsjang): this is only needed for collecting UMA stat. Will be deleted
118 // when this class is used for actual blocking.
119
120 #define SITE_ISOLATION_POLICY_COUNT_BLOCK(BUCKET_PREFIX) \
121 UMA_HISTOGRAM_COUNTS( BUCKET_PREFIX ".Blocked", 1); \
122 if (renderable_status_code) { \
123 UMA_HISTOGRAM_ENUMERATION( \
124 BUCKET_PREFIX ".Blocked.RenderableStatusCode", \
125 resp_data.target_type, \
126 WebURLRequest::TargetIsUnspecified + 1); \
127 } else { \
128 UMA_HISTOGRAM_COUNTS(BUCKET_PREFIX ".Blocked.NonRenderableStatusCode",1);\
129 }
130
131 #define SITE_ISOLATION_POLICY_COUNT_NO_SNIFF_BLOCK(BUCKET_PREFIX) \
132 UMA_HISTOGRAM_COUNTS( BUCKET_PREFIX ".NoSniffBlocked", 1); \
133 if (renderable_status_code) { \
134 UMA_HISTOGRAM_ENUMERATION( \
135 BUCKET_PREFIX ".NoSniffBlocked.RenderableStatusCode", \
136 resp_data.target_type, \
137 WebURLRequest::TargetIsUnspecified + 1); \
138 } else { \
139 UMA_HISTOGRAM_ENUMERATION( \
140 BUCKET_PREFIX ".NoSniffBlocked.NonRenderableStatusCode", \
141 resp_data.target_type, \
142 WebURLRequest::TargetIsUnspecified + 1); \
143 }
144
145 #define SITE_ISOLATION_POLICY_COUNT_NOTBLOCK(BUCKET_PREFIX) \
146 UMA_HISTOGRAM_COUNTS(BUCKET_PREFIX ".NotBlocked", 1); \
147 if (is_sniffed_for_js) \
148 UMA_HISTOGRAM_COUNTS(BUCKET_PREFIX ".NotBlocked.MaybeJS", 1); \
149
150 #define SITE_ISOLATION_POLICY_SNIFF_AND_COUNT(SNIFF_EXPR,BUCKET_PREFIX) \
151 if (SNIFF_EXPR) { \
152 SITE_ISOLATION_POLICY_COUNT_BLOCK(BUCKET_PREFIX) \
153 } else { \
154 if (resp_data.no_sniff) { \
155 SITE_ISOLATION_POLICY_COUNT_NO_SNIFF_BLOCK(BUCKET_PREFIX) \
156 } else { \
157 SITE_ISOLATION_POLICY_COUNT_NOTBLOCK(BUCKET_PREFIX) \
158 } \
159 }
160
161 void SiteIsolationPolicy::DidReceiveData(const char* data,
162 int length,
163 WebURL& web_response_url) {
164 GURL response_url(web_response_url);
165
166 UrlResponseMetaDataMap* url_responsedata_map = GetUrlResponseMetaDataMap();
167
168 if (url_responsedata_map->count(response_url) == 0)
169 return;
170
171 DCHECK_EQ(url_responsedata_map->count(response_url), 1U);
172 ResponseMetaData resp_data = (*url_responsedata_map)[response_url];
173 url_responsedata_map->erase(response_url);
174
175 // Record the length of the first received network packet to see if it's
176 // enough for sniffing.
177 UMA_HISTOGRAM_COUNTS("SiteIsolation.XSD.DataLength", length);
178
179 // Record the number of cross-site document responses with a specific mime
180 // type (text/html, text/xml, etc).
181 UMA_HISTOGRAM_ENUMERATION("SiteIsolation.XSD.MimeType",
182 resp_data.canonical_mime_type,
183 ResponseMetaData::MaxCanonicalMimeType);
184
185 // The content is blocked if it is sniffed for HTML/JSON/XML. When the blocked
186 // response is with an error status code, it is not disruptive by the
187 // following reasons : 1) the blocked content is not a binary object (such as
188 // an image) since it is sniffed for text; 2) then, this blocking only breaks
189 // the renderer behavior only if it is either JavaScript or CSS. However, the
190 // renderer doesn't use the contents of JS/CSS with unaffected status code
191 // (e.g, 404). 3) the renderer is expected not to use the cross-site document
192 // content for purposes other than JS/CSS (e.g, XHR).
193 bool renderable_status_code = IsRenderableStatusCodeForDocument(
194 resp_data.http_status_code);
195
196 // This is only used for false-negative analysis for non-blocked resources.
197 bool is_sniffed_for_js = SniffForJS(data, length);
198
199 // Record the number of responses whose content is sniffed for what its mime
200 // type claims it to be. For example, we apply a HTML sniffer for a document
201 // tagged with text/html here. Whenever this check becomes true, we'll block
202 // the response.
203 switch (resp_data.canonical_mime_type) {
204 case ResponseMetaData::HTML:
205 SITE_ISOLATION_POLICY_SNIFF_AND_COUNT(SniffForHTML(data, length),
206 "SiteIsolation.XSD.HTML");
207 break;
208 case ResponseMetaData::XML:
209 SITE_ISOLATION_POLICY_SNIFF_AND_COUNT(SniffForXML(data, length),
210 "SiteIsolation.XSD.XML");
211 break;
212 case ResponseMetaData::JSON:
213 SITE_ISOLATION_POLICY_SNIFF_AND_COUNT(SniffForJSON(data, length),
214 "SiteIsolation.XSD.JSON");
215 break;
216 case ResponseMetaData::Plain:
217 if (SniffForHTML(data, length)) {
218 SITE_ISOLATION_POLICY_COUNT_BLOCK(
219 "SiteIsolation.XSD.Plain.HTML");
220 } else if (SniffForXML(data, length)) {
221 SITE_ISOLATION_POLICY_COUNT_BLOCK(
222 "SiteIsolation.XSD.Plain.XML");
223 } else if (SniffForJSON(data, length)) {
224 SITE_ISOLATION_POLICY_COUNT_BLOCK(
225 "SiteIsolation.XSD.Plain.JSON");
226 } else if (is_sniffed_for_js) {
227 if (resp_data.no_sniff) {
228 SITE_ISOLATION_POLICY_COUNT_NO_SNIFF_BLOCK(
229 "SiteIsolation.XSD.Plain");
230 } else {
231 SITE_ISOLATION_POLICY_COUNT_NOTBLOCK(
232 "SiteIsolation.XSD.Plain");
233 }
234 }
235 break;
236 default :
237 NOTREACHED() <<
238 "Not a blockable mime type. This mime type shouldn't reach here.";
239 break;
240 }
241 }
242
243 #undef SITE_ISOLATION_POLICY_COUNT_NOTBLOCK
244 #undef SITE_ISOLATION_POLICY_SNIFF_AND_COUNT
245 #undef SITE_ISOLATION_POLICY_COUNT_BLOCK
246
247
248 void SiteIsolationPolicy::DidFinishResourceLoad(unsigned identifier) {
249 TargetTypeMap* id_target_map = GetIdTargetMap();
250 UrlResponseMetaDataMap* url_responsedata_map = GetUrlResponseMetaDataMap();
251 IdUrlMap* id_url_map = GetIdUrlMap();
252
253 id_target_map->erase(identifier);
254 if (!id_url_map->count(identifier)) {
255 url_responsedata_map->erase((*id_url_map)[identifier]);
256 id_url_map->erase(identifier);
257 }
258 }
259
260 void SiteIsolationPolicy::DidFinishResourceLoadForUrl(
261 const WebKit::WebURL& web_response_url) {
262 GURL response_url(web_response_url);
263
264 TargetTypeMap* id_target_map = GetIdTargetMap();
265 UrlResponseMetaDataMap* url_responsedata_map = GetUrlResponseMetaDataMap();
266 IdUrlMap* id_url_map = GetIdUrlMap();
267
268 if (!url_responsedata_map->count(response_url)) {
269 ResponseMetaData meta_data = (*url_responsedata_map)[response_url];
270 url_responsedata_map->erase(response_url);
271 id_target_map->erase(meta_data.request_identifier);
272 id_url_map->erase(meta_data.request_identifier);
273 }
274 }
275
276 ResponseMetaData::CanonicalMimeType SiteIsolationPolicy::GetCanonicalMimeType(
277 const WebURLResponse& response) {
278
279 // These are a thorough list of the mime types crawled over the top
280 // 50k sites related to HTML, XML, JSON, Plain.
281 static const char kTextHtml[] = "text/html";
282 static const char kTextXml[] = "text/xml";
283 static const char xAppRssXml[] = "application/rss+xml";
284 static const char kAppXml[] = "application/xml";
285 static const char kAppJson[] = "application/json";
286 static const char kTextJson[] = "text/json";
287 static const char kTextXjson[] = "text/x-json";
288 static const char kTextPlain[] = "text/plain";
289
290 const std::string mime_type = response.mimeType().utf8();
291
292 if (LowerCaseEqualsASCII(mime_type, kTextHtml)) {
293 return ResponseMetaData::HTML;
294 } else if (LowerCaseEqualsASCII(mime_type, kTextPlain)) {
295 return ResponseMetaData::Plain;
296 } else if (LowerCaseEqualsASCII(mime_type, kAppJson) ||
297 LowerCaseEqualsASCII(mime_type, kTextJson) ||
298 LowerCaseEqualsASCII(mime_type, kTextXjson)) {
299 return ResponseMetaData::JSON;
300 } else if (LowerCaseEqualsASCII(mime_type, kTextXml) ||
301 LowerCaseEqualsASCII(mime_type, xAppRssXml) ||
302 LowerCaseEqualsASCII(mime_type, kAppXml)) {
303 return ResponseMetaData::XML;
304 } else {
305 return ResponseMetaData::Others;
306 }
307 }
308
309 bool SiteIsolationPolicy::IsBlockableScheme(const GURL& url) {
310 // We exclude ftp:// from here. FTP doesn't provide a Content-Type
311 // header which our policy depends on, so we cannot protect any
312 // document from FTP servers.
313 return url.SchemeIs("http") || url.SchemeIs("https");
314 }
315
316 bool SiteIsolationPolicy::IsSameSite(const GURL& frame_origin,
317 const GURL& response_url) {
Charlie Reis 2013/08/13 21:09:03 Please add a check for whether either URL is inval
dsjang 2013/08/13 21:49:52 Done.
318 if (frame_origin.scheme() != response_url.scheme())
319 return false;
320
321 // SameDomainOrHost() extracts the effective domains (public suffix plus one)
322 // from the two URLs and compare them.
323 // TODO(dsjang): use INCLUDE_PRIVATE_REGISTRIES when http://crbug.com/7988 is
324 // fixed.
325 return net::registry_controlled_domains::SameDomainOrHost(
326 frame_origin,
327 response_url,
328 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
329 }
330
331 bool SiteIsolationPolicy::IsFrameNavigating(WebKit::WebFrame* frame) {
332 // When a navigation starts, frame->provisionalDataSource() is set
333 // to a not-null value which stands for the request made for the
334 // navigation. As soon as the network request is committed to the
335 // frame, frame->provisionalDataSource() is converted to null, and
336 // the committed data source is moved to frame->dataSource(). This
337 // is the most reliable way to detect whether the frame is in
338 // navigation or not.
339 return frame->provisionalDataSource() != NULL;
340 }
341
342 // We don't use Webkit's existing CORS policy implementation since
343 // their policy works in terms of origins, not sites. For example,
344 // when frame is sub.a.com and it is not allowed to access a document
345 // with sub1.a.com. But under Site Isolation, it's allowed.
346 bool SiteIsolationPolicy::IsValidCorsHeaderSet(
347 GURL& frame_origin,
348 GURL& website_origin,
349 std::string access_control_origin) {
350 // Many websites are sending back "\"*\"" instead of "*". This is
351 // non-standard practice, and not supported by Chrome. Refer to
352 // CrossOriginAccessControl::passesAccessControlCheck().
353
354 // TODO(dsjang): * is not allowed for the response from a request
355 // with cookies. This allows for more than what the renderer will
356 // eventually be able to receive, so we won't see illegal cross-site
357 // documents allowed by this. We have to find a way to see if this
358 // response is from a cookie-tagged request or not in the future.
359 if (access_control_origin == "*")
360 return true;
361
362 // TODO(dsjang): The CORS spec only treats a fully specified URL, except for
363 // "*", but many websites are using just a domain for access_control_origin,
364 // and this is blocked by Webkit's CORS logic here :
365 // CrossOriginAccessControl::passesAccessControlCheck(). GURL is set
366 // is_valid() to false when it is created from a URL containing * in the
367 // domain part.
368
369 GURL cors_origin(access_control_origin);
370 return IsSameSite(frame_origin, cors_origin);
371 }
372
373 // This function is a slight modification of |net::SniffForHTML|.
374 bool SiteIsolationPolicy::SniffForHTML(const char* data, size_t length) {
375 // The content sniffer used by Chrome and Firefox are using "<!--"
376 // as one of the HTML signatures, but it also appears in valid
377 // JavaScript, considered as well-formed JS by the browser. Since
378 // we do not want to block any JS, we exclude it from our HTML
379 // signatures. This can weaken our document block policy, but we can
380 // break less websites.
381 // TODO(dsjang): parameterize |net::SniffForHTML| with an option
382 // that decides whether to include <!-- or not, so that we can
383 // remove this function.
384 const char* html_signatures[] = {"<!DOCTYPE html", // HTML5 spec
385 "<script", // HTML5 spec, Mozilla
386 "<html", // HTML5 spec, Mozilla
387 "<head", // HTML5 spec, Mozilla
388 "<iframe", // Mozilla
389 "<h1", // Mozilla
390 "<div", // Mozilla
391 "<font", // Mozilla
392 "<table", // Mozilla
393 "<a", // Mozilla
394 "<style", // Mozilla
395 "<title", // Mozilla
396 "<b", // Mozilla
397 "<body", // Mozilla
398 "<br", "<p" // Mozilla
399 };
400 return MatchesSignature(
401 data, length, html_signatures, arraysize(html_signatures));
402 }
403
404 bool SiteIsolationPolicy::SniffForXML(const char* data, size_t length) {
405 // TODO(dsjang): Chrome's mime_sniffer is using strncasecmp() for
406 // this signature. However, XML is case-sensitive. Don't we have to
407 // be more lenient only to block documents starting with the exact
408 // string <?xml rather than <?XML ?
409 const char* xml_signatures[] = {"<?xml" // Mozilla
410 };
411 return MatchesSignature(
412 data, length, xml_signatures, arraysize(xml_signatures));
413 }
414
415 bool SiteIsolationPolicy::SniffForJSON(const char* data, size_t length) {
416 // TODO(dsjang): We have to come up with a better way to sniff
417 // JSON. However, even RE cannot help us that much due to the fact
418 // that we don't do full parsing. This DFA starts with state 0, and
419 // finds {, "/' and : in that order. We're avoiding adding a
420 // dependency on a regular expression library.
421 const int kInitState = 0;
422 const int kLeftBraceState = 1;
423 const int kLeftQuoteState = 2;
424 const int kColonState = 3;
425 const int kDeadState = 4;
426
427 int state = kInitState;
428 for (size_t i = 0; i < length && state < kColonState; ++i) {
429 const char c = data[i];
430 if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
431 continue;
432
433 switch (state) {
434 case kInitState:
435 if (c == '{')
436 state = kLeftBraceState;
437 else
438 state = kDeadState;
439 break;
440 case kLeftBraceState:
441 if (c == '\"' || c == '\'')
442 state = kLeftQuoteState;
443 else
444 state = kDeadState;
445 break;
446 case kLeftQuoteState:
447 if (c == ':')
448 state = kColonState;
449 break;
450 default:
451 NOTREACHED();
452 break;
453 }
454 }
455 return state == kColonState;
456 }
457
458 bool SiteIsolationPolicy::MatchesSignature(const char* raw_data,
459 size_t raw_length,
460 const char* signatures[],
461 size_t arr_size) {
462 size_t start = 0;
463 // Skip white characters at the beginning of the document.
464 for (start = 0; start < raw_length; ++start) {
465 char c = raw_data[start];
466 if (!(c == ' ' || c == '\r' || c == '\n' || c == '\t'))
467 break;
468 }
469
470 // There is no not-whitespace character in this document.
471 if (!(start < raw_length))
472 return false;
473
474 const char* data = raw_data + start;
475 size_t length = raw_length - start;
476
477 for (size_t sig_index = 0; sig_index < arr_size; ++sig_index) {
478 const char* signature = signatures[sig_index];
479 size_t signature_length = strlen(signature);
480
481 if (length < signature_length)
482 continue;
483
484 if (!base::strncasecmp(signature, data, signature_length))
485 return true;
486 }
487 return false;
488 }
489
490 bool SiteIsolationPolicy::IsRenderableStatusCodeForDocument(int status_code) {
491 // Chrome only uses the content of a response with one of these status codes
492 // for CSS/JavaScript. For images, Chrome just ignores status code.
493 const int renderable_status_code[] = {200, 201, 202, 203, 206, 300, 301, 302,
494 303, 305, 306, 307};
495 for (size_t i = 0; i < arraysize(renderable_status_code); ++i) {
496 if (renderable_status_code[i] == status_code)
497 return true;
498 }
499 return false;
500 }
501
502 bool SiteIsolationPolicy::SniffForJS(const char* data, size_t length) {
503 // TODO(dsjang): This is a real hack. The only purpose of this function is to
504 // try to see if there's any possibility that this data can be JavaScript
505 // (superset of JS). This function will be removed once UMA stats are
506 // gathered.
507
508 // Search for "var " for JS detection.
509 for (size_t i = 0; i < length - 3; ++i) {
510 if (strncmp(data + i, "var ", 4) == 0)
511 return true;
512 }
513 return false;
514 }
515
516 TargetTypeMap* SiteIsolationPolicy::GetIdTargetMap() {
517 CR_DEFINE_STATIC_LOCAL(TargetTypeMap, id_target_map_, ());
518 return &id_target_map_;
519 }
520
521 UrlResponseMetaDataMap* SiteIsolationPolicy::GetUrlResponseMetaDataMap() {
522 CR_DEFINE_STATIC_LOCAL(UrlResponseMetaDataMap, url_responsedata_map_, ());
523 return &url_responsedata_map_;
524 }
525
526 IdUrlMap* SiteIsolationPolicy::GetIdUrlMap() {
527 CR_DEFINE_STATIC_LOCAL(IdUrlMap, id_url_map_, ());
528 return &id_url_map_;
529 }
530
531 } // namespace webkit_glue
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698