domains.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. from __future__ import annotations
  2. from functools import cached_property
  3. import dns
  4. import psl_dns
  5. from django.conf import settings
  6. from django.contrib.auth.models import AnonymousUser
  7. from django.core.exceptions import ValidationError
  8. from django.db import models
  9. from django.db.models import CharField, F, Manager, Q, Value
  10. from django.db.models.functions import Concat, Length
  11. from django_prometheus.models import ExportModelOperationsMixin
  12. from dns.exception import Timeout
  13. from dns.resolver import NoNameservers
  14. from rest_framework.exceptions import APIException
  15. from desecapi import logger, metrics, pdns
  16. from .base import validate_domain_name
  17. from .records import RRset
  18. psl = psl_dns.PSL(resolver=settings.PSL_RESOLVER, timeout=.5)
  19. class DomainManager(Manager):
  20. def filter_qname(self, qname: str, **kwargs) -> models.query.QuerySet:
  21. qs = self.annotate(name_length=Length('name')) # callers expect this to be present after returning
  22. try:
  23. Domain._meta.get_field('name').run_validators(qname.removeprefix('*.').lower())
  24. except ValidationError:
  25. return qs.none()
  26. return qs.annotate(
  27. dotted_name=Concat(Value('.'), 'name', output_field=CharField()),
  28. dotted_qname=Value(f'.{qname}', output_field=CharField()),
  29. ).filter(dotted_qname__endswith=F('dotted_name'), **kwargs)
  30. class Domain(ExportModelOperationsMixin('Domain'), models.Model):
  31. @staticmethod
  32. def _minimum_ttl_default():
  33. return settings.MINIMUM_TTL_DEFAULT
  34. class RenewalState(models.IntegerChoices):
  35. IMMORTAL = 0
  36. FRESH = 1
  37. NOTIFIED = 2
  38. WARNED = 3
  39. created = models.DateTimeField(auto_now_add=True)
  40. name = models.CharField(max_length=191,
  41. unique=True,
  42. validators=validate_domain_name)
  43. owner = models.ForeignKey('User', on_delete=models.PROTECT, related_name='domains')
  44. published = models.DateTimeField(null=True, blank=True)
  45. minimum_ttl = models.PositiveIntegerField(default=_minimum_ttl_default.__func__)
  46. renewal_state = models.IntegerField(choices=RenewalState.choices, default=RenewalState.IMMORTAL)
  47. renewal_changed = models.DateTimeField(auto_now_add=True)
  48. _keys = None
  49. objects = DomainManager()
  50. class Meta:
  51. constraints = [models.UniqueConstraint(fields=['id', 'owner'], name='unique_id_owner')]
  52. ordering = ('created',)
  53. def __init__(self, *args, **kwargs):
  54. if isinstance(kwargs.get('owner'), AnonymousUser):
  55. kwargs = {**kwargs, 'owner': None} # make a copy and override
  56. # Avoid super().__init__(owner=None, ...) to not mess up *values instantiation in django.db.models.Model.from_db
  57. super().__init__(*args, **kwargs)
  58. if self.pk is None and kwargs.get('renewal_state') is None and self.is_locally_registrable:
  59. self.renewal_state = Domain.RenewalState.FRESH
  60. @cached_property
  61. def public_suffix(self):
  62. try:
  63. public_suffix = psl.get_public_suffix(self.name)
  64. is_public_suffix = psl.is_public_suffix(self.name)
  65. except (Timeout, NoNameservers):
  66. public_suffix = self.name.rpartition('.')[2]
  67. is_public_suffix = ('.' not in self.name) # TLDs are public suffixes
  68. if is_public_suffix:
  69. return public_suffix
  70. # Take into account that any of the parent domains could be a local public suffix. To that
  71. # end, identify the longest local public suffix that is actually a suffix of domain_name.
  72. for local_public_suffix in settings.LOCAL_PUBLIC_SUFFIXES:
  73. has_local_public_suffix_parent = ('.' + self.name).endswith('.' + local_public_suffix)
  74. if has_local_public_suffix_parent and len(local_public_suffix) > len(public_suffix):
  75. public_suffix = local_public_suffix
  76. return public_suffix
  77. def is_covered_by_foreign_zone(self):
  78. # Generate a list of all domains connecting this one and its public suffix.
  79. # If another user owns a zone with one of these names, then the requested
  80. # domain is unavailable because it is part of the other user's zone.
  81. private_components = self.name.rsplit(self.public_suffix, 1)[0].rstrip('.')
  82. private_components = private_components.split('.') if private_components else []
  83. private_domains = ['.'.join(private_components[i:]) for i in range(0, len(private_components))]
  84. private_domains = [f'{private_domain}.{self.public_suffix}' for private_domain in private_domains]
  85. assert self.name == next(iter(private_domains), self.public_suffix)
  86. # Determine whether domain is covered by other users' zones
  87. return Domain.objects.filter(Q(name__in=private_domains) & ~Q(owner=self._owner_or_none)).exists()
  88. def covers_foreign_zone(self):
  89. # Note: This is not completely accurate: Ideally, we should only consider zones with identical public suffix.
  90. # (If a public suffix lies in between, it's ok.) However, as there could be many descendant zones, the accurate
  91. # check is expensive, so currently not implemented (PSL lookups for each of them).
  92. return Domain.objects.filter(Q(name__endswith=f'.{self.name}') & ~Q(owner=self._owner_or_none)).exists()
  93. def is_registrable(self):
  94. """
  95. Returns False if the domain name is reserved, a public suffix, or covered by / covers another user's domain.
  96. Otherwise, True is returned.
  97. """
  98. self.clean() # ensure .name is a domain name
  99. private_generation = self.name.count('.') - self.public_suffix.count('.')
  100. assert private_generation >= 0
  101. # .internal is reserved
  102. if f'.{self.name}'.endswith('.internal'):
  103. return False
  104. # Public suffixes can only be registered if they are local
  105. if private_generation == 0 and self.name not in settings.LOCAL_PUBLIC_SUFFIXES:
  106. return False
  107. # Disallow _acme-challenge.dedyn.io and the like. Rejects reserved direct children of public suffixes.
  108. reserved_prefixes = ('_', 'autoconfig.', 'autodiscover.',)
  109. if private_generation == 1 and any(self.name.startswith(prefix) for prefix in reserved_prefixes):
  110. return False
  111. # Domains covered by another user's zone can't be registered
  112. if self.is_covered_by_foreign_zone():
  113. return False
  114. # Domains that would cover another user's zone can't be registered
  115. if self.covers_foreign_zone():
  116. return False
  117. return True
  118. @property
  119. def keys(self):
  120. if not self._keys:
  121. self._keys = [{**key, 'managed': True} for key in pdns.get_keys(self)]
  122. try:
  123. unmanaged_keys = self.rrset_set.get(subname='', type='DNSKEY').records.all()
  124. except RRset.DoesNotExist:
  125. pass
  126. else:
  127. name = dns.name.from_text(self.name)
  128. for rr in unmanaged_keys:
  129. key = dns.rdata.from_text(dns.rdataclass.IN, dns.rdatatype.DNSKEY, rr.content)
  130. key_is_sep = key.flags & dns.rdtypes.ANY.DNSKEY.SEP
  131. self._keys.append({
  132. 'dnskey': rr.content,
  133. 'ds': [dns.dnssec.make_ds(name, key, algo).to_text() for algo in (2, 4)] if key_is_sep else [],
  134. 'flags': key.flags, # deprecated
  135. 'keytype': None, # deprecated
  136. 'managed': False,
  137. })
  138. return self._keys
  139. @property
  140. def touched(self):
  141. try:
  142. rrset_touched = max(updated for updated in self.rrset_set.values_list('touched', flat=True))
  143. except ValueError: # no RRsets (but there should be at least NS)
  144. return self.published # may be None if the domain was never published
  145. return max(rrset_touched, self.published or rrset_touched)
  146. @property
  147. def is_locally_registrable(self):
  148. return self.parent_domain_name in settings.LOCAL_PUBLIC_SUFFIXES
  149. @property
  150. def _owner_or_none(self):
  151. try:
  152. return self.owner
  153. except Domain.owner.RelatedObjectDoesNotExist:
  154. return None
  155. @property
  156. def parent_domain_name(self):
  157. return self._partitioned_name[1]
  158. @property
  159. def _partitioned_name(self):
  160. subname, _, parent_name = self.name.partition('.')
  161. return subname, parent_name or None
  162. def save(self, *args, **kwargs):
  163. self.full_clean(validate_unique=False)
  164. super().save(*args, **kwargs)
  165. def update_delegation(self, child_domain: Domain):
  166. child_subname, child_domain_name = child_domain._partitioned_name
  167. if self.name != child_domain_name:
  168. raise ValueError('Cannot update delegation of %s as it is not an immediate child domain of %s.' %
  169. (child_domain.name, self.name))
  170. # Always remove delegation so that we con properly recreate it
  171. for rrset in self.rrset_set.filter(subname=child_subname, type__in=['NS', 'DS']):
  172. rrset.delete()
  173. if child_domain.pk:
  174. # Domain real: (re-)set delegation
  175. child_keys = child_domain.keys
  176. if not child_keys:
  177. raise APIException('Cannot delegate %s, as it currently has no keys.' % child_domain.name)
  178. RRset.objects.create(domain=self, subname=child_subname, type='NS', ttl=3600, contents=settings.DEFAULT_NS)
  179. RRset.objects.create(domain=self, subname=child_subname, type='DS', ttl=300,
  180. contents=[ds for k in child_keys for ds in k['ds']])
  181. metrics.get('desecapi_autodelegation_created').inc()
  182. else:
  183. # Domain not real: that's it
  184. metrics.get('desecapi_autodelegation_deleted').inc()
  185. def delete(self):
  186. ret = super().delete()
  187. logger.warning(f'Domain {self.name} deleted (owner: {self.owner.pk})')
  188. return ret
  189. def __str__(self):
  190. return self.name