2 * Copyright (C) 2015 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23 * THE POSSIBILITY OF SUCH DAMAGE.
27 #import "NetworkExtensionContentFilter.h"
29 #if HAVE(NETWORK_EXTENSION)
31 #import "ContentFilterUnblockHandler.h"
33 #import "ResourceRequest.h"
34 #import "ResourceResponse.h"
35 #import "RuntimeApplicationChecks.h"
36 #import "SharedBuffer.h"
38 #import <objc/runtime.h>
39 #import <pal/spi/cocoa/NEFilterSourceSPI.h>
40 #import <wtf/SoftLinking.h>
42 SOFT_LINK_FRAMEWORK_OPTIONAL(NetworkExtension);
43 SOFT_LINK_CLASS_OPTIONAL(NetworkExtension, NEFilterSource);
45 // FIXME: Remove this once -setSourceAppPid: is declared in an SDK used by the builders
46 @interface NEFilterSource ()
47 - (void)setSourceAppPid:(pid_t)sourceAppPid;
50 static inline NSData *replacementDataFromDecisionInfo(NSDictionary *decisionInfo)
52 ASSERT_WITH_SECURITY_IMPLICATION(!decisionInfo || [decisionInfo isKindOfClass:[NSDictionary class]]);
53 return decisionInfo[NEFilterSourceOptionsPageData];
58 bool NetworkExtensionContentFilter::enabled()
60 bool enabled = [getNEFilterSourceClass() filterRequired];
61 LOG(ContentFiltering, "NetworkExtensionContentFilter is %s.\n", enabled ? "enabled" : "not enabled");
65 std::unique_ptr<NetworkExtensionContentFilter> NetworkExtensionContentFilter::create()
67 return std::make_unique<NetworkExtensionContentFilter>();
70 void NetworkExtensionContentFilter::initialize(const URL* url)
74 ASSERT(!m_neFilterSource);
75 m_queue = adoptOSObject(dispatch_queue_create("WebKit NetworkExtension Filtering", DISPATCH_QUEUE_SERIAL));
76 m_semaphore = adoptOSObject(dispatch_semaphore_create(0));
77 ASSERT_UNUSED(url, !url);
78 m_neFilterSource = adoptNS([allocNEFilterSourceInstance() initWithDecisionQueue:m_queue.get()]);
79 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300) || (PLATFORM(IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000)
80 [m_neFilterSource setSourceAppIdentifier:applicationBundleIdentifier()];
81 // FIXME: Remove the -respondsToSelector: check once -setSourceAppPid: is defined in an SDK used by the builders.
82 if ([m_neFilterSource respondsToSelector:@selector(setSourceAppPid:)])
83 [m_neFilterSource setSourceAppPid:presentingApplicationPID()];
87 void NetworkExtensionContentFilter::willSendRequest(ResourceRequest& request, const ResourceResponse& redirectResponse)
89 ASSERT(!request.isNull());
90 if (!request.url().protocolIsInHTTPFamily() || !enabled()) {
91 m_state = State::Allowed;
97 if (!redirectResponse.isNull()) {
98 responseReceived(redirectResponse);
103 RetainPtr<NSString> modifiedRequestURLString;
104 [m_neFilterSource willSendRequest:request.nsURLRequest(DoNotUpdateHTTPBody) decisionHandler:[this, &modifiedRequestURLString](NEFilterSourceStatus status, NSDictionary *decisionInfo) {
105 modifiedRequestURLString = decisionInfo[NEFilterSourceOptionsRedirectURL];
106 ASSERT(!modifiedRequestURLString || [modifiedRequestURLString isKindOfClass:[NSString class]]);
107 handleDecision(status, replacementDataFromDecisionInfo(decisionInfo));
110 // FIXME: We have to block here since DocumentLoader expects to have a
111 // blocked/not blocked answer from the filter immediately after calling
112 // addData(). We should find a way to make this asynchronous.
113 dispatch_semaphore_wait(m_semaphore.get(), DISPATCH_TIME_FOREVER);
115 if (!modifiedRequestURLString)
118 URL modifiedRequestURL { URL(), modifiedRequestURLString.get() };
119 if (!modifiedRequestURL.isValid()) {
120 LOG(ContentFiltering, "NetworkExtensionContentFilter failed to convert modified URL string %@ to a WebCore::URL.\n", modifiedRequestURLString.get());
124 request.setURL(modifiedRequestURL);
127 void NetworkExtensionContentFilter::responseReceived(const ResourceResponse& response)
129 if (!response.url().protocolIsInHTTPFamily()) {
130 m_state = State::Allowed;
134 [m_neFilterSource receivedResponse:response.nsURLResponse() decisionHandler:[this](NEFilterSourceStatus status, NSDictionary *decisionInfo) {
135 handleDecision(status, replacementDataFromDecisionInfo(decisionInfo));
138 // FIXME: We have to block here since DocumentLoader expects to have a
139 // blocked/not blocked answer from the filter immediately after calling
140 // addData(). We should find a way to make this asynchronous.
141 dispatch_semaphore_wait(m_semaphore.get(), DISPATCH_TIME_FOREVER);
144 void NetworkExtensionContentFilter::addData(const char* data, int length)
146 RetainPtr<NSData> copiedData { [NSData dataWithBytes:(void*)data length:length] };
148 [m_neFilterSource receivedData:copiedData.get() decisionHandler:[this](NEFilterSourceStatus status, NSDictionary *decisionInfo) {
149 handleDecision(status, replacementDataFromDecisionInfo(decisionInfo));
152 // FIXME: We have to block here since DocumentLoader expects to have a
153 // blocked/not blocked answer from the filter immediately after calling
154 // addData(). We should find a way to make this asynchronous.
155 dispatch_semaphore_wait(m_semaphore.get(), DISPATCH_TIME_FOREVER);
158 void NetworkExtensionContentFilter::finishedAddingData()
160 [m_neFilterSource finishedLoadingWithDecisionHandler:[this](NEFilterSourceStatus status, NSDictionary *decisionInfo) {
161 handleDecision(status, replacementDataFromDecisionInfo(decisionInfo));
164 // FIXME: We have to block here since DocumentLoader expects to have a
165 // blocked/not blocked answer from the filter immediately after calling
166 // finishedAddingData(). We should find a way to make this asynchronous.
167 dispatch_semaphore_wait(m_semaphore.get(), DISPATCH_TIME_FOREVER);
170 Ref<SharedBuffer> NetworkExtensionContentFilter::replacementData() const
172 ASSERT(didBlockData());
173 return SharedBuffer::create(m_replacementData.get());
176 #if ENABLE(CONTENT_FILTERING)
177 ContentFilterUnblockHandler NetworkExtensionContentFilter::unblockHandler() const
179 using DecisionHandlerFunction = ContentFilterUnblockHandler::DecisionHandlerFunction;
181 RetainPtr<NEFilterSource> neFilterSource { m_neFilterSource };
182 return ContentFilterUnblockHandler {
183 "nefilter-unblock"_s, [neFilterSource](DecisionHandlerFunction decisionHandler) {
184 [neFilterSource remediateWithDecisionHandler:[decisionHandler](NEFilterSourceStatus status, NSDictionary *) {
185 LOG(ContentFiltering, "NEFilterSource %s the unblock request.\n", status == NEFilterSourceStatusPass ? "allowed" : "did not allow");
186 decisionHandler(status == NEFilterSourceStatusPass);
193 void NetworkExtensionContentFilter::handleDecision(NEFilterSourceStatus status, NSData *replacementData)
195 ASSERT_WITH_SECURITY_IMPLICATION(!replacementData || [replacementData isKindOfClass:[NSData class]]);
198 case NEFilterSourceStatusPass:
199 case NEFilterSourceStatusError:
200 case NEFilterSourceStatusWhitelisted:
201 case NEFilterSourceStatusBlacklisted:
202 m_state = State::Allowed;
204 case NEFilterSourceStatusBlock:
205 m_state = State::Blocked;
207 case NEFilterSourceStatusNeedsMoreData:
208 m_state = State::Filtering;
213 m_replacementData = replacementData;
215 if (!needsMoreData())
216 LOG(ContentFiltering, "NetworkExtensionContentFilter stopped buffering with status %zd and replacement data length %zu.\n", status, replacementData.length);
218 dispatch_semaphore_signal(m_semaphore.get());
221 } // namespace WebCore
223 #endif // HAVE(NETWORK_EXTENSION)