Implement Strict Mixed Content Checking
[WebKit-https.git] / Source / WebCore / page / csp / ContentSecurityPolicy.cpp
1 /*
2  * Copyright (C) 2011 Google, Inc. All rights reserved.
3  * Copyright (C) 2013, 2016 Apple Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28 #include "ContentSecurityPolicy.h"
29
30 #include "ContentSecurityPolicyDirective.h"
31 #include "ContentSecurityPolicyDirectiveList.h"
32 #include "ContentSecurityPolicyDirectiveNames.h"
33 #include "ContentSecurityPolicyHash.h"
34 #include "ContentSecurityPolicySource.h"
35 #include "ContentSecurityPolicySourceList.h"
36 #include "CryptoDigest.h"
37 #include "DOMStringList.h"
38 #include "Document.h"
39 #include "DocumentLoader.h"
40 #include "EventNames.h"
41 #include "FormData.h"
42 #include "FormDataList.h"
43 #include "Frame.h"
44 #include "HTMLParserIdioms.h"
45 #include "InspectorInstrumentation.h"
46 #include "JSDOMWindowShell.h"
47 #include "JSMainThreadExecState.h"
48 #include "ParsingUtilities.h"
49 #include "PingLoader.h"
50 #include "ResourceRequest.h"
51 #include "RuntimeEnabledFeatures.h"
52 #include "SchemeRegistry.h"
53 #include "SecurityOrigin.h"
54 #include "SecurityPolicyViolationEvent.h"
55 #include "Settings.h"
56 #include "TextEncoding.h"
57 #include <inspector/InspectorValues.h>
58 #include <inspector/ScriptCallStack.h>
59 #include <inspector/ScriptCallStackFactory.h>
60 #include <wtf/SetForScope.h>
61 #include <wtf/text/StringBuilder.h>
62 #include <wtf/text/TextPosition.h>
63
64 using namespace Inspector;
65
66 namespace WebCore {
67
68 static String consoleMessageForViolation(const char* effectiveViolatedDirective, const ContentSecurityPolicyDirective& violatedDirective, const URL& blockedURL, const char* prefix, const char* subject = "it")
69 {
70     StringBuilder result;
71     if (violatedDirective.directiveList().isReportOnly())
72         result.appendLiteral("[Report Only] ");
73     result.append(prefix);
74     if (!blockedURL.isEmpty()) {
75         result.append(' ');
76         result.append(blockedURL.stringCenterEllipsizedToLength());
77     }
78     result.appendLiteral(" because ");
79     result.append(subject);
80     if (violatedDirective.isDefaultSrc()) {
81         result.appendLiteral(" appears in neither the ");
82         result.append(effectiveViolatedDirective);
83         result.appendLiteral(" directive nor the default-src directive of the Content Security Policy.");
84     } else {
85         result.appendLiteral(" does not appear in the ");
86         result.append(effectiveViolatedDirective);
87         result.appendLiteral(" directive of the Content Security Policy.");
88     }
89     return result.toString();
90 }
91
92 ContentSecurityPolicy::ContentSecurityPolicy(ScriptExecutionContext& scriptExecutionContext)
93     : m_scriptExecutionContext(&scriptExecutionContext)
94     , m_sandboxFlags(SandboxNone)
95 {
96     ASSERT(scriptExecutionContext.securityOrigin());
97     updateSourceSelf(*scriptExecutionContext.securityOrigin());
98 }
99
100 ContentSecurityPolicy::ContentSecurityPolicy(const SecurityOrigin& securityOrigin, const Frame* frame)
101     : m_frame(frame)
102     , m_sandboxFlags(SandboxNone)
103 {
104     updateSourceSelf(securityOrigin);
105 }
106
107 ContentSecurityPolicy::~ContentSecurityPolicy()
108 {
109 }
110
111 void ContentSecurityPolicy::copyStateFrom(const ContentSecurityPolicy* other) 
112 {
113     ASSERT(m_policies.isEmpty());
114     for (auto& policy : other->m_policies)
115         didReceiveHeader(policy->header(), policy->headerType(), ContentSecurityPolicy::PolicyFrom::Inherited);
116
117     copyUpgradeInsecureRequestStateFrom(*other);
118 }
119
120 void ContentSecurityPolicy::copyUpgradeInsecureRequestStateFrom(const ContentSecurityPolicy& other)
121 {
122     m_upgradeInsecureRequests = other.m_upgradeInsecureRequests;
123     m_insecureNavigationRequestsToUpgrade.add(other.m_insecureNavigationRequestsToUpgrade.begin(), other.m_insecureNavigationRequestsToUpgrade.end());
124 }
125
126 bool ContentSecurityPolicy::allowRunningOrDisplayingInsecureContent(const URL& url)
127 {
128     bool allow = true;
129     bool isReportOnly = false;
130     for (auto& policy : m_policies) {
131         if (!policy->hasBlockAllMixedContentDirective())
132             continue;
133
134         isReportOnly = policy->isReportOnly();
135
136         StringBuilder consoleMessage;
137         if (isReportOnly)
138             consoleMessage.appendLiteral("[Report Only] ");
139         consoleMessage.append("Blocked mixed content ");
140         consoleMessage.append(url.stringCenterEllipsizedToLength());
141         consoleMessage.appendLiteral(" because ");
142         consoleMessage.append("'block-all-mixed-content' appears in the Content Security Policy.");
143         reportViolation(ContentSecurityPolicyDirectiveNames::blockAllMixedContent, ContentSecurityPolicyDirectiveNames::blockAllMixedContent, *policy, url, consoleMessage.toString());
144
145         if (!isReportOnly)
146             allow = false;
147     }
148     return allow;
149 }
150
151 void ContentSecurityPolicy::didCreateWindowShell(JSDOMWindowShell& windowShell) const
152 {
153     JSDOMWindow* window = windowShell.window();
154     ASSERT(window);
155     ASSERT(window->scriptExecutionContext());
156     ASSERT(window->scriptExecutionContext()->contentSecurityPolicy() == this);
157     if (!windowShell.world().isNormal()) {
158         window->setEvalEnabled(true);
159         return;
160     }
161     window->setEvalEnabled(m_lastPolicyEvalDisabledErrorMessage.isNull(), m_lastPolicyEvalDisabledErrorMessage);
162 }
163
164 ContentSecurityPolicyResponseHeaders ContentSecurityPolicy::responseHeaders() const
165 {
166     ContentSecurityPolicyResponseHeaders result;
167     result.m_headers.reserveInitialCapacity(m_policies.size());
168     for (auto& policy : m_policies)
169         result.m_headers.uncheckedAppend({ policy->header(), policy->headerType() });
170     return result;
171 }
172
173 void ContentSecurityPolicy::didReceiveHeaders(const ContentSecurityPolicyResponseHeaders& headers, ReportParsingErrors reportParsingErrors)
174 {
175     SetForScope<bool> isReportingEnabled(m_isReportingEnabled, reportParsingErrors == ReportParsingErrors::Yes);
176     for (auto& header : headers.m_headers)
177         didReceiveHeader(header.first, header.second, ContentSecurityPolicy::PolicyFrom::HTTPHeader);
178 }
179
180 void ContentSecurityPolicy::didReceiveHeader(const String& header, ContentSecurityPolicyHeaderType type, ContentSecurityPolicy::PolicyFrom policyFrom)
181 {
182     // RFC2616, section 4.2 specifies that headers appearing multiple times can
183     // be combined with a comma. Walk the header string, and parse each comma
184     // separated chunk as a separate header.
185     auto characters = StringView(header).upconvertedCharacters();
186     const UChar* begin = characters;
187     const UChar* position = begin;
188     const UChar* end = begin + header.length();
189     while (position < end) {
190         skipUntil<UChar>(position, end, ',');
191
192         // header1,header2 OR header1
193         //        ^                  ^
194         m_policies.append(ContentSecurityPolicyDirectiveList::create(*this, String(begin, position - begin), type, policyFrom));
195
196         // Skip the comma, and begin the next header from the current position.
197         ASSERT(position == end || *position == ',');
198         skipExactly<UChar>(position, end, ',');
199         begin = position;
200     }
201
202     if (m_scriptExecutionContext)
203         applyPolicyToScriptExecutionContext();
204 }
205
206 void ContentSecurityPolicy::updateSourceSelf(const SecurityOrigin& securityOrigin)
207 {
208     m_selfSourceProtocol = securityOrigin.protocol();
209     m_selfSource = std::make_unique<ContentSecurityPolicySource>(*this, m_selfSourceProtocol, securityOrigin.host(), securityOrigin.port(), emptyString(), false, false);
210 }
211
212 void ContentSecurityPolicy::applyPolicyToScriptExecutionContext()
213 {
214     ASSERT(m_scriptExecutionContext);
215
216     // Update source self as the security origin may have changed between the time we were created and now.
217     // For instance, we may have been initially created for an about:blank iframe that later inherited the
218     // security origin of its owner document.
219     ASSERT(m_scriptExecutionContext->securityOrigin());
220     updateSourceSelf(*m_scriptExecutionContext->securityOrigin());
221
222     bool enableStrictMixedContentMode = false;
223     for (auto& policy : m_policies) {
224         const ContentSecurityPolicyDirective* violatedDirective = policy->violatedDirectiveForUnsafeEval();
225         if (violatedDirective && !violatedDirective->directiveList().isReportOnly())
226             m_lastPolicyEvalDisabledErrorMessage = policy->evalDisabledErrorMessage();
227         if (policy->hasBlockAllMixedContentDirective() && !policy->isReportOnly())
228             enableStrictMixedContentMode = true;
229     }
230
231     if (!m_lastPolicyEvalDisabledErrorMessage.isNull())
232         m_scriptExecutionContext->disableEval(m_lastPolicyEvalDisabledErrorMessage);
233     if (m_sandboxFlags != SandboxNone && is<Document>(m_scriptExecutionContext))
234         m_scriptExecutionContext->enforceSandboxFlags(m_sandboxFlags);
235     if (enableStrictMixedContentMode)
236         m_scriptExecutionContext->setStrictMixedContentMode(true);
237 }
238
239 void ContentSecurityPolicy::setOverrideAllowInlineStyle(bool value)
240 {
241     m_overrideInlineStyleAllowed = value;
242 }
243
244 bool ContentSecurityPolicy::urlMatchesSelf(const URL& url) const
245 {
246     return m_selfSource->matches(url);
247 }
248
249 bool ContentSecurityPolicy::allowContentSecurityPolicySourceStarToMatchAnyProtocol() const
250 {
251     if (Settings* settings = is<Document>(m_scriptExecutionContext) ? downcast<Document>(*m_scriptExecutionContext).settings() : nullptr)
252         return settings->allowContentSecurityPolicySourceStarToMatchAnyProtocol();
253     return false;
254 }
255
256 bool ContentSecurityPolicy::protocolMatchesSelf(const URL& url) const
257 {
258     if (equalLettersIgnoringASCIICase(m_selfSourceProtocol, "http"))
259         return url.protocolIsInHTTPFamily();
260     return equalIgnoringASCIICase(url.protocol(), m_selfSourceProtocol);
261 }
262
263 template<typename Predicate, typename... Args>
264 typename std::enable_if<!std::is_convertible<Predicate, ContentSecurityPolicy::ViolatedDirectiveCallback>::value, bool>::type ContentSecurityPolicy::allPoliciesWithDispositionAllow(Disposition disposition, Predicate&& predicate, Args&&... args) const
265 {
266     bool isReportOnly = disposition == ContentSecurityPolicy::Disposition::ReportOnly;
267     for (auto& policy : m_policies) {
268         if (policy->isReportOnly() != isReportOnly)
269             continue;
270         if ((policy.get()->*predicate)(std::forward<Args>(args)...))
271             return false;
272     }
273     return true;
274 }
275
276 template<typename Predicate, typename... Args>
277 bool ContentSecurityPolicy::allPoliciesWithDispositionAllow(Disposition disposition, ViolatedDirectiveCallback&& callback, Predicate&& predicate, Args&&... args) const
278 {
279     bool isReportOnly = disposition == ContentSecurityPolicy::Disposition::ReportOnly;
280     bool isAllowed = true;
281     for (auto& policy : m_policies) {
282         if (policy->isReportOnly() != isReportOnly)
283             continue;
284         if (const ContentSecurityPolicyDirective* violatedDirective = (policy.get()->*predicate)(std::forward<Args>(args)...)) {
285             isAllowed = false;
286             callback(*violatedDirective);
287         }
288     }
289     return isAllowed;
290 }
291
292 template<typename Predicate, typename... Args>
293 bool ContentSecurityPolicy::allPoliciesAllow(ViolatedDirectiveCallback&& callback, Predicate&& predicate, Args&&... args) const
294 {
295     bool isAllowed = true;
296     for (auto& policy : m_policies) {
297         if (const ContentSecurityPolicyDirective* violatedDirective = (policy.get()->*predicate)(std::forward<Args>(args)...)) {
298             if (!violatedDirective->directiveList().isReportOnly())
299                 isAllowed = false;
300             callback(*violatedDirective);
301         }
302     }
303     return isAllowed;
304 }
305
306 static CryptoDigest::Algorithm toCryptoDigestAlgorithm(ContentSecurityPolicyHashAlgorithm algorithm)
307 {
308     switch (algorithm) {
309     case ContentSecurityPolicyHashAlgorithm::SHA_256:
310         return CryptoDigest::Algorithm::SHA_256;
311     case ContentSecurityPolicyHashAlgorithm::SHA_384:
312         return CryptoDigest::Algorithm::SHA_384;
313     case ContentSecurityPolicyHashAlgorithm::SHA_512:
314         return CryptoDigest::Algorithm::SHA_512;
315     }
316     ASSERT_NOT_REACHED();
317     return CryptoDigest::Algorithm::SHA_512;
318 }
319
320 template<typename Predicate>
321 ContentSecurityPolicy::HashInEnforcedAndReportOnlyPoliciesPair ContentSecurityPolicy::findHashOfContentInPolicies(Predicate&& predicate, const String& content, OptionSet<ContentSecurityPolicyHashAlgorithm> algorithms) const
322 {
323     if (algorithms.isEmpty() || content.isEmpty())
324         return { false, false };
325
326     // FIXME: We should compute the document encoding once and cache it instead of computing it on each invocation.
327     TextEncoding documentEncoding;
328     if (is<Document>(m_scriptExecutionContext))
329         documentEncoding = downcast<Document>(*m_scriptExecutionContext).textEncoding();
330     const TextEncoding& encodingToUse = documentEncoding.isValid() ? documentEncoding : UTF8Encoding();
331
332     // FIXME: Compute the digest with respect to the raw bytes received from the page.
333     // See <https://bugs.webkit.org/show_bug.cgi?id=155184>.
334     CString contentCString = encodingToUse.encode(content, EntitiesForUnencodables);
335     bool foundHashInEnforcedPolicies = false;
336     bool foundHashInReportOnlyPolicies = false;
337     for (auto algorithm : algorithms) {
338         auto cryptoDigest = CryptoDigest::create(toCryptoDigestAlgorithm(algorithm));
339         cryptoDigest->addBytes(contentCString.data(), contentCString.length());
340         ContentSecurityPolicyHash hash = { algorithm, cryptoDigest->computeHash() };
341         if (!foundHashInEnforcedPolicies && allPoliciesWithDispositionAllow(ContentSecurityPolicy::Disposition::Enforce, std::forward<Predicate>(predicate), hash))
342             foundHashInEnforcedPolicies = true;
343         if (!foundHashInReportOnlyPolicies && allPoliciesWithDispositionAllow(ContentSecurityPolicy::Disposition::ReportOnly, std::forward<Predicate>(predicate), hash))
344             foundHashInReportOnlyPolicies = true;
345         if (foundHashInEnforcedPolicies && foundHashInReportOnlyPolicies)
346             break;
347     }
348     return { foundHashInEnforcedPolicies, foundHashInReportOnlyPolicies };
349 }
350
351 bool ContentSecurityPolicy::allowJavaScriptURLs(const String& contextURL, const WTF::OrdinalNumber& contextLine, bool overrideContentSecurityPolicy) const
352 {
353     if (overrideContentSecurityPolicy)
354         return true;
355     auto handleViolatedDirective = [&] (const ContentSecurityPolicyDirective& violatedDirective) {
356         String consoleMessage = consoleMessageForViolation(ContentSecurityPolicyDirectiveNames::scriptSrc, violatedDirective, URL(), "Refused to execute a script", "its hash, its nonce, or 'unsafe-inline'");
357         reportViolation(ContentSecurityPolicyDirectiveNames::scriptSrc, violatedDirective, URL(), consoleMessage, contextURL, TextPosition(contextLine, WTF::OrdinalNumber()));
358         if (!violatedDirective.directiveList().isReportOnly())
359             reportBlockedScriptExecutionToInspector(violatedDirective.text());
360     };
361     return allPoliciesAllow(WTFMove(handleViolatedDirective), &ContentSecurityPolicyDirectiveList::violatedDirectiveForUnsafeInlineScript);
362 }
363
364 bool ContentSecurityPolicy::allowInlineEventHandlers(const String& contextURL, const WTF::OrdinalNumber& contextLine, bool overrideContentSecurityPolicy) const
365 {
366     if (overrideContentSecurityPolicy)
367         return true;
368     auto handleViolatedDirective = [&] (const ContentSecurityPolicyDirective& violatedDirective) {
369         String consoleMessage = consoleMessageForViolation(ContentSecurityPolicyDirectiveNames::scriptSrc, violatedDirective, URL(), "Refused to execute a script for an inline event handler", "'unsafe-inline'");
370         reportViolation(ContentSecurityPolicyDirectiveNames::scriptSrc, violatedDirective, URL(), consoleMessage, contextURL, TextPosition(contextLine, WTF::OrdinalNumber()));
371         if (!violatedDirective.directiveList().isReportOnly())
372             reportBlockedScriptExecutionToInspector(violatedDirective.text());
373     };
374     return allPoliciesAllow(WTFMove(handleViolatedDirective), &ContentSecurityPolicyDirectiveList::violatedDirectiveForUnsafeInlineScript);
375 }
376
377 bool ContentSecurityPolicy::allowScriptWithNonce(const String& nonce, bool overrideContentSecurityPolicy) const
378 {
379     if (overrideContentSecurityPolicy)
380         return true;
381     String strippedNonce = stripLeadingAndTrailingHTMLSpaces(nonce);
382     if (strippedNonce.isEmpty())
383         return false;
384     // FIXME: We need to report violations in report-only policies. See <https://bugs.webkit.org/show_bug.cgi?id=159830>.
385     return allPoliciesWithDispositionAllow(ContentSecurityPolicy::Disposition::Enforce, &ContentSecurityPolicyDirectiveList::violatedDirectiveForScriptNonce, strippedNonce);
386 }
387
388 bool ContentSecurityPolicy::allowStyleWithNonce(const String& nonce, bool overrideContentSecurityPolicy) const
389 {
390     if (overrideContentSecurityPolicy)
391         return true;
392     String strippedNonce = stripLeadingAndTrailingHTMLSpaces(nonce);
393     if (strippedNonce.isEmpty())
394         return false;
395     // FIXME: We need to report violations in report-only policies. See <https://bugs.webkit.org/show_bug.cgi?id=159830>.
396     return allPoliciesWithDispositionAllow(ContentSecurityPolicy::Disposition::Enforce, &ContentSecurityPolicyDirectiveList::violatedDirectiveForStyleNonce, strippedNonce);
397 }
398
399 bool ContentSecurityPolicy::allowInlineScript(const String& contextURL, const WTF::OrdinalNumber& contextLine, const String& scriptContent, bool overrideContentSecurityPolicy) const
400 {
401     if (overrideContentSecurityPolicy)
402         return true;
403     bool foundHashInEnforcedPolicies;
404     bool foundHashInReportOnlyPolicies;
405     std::tie(foundHashInEnforcedPolicies, foundHashInReportOnlyPolicies) = findHashOfContentInPolicies(&ContentSecurityPolicyDirectiveList::violatedDirectiveForScriptHash, scriptContent, m_hashAlgorithmsForInlineScripts);
406     if (foundHashInEnforcedPolicies && foundHashInReportOnlyPolicies)
407         return true;
408     auto handleViolatedDirective = [&] (const ContentSecurityPolicyDirective& violatedDirective) {
409         String consoleMessage = consoleMessageForViolation(ContentSecurityPolicyDirectiveNames::scriptSrc, violatedDirective, URL(), "Refused to execute a script", "its hash, its nonce, or 'unsafe-inline'");
410         reportViolation(ContentSecurityPolicyDirectiveNames::scriptSrc, violatedDirective, URL(), consoleMessage, contextURL, TextPosition(contextLine, WTF::OrdinalNumber()));
411         if (!violatedDirective.directiveList().isReportOnly())
412             reportBlockedScriptExecutionToInspector(violatedDirective.text());
413     };
414     // FIXME: We should not report that the inline script violated a policy when its hash matched a source
415     // expression in the policy and the page has more than one policy. See <https://bugs.webkit.org/show_bug.cgi?id=159832>.
416     if (!foundHashInReportOnlyPolicies)
417         allPoliciesWithDispositionAllow(ContentSecurityPolicy::Disposition::ReportOnly, handleViolatedDirective, &ContentSecurityPolicyDirectiveList::violatedDirectiveForUnsafeInlineScript);
418     return foundHashInEnforcedPolicies || allPoliciesWithDispositionAllow(ContentSecurityPolicy::Disposition::Enforce, handleViolatedDirective, &ContentSecurityPolicyDirectiveList::violatedDirectiveForUnsafeInlineScript);
419 }
420
421 bool ContentSecurityPolicy::allowInlineStyle(const String& contextURL, const WTF::OrdinalNumber& contextLine, const String& styleContent, bool overrideContentSecurityPolicy) const
422 {
423     if (overrideContentSecurityPolicy)
424         return true;
425     if (m_overrideInlineStyleAllowed)
426         return true;
427     bool foundHashInEnforcedPolicies;
428     bool foundHashInReportOnlyPolicies;
429     std::tie(foundHashInEnforcedPolicies, foundHashInReportOnlyPolicies) = findHashOfContentInPolicies(&ContentSecurityPolicyDirectiveList::violatedDirectiveForStyleHash, styleContent, m_hashAlgorithmsForInlineStylesheets);
430     if (foundHashInEnforcedPolicies && foundHashInReportOnlyPolicies)
431         return true;
432     auto handleViolatedDirective = [&] (const ContentSecurityPolicyDirective& violatedDirective) {
433         String consoleMessage = consoleMessageForViolation(ContentSecurityPolicyDirectiveNames::styleSrc, violatedDirective, URL(), "Refused to apply a stylesheet", "its hash, its nonce, or 'unsafe-inline'");
434         reportViolation(ContentSecurityPolicyDirectiveNames::styleSrc, violatedDirective, URL(), consoleMessage, contextURL, TextPosition(contextLine, WTF::OrdinalNumber()));
435     };
436     // FIXME: We should not report that the inline stylesheet violated a policy when its hash matched a source
437     // expression in the policy and the page has more than one policy. See <https://bugs.webkit.org/show_bug.cgi?id=159832>.
438     if (!foundHashInReportOnlyPolicies)
439         allPoliciesWithDispositionAllow(ContentSecurityPolicy::Disposition::ReportOnly, handleViolatedDirective, &ContentSecurityPolicyDirectiveList::violatedDirectiveForUnsafeInlineStyle);
440     return foundHashInEnforcedPolicies || allPoliciesWithDispositionAllow(ContentSecurityPolicy::Disposition::Enforce, handleViolatedDirective, &ContentSecurityPolicyDirectiveList::violatedDirectiveForUnsafeInlineStyle);
441 }
442
443 bool ContentSecurityPolicy::allowEval(JSC::ExecState* state, bool overrideContentSecurityPolicy) const
444 {
445     if (overrideContentSecurityPolicy)
446         return true;
447     auto handleViolatedDirective = [&] (const ContentSecurityPolicyDirective& violatedDirective) {
448         String consoleMessage = consoleMessageForViolation(ContentSecurityPolicyDirectiveNames::scriptSrc, violatedDirective, URL(), "Refused to execute a script", "'unsafe-eval'");
449         reportViolation(ContentSecurityPolicyDirectiveNames::scriptSrc, violatedDirective, URL(), consoleMessage, state);
450         if (!violatedDirective.directiveList().isReportOnly())
451             reportBlockedScriptExecutionToInspector(violatedDirective.text());
452     };
453     return allPoliciesAllow(WTFMove(handleViolatedDirective), &ContentSecurityPolicyDirectiveList::violatedDirectiveForUnsafeEval);
454 }
455
456 bool ContentSecurityPolicy::allowFrameAncestors(const Frame& frame, const URL& url, bool overrideContentSecurityPolicy) const
457 {
458     if (overrideContentSecurityPolicy)
459         return true;
460     Frame& topFrame = frame.tree().top();
461     if (&frame == &topFrame)
462         return true;
463     String sourceURL;
464     TextPosition sourcePosition(WTF::OrdinalNumber::beforeFirst(), WTF::OrdinalNumber());
465     auto handleViolatedDirective = [&] (const ContentSecurityPolicyDirective& violatedDirective) {
466         String consoleMessage = consoleMessageForViolation(ContentSecurityPolicyDirectiveNames::frameAncestors, violatedDirective, url, "Refused to load");
467         reportViolation(ContentSecurityPolicyDirectiveNames::frameAncestors, violatedDirective, url, consoleMessage, sourceURL, sourcePosition);
468     };
469     return allPoliciesAllow(WTFMove(handleViolatedDirective), &ContentSecurityPolicyDirectiveList::violatedDirectiveForFrameAncestor, frame);
470 }
471
472 bool ContentSecurityPolicy::allowPluginType(const String& type, const String& typeAttribute, const URL& url, bool overrideContentSecurityPolicy) const
473 {
474     if (overrideContentSecurityPolicy)
475         return true;
476     String sourceURL;
477     TextPosition sourcePosition(WTF::OrdinalNumber::beforeFirst(), WTF::OrdinalNumber());
478     auto handleViolatedDirective = [&] (const ContentSecurityPolicyDirective& violatedDirective) {
479         String consoleMessage = consoleMessageForViolation(ContentSecurityPolicyDirectiveNames::pluginTypes, violatedDirective, url, "Refused to load", "its MIME type");
480         reportViolation(ContentSecurityPolicyDirectiveNames::pluginTypes, violatedDirective, url, consoleMessage, sourceURL, sourcePosition);
481     };
482     return allPoliciesAllow(WTFMove(handleViolatedDirective), &ContentSecurityPolicyDirectiveList::violatedDirectiveForPluginType, type, typeAttribute);
483 }
484
485 bool ContentSecurityPolicy::allowObjectFromSource(const URL& url, RedirectResponseReceived redirectResponseReceived) const
486 {
487     if (SchemeRegistry::schemeShouldBypassContentSecurityPolicy(url.protocol().toStringWithoutCopying()))
488         return true;
489     // As per section object-src of the Content Security Policy Level 3 spec., <http://w3c.github.io/webappsec-csp> (Editor's Draft, 29 February 2016),
490     // "If plugin content is loaded without an associated URL (perhaps an object element lacks a data attribute, but loads some default plugin based
491     // on the specified type), it MUST be blocked if object-src's value is 'none', but will otherwise be allowed".
492     String sourceURL;
493     TextPosition sourcePosition(WTF::OrdinalNumber::beforeFirst(), WTF::OrdinalNumber());
494     auto handleViolatedDirective = [&] (const ContentSecurityPolicyDirective& violatedDirective) {
495         String consoleMessage = consoleMessageForViolation(ContentSecurityPolicyDirectiveNames::objectSrc, violatedDirective, url, "Refused to load");
496         reportViolation(ContentSecurityPolicyDirectiveNames::objectSrc, violatedDirective, url, consoleMessage, sourceURL, sourcePosition);
497     };
498     return allPoliciesAllow(WTFMove(handleViolatedDirective), &ContentSecurityPolicyDirectiveList::violatedDirectiveForObjectSource, url, redirectResponseReceived == RedirectResponseReceived::Yes, ContentSecurityPolicySourceListDirective::ShouldAllowEmptyURLIfSourceListIsNotNone::Yes);
499 }
500
501 bool ContentSecurityPolicy::allowChildFrameFromSource(const URL& url, RedirectResponseReceived redirectResponseReceived) const
502 {
503     if (SchemeRegistry::schemeShouldBypassContentSecurityPolicy(url.protocol().toStringWithoutCopying()))
504         return true;
505     String sourceURL;
506     TextPosition sourcePosition(WTF::OrdinalNumber::beforeFirst(), WTF::OrdinalNumber());
507     auto handleViolatedDirective = [&] (const ContentSecurityPolicyDirective& violatedDirective) {
508         const char* effectiveViolatedDirective = violatedDirective.name() == ContentSecurityPolicyDirectiveNames::frameSrc ? ContentSecurityPolicyDirectiveNames::frameSrc : ContentSecurityPolicyDirectiveNames::childSrc;
509         String consoleMessage = consoleMessageForViolation(effectiveViolatedDirective, violatedDirective, url, "Refused to load");
510         reportViolation(effectiveViolatedDirective, violatedDirective, url, consoleMessage, sourceURL, sourcePosition);
511     };
512     return allPoliciesAllow(WTFMove(handleViolatedDirective), &ContentSecurityPolicyDirectiveList::violatedDirectiveForFrame, url, redirectResponseReceived == RedirectResponseReceived::Yes);
513 }
514
515 bool ContentSecurityPolicy::allowResourceFromSource(const URL& url, RedirectResponseReceived redirectResponseReceived, const char* name, ResourcePredicate resourcePredicate) const
516 {
517     if (SchemeRegistry::schemeShouldBypassContentSecurityPolicy(url.protocol().toStringWithoutCopying()))
518         return true;
519     String sourceURL;
520     TextPosition sourcePosition(WTF::OrdinalNumber::beforeFirst(), WTF::OrdinalNumber());
521     auto handleViolatedDirective = [&] (const ContentSecurityPolicyDirective& violatedDirective) {
522         String consoleMessage = consoleMessageForViolation(name, violatedDirective, url, "Refused to load");
523         reportViolation(name, violatedDirective, url, consoleMessage, sourceURL, sourcePosition);
524     };
525     return allPoliciesAllow(WTFMove(handleViolatedDirective), resourcePredicate, url, redirectResponseReceived == RedirectResponseReceived::Yes);
526 }
527
528 bool ContentSecurityPolicy::allowChildContextFromSource(const URL& url, RedirectResponseReceived redirectResponseReceived) const
529 {
530     return allowResourceFromSource(url, redirectResponseReceived, ContentSecurityPolicyDirectiveNames::childSrc, &ContentSecurityPolicyDirectiveList::violatedDirectiveForChildContext);
531 }
532
533 bool ContentSecurityPolicy::allowScriptFromSource(const URL& url, RedirectResponseReceived redirectResponseReceived) const
534 {
535     return allowResourceFromSource(url, redirectResponseReceived, ContentSecurityPolicyDirectiveNames::scriptSrc, &ContentSecurityPolicyDirectiveList::violatedDirectiveForScript);
536 }
537
538 bool ContentSecurityPolicy::allowImageFromSource(const URL& url, RedirectResponseReceived redirectResponseReceived) const
539 {
540     return allowResourceFromSource(url, redirectResponseReceived, ContentSecurityPolicyDirectiveNames::imgSrc, &ContentSecurityPolicyDirectiveList::violatedDirectiveForImage);
541 }
542
543 bool ContentSecurityPolicy::allowStyleFromSource(const URL& url, RedirectResponseReceived redirectResponseReceived) const
544 {
545     return allowResourceFromSource(url, redirectResponseReceived, ContentSecurityPolicyDirectiveNames::styleSrc, &ContentSecurityPolicyDirectiveList::violatedDirectiveForStyle);
546 }
547
548 bool ContentSecurityPolicy::allowFontFromSource(const URL& url, RedirectResponseReceived redirectResponseReceived) const
549 {
550     return allowResourceFromSource(url, redirectResponseReceived, ContentSecurityPolicyDirectiveNames::fontSrc, &ContentSecurityPolicyDirectiveList::violatedDirectiveForFont);
551 }
552
553 bool ContentSecurityPolicy::allowMediaFromSource(const URL& url, RedirectResponseReceived redirectResponseReceived) const
554 {
555     return allowResourceFromSource(url, redirectResponseReceived, ContentSecurityPolicyDirectiveNames::mediaSrc, &ContentSecurityPolicyDirectiveList::violatedDirectiveForMedia);
556 }
557
558 bool ContentSecurityPolicy::allowConnectToSource(const URL& url, RedirectResponseReceived redirectResponseReceived) const
559 {
560     if (SchemeRegistry::schemeShouldBypassContentSecurityPolicy(url.protocol().toStringWithoutCopying()))
561         return true;
562     String sourceURL;
563     TextPosition sourcePosition(WTF::OrdinalNumber::beforeFirst(), WTF::OrdinalNumber());
564     auto handleViolatedDirective = [&] (const ContentSecurityPolicyDirective& violatedDirective) {
565         String consoleMessage = consoleMessageForViolation(ContentSecurityPolicyDirectiveNames::connectSrc, violatedDirective, url, "Refused to connect to");
566         reportViolation(ContentSecurityPolicyDirectiveNames::connectSrc, violatedDirective, url, consoleMessage, sourceURL, sourcePosition);
567     };
568     return allPoliciesAllow(WTFMove(handleViolatedDirective), &ContentSecurityPolicyDirectiveList::violatedDirectiveForConnectSource, url, redirectResponseReceived == RedirectResponseReceived::Yes);
569 }
570
571 bool ContentSecurityPolicy::allowFormAction(const URL& url, RedirectResponseReceived redirectResponseReceived) const
572 {
573     return allowResourceFromSource(url, redirectResponseReceived, ContentSecurityPolicyDirectiveNames::formAction, &ContentSecurityPolicyDirectiveList::violatedDirectiveForFormAction);
574 }
575
576 bool ContentSecurityPolicy::allowBaseURI(const URL& url, bool overrideContentSecurityPolicy) const
577 {
578     if (overrideContentSecurityPolicy)
579         return true;
580     if (SchemeRegistry::schemeShouldBypassContentSecurityPolicy(url.protocol().toStringWithoutCopying()))
581         return true;
582     String sourceURL;
583     TextPosition sourcePosition(WTF::OrdinalNumber::beforeFirst(), WTF::OrdinalNumber());
584     auto handleViolatedDirective = [&] (const ContentSecurityPolicyDirective& violatedDirective) {
585         String consoleMessage = consoleMessageForViolation(ContentSecurityPolicyDirectiveNames::baseURI, violatedDirective, url, "Refused to change the document base URL to");
586         reportViolation(ContentSecurityPolicyDirectiveNames::baseURI, violatedDirective, url, consoleMessage, sourceURL, sourcePosition);
587     };
588     return allPoliciesAllow(WTFMove(handleViolatedDirective), &ContentSecurityPolicyDirectiveList::violatedDirectiveForBaseURI, url);
589 }
590
591 static String stripURLForUseInReport(Document& document, const URL& url)
592 {
593     if (!url.isValid())
594         return String();
595     if (!url.isHierarchical() || url.protocolIs("file"))
596         return url.protocol().toString();
597     return document.securityOrigin()->canRequest(url) ? url.strippedForUseAsReferrer() : SecurityOrigin::create(url).get().toString();
598 }
599
600 void ContentSecurityPolicy::reportViolation(const String& violatedDirective, const ContentSecurityPolicyDirective& effectiveViolatedDirective, const URL& blockedURL, const String& consoleMessage, JSC::ExecState* state) const
601 {
602     // FIXME: Extract source file and source position from JSC::ExecState.
603     return reportViolation(violatedDirective, effectiveViolatedDirective.text(), effectiveViolatedDirective.directiveList(), blockedURL, consoleMessage, String(), TextPosition(WTF::OrdinalNumber::beforeFirst(), WTF::OrdinalNumber::beforeFirst()), state);
604 }
605
606 void ContentSecurityPolicy::reportViolation(const String& effectiveViolatedDirective, const String& violatedDirective, const ContentSecurityPolicyDirectiveList& violatedDirectiveList, const URL& blockedURL, const String& consoleMessage, JSC::ExecState* state) const
607 {
608     // FIXME: Extract source file and source position from JSC::ExecState.
609     return reportViolation(effectiveViolatedDirective, violatedDirective, violatedDirectiveList, blockedURL, consoleMessage, String(), TextPosition(WTF::OrdinalNumber::beforeFirst(), WTF::OrdinalNumber::beforeFirst()), state);
610 }
611
612 void ContentSecurityPolicy::reportViolation(const String& effectiveViolatedDirective, const ContentSecurityPolicyDirective& violatedDirective, const URL& blockedURL, const String& consoleMessage, const String& sourceURL, const TextPosition& sourcePosition, JSC::ExecState* state) const
613 {
614     return reportViolation(effectiveViolatedDirective, violatedDirective.text(), violatedDirective.directiveList(), blockedURL, consoleMessage, sourceURL, sourcePosition, state);
615 }
616
617 void ContentSecurityPolicy::reportViolation(const String& effectiveViolatedDirective, const String& violatedDirective, const ContentSecurityPolicyDirectiveList& violatedDirectiveList, const URL& blockedURL, const String& consoleMessage, const String& sourceURL, const TextPosition& sourcePosition, JSC::ExecState* state) const
618 {
619     logToConsole(consoleMessage, sourceURL, sourcePosition.m_line, state);
620
621     if (!m_isReportingEnabled)
622         return;
623
624     // FIXME: Support sending reports from worker.
625     if (!is<Document>(m_scriptExecutionContext) && !m_frame)
626         return;
627
628     ASSERT(!m_frame || effectiveViolatedDirective == ContentSecurityPolicyDirectiveNames::frameAncestors);
629
630     Document& document = is<Document>(m_scriptExecutionContext) ? downcast<Document>(*m_scriptExecutionContext) : *m_frame->document();
631     Frame* frame = document.frame();
632     ASSERT(!m_frame || m_frame == frame);
633     if (!frame)
634         return;
635
636     String documentURI;
637     String blockedURI;
638     if (is<Document>(m_scriptExecutionContext)) {
639         documentURI = document.url().strippedForUseAsReferrer();
640         blockedURI = stripURLForUseInReport(document, blockedURL);
641     } else {
642         // The URL of |document| may not have been initialized (say, when reporting a frame-ancestors violation).
643         // So, we use the URL of the blocked document for the protected document URL.
644         documentURI = blockedURL;
645         blockedURI = blockedURL;
646     }
647     String violatedDirectiveText = violatedDirective;
648     String originalPolicy = violatedDirectiveList.header();
649     String referrer = document.referrer();
650     ASSERT(document.loader());
651     unsigned short statusCode = document.url().protocolIs("http") && document.loader() ? document.loader()->response().httpStatusCode() : 0;
652
653     String sourceFile;
654     int lineNumber = 0;
655     int columnNumber = 0;
656     RefPtr<ScriptCallStack> stack = createScriptCallStack(JSMainThreadExecState::currentState(), 2);
657     const ScriptCallFrame* callFrame = stack->firstNonNativeCallFrame();
658     if (callFrame && callFrame->lineNumber()) {
659         sourceFile = stripURLForUseInReport(document, URL(URL(), callFrame->sourceURL()));
660         lineNumber = callFrame->lineNumber();
661         columnNumber = callFrame->columnNumber();
662     }
663
664     // 1. Dispatch violation event.
665     bool canBubble = false;
666     bool cancelable = false;
667     document.enqueueDocumentEvent(SecurityPolicyViolationEvent::create(eventNames().securitypolicyviolationEvent, canBubble, cancelable, documentURI, referrer, blockedURI, violatedDirectiveText, effectiveViolatedDirective, originalPolicy, sourceFile, statusCode, lineNumber, columnNumber));
668
669     // 2. Send violation report (if applicable).
670     const Vector<String>& reportURIs = violatedDirectiveList.reportURIs();
671     if (reportURIs.isEmpty())
672         return;
673
674     // We need to be careful here when deciding what information to send to the
675     // report-uri. Currently, we send only the current document's URL and the
676     // directive that was violated. The document's URL is safe to send because
677     // it's the document itself that's requesting that it be sent. You could
678     // make an argument that we shouldn't send HTTPS document URLs to HTTP
679     // report-uris (for the same reasons that we suppress the Referer in that
680     // case), but the Referer is sent implicitly whereas this request is only
681     // sent explicitly. As for which directive was violated, that's pretty
682     // harmless information.
683
684     auto cspReport = InspectorObject::create();
685     cspReport->setString(ASCIILiteral("document-uri"), documentURI);
686     cspReport->setString(ASCIILiteral("referrer"), referrer);
687     cspReport->setString(ASCIILiteral("violated-directive"), violatedDirectiveText);
688     cspReport->setString(ASCIILiteral("effective-directive"), effectiveViolatedDirective);
689     cspReport->setString(ASCIILiteral("original-policy"), originalPolicy);
690     cspReport->setString(ASCIILiteral("blocked-uri"), blockedURI);
691     cspReport->setInteger(ASCIILiteral("status-code"), statusCode);
692     if (!sourceFile.isNull()) {
693         cspReport->setString(ASCIILiteral("source-file"), sourceFile);
694         cspReport->setInteger(ASCIILiteral("line-number"), lineNumber);
695         cspReport->setInteger(ASCIILiteral("column-number"), columnNumber);
696     }
697
698     RefPtr<InspectorObject> reportObject = InspectorObject::create();
699     reportObject->setObject(ASCIILiteral("csp-report"), WTFMove(cspReport));
700
701     RefPtr<FormData> report = FormData::create(reportObject->toJSONString().utf8());
702     for (const auto& url : reportURIs)
703         PingLoader::sendViolationReport(*frame, is<Document>(m_scriptExecutionContext) ? document.completeURL(url) : document.completeURL(url, blockedURL), report.copyRef(), ViolationReportType::ContentSecurityPolicy);
704 }
705
706 void ContentSecurityPolicy::reportUnsupportedDirective(const String& name) const
707 {
708     String message;
709     if (equalLettersIgnoringASCIICase(name, "allow"))
710         message = ASCIILiteral("The 'allow' directive has been replaced with 'default-src'. Please use that directive instead, as 'allow' has no effect.");
711     else if (equalLettersIgnoringASCIICase(name, "options"))
712         message = ASCIILiteral("The 'options' directive has been replaced with 'unsafe-inline' and 'unsafe-eval' source expressions for the 'script-src' and 'style-src' directives. Please use those directives instead, as 'options' has no effect.");
713     else if (equalLettersIgnoringASCIICase(name, "policy-uri"))
714         message = ASCIILiteral("The 'policy-uri' directive has been removed from the specification. Please specify a complete policy via the Content-Security-Policy header.");
715     else
716         message = makeString("Unrecognized Content-Security-Policy directive '", name, "'.\n"); // FIXME: Why does this include a newline?
717
718     logToConsole(message);
719 }
720
721 void ContentSecurityPolicy::reportDirectiveAsSourceExpression(const String& directiveName, const String& sourceExpression) const
722 {
723     logToConsole("The Content Security Policy directive '" + directiveName + "' contains '" + sourceExpression + "' as a source expression. Did you mean '" + directiveName + " ...; " + sourceExpression + "...' (note the semicolon)?");
724 }
725
726 void ContentSecurityPolicy::reportDuplicateDirective(const String& name) const
727 {
728     logToConsole(makeString("Ignoring duplicate Content-Security-Policy directive '", name, "'.\n"));
729 }
730
731 void ContentSecurityPolicy::reportInvalidPluginTypes(const String& pluginType) const
732 {
733     String message;
734     if (pluginType.isNull())
735         message = "'plugin-types' Content Security Policy directive is empty; all plugins will be blocked.\n";
736     else
737         message = makeString("Invalid plugin type in 'plugin-types' Content Security Policy directive: '", pluginType, "'.\n");
738     logToConsole(message);
739 }
740
741 void ContentSecurityPolicy::reportInvalidSandboxFlags(const String& invalidFlags) const
742 {
743     logToConsole("Error while parsing the 'sandbox' Content Security Policy directive: " + invalidFlags);
744 }
745
746 void ContentSecurityPolicy::reportInvalidDirectiveInReportOnlyMode(const String& directiveName) const
747 {
748     logToConsole("The Content Security Policy directive '" + directiveName + "' is ignored when delivered in a report-only policy.");
749 }
750
751 void ContentSecurityPolicy::reportInvalidDirectiveInHTTPEquivMeta(const String& directiveName) const
752 {
753     logToConsole("The Content Security Policy directive '" + directiveName + "' is ignored when delivered via an HTML meta element.");
754 }
755
756 void ContentSecurityPolicy::reportInvalidDirectiveValueCharacter(const String& directiveName, const String& value) const
757 {
758     String message = makeString("The value for Content Security Policy directive '", directiveName, "' contains an invalid character: '", value, "'. Non-whitespace characters outside ASCII 0x21-0x7E must be percent-encoded, as described in RFC 3986, section 2.1: http://tools.ietf.org/html/rfc3986#section-2.1.");
759     logToConsole(message);
760 }
761
762 void ContentSecurityPolicy::reportInvalidPathCharacter(const String& directiveName, const String& value, const char invalidChar) const
763 {
764     ASSERT(invalidChar == '#' || invalidChar == '?');
765
766     String ignoring;
767     if (invalidChar == '?')
768         ignoring = "The query component, including the '?', will be ignored.";
769     else
770         ignoring = "The fragment identifier, including the '#', will be ignored.";
771
772     String message = makeString("The source list for Content Security Policy directive '", directiveName, "' contains a source with an invalid path: '", value, "'. ", ignoring);
773     logToConsole(message);
774 }
775
776 void ContentSecurityPolicy::reportInvalidSourceExpression(const String& directiveName, const String& source) const
777 {
778     String message = makeString("The source list for Content Security Policy directive '", directiveName, "' contains an invalid source: '", source, "'. It will be ignored.");
779     if (equalLettersIgnoringASCIICase(source, "'none'"))
780         message = makeString(message, " Note that 'none' has no effect unless it is the only expression in the source list.");
781     logToConsole(message);
782 }
783
784 void ContentSecurityPolicy::reportMissingReportURI(const String& policy) const
785 {
786     logToConsole("The Content Security Policy '" + policy + "' was delivered in report-only mode, but does not specify a 'report-uri'; the policy will have no effect. Please either add a 'report-uri' directive, or deliver the policy via the 'Content-Security-Policy' header.");
787 }
788
789 void ContentSecurityPolicy::logToConsole(const String& message, const String& contextURL, const WTF::OrdinalNumber& contextLine, JSC::ExecState* state) const
790 {
791     if (!m_isReportingEnabled)
792         return;
793
794     // FIXME: <http://webkit.org/b/114317> ContentSecurityPolicy::logToConsole should include a column number
795     if (m_scriptExecutionContext)
796         m_scriptExecutionContext->addConsoleMessage(MessageSource::Security, MessageLevel::Error, message, contextURL, contextLine.oneBasedInt(), 0, state);
797     else if (m_frame && m_frame->document())
798         static_cast<ScriptExecutionContext*>(m_frame->document())->addConsoleMessage(MessageSource::Security, MessageLevel::Error, message, contextURL, contextLine.oneBasedInt(), 0, state);
799 }
800
801 void ContentSecurityPolicy::reportBlockedScriptExecutionToInspector(const String& directiveText) const
802 {
803     if (m_scriptExecutionContext)
804         InspectorInstrumentation::scriptExecutionBlockedByCSP(m_scriptExecutionContext, directiveText);
805 }
806
807 bool ContentSecurityPolicy::experimentalFeaturesEnabled() const
808 {
809 #if ENABLE(CSP_NEXT)
810     return RuntimeEnabledFeatures::sharedFeatures().experimentalContentSecurityPolicyFeaturesEnabled();
811 #else
812     return false;
813 #endif
814 }
815
816 void ContentSecurityPolicy::upgradeInsecureRequestIfNeeded(ResourceRequest& request, InsecureRequestType requestType) const
817 {
818     URL url = request.url();
819     upgradeInsecureRequestIfNeeded(url, requestType);
820     request.setURL(url);
821 }
822
823 void ContentSecurityPolicy::upgradeInsecureRequestIfNeeded(URL& url, InsecureRequestType requestType) const
824 {
825     if (!url.protocolIs("http") && !url.protocolIs("ws"))
826         return;
827
828     bool upgradeRequest = m_insecureNavigationRequestsToUpgrade.contains(SecurityOrigin::create(url));
829     if (requestType == InsecureRequestType::Load || requestType == InsecureRequestType::FormSubmission)
830         upgradeRequest |= m_upgradeInsecureRequests;
831     
832     if (!upgradeRequest)
833         return;
834
835     if (url.protocolIs("http"))
836         url.setProtocol("https");
837     else if (url.protocolIs("ws"))
838         url.setProtocol("wss");
839     else
840         return;
841     
842     if (url.port() && url.port().value() == 80)
843         url.setPort(443);
844 }
845
846 void ContentSecurityPolicy::setUpgradeInsecureRequests(bool upgradeInsecureRequests)
847 {
848     m_upgradeInsecureRequests = upgradeInsecureRequests;
849     if (!m_upgradeInsecureRequests)
850         return;
851
852     if (!m_scriptExecutionContext)
853         return;
854
855     // Store the upgrade domain as an 'insecure' protocol so we can quickly identify
856     // origins we should upgrade.
857     URL upgradeURL = m_scriptExecutionContext->url();
858     if (upgradeURL.protocolIs("https"))
859         upgradeURL.setProtocol("http");
860     else if (upgradeURL.protocolIs("wss"))
861         upgradeURL.setProtocol("ws");
862     
863     m_insecureNavigationRequestsToUpgrade.add(SecurityOrigin::create(upgradeURL));
864 }
865
866 void ContentSecurityPolicy::inheritInsecureNavigationRequestsToUpgradeFromOpener(const ContentSecurityPolicy& other)
867 {
868     m_insecureNavigationRequestsToUpgrade.add(other.m_insecureNavigationRequestsToUpgrade.begin(), other.m_insecureNavigationRequestsToUpgrade.end());
869 }
870
871 HashSet<RefPtr<SecurityOrigin>>&& ContentSecurityPolicy::takeNavigationRequestsToUpgrade()
872 {
873     return WTFMove(m_insecureNavigationRequestsToUpgrade);
874 }
875
876 void ContentSecurityPolicy::setInsecureNavigationRequestsToUpgrade(HashSet<RefPtr<SecurityOrigin>>&& insecureNavigationRequests)
877 {
878     m_insecureNavigationRequestsToUpgrade = WTFMove(insecureNavigationRequests);
879 }
880
881 }