• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // NB: Modelled after Mozilla's code (originally written by Pamela Greene,
6 // later modified by others), but almost entirely rewritten for Chrome.
7 //   (netwerk/dns/src/nsEffectiveTLDService.cpp)
8 /* ***** BEGIN LICENSE BLOCK *****
9  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
10  *
11  * The contents of this file are subject to the Mozilla Public License Version
12  * 1.1 (the "License"); you may not use this file except in compliance with
13  * the License. You may obtain a copy of the License at
14  * http://www.mozilla.org/MPL/
15  *
16  * Software distributed under the License is distributed on an "AS IS" basis,
17  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
18  * for the specific language governing rights and limitations under the
19  * License.
20  *
21  * The Original Code is Mozilla Effective-TLD Service
22  *
23  * The Initial Developer of the Original Code is
24  * Google Inc.
25  * Portions created by the Initial Developer are Copyright (C) 2006
26  * the Initial Developer. All Rights Reserved.
27  *
28  * Contributor(s):
29  *   Pamela Greene <pamg.bugs@gmail.com> (original author)
30  *   Daniel Witte <dwitte@stanford.edu>
31  *
32  * Alternatively, the contents of this file may be used under the terms of
33  * either the GNU General Public License Version 2 or later (the "GPL"), or
34  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
35  * in which case the provisions of the GPL or the LGPL are applicable instead
36  * of those above. If you wish to allow use of your version of this file only
37  * under the terms of either the GPL or the LGPL, and not to allow others to
38  * use your version of this file under the terms of the MPL, indicate your
39  * decision by deleting the provisions above and replace them with the notice
40  * and other provisions required by the GPL or the LGPL. If you do not delete
41  * the provisions above, a recipient may use your version of this file under
42  * the terms of any one of the MPL, the GPL or the LGPL.
43  *
44  * ***** END LICENSE BLOCK ***** */
45 
46 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
47 
48 #include <cstdint>
49 #include <ostream>
50 #include <string_view>
51 
52 #include "base/check_op.h"
53 #include "base/containers/span.h"
54 #include "base/notreached.h"
55 #include "base/strings/string_util.h"
56 #include "base/strings/utf_string_conversions.h"
57 #include "net/base/lookup_string_in_fixed_set.h"
58 #include "net/base/net_module.h"
59 #include "net/base/url_util.h"
60 #include "url/gurl.h"
61 #include "url/origin.h"
62 #include "url/third_party/mozilla/url_parse.h"
63 #include "url/url_util.h"
64 
65 namespace net::registry_controlled_domains {
66 
67 namespace {
68 #include "net/base/registry_controlled_domains/effective_tld_names-reversed-inc.cc"
69 
70 // See make_dafsa.py for documentation of the generated dafsa byte array.
71 
72 // This is mutable so that it can be overridden for testing.
73 base::span<const uint8_t> g_graph = kDafsa;
74 
75 struct MappedHostComponent {
76   size_t original_begin;
77   size_t original_end;
78 
79   size_t canonical_begin;
80   size_t canonical_end;
81 };
82 
83 // Used as the output of functions that calculate the registry length in a
84 // hostname. |registry_length| is the length of the registry identifier (or zero
85 // if none is found or the hostname is itself a registry identifier).
86 // |is_registry_identifier| is true if the host is itself a match for a registry
87 // identifier.
88 struct RegistryLengthOutput {
89   size_t registry_length;
90   bool is_registry_identifier;
91 };
92 
93 // This version assumes we already removed leading dots from host as well as the
94 // last trailing dot if it had one. If the host is itself a registry identifier,
95 // the returned |registry_length| will be 0 and |is_registry_identifier| will be
96 // true.
GetRegistryLengthInTrimmedHost(std::string_view host,UnknownRegistryFilter unknown_filter,PrivateRegistryFilter private_filter)97 RegistryLengthOutput GetRegistryLengthInTrimmedHost(
98     std::string_view host,
99     UnknownRegistryFilter unknown_filter,
100     PrivateRegistryFilter private_filter) {
101   size_t length;
102   int type = LookupSuffixInReversedSet(
103       g_graph, private_filter == INCLUDE_PRIVATE_REGISTRIES, host, &length);
104 
105   CHECK_LE(length, host.size());
106 
107   // No rule found in the registry.
108   if (type == kDafsaNotFound) {
109     // If we allow unknown registries, return the length of last subcomponent.
110     if (unknown_filter == INCLUDE_UNKNOWN_REGISTRIES) {
111       const size_t last_dot = host.find_last_of('.');
112       if (last_dot != std::string_view::npos) {
113         length = host.size() - last_dot - 1;
114         return {length, false};
115       }
116     }
117     return {length, false};
118   }
119 
120   // Exception rules override wildcard rules when the domain is an exact
121   // match, but wildcards take precedence when there's a subdomain.
122   if (type & kDafsaWildcardRule) {
123     // If the complete host matches, then the host is the wildcard suffix, so
124     // return 0.
125     if (length == host.size()) {
126       length = 0;
127       return {length, true};
128     }
129 
130     CHECK_LE(length + 2, host.size());
131     CHECK_EQ('.', host[host.size() - length - 1]);
132 
133     const size_t preceding_dot =
134         host.find_last_of('.', host.size() - length - 2);
135 
136     // If no preceding dot, then the host is the registry itself, so return 0.
137     if (preceding_dot == std::string_view::npos) {
138       return {0, true};
139     }
140 
141     // Return suffix size plus size of subdomain.
142     return {host.size() - preceding_dot - 1, false};
143   }
144 
145   if (type & kDafsaExceptionRule) {
146     size_t first_dot = host.find_first_of('.', host.size() - length);
147     if (first_dot == std::string_view::npos) {
148       // If we get here, we had an exception rule with no dots (e.g.
149       // "!foo").  This would only be valid if we had a corresponding
150       // wildcard rule, which would have to be "*".  But we explicitly
151       // disallow that case, so this kind of rule is invalid.
152       // TODO(crbug.com/40406311): This assumes that all wildcard entries,
153       // such as *.foo.invalid, also have their parent, foo.invalid, as an entry
154       // on the PSL, which is why it returns the length of foo.invalid. This
155       // isn't entirely correct.
156       NOTREACHED() << "Invalid exception rule";
157     }
158     return {host.length() - first_dot - 1, false};
159   }
160 
161   CHECK_NE(type, kDafsaNotFound);
162 
163   // If a complete match, then the host is the registry itself, so return 0.
164   if (length == host.size()) {
165     return {0, true};
166   }
167 
168   return {length, false};
169 }
170 
GetRegistryLengthImpl(std::string_view host,UnknownRegistryFilter unknown_filter,PrivateRegistryFilter private_filter)171 RegistryLengthOutput GetRegistryLengthImpl(
172     std::string_view host,
173     UnknownRegistryFilter unknown_filter,
174     PrivateRegistryFilter private_filter) {
175   if (host.empty())
176     return {std::string::npos, false};
177 
178   // Skip leading dots.
179   const size_t host_check_begin = host.find_first_not_of('.');
180   if (host_check_begin == std::string_view::npos) {
181     return {0, false};  // Host is only dots.
182   }
183 
184   // A single trailing dot isn't relevant in this determination, but does need
185   // to be included in the final returned length.
186   size_t host_check_end = host.size();
187   if (host.back() == '.')
188     --host_check_end;
189 
190   RegistryLengthOutput output = GetRegistryLengthInTrimmedHost(
191       host.substr(host_check_begin, host_check_end - host_check_begin),
192       unknown_filter, private_filter);
193 
194   if (output.registry_length == 0) {
195     return output;
196   }
197 
198   output.registry_length =
199       output.registry_length + host.size() - host_check_end;
200   return output;
201 }
202 
GetDomainAndRegistryImpl(std::string_view host,PrivateRegistryFilter private_filter)203 std::string_view GetDomainAndRegistryImpl(
204     std::string_view host,
205     PrivateRegistryFilter private_filter) {
206   CHECK(!host.empty());
207 
208   // Find the length of the registry for this host.
209   const RegistryLengthOutput registry_length_output =
210       GetRegistryLengthImpl(host, INCLUDE_UNKNOWN_REGISTRIES, private_filter);
211   if ((registry_length_output.registry_length == std::string::npos) ||
212       (registry_length_output.registry_length == 0)) {
213     return std::string_view();  // No registry.
214   }
215   // The "2" in this next line is 1 for the dot, plus a 1-char minimum preceding
216   // subcomponent length.
217   CHECK_GE(host.length(), 2u);
218   CHECK_LE(registry_length_output.registry_length, host.length() - 2)
219       << "Host does not have at least one subcomponent before registry!";
220 
221   // Move past the dot preceding the registry, and search for the next previous
222   // dot.  Return the host from after that dot, or the whole host when there is
223   // no dot.
224   const size_t dot = host.rfind(
225       '.', host.length() - registry_length_output.registry_length - 2);
226   if (dot == std::string::npos)
227     return host;
228   return host.substr(dot + 1);
229 }
230 
231 // Same as GetDomainAndRegistry, but returns the domain and registry as a
232 // std::string_view that references the underlying string of the passed-in
233 // |gurl|.
234 // TODO(pkalinnikov): Eliminate this helper by exposing std::string_view as the
235 // interface type for all the APIs.
GetDomainAndRegistryAsStringPiece(std::string_view host,PrivateRegistryFilter filter)236 std::string_view GetDomainAndRegistryAsStringPiece(
237     std::string_view host,
238     PrivateRegistryFilter filter) {
239   if (host.empty() || url::HostIsIPAddress(host))
240     return std::string_view();
241   return GetDomainAndRegistryImpl(host, filter);
242 }
243 
244 // These two functions append the given string as-is to the given output,
245 // converting to UTF-8 if necessary.
AppendInvalidString(std::string_view str,url::CanonOutput * output)246 void AppendInvalidString(std::string_view str, url::CanonOutput* output) {
247   output->Append(str);
248 }
AppendInvalidString(std::u16string_view str,url::CanonOutput * output)249 void AppendInvalidString(std::u16string_view str, url::CanonOutput* output) {
250   output->Append(base::UTF16ToUTF8(str));
251 }
252 
253 // Backend for PermissiveGetHostRegistryLength that handles both UTF-8 and
254 // UTF-16 input.
255 template <typename T, typename CharT = typename T::value_type>
DoPermissiveGetHostRegistryLength(T host,UnknownRegistryFilter unknown_filter,PrivateRegistryFilter private_filter)256 size_t DoPermissiveGetHostRegistryLength(T host,
257                                          UnknownRegistryFilter unknown_filter,
258                                          PrivateRegistryFilter private_filter) {
259   std::string canonical_host;  // Do not modify outside of canon_output.
260   canonical_host.reserve(host.length());
261   url::StdStringCanonOutput canon_output(&canonical_host);
262 
263   std::vector<MappedHostComponent> components;
264 
265   for (size_t current = 0; current < host.length(); current++) {
266     size_t begin = current;
267 
268     // Advance to next "." or end.
269     current = host.find('.', begin);
270     if (current == std::string::npos)
271       current = host.length();
272 
273     MappedHostComponent mapping;
274     mapping.original_begin = begin;
275     mapping.original_end = current;
276     mapping.canonical_begin = canon_output.length();
277 
278     // Try to append the canonicalized version of this component.
279     int current_len = static_cast<int>(current - begin);
280     if (!url::CanonicalizeHostSubstring(
281             host.data(), url::Component(static_cast<int>(begin), current_len),
282             &canon_output)) {
283       // Failed to canonicalize this component; append as-is.
284       AppendInvalidString(host.substr(begin, current_len), &canon_output);
285     }
286 
287     mapping.canonical_end = canon_output.length();
288     components.push_back(mapping);
289 
290     if (current < host.length())
291       canon_output.push_back('.');
292   }
293   canon_output.Complete();
294 
295   size_t canonical_rcd_len =
296       GetRegistryLengthImpl(canonical_host, unknown_filter, private_filter)
297           .registry_length;
298   if (canonical_rcd_len == 0 || canonical_rcd_len == std::string::npos)
299     return canonical_rcd_len;  // Error or no registry controlled domain.
300 
301   // Find which host component the result started in.
302   size_t canonical_rcd_begin = canonical_host.length() - canonical_rcd_len;
303   for (const auto& mapping : components) {
304     // In the common case, GetRegistryLengthImpl will identify the beginning
305     // of a component and we can just return where that component was in the
306     // original string.
307     if (canonical_rcd_begin == mapping.canonical_begin)
308       return host.length() - mapping.original_begin;
309 
310     if (canonical_rcd_begin >= mapping.canonical_end)
311       continue;
312 
313     // The registry controlled domain begin was identified as being in the
314     // middle of this dot-separated domain component in the non-canonical
315     // input. This indicates some form of escaped dot, or a non-ASCII
316     // character that was canonicalized to a dot.
317     //
318     // Brute-force search from the end by repeatedly canonicalizing longer
319     // substrings until we get a match for the canonicalized version. This
320     // can't be done with binary search because canonicalization might increase
321     // or decrease the length of the produced string depending on where it's
322     // split. This depends on the canonicalization process not changing the
323     // order of the characters. Punycode can change the order of characters,
324     // but it doesn't work across dots so this is safe.
325 
326     // Expected canonical registry controlled domain.
327     std::string_view canonical_rcd(&canonical_host[canonical_rcd_begin],
328                                    canonical_rcd_len);
329 
330     for (int current_try = static_cast<int>(mapping.original_end) - 1;
331          current_try >= static_cast<int>(mapping.original_begin);
332          current_try--) {
333       std::string try_string;
334       url::StdStringCanonOutput try_output(&try_string);
335 
336       if (!url::CanonicalizeHostSubstring(
337               host.data(),
338               url::Component(
339                   current_try,
340                   static_cast<int>(mapping.original_end) - current_try),
341               &try_output))
342         continue;  // Invalid substring, skip.
343 
344       try_output.Complete();
345       if (try_string == canonical_rcd)
346         return host.length() - current_try;
347     }
348   }
349 
350   NOTREACHED();
351 }
352 
SameDomainOrHost(std::string_view host1,std::string_view host2,PrivateRegistryFilter filter)353 bool SameDomainOrHost(std::string_view host1,
354                       std::string_view host2,
355                       PrivateRegistryFilter filter) {
356   // Quickly reject cases where either host is empty.
357   if (host1.empty() || host2.empty())
358     return false;
359 
360   // Check for exact host matches, which is faster than looking up the domain
361   // and registry.
362   if (host1 == host2)
363     return true;
364 
365   // Check for a domain and registry match.
366   std::string_view domain1 = GetDomainAndRegistryAsStringPiece(host1, filter);
367   return !domain1.empty() &&
368          (domain1 == GetDomainAndRegistryAsStringPiece(host2, filter));
369 }
370 
371 }  // namespace
372 
GetDomainAndRegistry(const GURL & gurl,PrivateRegistryFilter filter)373 std::string GetDomainAndRegistry(const GURL& gurl,
374                                  PrivateRegistryFilter filter) {
375   return std::string(
376       GetDomainAndRegistryAsStringPiece(gurl.host_piece(), filter));
377 }
378 
GetDomainAndRegistry(const url::Origin & origin,PrivateRegistryFilter filter)379 std::string GetDomainAndRegistry(const url::Origin& origin,
380                                  PrivateRegistryFilter filter) {
381   return std::string(GetDomainAndRegistryAsStringPiece(origin.host(), filter));
382 }
383 
GetDomainAndRegistry(std::string_view host,PrivateRegistryFilter filter)384 std::string GetDomainAndRegistry(std::string_view host,
385                                  PrivateRegistryFilter filter) {
386   url::CanonHostInfo host_info;
387   const std::string canon_host(CanonicalizeHost(host, &host_info));
388   if (canon_host.empty() || host_info.IsIPAddress())
389     return std::string();
390   return std::string(GetDomainAndRegistryImpl(canon_host, filter));
391 }
392 
GetDomainAndRegistryAsStringPiece(const url::Origin & origin,PrivateRegistryFilter filter)393 std::string_view GetDomainAndRegistryAsStringPiece(
394     const url::Origin& origin,
395     PrivateRegistryFilter filter) {
396   return GetDomainAndRegistryAsStringPiece(origin.host(), filter);
397 }
398 
SameDomainOrHost(const GURL & gurl1,const GURL & gurl2,PrivateRegistryFilter filter)399 bool SameDomainOrHost(
400     const GURL& gurl1,
401     const GURL& gurl2,
402     PrivateRegistryFilter filter) {
403   return SameDomainOrHost(gurl1.host_piece(), gurl2.host_piece(), filter);
404 }
405 
SameDomainOrHost(const url::Origin & origin1,const url::Origin & origin2,PrivateRegistryFilter filter)406 bool SameDomainOrHost(const url::Origin& origin1,
407                       const url::Origin& origin2,
408                       PrivateRegistryFilter filter) {
409   return SameDomainOrHost(origin1.host(), origin2.host(), filter);
410 }
411 
SameDomainOrHost(const url::Origin & origin1,const std::optional<url::Origin> & origin2,PrivateRegistryFilter filter)412 bool SameDomainOrHost(const url::Origin& origin1,
413                       const std::optional<url::Origin>& origin2,
414                       PrivateRegistryFilter filter) {
415   return origin2.has_value() &&
416          SameDomainOrHost(origin1, origin2.value(), filter);
417 }
418 
SameDomainOrHost(const GURL & gurl,const url::Origin & origin,PrivateRegistryFilter filter)419 bool SameDomainOrHost(const GURL& gurl,
420                       const url::Origin& origin,
421                       PrivateRegistryFilter filter) {
422   return SameDomainOrHost(gurl.host_piece(), origin.host(), filter);
423 }
424 
GetRegistryLength(const GURL & gurl,UnknownRegistryFilter unknown_filter,PrivateRegistryFilter private_filter)425 size_t GetRegistryLength(
426     const GURL& gurl,
427     UnknownRegistryFilter unknown_filter,
428     PrivateRegistryFilter private_filter) {
429   return GetRegistryLengthImpl(gurl.host_piece(), unknown_filter,
430                                private_filter)
431       .registry_length;
432 }
433 
HostHasRegistryControlledDomain(std::string_view host,UnknownRegistryFilter unknown_filter,PrivateRegistryFilter private_filter)434 bool HostHasRegistryControlledDomain(std::string_view host,
435                                      UnknownRegistryFilter unknown_filter,
436                                      PrivateRegistryFilter private_filter) {
437   url::CanonHostInfo host_info;
438   const std::string canon_host(CanonicalizeHost(host, &host_info));
439 
440   size_t rcd_length;
441   switch (host_info.family) {
442     case url::CanonHostInfo::IPV4:
443     case url::CanonHostInfo::IPV6:
444       // IP addresses don't have R.C.D.'s.
445       return false;
446     case url::CanonHostInfo::BROKEN:
447       // Host is not canonicalizable. Fall back to the slower "permissive"
448       // version.
449       rcd_length =
450           PermissiveGetHostRegistryLength(host, unknown_filter, private_filter);
451       break;
452     case url::CanonHostInfo::NEUTRAL:
453       rcd_length =
454           GetRegistryLengthImpl(canon_host, unknown_filter, private_filter)
455               .registry_length;
456       break;
457     default:
458       NOTREACHED();
459   }
460   return (rcd_length != 0) && (rcd_length != std::string::npos);
461 }
462 
HostIsRegistryIdentifier(std::string_view canon_host,PrivateRegistryFilter private_filter)463 bool HostIsRegistryIdentifier(std::string_view canon_host,
464                               PrivateRegistryFilter private_filter) {
465   // The input is expected to be a valid, canonicalized hostname (not an IP
466   // address).
467   CHECK(!canon_host.empty());
468   url::CanonHostInfo host_info;
469   std::string canonicalized = CanonicalizeHost(canon_host, &host_info);
470   CHECK_EQ(canonicalized, canon_host);
471   CHECK_EQ(host_info.family, url::CanonHostInfo::NEUTRAL);
472   return GetRegistryLengthImpl(canon_host, EXCLUDE_UNKNOWN_REGISTRIES,
473                                private_filter)
474       .is_registry_identifier;
475 }
476 
GetCanonicalHostRegistryLength(std::string_view canon_host,UnknownRegistryFilter unknown_filter,PrivateRegistryFilter private_filter)477 size_t GetCanonicalHostRegistryLength(std::string_view canon_host,
478                                       UnknownRegistryFilter unknown_filter,
479                                       PrivateRegistryFilter private_filter) {
480 #ifndef NDEBUG
481   // Ensure passed-in host name is canonical.
482   url::CanonHostInfo host_info;
483   DCHECK_EQ(net::CanonicalizeHost(canon_host, &host_info), canon_host);
484 #endif
485 
486   return GetRegistryLengthImpl(canon_host, unknown_filter, private_filter)
487       .registry_length;
488 }
489 
PermissiveGetHostRegistryLength(std::string_view host,UnknownRegistryFilter unknown_filter,PrivateRegistryFilter private_filter)490 size_t PermissiveGetHostRegistryLength(std::string_view host,
491                                        UnknownRegistryFilter unknown_filter,
492                                        PrivateRegistryFilter private_filter) {
493   return DoPermissiveGetHostRegistryLength(host, unknown_filter,
494                                            private_filter);
495 }
496 
PermissiveGetHostRegistryLength(std::u16string_view host,UnknownRegistryFilter unknown_filter,PrivateRegistryFilter private_filter)497 size_t PermissiveGetHostRegistryLength(std::u16string_view host,
498                                        UnknownRegistryFilter unknown_filter,
499                                        PrivateRegistryFilter private_filter) {
500   return DoPermissiveGetHostRegistryLength(host, unknown_filter,
501                                            private_filter);
502 }
503 
ResetFindDomainGraphForTesting()504 void ResetFindDomainGraphForTesting() {
505   g_graph = kDafsa;
506 }
507 
SetFindDomainGraphForTesting(base::span<const uint8_t> domains)508 void SetFindDomainGraphForTesting(base::span<const uint8_t> domains) {
509   CHECK(!domains.empty());
510   g_graph = domains;
511 }
512 
513 }  // namespace net::registry_controlled_domains
514