Implement Same-Site cookies
[WebKit-https.git] / Source / WebCore / page / SecurityPolicy.cpp
1 /*
2  * Copyright (C) 2011 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
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  * 3.  Neither the name of Google, Inc. ("Google") nor the names of
14  *     its contributors may be used to endorse or promote products derived
15  *     from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY GOOGLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include "config.h"
30 #include "SecurityPolicy.h"
31
32 #include "OriginAccessEntry.h"
33 #include "SecurityOrigin.h"
34 #include "URL.h"
35 #include <memory>
36 #include <wtf/HashMap.h>
37 #include <wtf/MainThread.h>
38 #include <wtf/NeverDestroyed.h>
39 #include <wtf/text/StringHash.h>
40
41 namespace WebCore {
42
43 static SecurityPolicy::LocalLoadPolicy localLoadPolicy = SecurityPolicy::AllowLocalLoadsForLocalOnly;
44
45 typedef Vector<OriginAccessEntry> OriginAccessWhiteList;
46 typedef HashMap<String, std::unique_ptr<OriginAccessWhiteList>> OriginAccessMap;
47
48 static Lock& originAccessMapLock()
49 {
50     static NeverDestroyed<Lock> lock;
51     return lock;
52 }
53
54 static OriginAccessMap& originAccessMap()
55 {
56     ASSERT(originAccessMapLock().isHeld());
57     static NeverDestroyed<OriginAccessMap> originAccessMap;
58     return originAccessMap;
59 }
60
61 bool SecurityPolicy::shouldHideReferrer(const URL& url, const String& referrer)
62 {
63     bool referrerIsSecureURL = protocolIs(referrer, "https");
64     bool referrerIsWebURL = referrerIsSecureURL || protocolIs(referrer, "http");
65
66     if (!referrerIsWebURL)
67         return true;
68
69     if (!referrerIsSecureURL)
70         return false;
71
72     bool URLIsSecureURL = url.protocolIs("https");
73
74     return !URLIsSecureURL;
75 }
76
77 String SecurityPolicy::referrerToOriginString(const String& referrer)
78 {
79     String originString = SecurityOrigin::createFromString(referrer)->toString();
80     if (originString == "null")
81         return String();
82     // A security origin is not a canonical URL as it lacks a path. Add /
83     // to turn it into a canonical URL we can use as referrer.
84     return originString + "/";
85 }
86
87 String SecurityPolicy::generateReferrerHeader(ReferrerPolicy referrerPolicy, const URL& url, const String& referrer)
88 {
89     ASSERT(referrer == URL(URL(), referrer).strippedForUseAsReferrer());
90
91     if (referrer.isEmpty())
92         return String();
93
94     if (!protocolIsInHTTPFamily(referrer))
95         return String();
96
97     switch (referrerPolicy) {
98     case ReferrerPolicy::EmptyString:
99         ASSERT_NOT_REACHED();
100         break;
101     case ReferrerPolicy::NoReferrer:
102         return String();
103     case ReferrerPolicy::NoReferrerWhenDowngrade:
104         break;
105     case ReferrerPolicy::SameOrigin: {
106         auto origin = SecurityOrigin::createFromString(referrer);
107         if (!origin->canRequest(url))
108             return String();
109         break;
110     }
111     case ReferrerPolicy::Origin:
112         return referrerToOriginString(referrer);
113     case ReferrerPolicy::StrictOrigin:
114         if (shouldHideReferrer(url, referrer))
115             return String();
116         return referrerToOriginString(referrer);
117     case ReferrerPolicy::OriginWhenCrossOrigin: {
118         auto origin = SecurityOrigin::createFromString(referrer);
119         if (!origin->canRequest(url))
120             return referrerToOriginString(referrer);
121         break;
122     }
123     case ReferrerPolicy::StrictOriginWhenCrossOrigin: {
124         auto origin = SecurityOrigin::createFromString(referrer);
125         if (!origin->canRequest(url)) {
126             if (shouldHideReferrer(url, referrer))
127                 return String();
128             return referrerToOriginString(referrer);
129         }
130         break;
131     }
132     case ReferrerPolicy::UnsafeUrl:
133         return referrer;
134     }
135
136     return shouldHideReferrer(url, referrer) ? String() : referrer;
137 }
138
139 bool SecurityPolicy::shouldInheritSecurityOriginFromOwner(const URL& url)
140 {
141     // Paraphrased from <https://html.spec.whatwg.org/multipage/browsers.html#origin> (8 July 2016)
142     //
143     // If a Document has the address "about:blank"
144     //      The origin of the document is the origin it was assigned when its browsing context was created.
145     // If a Document has the address "about:srcdoc"
146     //      The origin of the document is the origin of its parent document.
147     //
148     // Note: We generalize this to invalid URLs because we treat such URLs as about:blank.
149     //
150     return url.isEmpty() || equalIgnoringASCIICase(url.string(), blankURL()) || equalLettersIgnoringASCIICase(url.string(), "about:srcdoc");
151 }
152
153 void SecurityPolicy::setLocalLoadPolicy(LocalLoadPolicy policy)
154 {
155     localLoadPolicy = policy;
156 }
157
158 bool SecurityPolicy::restrictAccessToLocal()
159 {
160     return localLoadPolicy != SecurityPolicy::AllowLocalLoadsForAll;
161 }
162
163 bool SecurityPolicy::allowSubstituteDataAccessToLocal()
164 {
165     return localLoadPolicy != SecurityPolicy::AllowLocalLoadsForLocalOnly;
166 }
167
168 bool SecurityPolicy::isAccessWhiteListed(const SecurityOrigin* activeOrigin, const SecurityOrigin* targetOrigin)
169 {
170     Locker<Lock> locker(originAccessMapLock());
171     if (OriginAccessWhiteList* list = originAccessMap().get(activeOrigin->toString())) {
172         for (auto& entry : *list) {
173             if (entry.matchesOrigin(*targetOrigin))
174                 return true;
175         }
176     }
177     return false;
178 }
179
180 bool SecurityPolicy::isAccessToURLWhiteListed(const SecurityOrigin* activeOrigin, const URL& url)
181 {
182     Ref<SecurityOrigin> targetOrigin(SecurityOrigin::create(url));
183     return isAccessWhiteListed(activeOrigin, &targetOrigin.get());
184 }
185
186 void SecurityPolicy::addOriginAccessWhitelistEntry(const SecurityOrigin& sourceOrigin, const String& destinationProtocol, const String& destinationDomain, bool allowDestinationSubdomains)
187 {
188     ASSERT(!sourceOrigin.isUnique());
189     if (sourceOrigin.isUnique())
190         return;
191
192     String sourceString = sourceOrigin.toString();
193
194     Locker<Lock> locker(originAccessMapLock());
195     OriginAccessMap::AddResult result = originAccessMap().add(sourceString, nullptr);
196     if (result.isNewEntry)
197         result.iterator->value = std::make_unique<OriginAccessWhiteList>();
198
199     OriginAccessWhiteList* list = result.iterator->value.get();
200     list->append(OriginAccessEntry(destinationProtocol, destinationDomain, allowDestinationSubdomains ? OriginAccessEntry::AllowSubdomains : OriginAccessEntry::DisallowSubdomains, OriginAccessEntry::TreatIPAddressAsIPAddress));
201 }
202
203 void SecurityPolicy::removeOriginAccessWhitelistEntry(const SecurityOrigin& sourceOrigin, const String& destinationProtocol, const String& destinationDomain, bool allowDestinationSubdomains)
204 {
205     ASSERT(!sourceOrigin.isUnique());
206     if (sourceOrigin.isUnique())
207         return;
208
209     String sourceString = sourceOrigin.toString();
210
211     Locker<Lock> locker(originAccessMapLock());
212     OriginAccessMap& map = originAccessMap();
213     OriginAccessMap::iterator it = map.find(sourceString);
214     if (it == map.end())
215         return;
216
217     OriginAccessWhiteList& list = *it->value;
218     OriginAccessEntry originAccessEntry(destinationProtocol, destinationDomain, allowDestinationSubdomains ? OriginAccessEntry::AllowSubdomains : OriginAccessEntry::DisallowSubdomains, OriginAccessEntry::TreatIPAddressAsIPAddress);
219     if (!list.removeFirst(originAccessEntry))
220         return;
221
222     if (list.isEmpty())
223         map.remove(it);
224 }
225
226 void SecurityPolicy::resetOriginAccessWhitelists()
227 {
228     Locker<Lock> locker(originAccessMapLock());
229     originAccessMap().clear();
230 }
231
232 } // namespace WebCore