dbeda87e4b8e9105db8f0728db9afe81197764e1
[WebKit-https.git] / Source / WebCore / loader / PolicyChecker.cpp
1 /*
2  * Copyright (C) 2006-2016 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
4  * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer. 
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution. 
15  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission. 
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "PolicyChecker.h"
33
34 #include "ContentFilter.h"
35 #include "ContentSecurityPolicy.h"
36 #include "DOMWindow.h"
37 #include "DocumentLoader.h"
38 #include "Event.h"
39 #include "EventNames.h"
40 #include "FormState.h"
41 #include "Frame.h"
42 #include "FrameLoader.h"
43 #include "FrameLoaderClient.h"
44 #include "HTMLFormElement.h"
45 #include "HTMLFrameOwnerElement.h"
46 #include "HTMLPlugInElement.h"
47
48 #if USE(QUICK_LOOK)
49 #include "QuickLook.h"
50 #endif
51
52 namespace WebCore {
53
54 static bool isAllowedByContentSecurityPolicy(const URL& url, const Element* ownerElement, bool didReceiveRedirectResponse)
55 {
56     if (!ownerElement)
57         return true;
58     // Elements in user agent show tree should load whatever the embedding document policy is.
59     if (ownerElement->isInUserAgentShadowTree())
60         return true;
61
62     auto redirectResponseReceived = didReceiveRedirectResponse ? ContentSecurityPolicy::RedirectResponseReceived::Yes : ContentSecurityPolicy::RedirectResponseReceived::No;
63
64     ASSERT(ownerElement->document().contentSecurityPolicy());
65     if (is<HTMLPlugInElement>(ownerElement))
66         return ownerElement->document().contentSecurityPolicy()->allowObjectFromSource(url, redirectResponseReceived);
67     return ownerElement->document().contentSecurityPolicy()->allowChildFrameFromSource(url, redirectResponseReceived);
68 }
69
70 PolicyChecker::PolicyChecker(Frame& frame)
71     : m_frame(frame)
72     , m_delegateIsDecidingNavigationPolicy(false)
73     , m_delegateIsHandlingUnimplementablePolicy(false)
74     , m_loadType(FrameLoadType::Standard)
75 {
76 }
77
78 void PolicyChecker::checkNavigationPolicy(const ResourceRequest& newRequest, bool didReceiveRedirectResponse, NavigationPolicyDecisionFunction function)
79 {
80     checkNavigationPolicy(newRequest, didReceiveRedirectResponse, m_frame.loader().activeDocumentLoader(), nullptr, WTFMove(function));
81 }
82
83 void PolicyChecker::checkNavigationPolicy(const ResourceRequest& request, bool didReceiveRedirectResponse, DocumentLoader* loader, FormState* formState, NavigationPolicyDecisionFunction function)
84 {
85     NavigationAction action = loader->triggeringAction();
86     if (action.isEmpty()) {
87         action = NavigationAction { *m_frame.document(), request, NavigationType::Other, loader->shouldOpenExternalURLsPolicyToPropagate() };
88         loader->setTriggeringAction(action);
89     }
90
91     // Don't ask more than once for the same request or if we are loading an empty URL.
92     // This avoids confusion on the part of the client.
93     if (equalIgnoringHeaderFields(request, loader->lastCheckedRequest()) || (!request.isNull() && request.url().isEmpty())) {
94         function(request, 0, true);
95         loader->setLastCheckedRequest(request);
96         return;
97     }
98
99     // We are always willing to show alternate content for unreachable URLs;
100     // treat it like a reload so it maintains the right state for b/f list.
101     auto& substituteData = loader->substituteData();
102     if (substituteData.isValid() && !substituteData.failingURL().isEmpty()) {
103         bool shouldContinue = true;
104 #if ENABLE(CONTENT_FILTERING)
105         shouldContinue = ContentFilter::continueAfterSubstituteDataRequest(*m_frame.loader().activeDocumentLoader(), substituteData);
106 #endif
107         if (isBackForwardLoadType(m_loadType))
108             m_loadType = FrameLoadType::Reload;
109         function(request, 0, shouldContinue);
110         return;
111     }
112
113     if (!isAllowedByContentSecurityPolicy(request.url(), m_frame.ownerElement(), didReceiveRedirectResponse)) {
114         if (m_frame.ownerElement()) {
115             // Fire a load event (even though we were blocked by CSP) as timing attacks would otherwise
116             // reveal that the frame was blocked. This way, it looks like any other cross-origin page load.
117             m_frame.ownerElement()->dispatchEvent(Event::create(eventNames().loadEvent, false, false));
118         }
119         function(request, 0, false);
120         return;
121     }
122
123     loader->setLastCheckedRequest(request);
124
125     m_callback.set(request, formState, WTFMove(function));
126
127 #if USE(QUICK_LOOK)
128     // Always allow QuickLook-generated URLs based on the protocol scheme.
129     if (!request.isNull() && isQuickLookPreviewURL(request.url())) {
130         continueAfterNavigationPolicy(PolicyUse);
131         return;
132     }
133 #endif
134
135 #if ENABLE(CONTENT_FILTERING)
136     if (m_contentFilterUnblockHandler.canHandleRequest(request)) {
137         RefPtr<Frame> frame { &m_frame };
138         m_contentFilterUnblockHandler.requestUnblockAsync([frame](bool unblocked) {
139             if (unblocked)
140                 frame->loader().reload();
141         });
142         continueAfterNavigationPolicy(PolicyIgnore);
143         return;
144     }
145     m_contentFilterUnblockHandler = { };
146 #endif
147
148     m_delegateIsDecidingNavigationPolicy = true;
149     m_suggestedFilename = action.downloadAttribute().isEmpty() ? nullAtom : action.downloadAttribute();
150     m_frame.loader().client().dispatchDecidePolicyForNavigationAction(action, request, formState, [this](PolicyAction action) {
151         continueAfterNavigationPolicy(action);
152     });
153     m_delegateIsDecidingNavigationPolicy = false;
154 }
155
156 void PolicyChecker::checkNewWindowPolicy(const NavigationAction& action, const ResourceRequest& request, FormState* formState, const String& frameName, NewWindowPolicyDecisionFunction function)
157 {
158     if (m_frame.document() && m_frame.document()->isSandboxed(SandboxPopups))
159         return continueAfterNavigationPolicy(PolicyIgnore);
160
161     if (!DOMWindow::allowPopUp(m_frame))
162         return continueAfterNavigationPolicy(PolicyIgnore);
163
164     m_callback.set(request, formState, frameName, action, WTFMove(function));
165     m_frame.loader().client().dispatchDecidePolicyForNewWindowAction(action, request, formState, frameName, [this](PolicyAction action) {
166         continueAfterNewWindowPolicy(action);
167     });
168 }
169
170 void PolicyChecker::checkContentPolicy(const ResourceResponse& response, ContentPolicyDecisionFunction function)
171 {
172     m_callback.set(WTFMove(function));
173     m_frame.loader().client().dispatchDecidePolicyForResponse(response, m_frame.loader().activeDocumentLoader()->request(), [this](PolicyAction action) {
174         continueAfterContentPolicy(action);
175     });
176 }
177
178 void PolicyChecker::cancelCheck()
179 {
180     m_frame.loader().client().cancelPolicyCheck();
181     m_callback = { };
182 }
183
184 void PolicyChecker::stopCheck()
185 {
186     m_frame.loader().client().cancelPolicyCheck();
187     PolicyCallback callback = WTFMove(m_callback);
188     callback.cancel();
189 }
190
191 void PolicyChecker::cannotShowMIMEType(const ResourceResponse& response)
192 {
193     handleUnimplementablePolicy(m_frame.loader().client().cannotShowMIMETypeError(response));
194 }
195
196 void PolicyChecker::continueLoadAfterWillSubmitForm(PolicyAction)
197 {
198     // See header file for an explaination of why this function
199     // isn't like the others.
200     m_frame.loader().continueLoadAfterWillSubmitForm();
201 }
202
203 void PolicyChecker::continueAfterNavigationPolicy(PolicyAction policy)
204 {
205     PolicyCallback callback = WTFMove(m_callback);
206
207     bool shouldContinue = policy == PolicyUse;
208
209     switch (policy) {
210         case PolicyIgnore:
211             callback.clearRequest();
212             break;
213         case PolicyDownload: {
214             ResourceRequest request = callback.request();
215             m_frame.loader().setOriginalURLForDownloadRequest(request);
216             m_frame.loader().client().startDownload(request, m_suggestedFilename);
217             callback.clearRequest();
218             break;
219         }
220         case PolicyUse: {
221             ResourceRequest request(callback.request());
222
223             if (!m_frame.loader().client().canHandleRequest(request)) {
224                 handleUnimplementablePolicy(m_frame.loader().client().cannotShowURLError(callback.request()));
225                 callback.clearRequest();
226                 shouldContinue = false;
227             }
228             break;
229         }
230     }
231
232     callback.call(shouldContinue);
233 }
234
235 void PolicyChecker::continueAfterNewWindowPolicy(PolicyAction policy)
236 {
237     PolicyCallback callback = WTFMove(m_callback);
238
239     switch (policy) {
240         case PolicyIgnore:
241             callback.clearRequest();
242             break;
243         case PolicyDownload:
244             m_frame.loader().client().startDownload(callback.request());
245             callback.clearRequest();
246             break;
247         case PolicyUse:
248             break;
249     }
250
251     callback.call(policy == PolicyUse);
252 }
253
254 void PolicyChecker::continueAfterContentPolicy(PolicyAction policy)
255 {
256     PolicyCallback callback = WTFMove(m_callback);
257     callback.call(policy);
258 }
259
260 void PolicyChecker::handleUnimplementablePolicy(const ResourceError& error)
261 {
262     m_delegateIsHandlingUnimplementablePolicy = true;
263     m_frame.loader().client().dispatchUnableToImplementPolicy(error);
264     m_delegateIsHandlingUnimplementablePolicy = false;
265 }
266
267 } // namespace WebCore