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