xref: /aosp_15_r20/external/cronet/net/base/registry_controlled_domains/registry_controlled_domain.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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 <[email protected]> (original author)
30  *   Daniel Witte <[email protected]>
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 <ostream>
49 #include <string_view>
50 
51 #include "base/check_op.h"
52 #include "base/notreached.h"
53 #include "base/strings/string_util.h"
54 #include "base/strings/utf_string_conversions.h"
55 #include "net/base/lookup_string_in_fixed_set.h"
56 #include "net/base/net_module.h"
57 #include "net/base/url_util.h"
58 #include "url/gurl.h"
59 #include "url/origin.h"
60 #include "url/third_party/mozilla/url_parse.h"
61 #include "url/url_util.h"
62 
63 namespace net::registry_controlled_domains {
64 
65 namespace {
66 #include "net/base/registry_controlled_domains/effective_tld_names-reversed-inc.cc"
67 
68 // See make_dafsa.py for documentation of the generated dafsa byte array.
69 
70 const unsigned char* g_graph = kDafsa;
71 size_t g_graph_length = sizeof(kDafsa);
72 
73 struct MappedHostComponent {
74   size_t original_begin;
75   size_t original_end;
76 
77   size_t canonical_begin;
78   size_t canonical_end;
79 };
80 
81 // This version assumes we already removed leading dots from host as well as the
82 // last trailing dot if it had one.
GetRegistryLengthInTrimmedHost(std::string_view host,UnknownRegistryFilter unknown_filter,PrivateRegistryFilter private_filter)83 size_t GetRegistryLengthInTrimmedHost(std::string_view host,
84                                       UnknownRegistryFilter unknown_filter,
85                                       PrivateRegistryFilter private_filter) {
86   size_t length;
87   int type = LookupSuffixInReversedSet(
88       g_graph, g_graph_length, private_filter == INCLUDE_PRIVATE_REGISTRIES,
89       host, &length);
90 
91   CHECK_LE(length, host.size());
92 
93   // No rule found in the registry.
94   if (type == kDafsaNotFound) {
95     // If we allow unknown registries, return the length of last subcomponent.
96     if (unknown_filter == INCLUDE_UNKNOWN_REGISTRIES) {
97       const size_t last_dot = host.find_last_of('.');
98       if (last_dot != std::string_view::npos) {
99         return host.size() - last_dot - 1;
100       }
101     }
102     return 0;
103   }
104 
105   // Exception rules override wildcard rules when the domain is an exact
106   // match, but wildcards take precedence when there's a subdomain.
107   if (type & kDafsaWildcardRule) {
108     // If the complete host matches, then the host is the wildcard suffix, so
109     // return 0.
110     if (length == host.size())
111       return 0;
112 
113     CHECK_LE(length + 2, host.size());
114     CHECK_EQ('.', host[host.size() - length - 1]);
115 
116     const size_t preceding_dot =
117         host.find_last_of('.', host.size() - length - 2);
118 
119     // If no preceding dot, then the host is the registry itself, so return 0.
120     if (preceding_dot == std::string_view::npos) {
121       return 0;
122     }
123 
124     // Return suffix size plus size of subdomain.
125     return host.size() - preceding_dot - 1;
126   }
127 
128   if (type & kDafsaExceptionRule) {
129     size_t first_dot = host.find_first_of('.', host.size() - length);
130     if (first_dot == std::string_view::npos) {
131       // If we get here, we had an exception rule with no dots (e.g.
132       // "!foo").  This would only be valid if we had a corresponding
133       // wildcard rule, which would have to be "*".  But we explicitly
134       // disallow that case, so this kind of rule is invalid.
135       // TODO(https://crbug.com/459802): This assumes that all wildcard entries,
136       // such as *.foo.invalid, also have their parent, foo.invalid, as an entry
137       // on the PSL, which is why it returns the length of foo.invalid. This
138       // isn't entirely correct.
139       NOTREACHED() << "Invalid exception rule";
140       return 0;
141     }
142     return host.length() - first_dot - 1;
143   }
144 
145   CHECK_NE(type, kDafsaNotFound);
146 
147   // If a complete match, then the host is the registry itself, so return 0.
148   if (length == host.size())
149     return 0;
150 
151   return length;
152 }
153 
GetRegistryLengthImpl(std::string_view host,UnknownRegistryFilter unknown_filter,PrivateRegistryFilter private_filter)154 size_t GetRegistryLengthImpl(std::string_view host,
155                              UnknownRegistryFilter unknown_filter,
156                              PrivateRegistryFilter private_filter) {
157   if (host.empty())
158     return std::string::npos;
159 
160   // Skip leading dots.
161   const size_t host_check_begin = host.find_first_not_of('.');
162   if (host_check_begin == std::string_view::npos) {
163     return 0;  // Host is only dots.
164   }
165 
166   // A single trailing dot isn't relevant in this determination, but does need
167   // to be included in the final returned length.
168   size_t host_check_end = host.size();
169   if (host.back() == '.')
170     --host_check_end;
171 
172   size_t length = GetRegistryLengthInTrimmedHost(
173       host.substr(host_check_begin, host_check_end - host_check_begin),
174       unknown_filter, private_filter);
175 
176   if (length == 0)
177     return 0;
178 
179   return length + host.size() - host_check_end;
180 }
181 
GetDomainAndRegistryImpl(std::string_view host,PrivateRegistryFilter private_filter)182 std::string_view GetDomainAndRegistryImpl(
183     std::string_view host,
184     PrivateRegistryFilter private_filter) {
185   CHECK(!host.empty());
186 
187   // Find the length of the registry for this host.
188   const size_t registry_length =
189       GetRegistryLengthImpl(host, INCLUDE_UNKNOWN_REGISTRIES, private_filter);
190   if ((registry_length == std::string::npos) || (registry_length == 0))
191     return std::string_view();  // No registry.
192   // The "2" in this next line is 1 for the dot, plus a 1-char minimum preceding
193   // subcomponent length.
194   CHECK_GE(host.length(), 2u);
195   CHECK_LE(registry_length, host.length() - 2)
196       << "Host does not have at least one subcomponent before registry!";
197 
198   // Move past the dot preceding the registry, and search for the next previous
199   // dot.  Return the host from after that dot, or the whole host when there is
200   // no dot.
201   const size_t dot = host.rfind('.', host.length() - registry_length - 2);
202   if (dot == std::string::npos)
203     return host;
204   return host.substr(dot + 1);
205 }
206 
207 // Same as GetDomainAndRegistry, but returns the domain and registry as a
208 // StringPiece that references the underlying string of the passed-in |gurl|.
209 // TODO(pkalinnikov): Eliminate this helper by exposing StringPiece as the
210 // interface type for all the APIs.
GetDomainAndRegistryAsStringPiece(std::string_view host,PrivateRegistryFilter filter)211 std::string_view GetDomainAndRegistryAsStringPiece(
212     std::string_view host,
213     PrivateRegistryFilter filter) {
214   if (host.empty() || url::HostIsIPAddress(host))
215     return std::string_view();
216   return GetDomainAndRegistryImpl(host, filter);
217 }
218 
219 // These two functions append the given string as-is to the given output,
220 // converting to UTF-8 if necessary.
AppendInvalidString(std::string_view str,url::CanonOutput * output)221 void AppendInvalidString(std::string_view str, url::CanonOutput* output) {
222   output->Append(str);
223 }
AppendInvalidString(std::u16string_view str,url::CanonOutput * output)224 void AppendInvalidString(std::u16string_view str, url::CanonOutput* output) {
225   output->Append(base::UTF16ToUTF8(str));
226 }
227 
228 // Backend for PermissiveGetHostRegistryLength that handles both UTF-8 and
229 // UTF-16 input.
230 template <typename T, typename CharT = typename T::value_type>
DoPermissiveGetHostRegistryLength(T host,UnknownRegistryFilter unknown_filter,PrivateRegistryFilter private_filter)231 size_t DoPermissiveGetHostRegistryLength(T host,
232                                          UnknownRegistryFilter unknown_filter,
233                                          PrivateRegistryFilter private_filter) {
234   std::string canonical_host;  // Do not modify outside of canon_output.
235   canonical_host.reserve(host.length());
236   url::StdStringCanonOutput canon_output(&canonical_host);
237 
238   std::vector<MappedHostComponent> components;
239 
240   for (size_t current = 0; current < host.length(); current++) {
241     size_t begin = current;
242 
243     // Advance to next "." or end.
244     current = host.find('.', begin);
245     if (current == std::string::npos)
246       current = host.length();
247 
248     MappedHostComponent mapping;
249     mapping.original_begin = begin;
250     mapping.original_end = current;
251     mapping.canonical_begin = canon_output.length();
252 
253     // Try to append the canonicalized version of this component.
254     int current_len = static_cast<int>(current - begin);
255     if (!url::CanonicalizeHostSubstring(
256             host.data(), url::Component(static_cast<int>(begin), current_len),
257             &canon_output)) {
258       // Failed to canonicalize this component; append as-is.
259       AppendInvalidString(host.substr(begin, current_len), &canon_output);
260     }
261 
262     mapping.canonical_end = canon_output.length();
263     components.push_back(mapping);
264 
265     if (current < host.length())
266       canon_output.push_back('.');
267   }
268   canon_output.Complete();
269 
270   size_t canonical_rcd_len =
271       GetRegistryLengthImpl(canonical_host, unknown_filter, private_filter);
272   if (canonical_rcd_len == 0 || canonical_rcd_len == std::string::npos)
273     return canonical_rcd_len;  // Error or no registry controlled domain.
274 
275   // Find which host component the result started in.
276   size_t canonical_rcd_begin = canonical_host.length() - canonical_rcd_len;
277   for (const auto& mapping : components) {
278     // In the common case, GetRegistryLengthImpl will identify the beginning
279     // of a component and we can just return where that component was in the
280     // original string.
281     if (canonical_rcd_begin == mapping.canonical_begin)
282       return host.length() - mapping.original_begin;
283 
284     if (canonical_rcd_begin >= mapping.canonical_end)
285       continue;
286 
287     // The registry controlled domain begin was identified as being in the
288     // middle of this dot-separated domain component in the non-canonical
289     // input. This indicates some form of escaped dot, or a non-ASCII
290     // character that was canonicalized to a dot.
291     //
292     // Brute-force search from the end by repeatedly canonicalizing longer
293     // substrings until we get a match for the canonicalized version. This
294     // can't be done with binary search because canonicalization might increase
295     // or decrease the length of the produced string depending on where it's
296     // split. This depends on the canonicalization process not changing the
297     // order of the characters. Punycode can change the order of characters,
298     // but it doesn't work across dots so this is safe.
299 
300     // Expected canonical registry controlled domain.
301     std::string_view canonical_rcd(&canonical_host[canonical_rcd_begin],
302                                    canonical_rcd_len);
303 
304     for (int current_try = static_cast<int>(mapping.original_end) - 1;
305          current_try >= static_cast<int>(mapping.original_begin);
306          current_try--) {
307       std::string try_string;
308       url::StdStringCanonOutput try_output(&try_string);
309 
310       if (!url::CanonicalizeHostSubstring(
311               host.data(),
312               url::Component(
313                   current_try,
314                   static_cast<int>(mapping.original_end) - current_try),
315               &try_output))
316         continue;  // Invalid substring, skip.
317 
318       try_output.Complete();
319       if (try_string == canonical_rcd)
320         return host.length() - current_try;
321     }
322   }
323 
324   NOTREACHED();
325   return canonical_rcd_len;
326 }
327 
SameDomainOrHost(std::string_view host1,std::string_view host2,PrivateRegistryFilter filter)328 bool SameDomainOrHost(std::string_view host1,
329                       std::string_view host2,
330                       PrivateRegistryFilter filter) {
331   // Quickly reject cases where either host is empty.
332   if (host1.empty() || host2.empty())
333     return false;
334 
335   // Check for exact host matches, which is faster than looking up the domain
336   // and registry.
337   if (host1 == host2)
338     return true;
339 
340   // Check for a domain and registry match.
341   std::string_view domain1 = GetDomainAndRegistryAsStringPiece(host1, filter);
342   return !domain1.empty() &&
343          (domain1 == GetDomainAndRegistryAsStringPiece(host2, filter));
344 }
345 
346 }  // namespace
347 
GetDomainAndRegistry(const GURL & gurl,PrivateRegistryFilter filter)348 std::string GetDomainAndRegistry(const GURL& gurl,
349                                  PrivateRegistryFilter filter) {
350   return std::string(
351       GetDomainAndRegistryAsStringPiece(gurl.host_piece(), filter));
352 }
353 
GetDomainAndRegistry(const url::Origin & origin,PrivateRegistryFilter filter)354 std::string GetDomainAndRegistry(const url::Origin& origin,
355                                  PrivateRegistryFilter filter) {
356   return std::string(GetDomainAndRegistryAsStringPiece(origin.host(), filter));
357 }
358 
GetDomainAndRegistry(std::string_view host,PrivateRegistryFilter filter)359 std::string GetDomainAndRegistry(std::string_view host,
360                                  PrivateRegistryFilter filter) {
361   url::CanonHostInfo host_info;
362   const std::string canon_host(CanonicalizeHost(host, &host_info));
363   if (canon_host.empty() || host_info.IsIPAddress())
364     return std::string();
365   return std::string(GetDomainAndRegistryImpl(canon_host, filter));
366 }
367 
SameDomainOrHost(const GURL & gurl1,const GURL & gurl2,PrivateRegistryFilter filter)368 bool SameDomainOrHost(
369     const GURL& gurl1,
370     const GURL& gurl2,
371     PrivateRegistryFilter filter) {
372   return SameDomainOrHost(gurl1.host_piece(), gurl2.host_piece(), filter);
373 }
374 
SameDomainOrHost(const url::Origin & origin1,const url::Origin & origin2,PrivateRegistryFilter filter)375 bool SameDomainOrHost(const url::Origin& origin1,
376                       const url::Origin& origin2,
377                       PrivateRegistryFilter filter) {
378   return SameDomainOrHost(origin1.host(), origin2.host(), filter);
379 }
380 
SameDomainOrHost(const url::Origin & origin1,const std::optional<url::Origin> & origin2,PrivateRegistryFilter filter)381 bool SameDomainOrHost(const url::Origin& origin1,
382                       const std::optional<url::Origin>& origin2,
383                       PrivateRegistryFilter filter) {
384   return origin2.has_value() &&
385          SameDomainOrHost(origin1, origin2.value(), filter);
386 }
387 
SameDomainOrHost(const GURL & gurl,const url::Origin & origin,PrivateRegistryFilter filter)388 bool SameDomainOrHost(const GURL& gurl,
389                       const url::Origin& origin,
390                       PrivateRegistryFilter filter) {
391   return SameDomainOrHost(gurl.host_piece(), origin.host(), filter);
392 }
393 
GetRegistryLength(const GURL & gurl,UnknownRegistryFilter unknown_filter,PrivateRegistryFilter private_filter)394 size_t GetRegistryLength(
395     const GURL& gurl,
396     UnknownRegistryFilter unknown_filter,
397     PrivateRegistryFilter private_filter) {
398   return GetRegistryLengthImpl(gurl.host_piece(), unknown_filter,
399                                private_filter);
400 }
401 
HostHasRegistryControlledDomain(std::string_view host,UnknownRegistryFilter unknown_filter,PrivateRegistryFilter private_filter)402 bool HostHasRegistryControlledDomain(std::string_view host,
403                                      UnknownRegistryFilter unknown_filter,
404                                      PrivateRegistryFilter private_filter) {
405   url::CanonHostInfo host_info;
406   const std::string canon_host(CanonicalizeHost(host, &host_info));
407 
408   size_t rcd_length;
409   switch (host_info.family) {
410     case url::CanonHostInfo::IPV4:
411     case url::CanonHostInfo::IPV6:
412       // IP addresses don't have R.C.D.'s.
413       return false;
414     case url::CanonHostInfo::BROKEN:
415       // Host is not canonicalizable. Fall back to the slower "permissive"
416       // version.
417       rcd_length =
418           PermissiveGetHostRegistryLength(host, unknown_filter, private_filter);
419       break;
420     case url::CanonHostInfo::NEUTRAL:
421       rcd_length =
422           GetRegistryLengthImpl(canon_host, unknown_filter, private_filter);
423       break;
424     default:
425       NOTREACHED();
426       return false;
427   }
428   return (rcd_length != 0) && (rcd_length != std::string::npos);
429 }
430 
GetCanonicalHostRegistryLength(std::string_view canon_host,UnknownRegistryFilter unknown_filter,PrivateRegistryFilter private_filter)431 size_t GetCanonicalHostRegistryLength(std::string_view canon_host,
432                                       UnknownRegistryFilter unknown_filter,
433                                       PrivateRegistryFilter private_filter) {
434 #ifndef NDEBUG
435   // Ensure passed-in host name is canonical.
436   url::CanonHostInfo host_info;
437   DCHECK_EQ(net::CanonicalizeHost(canon_host, &host_info), canon_host);
438 #endif
439 
440   return GetRegistryLengthImpl(canon_host, unknown_filter, private_filter);
441 }
442 
PermissiveGetHostRegistryLength(std::string_view host,UnknownRegistryFilter unknown_filter,PrivateRegistryFilter private_filter)443 size_t PermissiveGetHostRegistryLength(std::string_view host,
444                                        UnknownRegistryFilter unknown_filter,
445                                        PrivateRegistryFilter private_filter) {
446   return DoPermissiveGetHostRegistryLength(host, unknown_filter,
447                                            private_filter);
448 }
449 
PermissiveGetHostRegistryLength(std::u16string_view host,UnknownRegistryFilter unknown_filter,PrivateRegistryFilter private_filter)450 size_t PermissiveGetHostRegistryLength(std::u16string_view host,
451                                        UnknownRegistryFilter unknown_filter,
452                                        PrivateRegistryFilter private_filter) {
453   return DoPermissiveGetHostRegistryLength(host, unknown_filter,
454                                            private_filter);
455 }
456 
ResetFindDomainGraphForTesting()457 void ResetFindDomainGraphForTesting() {
458   g_graph = kDafsa;
459   g_graph_length = sizeof(kDafsa);
460 }
461 
SetFindDomainGraphForTesting(const unsigned char * domains,size_t length)462 void SetFindDomainGraphForTesting(const unsigned char* domains, size_t length) {
463   CHECK(domains);
464   CHECK_NE(length, 0u);
465   g_graph = domains;
466   g_graph_length = length;
467 }
468 
469 }  // namespace net::registry_controlled_domains
470