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 "URL.h"
33#include <wtf/MainThread.h>
34#include "OriginAccessEntry.h"
35#include "SecurityOrigin.h"
36#include <memory>
37#include <wtf/text/StringHash.h>
38
39namespace WebCore {
40
41static SecurityPolicy::LocalLoadPolicy localLoadPolicy = SecurityPolicy::AllowLocalLoadsForLocalOnly;
42
43typedef Vector<OriginAccessEntry> OriginAccessWhiteList;
44typedef HashMap<String, std::unique_ptr<OriginAccessWhiteList>> OriginAccessMap;
45
46static OriginAccessMap& originAccessMap()
47{
48    DEPRECATED_DEFINE_STATIC_LOCAL(OriginAccessMap, originAccessMap, ());
49    return originAccessMap;
50}
51
52bool SecurityPolicy::shouldHideReferrer(const URL& url, const String& referrer)
53{
54    bool referrerIsSecureURL = protocolIs(referrer, "https");
55    bool referrerIsWebURL = referrerIsSecureURL || protocolIs(referrer, "http");
56
57    if (!referrerIsWebURL)
58        return true;
59
60    if (!referrerIsSecureURL)
61        return false;
62
63    bool URLIsSecureURL = url.protocolIs("https");
64
65    return !URLIsSecureURL;
66}
67
68String SecurityPolicy::generateReferrerHeader(ReferrerPolicy referrerPolicy, const URL& url, const String& referrer)
69{
70    if (referrer.isEmpty())
71        return String();
72
73    if (!protocolIsInHTTPFamily(referrer))
74        return String();
75
76    switch (referrerPolicy) {
77    case ReferrerPolicyNever:
78        return String();
79    case ReferrerPolicyAlways:
80        return referrer;
81    case ReferrerPolicyOrigin: {
82        String origin = SecurityOrigin::createFromString(referrer)->toString();
83        if (origin == "null")
84            return String();
85        // A security origin is not a canonical URL as it lacks a path. Add /
86        // to turn it into a canonical URL we can use as referrer.
87        return origin + "/";
88    }
89    case ReferrerPolicyDefault:
90        break;
91    }
92
93    return shouldHideReferrer(url, referrer) ? String() : referrer;
94}
95
96void SecurityPolicy::setLocalLoadPolicy(LocalLoadPolicy policy)
97{
98    localLoadPolicy = policy;
99}
100
101bool SecurityPolicy::restrictAccessToLocal()
102{
103    return localLoadPolicy != SecurityPolicy::AllowLocalLoadsForAll;
104}
105
106bool SecurityPolicy::allowSubstituteDataAccessToLocal()
107{
108    return localLoadPolicy != SecurityPolicy::AllowLocalLoadsForLocalOnly;
109}
110
111bool SecurityPolicy::isAccessWhiteListed(const SecurityOrigin* activeOrigin, const SecurityOrigin* targetOrigin)
112{
113    if (OriginAccessWhiteList* list = originAccessMap().get(activeOrigin->toString())) {
114        for (size_t i = 0; i < list->size();  ++i) {
115           if (list->at(i).matchesOrigin(*targetOrigin))
116               return true;
117       }
118    }
119    return false;
120}
121
122bool SecurityPolicy::isAccessToURLWhiteListed(const SecurityOrigin* activeOrigin, const URL& url)
123{
124    RefPtr<SecurityOrigin> targetOrigin = SecurityOrigin::create(url);
125    return isAccessWhiteListed(activeOrigin, targetOrigin.get());
126}
127
128void SecurityPolicy::addOriginAccessWhitelistEntry(const SecurityOrigin& sourceOrigin, const String& destinationProtocol, const String& destinationDomain, bool allowDestinationSubdomains)
129{
130    ASSERT(isMainThread());
131    ASSERT(!sourceOrigin.isUnique());
132    if (sourceOrigin.isUnique())
133        return;
134
135    String sourceString = sourceOrigin.toString();
136    OriginAccessMap::AddResult result = originAccessMap().add(sourceString, nullptr);
137    if (result.isNewEntry)
138        result.iterator->value = std::make_unique<OriginAccessWhiteList>();
139
140    OriginAccessWhiteList* list = result.iterator->value.get();
141    list->append(OriginAccessEntry(destinationProtocol, destinationDomain, allowDestinationSubdomains ? OriginAccessEntry::AllowSubdomains : OriginAccessEntry::DisallowSubdomains));
142}
143
144void SecurityPolicy::removeOriginAccessWhitelistEntry(const SecurityOrigin& sourceOrigin, const String& destinationProtocol, const String& destinationDomain, bool allowDestinationSubdomains)
145{
146    ASSERT(isMainThread());
147    ASSERT(!sourceOrigin.isUnique());
148    if (sourceOrigin.isUnique())
149        return;
150
151    String sourceString = sourceOrigin.toString();
152    OriginAccessMap& map = originAccessMap();
153    OriginAccessMap::iterator it = map.find(sourceString);
154    if (it == map.end())
155        return;
156
157    OriginAccessWhiteList* list = it->value.get();
158    size_t index = list->find(OriginAccessEntry(destinationProtocol, destinationDomain, allowDestinationSubdomains ? OriginAccessEntry::AllowSubdomains : OriginAccessEntry::DisallowSubdomains));
159    if (index == notFound)
160        return;
161
162    list->remove(index);
163
164    if (list->isEmpty())
165        map.remove(it);
166}
167
168void SecurityPolicy::resetOriginAccessWhitelists()
169{
170    ASSERT(isMainThread());
171    originAccessMap().clear();
172}
173
174} // namespace WebCore
175