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

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

Powered by Google App Engine
This is Rietveld 408576698