Move URL from WebCore to WTF
[WebKit-https.git] / Source / WebCore / page / csp / ContentSecurityPolicy.h
1 /*
2  * Copyright (C) 2011 Google, Inc. All rights reserved.
3  * Copyright (C) 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 #pragma once
28
29 #include "ContentSecurityPolicyHash.h"
30 #include "ContentSecurityPolicyResponseHeaders.h"
31 #include "SecurityContext.h"
32 #include "SecurityOrigin.h"
33 #include "SecurityOriginHash.h"
34 #include <functional>
35 #include <wtf/HashSet.h>
36 #include <wtf/Vector.h>
37 #include <wtf/text/TextPosition.h>
38
39 namespace JSC {
40 class ExecState;
41 }
42
43 namespace WTF {
44 class OrdinalNumber;
45 }
46
47 namespace WebCore {
48
49 class ContentSecurityPolicyDirective;
50 class ContentSecurityPolicyDirectiveList;
51 class ContentSecurityPolicySource;
52 class DOMStringList;
53 class Frame;
54 class JSWindowProxy;
55 class ResourceRequest;
56 class ScriptExecutionContext;
57 class SecurityOrigin;
58 class TextEncoding;
59 struct ContentSecurityPolicyClient;
60
61 typedef Vector<std::unique_ptr<ContentSecurityPolicyDirectiveList>> CSPDirectiveListVector;
62
63 class ContentSecurityPolicy {
64     WTF_MAKE_FAST_ALLOCATED;
65 public:
66     explicit ContentSecurityPolicy(URL&&, ScriptExecutionContext&);
67     WEBCORE_EXPORT explicit ContentSecurityPolicy(URL&&, ContentSecurityPolicyClient* = nullptr);
68     WEBCORE_EXPORT ~ContentSecurityPolicy();
69
70     void copyStateFrom(const ContentSecurityPolicy*);
71     void copyUpgradeInsecureRequestStateFrom(const ContentSecurityPolicy&);
72     void createPolicyForPluginDocumentFrom(const ContentSecurityPolicy&);
73
74     void didCreateWindowProxy(JSWindowProxy&) const;
75
76     enum class PolicyFrom {
77         API,
78         HTTPEquivMeta,
79         HTTPHeader,
80         Inherited,
81         InheritedForPluginDocument,
82     };
83     WEBCORE_EXPORT ContentSecurityPolicyResponseHeaders responseHeaders() const;
84     enum ReportParsingErrors { No, Yes };
85     WEBCORE_EXPORT void didReceiveHeaders(const ContentSecurityPolicyResponseHeaders&, String&& referrer, ReportParsingErrors = ReportParsingErrors::Yes);
86     void didReceiveHeader(const String&, ContentSecurityPolicyHeaderType, ContentSecurityPolicy::PolicyFrom, String&& referrer, int httpStatusCode = 0);
87
88     bool allowScriptWithNonce(const String& nonce, bool overrideContentSecurityPolicy = false) const;
89     bool allowStyleWithNonce(const String& nonce, bool overrideContentSecurityPolicy = false) const;
90
91     bool allowJavaScriptURLs(const String& contextURL, const WTF::OrdinalNumber& contextLine, bool overrideContentSecurityPolicy = false) const;
92     bool allowInlineEventHandlers(const String& contextURL, const WTF::OrdinalNumber& contextLine, bool overrideContentSecurityPolicy = false) const;
93     bool allowInlineScript(const String& contextURL, const WTF::OrdinalNumber& contextLine, const String& scriptContent, bool overrideContentSecurityPolicy = false) const;
94     bool allowInlineStyle(const String& contextURL, const WTF::OrdinalNumber& contextLine, const String& styleContent, bool overrideContentSecurityPolicy = false) const;
95
96     bool allowEval(JSC::ExecState*, bool overrideContentSecurityPolicy = false) const;
97
98     bool allowPluginType(const String& type, const String& typeAttribute, const URL&, bool overrideContentSecurityPolicy = false) const;
99
100     bool allowFrameAncestors(const Frame&, const URL&, bool overrideContentSecurityPolicy = false) const;
101     WEBCORE_EXPORT bool allowFrameAncestors(const Vector<RefPtr<SecurityOrigin>>& ancestorOrigins, const URL&, bool overrideContentSecurityPolicy = false) const;
102
103     enum class RedirectResponseReceived { No, Yes };
104     WEBCORE_EXPORT bool allowScriptFromSource(const URL&, RedirectResponseReceived = RedirectResponseReceived::No) const;
105     bool allowImageFromSource(const URL&, RedirectResponseReceived = RedirectResponseReceived::No) const;
106     bool allowStyleFromSource(const URL&, RedirectResponseReceived = RedirectResponseReceived::No) const;
107     bool allowFontFromSource(const URL&, RedirectResponseReceived = RedirectResponseReceived::No) const;
108 #if ENABLE(APPLICATION_MANIFEST)
109     bool allowManifestFromSource(const URL&, RedirectResponseReceived = RedirectResponseReceived::No) const;
110 #endif
111     bool allowMediaFromSource(const URL&, RedirectResponseReceived = RedirectResponseReceived::No) const;
112
113     bool allowChildFrameFromSource(const URL&, RedirectResponseReceived = RedirectResponseReceived::No) const;
114     WEBCORE_EXPORT bool allowChildContextFromSource(const URL&, RedirectResponseReceived = RedirectResponseReceived::No) const;
115     WEBCORE_EXPORT bool allowConnectToSource(const URL&, RedirectResponseReceived = RedirectResponseReceived::No) const;
116     bool allowFormAction(const URL&, RedirectResponseReceived = RedirectResponseReceived::No) const;
117
118     bool allowObjectFromSource(const URL&, RedirectResponseReceived = RedirectResponseReceived::No) const;
119     bool allowBaseURI(const URL&, bool overrideContentSecurityPolicy = false) const;
120
121     void setOverrideAllowInlineStyle(bool);
122
123     void gatherReportURIs(DOMStringList&) const;
124
125     bool allowRunningOrDisplayingInsecureContent(const URL&);
126
127     // The following functions are used by internal data structures to call back into this object when parsing, validating,
128     // and applying a Content Security Policy.
129     // FIXME: We should make the various directives serve only as state stores for the parsed policy and remove these functions.
130     // This class should traverse the directives, validating the policy, and applying it to the script execution context.
131
132     // Used by ContentSecurityPolicyMediaListDirective
133     void reportInvalidPluginTypes(const String&) const;
134
135     // Used by ContentSecurityPolicySourceList
136     void reportDirectiveAsSourceExpression(const String& directiveName, const String& sourceExpression) const;
137     void reportInvalidPathCharacter(const String& directiveName, const String& value, const char) const;
138     void reportInvalidSourceExpression(const String& directiveName, const String& source) const;
139     bool urlMatchesSelf(const URL&) const;
140     bool allowContentSecurityPolicySourceStarToMatchAnyProtocol() const;
141
142     // Used by ContentSecurityPolicyDirectiveList
143     void reportDuplicateDirective(const String&) const;
144     void reportInvalidDirectiveValueCharacter(const String& directiveName, const String& value) const;
145     void reportInvalidSandboxFlags(const String&) const;
146     void reportInvalidDirectiveInReportOnlyMode(const String&) const;
147     void reportInvalidDirectiveInHTTPEquivMeta(const String&) const;
148     void reportMissingReportURI(const String&) const;
149     void reportUnsupportedDirective(const String&) const;
150     void enforceSandboxFlags(SandboxFlags sandboxFlags) { m_sandboxFlags |= sandboxFlags; }
151     void addHashAlgorithmsForInlineScripts(OptionSet<ContentSecurityPolicyHashAlgorithm> hashAlgorithmsForInlineScripts)
152     {
153         m_hashAlgorithmsForInlineScripts.add(hashAlgorithmsForInlineScripts);
154     }
155     void addHashAlgorithmsForInlineStylesheets(OptionSet<ContentSecurityPolicyHashAlgorithm> hashAlgorithmsForInlineStylesheets)
156     {
157         m_hashAlgorithmsForInlineStylesheets.add(hashAlgorithmsForInlineStylesheets);
158     }
159
160     // Used by ContentSecurityPolicySource
161     bool protocolMatchesSelf(const URL&) const;
162
163     void setUpgradeInsecureRequests(bool);
164     bool upgradeInsecureRequests() const { return m_upgradeInsecureRequests; }
165     enum class InsecureRequestType { Load, FormSubmission, Navigation };
166     WEBCORE_EXPORT void upgradeInsecureRequestIfNeeded(ResourceRequest&, InsecureRequestType) const;
167     WEBCORE_EXPORT void upgradeInsecureRequestIfNeeded(URL&, InsecureRequestType) const;
168
169     HashSet<SecurityOriginData> takeNavigationRequestsToUpgrade();
170     void inheritInsecureNavigationRequestsToUpgradeFromOpener(const ContentSecurityPolicy&);
171     void setInsecureNavigationRequestsToUpgrade(HashSet<SecurityOriginData>&&);
172
173     void setClient(ContentSecurityPolicyClient* client) { m_client = client; }
174
175 private:
176     void logToConsole(const String& message, const String& contextURL = String(), const WTF::OrdinalNumber& contextLine = WTF::OrdinalNumber::beforeFirst(), JSC::ExecState* = nullptr) const;
177     void updateSourceSelf(const SecurityOrigin&);
178     void applyPolicyToScriptExecutionContext();
179
180     // Implements the deprecated CSP2 "strip uri for reporting" algorithm from <https://www.w3.org/TR/CSP2/#violation-reports>.
181     String deprecatedURLForReporting(const URL&) const;
182
183     const TextEncoding& documentEncoding() const;
184
185     enum class Disposition {
186         Enforce,
187         ReportOnly,
188     };
189
190     using ViolatedDirectiveCallback = std::function<void (const ContentSecurityPolicyDirective&)>;
191
192     template<typename Predicate, typename... Args>
193     typename std::enable_if<!std::is_convertible<Predicate, ViolatedDirectiveCallback>::value, bool>::type allPoliciesWithDispositionAllow(Disposition, Predicate&&, Args&&...) const;
194
195     template<typename Predicate, typename... Args>
196     bool allPoliciesWithDispositionAllow(Disposition, ViolatedDirectiveCallback&&, Predicate&&, Args&&...) const;
197
198     template<typename Predicate, typename... Args>
199     bool allPoliciesAllow(ViolatedDirectiveCallback&&, Predicate&&, Args&&...) const WARN_UNUSED_RETURN;
200
201     using ResourcePredicate = const ContentSecurityPolicyDirective *(ContentSecurityPolicyDirectiveList::*)(const URL &, bool) const;
202     bool allowResourceFromSource(const URL&, RedirectResponseReceived, const char*, ResourcePredicate) const;
203
204     using HashInEnforcedAndReportOnlyPoliciesPair = std::pair<bool, bool>;
205     template<typename Predicate> HashInEnforcedAndReportOnlyPoliciesPair findHashOfContentInPolicies(Predicate&&, const String& content, OptionSet<ContentSecurityPolicyHashAlgorithm>) const WARN_UNUSED_RETURN;
206
207     void reportViolation(const String& effectiveViolatedDirective, const ContentSecurityPolicyDirective& violatedDirective, const URL& blockedURL, const String& consoleMessage, JSC::ExecState*) const;
208     void reportViolation(const String& effectiveViolatedDirective, const String& violatedDirective, const ContentSecurityPolicyDirectiveList&, const URL& blockedURL, const String& consoleMessage, JSC::ExecState* = nullptr) const;
209     void reportViolation(const String& effectiveViolatedDirective, const ContentSecurityPolicyDirective& violatedDirective, const URL& blockedURL, const String& consoleMessage, const String& sourceURL, const TextPosition& sourcePosition, JSC::ExecState* = nullptr) const;
210     void reportViolation(const String& effectiveViolatedDirective, const String& violatedDirective, const ContentSecurityPolicyDirectiveList& violatedDirectiveList, const URL& blockedURL, const String& consoleMessage, const String& sourceURL, const TextPosition& sourcePosition, JSC::ExecState*) const;
211     void reportBlockedScriptExecutionToInspector(const String& directiveText) const;
212
213     // We can never have both a script execution context and a ContentSecurityPolicyClient.
214     ScriptExecutionContext* m_scriptExecutionContext { nullptr };
215     ContentSecurityPolicyClient* m_client { nullptr };
216     URL m_protectedURL;
217     std::unique_ptr<ContentSecurityPolicySource> m_selfSource;
218     String m_selfSourceProtocol;
219     CSPDirectiveListVector m_policies;
220     String m_lastPolicyEvalDisabledErrorMessage;
221     String m_lastPolicyWebAssemblyDisabledErrorMessage;
222     String m_referrer;
223     SandboxFlags m_sandboxFlags { SandboxNone };
224     bool m_overrideInlineStyleAllowed { false };
225     bool m_isReportingEnabled { true };
226     bool m_upgradeInsecureRequests { false };
227     bool m_hasAPIPolicy { false };
228     int m_httpStatusCode { 0 };
229     OptionSet<ContentSecurityPolicyHashAlgorithm> m_hashAlgorithmsForInlineScripts;
230     OptionSet<ContentSecurityPolicyHashAlgorithm> m_hashAlgorithmsForInlineStylesheets;
231     HashSet<SecurityOriginData> m_insecureNavigationRequestsToUpgrade;
232     mutable std::optional<ContentSecurityPolicyResponseHeaders> m_cachedResponseHeaders;
233 };
234
235 }