domains.py 11 KB

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