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