summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/platform/weborigin/security_policy.cc
blob: 3ce6e47dc30481f51702ef2cdfd18c1a2fef390a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*
 * Copyright (C) 2011 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Google, Inc. ("Google") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY GOOGLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "third_party/blink/renderer/platform/weborigin/security_policy.h"

#include <memory>

#include "base/strings/pattern.h"
#include "services/network/public/cpp/cors/origin_access_list.h"
#include "services/network/public/mojom/referrer_policy.mojom-blink.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/parsing_utilities.h"
#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h"
#include "third_party/blink/renderer/platform/wtf/threading.h"
#include "third_party/blink/renderer/platform/wtf/threading_primitives.h"
#include "third_party/blink/renderer/platform/wtf/wtf.h"
#include "url/gurl.h"

namespace blink {

static Mutex& GetMutex() {
  DEFINE_THREAD_SAFE_STATIC_LOCAL(Mutex, mutex, ());
  return mutex;
}

static network::cors::OriginAccessList& GetOriginAccessList() {
  DEFINE_THREAD_SAFE_STATIC_LOCAL(network::cors::OriginAccessList,
                                  origin_access_list, ());
  return origin_access_list;
}

using OriginSet = HashSet<String>;

static OriginSet& TrustworthyOriginSafelist() {
  DEFINE_STATIC_LOCAL(OriginSet, safelist, ());
  return safelist;
}

network::mojom::ReferrerPolicy ReferrerPolicyResolveDefault(
    network::mojom::ReferrerPolicy referrer_policy) {
  if (referrer_policy == network::mojom::ReferrerPolicy::kDefault) {
    if (RuntimeEnabledFeatures::ReducedReferrerGranularityEnabled()) {
      return network::mojom::ReferrerPolicy::kStrictOriginWhenCrossOrigin;
    } else {
      return network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade;
    }
  }

  return referrer_policy;
}

void SecurityPolicy::Init() {
  TrustworthyOriginSafelist();
}

bool SecurityPolicy::ShouldHideReferrer(const KURL& url, const KURL& referrer) {
  bool referrer_is_secure_url = referrer.ProtocolIs("https");
  bool scheme_is_allowed =
      SchemeRegistry::ShouldTreatURLSchemeAsAllowedForReferrer(
          referrer.Protocol());

  if (!scheme_is_allowed)
    return true;

  if (!referrer_is_secure_url)
    return false;

  bool url_is_secure_url = url.ProtocolIs("https");

  return !url_is_secure_url;
}

Referrer SecurityPolicy::GenerateReferrer(
    network::mojom::ReferrerPolicy referrer_policy,
    const KURL& url,
    const String& referrer) {
  network::mojom::ReferrerPolicy referrer_policy_no_default =
      ReferrerPolicyResolveDefault(referrer_policy);
  if (referrer == Referrer::NoReferrer())
    return Referrer(Referrer::NoReferrer(), referrer_policy_no_default);
  DCHECK(!referrer.IsEmpty());

  KURL referrer_url = KURL(NullURL(), referrer).UrlStrippedForUseAsReferrer();

  if (!referrer_url.IsValid())
    return Referrer(Referrer::NoReferrer(), referrer_policy_no_default);

  if (SecurityOrigin::ShouldUseInnerURL(url))
    return Referrer(Referrer::NoReferrer(), referrer_policy_no_default);

  // 5. Let referrerOrigin be the result of stripping referrerSource for use as
  // a referrer, with the origin-only flag set to true.
  KURL referrer_origin = referrer_url;
  referrer_origin.SetPath(String());
  referrer_origin.SetQuery(String());

  // 6. If the result of serializing referrerURL is a string whose length is
  // greater than 4096, set referrerURL to referrerOrigin.
  if (referrer_url.GetString().length() > 4096)
    referrer_url = referrer_origin;

  switch (referrer_policy_no_default) {
    case network::mojom::ReferrerPolicy::kNever:
      return Referrer(Referrer::NoReferrer(), referrer_policy_no_default);
    case network::mojom::ReferrerPolicy::kAlways:
      return Referrer(referrer_url, referrer_policy_no_default);
    case network::mojom::ReferrerPolicy::kOrigin: {
      return Referrer(referrer_origin, referrer_policy_no_default);
    }
    case network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin: {
      if (!SecurityOrigin::AreSameOrigin(referrer_url, url)) {
        return Referrer(referrer_origin, referrer_policy_no_default);
      }
      break;
    }
    case network::mojom::ReferrerPolicy::kSameOrigin: {
      if (!SecurityOrigin::AreSameOrigin(referrer_url, url)) {
        return Referrer(Referrer::NoReferrer(), referrer_policy_no_default);
      }
      return Referrer(referrer_url, referrer_policy_no_default);
    }
    case network::mojom::ReferrerPolicy::kStrictOrigin: {
      return Referrer(ShouldHideReferrer(url, referrer_url)
                          ? Referrer::NoReferrer()
                          : referrer_origin,
                      referrer_policy_no_default);
    }
    case network::mojom::ReferrerPolicy::kStrictOriginWhenCrossOrigin: {
      if (!SecurityOrigin::AreSameOrigin(referrer_url, url)) {
        return Referrer(ShouldHideReferrer(url, referrer_url)
                            ? Referrer::NoReferrer()
                            : referrer_origin,
                        referrer_policy_no_default);
      }
      break;
    }
    case network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade:
      break;
    case network::mojom::ReferrerPolicy::kDefault:
      NOTREACHED();
      break;
  }

  return Referrer(ShouldHideReferrer(url, referrer_url) ? Referrer::NoReferrer()
                                                        : referrer_url,
                  referrer_policy_no_default);
}

void SecurityPolicy::AddOriginToTrustworthySafelist(
    const String& origin_or_pattern) {
#if DCHECK_IS_ON()
  // Must be called before we start other threads.
  DCHECK(WTF::IsBeforeThreadCreated());
#endif
  // Origins and hostname patterns must be canonicalized (including
  // canonicalization to 8-bit strings) before being inserted into
  // TrustworthyOriginSafelist().
  CHECK(origin_or_pattern.Is8Bit());
  TrustworthyOriginSafelist().insert(origin_or_pattern);
}

bool SecurityPolicy::IsOriginTrustworthySafelisted(
    const SecurityOrigin& origin) {
  // Early return if |origin| cannot possibly be matched.
  if (origin.IsOpaque() || TrustworthyOriginSafelist().IsEmpty())
    return false;

  if (TrustworthyOriginSafelist().Contains(origin.ToRawString()))
    return true;

  // KURL and SecurityOrigin hosts should be canonicalized to 8-bit strings.
  CHECK(origin.Host().Is8Bit());
  StringUTF8Adaptor host_adaptor(origin.Host());
  for (const auto& origin_or_pattern : TrustworthyOriginSafelist()) {
    StringUTF8Adaptor origin_or_pattern_adaptor(origin_or_pattern);
    if (base::MatchPattern(host_adaptor.AsStringPiece(),
                           origin_or_pattern_adaptor.AsStringPiece())) {
      return true;
    }
  }

  return false;
}

bool SecurityPolicy::IsUrlTrustworthySafelisted(const KURL& url) {
  // Early return to avoid initializing the SecurityOrigin.
  if (TrustworthyOriginSafelist().IsEmpty())
    return false;
  return IsOriginTrustworthySafelisted(*SecurityOrigin::Create(url).get());
}

bool SecurityPolicy::IsOriginAccessAllowed(
    const SecurityOrigin* active_origin,
    const SecurityOrigin* target_origin) {
  MutexLocker lock(GetMutex());
  return GetOriginAccessList().CheckAccessState(
             active_origin->ToUrlOrigin(),
             target_origin->ToUrlOrigin().GetURL()) ==
         network::cors::OriginAccessList::AccessState::kAllowed;
}

bool SecurityPolicy::IsOriginAccessToURLAllowed(
    const SecurityOrigin* active_origin,
    const KURL& url) {
  MutexLocker lock(GetMutex());
  return GetOriginAccessList().CheckAccessState(active_origin->ToUrlOrigin(),
                                                url) ==
         network::cors::OriginAccessList::AccessState::kAllowed;
}

void SecurityPolicy::AddOriginAccessAllowListEntry(
    const SecurityOrigin& source_origin,
    const String& destination_protocol,
    const String& destination_domain,
    const uint16_t port,
    const network::mojom::CorsDomainMatchMode domain_match_mode,
    const network::mojom::CorsPortMatchMode port_match_mode,
    const network::mojom::CorsOriginAccessMatchPriority priority) {
  MutexLocker lock(GetMutex());
  GetOriginAccessList().AddAllowListEntryForOrigin(
      source_origin.ToUrlOrigin(), destination_protocol.Utf8(),
      destination_domain.Utf8(), port, domain_match_mode, port_match_mode,
      priority);
}

void SecurityPolicy::AddOriginAccessBlockListEntry(
    const SecurityOrigin& source_origin,
    const String& destination_protocol,
    const String& destination_domain,
    const uint16_t port,
    const network::mojom::CorsDomainMatchMode domain_match_mode,
    const network::mojom::CorsPortMatchMode port_match_mode,
    const network::mojom::CorsOriginAccessMatchPriority priority) {
  MutexLocker lock(GetMutex());
  GetOriginAccessList().AddBlockListEntryForOrigin(
      source_origin.ToUrlOrigin(), destination_protocol.Utf8(),
      destination_domain.Utf8(), port, domain_match_mode, port_match_mode,
      priority);
}

void SecurityPolicy::ClearOriginAccessListForOrigin(
    const SecurityOrigin& source_origin) {
  MutexLocker lock(GetMutex());
  GetOriginAccessList().ClearForOrigin(source_origin.ToUrlOrigin());
}

void SecurityPolicy::ClearOriginAccessList() {
  MutexLocker lock(GetMutex());
  GetOriginAccessList().Clear();
}

bool SecurityPolicy::ReferrerPolicyFromString(
    const String& policy,
    ReferrerPolicyLegacyKeywordsSupport legacy_keywords_support,
    network::mojom::ReferrerPolicy* result) {
  DCHECK(!policy.IsNull());
  bool support_legacy_keywords =
      (legacy_keywords_support == kSupportReferrerPolicyLegacyKeywords);

  if (EqualIgnoringASCIICase(policy, "no-referrer") ||
      (support_legacy_keywords && (EqualIgnoringASCIICase(policy, "never") ||
                                   EqualIgnoringASCIICase(policy, "none")))) {
    *result = network::mojom::ReferrerPolicy::kNever;
    return true;
  }
  if (EqualIgnoringASCIICase(policy, "unsafe-url") ||
      (support_legacy_keywords && EqualIgnoringASCIICase(policy, "always"))) {
    *result = network::mojom::ReferrerPolicy::kAlways;
    return true;
  }
  if (EqualIgnoringASCIICase(policy, "origin")) {
    *result = network::mojom::ReferrerPolicy::kOrigin;
    return true;
  }
  if (EqualIgnoringASCIICase(policy, "origin-when-cross-origin") ||
      (support_legacy_keywords &&
       EqualIgnoringASCIICase(policy, "origin-when-crossorigin"))) {
    *result = network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin;
    return true;
  }
  if (EqualIgnoringASCIICase(policy, "same-origin")) {
    *result = network::mojom::ReferrerPolicy::kSameOrigin;
    return true;
  }
  if (EqualIgnoringASCIICase(policy, "strict-origin")) {
    *result = network::mojom::ReferrerPolicy::kStrictOrigin;
    return true;
  }
  if (EqualIgnoringASCIICase(policy, "strict-origin-when-cross-origin")) {
    *result = network::mojom::ReferrerPolicy::kStrictOriginWhenCrossOrigin;
    return true;
  }
  if (EqualIgnoringASCIICase(policy, "no-referrer-when-downgrade") ||
      (support_legacy_keywords && EqualIgnoringASCIICase(policy, "default"))) {
    *result = network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade;
    return true;
  }
  return false;
}

namespace {

template <typename CharType>
inline bool IsASCIIAlphaOrHyphen(CharType c) {
  return IsASCIIAlpha(c) || c == '-';
}

}  // namespace

bool SecurityPolicy::ReferrerPolicyFromHeaderValue(
    const String& header_value,
    ReferrerPolicyLegacyKeywordsSupport legacy_keywords_support,
    network::mojom::ReferrerPolicy* result) {
  network::mojom::ReferrerPolicy referrer_policy =
      network::mojom::ReferrerPolicy::kDefault;

  Vector<String> tokens;
  header_value.Split(',', true, tokens);
  for (const auto& token : tokens) {
    network::mojom::ReferrerPolicy current_result;
    auto stripped_token = token.StripWhiteSpace();
    if (SecurityPolicy::ReferrerPolicyFromString(token.StripWhiteSpace(),
                                                 legacy_keywords_support,
                                                 &current_result)) {
      referrer_policy = current_result;
    } else {
      Vector<UChar> characters;
      stripped_token.AppendTo(characters);
      const UChar* position = characters.data();
      UChar* end = characters.data() + characters.size();
      SkipWhile<UChar, IsASCIIAlphaOrHyphen>(position, end);
      if (position != end)
        return false;
    }
  }

  if (referrer_policy == network::mojom::ReferrerPolicy::kDefault)
    return false;

  *result = referrer_policy;
  return true;
}

}  // namespace blink