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

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

Powered by Google App Engine
This is Rietveld 408576698