domains.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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._state.adding may be incorrect during signal processing (change tracker)
  68. self.pk is None
  69. and kwargs.get("renewal_state") is None
  70. and self.is_locally_registrable
  71. ):
  72. self.renewal_state = Domain.RenewalState.FRESH
  73. @cached_property
  74. def public_suffix(self):
  75. try:
  76. public_suffix = psl.get_public_suffix(self.name)
  77. is_public_suffix = psl.is_public_suffix(self.name)
  78. except (Timeout, NoNameservers):
  79. public_suffix = self.name.rpartition(".")[2]
  80. is_public_suffix = "." not in self.name # TLDs are public suffixes
  81. if is_public_suffix:
  82. return public_suffix
  83. # Take into account that any of the parent domains could be a local public suffix. To that
  84. # end, identify the longest local public suffix that is actually a suffix of domain_name.
  85. for local_public_suffix in settings.LOCAL_PUBLIC_SUFFIXES:
  86. has_local_public_suffix_parent = ("." + self.name).endswith(
  87. "." + local_public_suffix
  88. )
  89. if has_local_public_suffix_parent and len(local_public_suffix) > len(
  90. public_suffix
  91. ):
  92. public_suffix = local_public_suffix
  93. return public_suffix
  94. def is_covered_by_foreign_zone(self):
  95. # Generate a list of all domains connecting this one and its public suffix.
  96. # If another user owns a zone with one of these names, then the requested
  97. # domain is unavailable because it is part of the other user's zone.
  98. private_components = self.name.rsplit(self.public_suffix, 1)[0].rstrip(".")
  99. private_components = private_components.split(".") if private_components else []
  100. private_domains = [
  101. ".".join(private_components[i:]) for i in range(0, len(private_components))
  102. ]
  103. private_domains = [
  104. f"{private_domain}.{self.public_suffix}"
  105. for private_domain in private_domains
  106. ]
  107. assert self.name == next(iter(private_domains), self.public_suffix)
  108. # Determine whether domain is covered by other users' zones
  109. return Domain.objects.filter(
  110. Q(name__in=private_domains) & ~Q(owner=self._owner_or_none)
  111. ).exists()
  112. def covers_foreign_zone(self):
  113. # Note: This is not completely accurate: Ideally, we should only consider zones with identical public suffix.
  114. # (If a public suffix lies in between, it's ok.) However, as there could be many descendant zones, the accurate
  115. # check is expensive, so currently not implemented (PSL lookups for each of them).
  116. return Domain.objects.filter(
  117. Q(name__endswith=f".{self.name}") & ~Q(owner=self._owner_or_none)
  118. ).exists()
  119. def is_registrable(self):
  120. """
  121. Returns False if the domain name is reserved, a public suffix, or covered by / covers another user's domain.
  122. Otherwise, True is returned.
  123. """
  124. self.clean() # ensure .name is a domain name
  125. private_generation = self.name.count(".") - self.public_suffix.count(".")
  126. assert private_generation >= 0
  127. # .internal is reserved
  128. if f".{self.name}".endswith(".internal"):
  129. return False
  130. # Public suffixes can only be registered if they are local
  131. if private_generation == 0 and self.name not in settings.LOCAL_PUBLIC_SUFFIXES:
  132. return False
  133. # Disallow _acme-challenge.dedyn.io and the like. Rejects reserved direct children of public suffixes.
  134. reserved_prefixes = (
  135. "_",
  136. "autoconfig.",
  137. "autodiscover.",
  138. )
  139. if private_generation == 1 and any(
  140. self.name.startswith(prefix) for prefix in reserved_prefixes
  141. ):
  142. return False
  143. # Domains covered by another user's zone can't be registered
  144. if self.is_covered_by_foreign_zone():
  145. return False
  146. # Domains that would cover another user's zone can't be registered
  147. if self.covers_foreign_zone():
  148. return False
  149. return True
  150. @property
  151. def keys(self):
  152. if not self._keys:
  153. self._keys = [{**key, "managed": True} for key in pdns.get_keys(self)]
  154. try:
  155. unmanaged_keys = self.rrset_set.get(
  156. subname="", type="DNSKEY"
  157. ).records.all()
  158. except RRset.DoesNotExist:
  159. pass
  160. else:
  161. name = dns.name.from_text(self.name)
  162. for rr in unmanaged_keys:
  163. key = dns.rdata.from_text(
  164. dns.rdataclass.IN, dns.rdatatype.DNSKEY, rr.content
  165. )
  166. key_is_sep = key.flags & dns.rdtypes.ANY.DNSKEY.SEP
  167. self._keys.append(
  168. {
  169. "dnskey": rr.content,
  170. "ds": (
  171. [
  172. dns.dnssec.make_ds(name, key, algo).to_text()
  173. for algo in (2, 4)
  174. ]
  175. if key_is_sep
  176. else []
  177. ),
  178. "flags": key.flags, # deprecated
  179. "keytype": None, # deprecated
  180. "managed": False,
  181. }
  182. )
  183. return self._keys
  184. @property
  185. def touched(self):
  186. try:
  187. rrset_touched = max(
  188. updated for updated in self.rrset_set.values_list("touched", flat=True)
  189. )
  190. except ValueError: # no RRsets (but there should be at least NS)
  191. return self.published # may be None if the domain was never published
  192. return max(rrset_touched, self.published or rrset_touched)
  193. @property
  194. def is_locally_registrable(self):
  195. return self.parent_domain_name in settings.LOCAL_PUBLIC_SUFFIXES
  196. @property
  197. def _owner_or_none(self):
  198. try:
  199. return self.owner
  200. except Domain.owner.RelatedObjectDoesNotExist:
  201. return None
  202. @property
  203. def parent_domain_name(self):
  204. return self._partitioned_name[1]
  205. @property
  206. def _partitioned_name(self):
  207. subname, _, parent_name = self.name.partition(".")
  208. return subname, parent_name or None
  209. @property
  210. def zonefile(self):
  211. return pdns.get_zonefile(self)
  212. def save(self, *args, **kwargs):
  213. self.full_clean(validate_unique=False)
  214. super().save(*args, **kwargs)
  215. def update_delegation(self, child_domain: Domain):
  216. child_subname, child_domain_name = child_domain._partitioned_name
  217. if self.name != child_domain_name:
  218. raise ValueError(
  219. "Cannot update delegation of %s as it is not an immediate child domain of %s."
  220. % (child_domain.name, self.name)
  221. )
  222. # Always remove delegation so that we con properly recreate it
  223. for rrset in self.rrset_set.filter(
  224. subname=child_subname, type__in=["NS", "DS"]
  225. ):
  226. rrset.delete()
  227. if child_domain.pk:
  228. # Domain real: (re-)set delegation
  229. child_keys = child_domain.keys
  230. if not child_keys:
  231. raise APIException(
  232. "Cannot delegate %s, as it currently has no keys."
  233. % child_domain.name
  234. )
  235. RRset.objects.create(
  236. domain=self,
  237. subname=child_subname,
  238. type="NS",
  239. ttl=3600,
  240. contents=settings.DEFAULT_NS,
  241. )
  242. RRset.objects.create(
  243. domain=self,
  244. subname=child_subname,
  245. type="DS",
  246. ttl=300,
  247. contents=[ds for k in child_keys for ds in k["ds"]],
  248. )
  249. metrics.get("desecapi_autodelegation_created").inc()
  250. else:
  251. # Domain not real: that's it
  252. metrics.get("desecapi_autodelegation_deleted").inc()
  253. def delete(self, *args, **kwargs):
  254. ret = super().delete(*args, **kwargs)
  255. logger.warning(f"Domain {self.name} deleted (owner: {self.owner.pk})")
  256. return ret
  257. def __str__(self):
  258. return self.name