models.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. from __future__ import annotations
  2. import binascii
  3. import ipaddress
  4. import json
  5. import logging
  6. import re
  7. import secrets
  8. import string
  9. import time
  10. import uuid
  11. from datetime import timedelta
  12. from functools import cached_property
  13. from hashlib import sha256
  14. import dns
  15. import pgtrigger
  16. import psl_dns
  17. import rest_framework.authtoken.models
  18. from django.conf import settings
  19. from django.contrib.auth.hashers import make_password
  20. from django.contrib.auth.models import AbstractBaseUser, AnonymousUser, BaseUserManager
  21. from django.contrib.postgres.constraints import ExclusionConstraint
  22. from django.contrib.postgres.fields import ArrayField, CIEmailField, RangeOperators
  23. from django.core.exceptions import ValidationError
  24. from django.core.mail import EmailMessage, get_connection
  25. from django.core.validators import MinValueValidator, RegexValidator
  26. from django.db import models, transaction
  27. from django.db.models import CharField, F, Manager, Q, Value
  28. from django.db.models.expressions import RawSQL
  29. from django.db.models.functions import Concat, Length
  30. from django.template.loader import get_template
  31. from django.utils import timezone
  32. from django_prometheus.models import ExportModelOperationsMixin
  33. from dns import rdataclass, rdatatype
  34. from dns.exception import Timeout
  35. from dns.rdtypes import ANY, IN
  36. from dns.resolver import NoNameservers
  37. from netfields import CidrAddressField, NetManager
  38. from rest_framework.exceptions import APIException
  39. from desecapi import metrics
  40. from desecapi import pdns
  41. from desecapi.dns import AAAA, CDS, DLV, DS, LongQuotedTXT, MX, NS, SRV
  42. logger = logging.getLogger(__name__)
  43. psl = psl_dns.PSL(resolver=settings.PSL_RESOLVER, timeout=.5)
  44. def validate_lower(value):
  45. if value != value.lower():
  46. raise ValidationError('Invalid value (not lowercase): %(value)s',
  47. code='invalid',
  48. params={'value': value})
  49. def validate_upper(value):
  50. if value != value.upper():
  51. raise ValidationError('Invalid value (not uppercase): %(value)s',
  52. code='invalid',
  53. params={'value': value})
  54. class MyUserManager(BaseUserManager):
  55. def create_user(self, email, password, **extra_fields):
  56. """
  57. Creates and saves a User with the given email, date of
  58. birth and password.
  59. """
  60. if not email:
  61. raise ValueError('Users must have an email address')
  62. email = self.normalize_email(email)
  63. user = self.model(email=email, **extra_fields)
  64. user.set_password(password)
  65. user.save(using=self._db)
  66. return user
  67. def create_superuser(self, email, password):
  68. """
  69. Creates and saves a superuser with the given email, date of
  70. birth and password.
  71. """
  72. user = self.create_user(email, password=password)
  73. user.is_admin = True
  74. user.save(using=self._db)
  75. return user
  76. class User(ExportModelOperationsMixin('User'), AbstractBaseUser):
  77. @staticmethod
  78. def _limit_domains_default():
  79. return settings.LIMIT_USER_DOMAIN_COUNT_DEFAULT
  80. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  81. email = CIEmailField(
  82. verbose_name='email address',
  83. unique=True,
  84. )
  85. is_active = models.BooleanField(default=True)
  86. is_admin = models.BooleanField(default=False)
  87. created = models.DateTimeField(auto_now_add=True)
  88. limit_domains = models.PositiveIntegerField(default=_limit_domains_default.__func__, null=True, blank=True)
  89. needs_captcha = models.BooleanField(default=True)
  90. objects = MyUserManager()
  91. USERNAME_FIELD = 'email'
  92. REQUIRED_FIELDS = []
  93. def get_full_name(self):
  94. return self.email
  95. def get_short_name(self):
  96. return self.email
  97. def __str__(self):
  98. return self.email
  99. # noinspection PyMethodMayBeStatic
  100. def has_perm(self, *_):
  101. """Does the user have a specific permission?"""
  102. # Simplest possible answer: Yes, always
  103. return True
  104. # noinspection PyMethodMayBeStatic
  105. def has_module_perms(self, *_):
  106. """Does the user have permissions to view the app `app_label`?"""
  107. # Simplest possible answer: Yes, always
  108. return True
  109. @property
  110. def is_staff(self):
  111. """Is the user a member of staff?"""
  112. # Simplest possible answer: All admins are staff
  113. return self.is_admin
  114. def activate(self):
  115. self.is_active = True
  116. self.needs_captcha = False
  117. self.save()
  118. def change_email(self, email):
  119. old_email = self.email
  120. self.email = email
  121. self.validate_unique()
  122. self.save()
  123. self.send_email('change-email-confirmation-old-email', recipient=old_email)
  124. def change_password(self, raw_password):
  125. self.set_password(raw_password)
  126. self.save()
  127. self.send_email('password-change-confirmation')
  128. def delete(self):
  129. pk = self.pk
  130. ret = super().delete()
  131. logger.warning(f'User {pk} deleted')
  132. return ret
  133. def send_email(self, reason, context=None, recipient=None):
  134. fast_lane = 'email_fast_lane'
  135. slow_lane = 'email_slow_lane'
  136. immediate_lane = 'email_immediate_lane'
  137. lanes = {
  138. 'activate': slow_lane,
  139. 'activate-with-domain': slow_lane,
  140. 'change-email': slow_lane,
  141. 'change-email-confirmation-old-email': fast_lane,
  142. 'password-change-confirmation': fast_lane,
  143. 'reset-password': fast_lane,
  144. 'delete-user': fast_lane,
  145. 'domain-dyndns': fast_lane,
  146. 'renew-domain': immediate_lane,
  147. }
  148. if reason not in lanes:
  149. raise ValueError(f'Cannot send email to user {self.pk} without a good reason: {reason}')
  150. context = context or {}
  151. content = get_template(f'emails/{reason}/content.txt').render(context)
  152. content += f'\nSupport Reference: user_id = {self.pk}\n'
  153. footer = get_template('emails/footer.txt').render()
  154. logger.warning(f'Queuing email for user account {self.pk} (reason: {reason}, lane: {lanes[reason]})')
  155. num_queued = EmailMessage(
  156. subject=get_template(f'emails/{reason}/subject.txt').render(context).strip(),
  157. body=content + footer,
  158. from_email=get_template('emails/from.txt').render(),
  159. to=[recipient or self.email],
  160. connection=get_connection(lane=lanes[reason], debug={'user': self.pk, 'reason': reason})
  161. ).send()
  162. metrics.get('desecapi_messages_queued').labels(reason, self.pk, lanes[reason]).observe(num_queued)
  163. return num_queued
  164. validate_domain_name = [
  165. validate_lower,
  166. RegexValidator(
  167. regex=r'^(([a-z0-9_-]{1,63})\.)*[a-z0-9-]{1,63}$',
  168. message='Domain names must be labels separated by dots. Labels may consist of up to 63 letters, digits, '
  169. 'hyphens, and underscores. The last label may not contain an underscore.',
  170. code='invalid_domain_name',
  171. flags=re.IGNORECASE
  172. )
  173. ]
  174. class DomainManager(Manager):
  175. def filter_qname(self, qname: str, **kwargs) -> models.query.QuerySet:
  176. try:
  177. Domain._meta.get_field('name').run_validators(qname.removeprefix('*.'))
  178. except ValidationError:
  179. raise ValueError
  180. return self.annotate(
  181. dotted_name=Concat(Value('.'), 'name', output_field=CharField()),
  182. dotted_qname=Value(f'.{qname}', output_field=CharField()),
  183. name_length=Length('name'),
  184. ).filter(dotted_qname__endswith=F('dotted_name'), **kwargs)
  185. class Domain(ExportModelOperationsMixin('Domain'), models.Model):
  186. @staticmethod
  187. def _minimum_ttl_default():
  188. return settings.MINIMUM_TTL_DEFAULT
  189. class RenewalState(models.IntegerChoices):
  190. IMMORTAL = 0
  191. FRESH = 1
  192. NOTIFIED = 2
  193. WARNED = 3
  194. created = models.DateTimeField(auto_now_add=True)
  195. name = models.CharField(max_length=191,
  196. unique=True,
  197. validators=validate_domain_name)
  198. owner = models.ForeignKey(User, on_delete=models.PROTECT, related_name='domains')
  199. published = models.DateTimeField(null=True, blank=True)
  200. replicated = models.DateTimeField(null=True, blank=True)
  201. replication_duration = models.DurationField(null=True, blank=True)
  202. minimum_ttl = models.PositiveIntegerField(default=_minimum_ttl_default.__func__)
  203. renewal_state = models.IntegerField(choices=RenewalState.choices, default=RenewalState.IMMORTAL)
  204. renewal_changed = models.DateTimeField(auto_now_add=True)
  205. _keys = None
  206. objects = DomainManager()
  207. class Meta:
  208. constraints = [models.UniqueConstraint(fields=['id', 'owner'], name='unique_id_owner')]
  209. ordering = ('created',)
  210. def __init__(self, *args, **kwargs):
  211. if isinstance(kwargs.get('owner'), AnonymousUser):
  212. kwargs = {**kwargs, 'owner': None} # make a copy and override
  213. # Avoid super().__init__(owner=None, ...) to not mess up *values instantiation in django.db.models.Model.from_db
  214. super().__init__(*args, **kwargs)
  215. if self.pk is None and kwargs.get('renewal_state') is None and self.is_locally_registrable:
  216. self.renewal_state = Domain.RenewalState.FRESH
  217. @cached_property
  218. def public_suffix(self):
  219. try:
  220. public_suffix = psl.get_public_suffix(self.name)
  221. is_public_suffix = psl.is_public_suffix(self.name)
  222. except (Timeout, NoNameservers):
  223. public_suffix = self.name.rpartition('.')[2]
  224. is_public_suffix = ('.' not in self.name) # TLDs are public suffixes
  225. except psl_dns.exceptions.UnsupportedRule as e:
  226. # It would probably be fine to treat this as a non-public suffix (with the TLD acting as the
  227. # public suffix and setting both public_suffix and is_public_suffix accordingly).
  228. # However, in order to allow to investigate the situation, it's better not catch
  229. # this exception. For web requests, our error handler turns it into a 503 error
  230. # and makes sure admins are notified.
  231. raise e
  232. if is_public_suffix:
  233. return public_suffix
  234. # Take into account that any of the parent domains could be a local public suffix. To that
  235. # end, identify the longest local public suffix that is actually a suffix of domain_name.
  236. for local_public_suffix in settings.LOCAL_PUBLIC_SUFFIXES:
  237. has_local_public_suffix_parent = ('.' + self.name).endswith('.' + local_public_suffix)
  238. if has_local_public_suffix_parent and len(local_public_suffix) > len(public_suffix):
  239. public_suffix = local_public_suffix
  240. return public_suffix
  241. def is_covered_by_foreign_zone(self):
  242. # Generate a list of all domains connecting this one and its public suffix.
  243. # If another user owns a zone with one of these names, then the requested
  244. # domain is unavailable because it is part of the other user's zone.
  245. private_components = self.name.rsplit(self.public_suffix, 1)[0].rstrip('.')
  246. private_components = private_components.split('.') if private_components else []
  247. private_domains = ['.'.join(private_components[i:]) for i in range(0, len(private_components))]
  248. private_domains = [f'{private_domain}.{self.public_suffix}' for private_domain in private_domains]
  249. assert self.name == next(iter(private_domains), self.public_suffix)
  250. # Determine whether domain is covered by other users' zones
  251. return Domain.objects.filter(Q(name__in=private_domains) & ~Q(owner=self._owner_or_none)).exists()
  252. def covers_foreign_zone(self):
  253. # Note: This is not completely accurate: Ideally, we should only consider zones with identical public suffix.
  254. # (If a public suffix lies in between, it's ok.) However, as there could be many descendant zones, the accurate
  255. # check is expensive, so currently not implemented (PSL lookups for each of them).
  256. return Domain.objects.filter(Q(name__endswith=f'.{self.name}') & ~Q(owner=self._owner_or_none)).exists()
  257. def is_registrable(self):
  258. """
  259. Returns False if the domain name is reserved, a public suffix, or covered by / covers another user's domain.
  260. Otherwise, True is returned.
  261. """
  262. self.clean() # ensure .name is a domain name
  263. private_generation = self.name.count('.') - self.public_suffix.count('.')
  264. assert private_generation >= 0
  265. # .internal is reserved
  266. if f'.{self.name}'.endswith('.internal'):
  267. return False
  268. # Public suffixes can only be registered if they are local
  269. if private_generation == 0 and self.name not in settings.LOCAL_PUBLIC_SUFFIXES:
  270. return False
  271. # Disallow _acme-challenge.dedyn.io and the like. Rejects reserved direct children of public suffixes.
  272. reserved_prefixes = ('_', 'autoconfig.', 'autodiscover.',)
  273. if private_generation == 1 and any(self.name.startswith(prefix) for prefix in reserved_prefixes):
  274. return False
  275. # Domains covered by another user's zone can't be registered
  276. if self.is_covered_by_foreign_zone():
  277. return False
  278. # Domains that would cover another user's zone can't be registered
  279. if self.covers_foreign_zone():
  280. return False
  281. return True
  282. @property
  283. def keys(self):
  284. if not self._keys:
  285. self._keys = pdns.get_keys(self)
  286. return self._keys
  287. @property
  288. def touched(self):
  289. try:
  290. rrset_touched = max(updated for updated in self.rrset_set.values_list('touched', flat=True))
  291. # If the domain has not been published yet, self.published is None and max() would fail
  292. return rrset_touched if not self.published else max(rrset_touched, self.published)
  293. except ValueError:
  294. # This can be none if the domain was never published and has no records (but there should be at least NS)
  295. return self.published
  296. @property
  297. def is_locally_registrable(self):
  298. return self.parent_domain_name in settings.LOCAL_PUBLIC_SUFFIXES
  299. @property
  300. def _owner_or_none(self):
  301. try:
  302. return self.owner
  303. except Domain.owner.RelatedObjectDoesNotExist:
  304. return None
  305. @property
  306. def parent_domain_name(self):
  307. return self._partitioned_name[1]
  308. @property
  309. def _partitioned_name(self):
  310. subname, _, parent_name = self.name.partition('.')
  311. return subname, parent_name or None
  312. def save(self, *args, **kwargs):
  313. self.full_clean(validate_unique=False)
  314. super().save(*args, **kwargs)
  315. def update_delegation(self, child_domain: Domain):
  316. child_subname, child_domain_name = child_domain._partitioned_name
  317. if self.name != child_domain_name:
  318. raise ValueError('Cannot update delegation of %s as it is not an immediate child domain of %s.' %
  319. (child_domain.name, self.name))
  320. # Always remove delegation so that we con properly recreate it
  321. for rrset in self.rrset_set.filter(subname=child_subname, type__in=['NS', 'DS']):
  322. rrset.delete()
  323. if child_domain.pk:
  324. # Domain real: (re-)set delegation
  325. child_keys = child_domain.keys
  326. if not child_keys:
  327. raise APIException('Cannot delegate %s, as it currently has no keys.' % child_domain.name)
  328. RRset.objects.create(domain=self, subname=child_subname, type='NS', ttl=3600, contents=settings.DEFAULT_NS)
  329. RRset.objects.create(domain=self, subname=child_subname, type='DS', ttl=300,
  330. contents=[ds for k in child_keys for ds in k['ds']])
  331. metrics.get('desecapi_autodelegation_created').inc()
  332. else:
  333. # Domain not real: that's it
  334. metrics.get('desecapi_autodelegation_deleted').inc()
  335. def delete(self):
  336. ret = super().delete()
  337. logger.warning(f'Domain {self.name} deleted (owner: {self.owner.pk})')
  338. return ret
  339. def __str__(self):
  340. return self.name
  341. class Token(ExportModelOperationsMixin('Token'), rest_framework.authtoken.models.Token):
  342. @staticmethod
  343. def _allowed_subnets_default():
  344. return [ipaddress.IPv4Network('0.0.0.0/0'), ipaddress.IPv6Network('::/0')]
  345. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  346. key = models.CharField("Key", max_length=128, db_index=True, unique=True)
  347. user = models.ForeignKey(User, on_delete=models.CASCADE)
  348. name = models.CharField('Name', blank=True, max_length=64)
  349. last_used = models.DateTimeField(null=True, blank=True)
  350. perm_manage_tokens = models.BooleanField(default=False)
  351. allowed_subnets = ArrayField(CidrAddressField(), default=_allowed_subnets_default.__func__)
  352. max_age = models.DurationField(null=True, default=None, validators=[MinValueValidator(timedelta(0))])
  353. max_unused_period = models.DurationField(null=True, default=None, validators=[MinValueValidator(timedelta(0))])
  354. domain_policies = models.ManyToManyField(Domain, through='TokenDomainPolicy')
  355. plain = None
  356. objects = NetManager()
  357. class Meta:
  358. constraints = [models.UniqueConstraint(fields=['id', 'user'], name='unique_id_user')]
  359. @property
  360. def is_valid(self):
  361. now = timezone.now()
  362. # Check max age
  363. try:
  364. if self.created + self.max_age < now:
  365. return False
  366. except TypeError:
  367. pass
  368. # Check regular usage requirement
  369. try:
  370. if (self.last_used or self.created) + self.max_unused_period < now:
  371. return False
  372. except TypeError:
  373. pass
  374. return True
  375. def generate_key(self):
  376. self.plain = secrets.token_urlsafe(21)
  377. self.key = Token.make_hash(self.plain)
  378. return self.key
  379. @staticmethod
  380. def make_hash(plain):
  381. return make_password(plain, salt='static', hasher='pbkdf2_sha256_iter1')
  382. def get_policy(self, *, domain=None):
  383. order_by = F('domain').asc(nulls_last=True) # default Postgres sorting, but: explicit is better than implicit
  384. return self.tokendomainpolicy_set.filter(Q(domain=domain) | Q(domain__isnull=True)).order_by(order_by).first()
  385. @transaction.atomic
  386. def delete(self):
  387. # This is needed because Model.delete() emulates cascade delete via django.db.models.deletion.Collector.delete()
  388. # which deletes related objects in pk order. However, the default policy has to be deleted last.
  389. # Perhaps this will change with https://code.djangoproject.com/ticket/21961
  390. self.tokendomainpolicy_set.filter(domain__isnull=False).delete()
  391. self.tokendomainpolicy_set.filter(domain__isnull=True).delete()
  392. return super().delete()
  393. @pgtrigger.register(
  394. # Ensure that token_user is consistent with token
  395. pgtrigger.Trigger(
  396. name='token_user',
  397. operation=pgtrigger.Update | pgtrigger.Insert,
  398. when=pgtrigger.Before,
  399. func='NEW.token_user_id = (SELECT user_id FROM desecapi_token WHERE id = NEW.token_id); RETURN NEW;',
  400. ),
  401. # Ensure that if there is *any* domain policy for a given token, there is always one with domain=None.
  402. pgtrigger.Trigger(
  403. name='default_policy_on_insert',
  404. operation=pgtrigger.Insert,
  405. when=pgtrigger.Before,
  406. # Trigger `condition` arguments (corresponding to WHEN clause) don't support subqueries, so we use `func`
  407. func="IF (NEW.domain_id IS NOT NULL and NOT EXISTS(SELECT * FROM desecapi_tokendomainpolicy WHERE domain_id IS NULL AND token_id = NEW.token_id)) THEN "
  408. " RAISE EXCEPTION 'Cannot insert non-default policy into % table when default policy is not present', TG_TABLE_NAME; "
  409. "END IF; RETURN NEW;",
  410. ),
  411. pgtrigger.Protect(
  412. name='default_policy_on_update',
  413. operation=pgtrigger.Update,
  414. when=pgtrigger.Before,
  415. condition=pgtrigger.Q(old__domain__isnull=True, new__domain__isnull=False),
  416. ),
  417. # Ideally, this would be a deferred trigger, but depends on https://github.com/Opus10/django-pgtrigger/issues/14
  418. pgtrigger.Trigger(
  419. name='default_policy_on_delete',
  420. operation=pgtrigger.Delete,
  421. when=pgtrigger.Before,
  422. # Trigger `condition` arguments (corresponding to WHEN clause) don't support subqueries, so we use `func`
  423. func="IF (OLD.domain_id IS NULL and EXISTS(SELECT * FROM desecapi_tokendomainpolicy WHERE domain_id IS NOT NULL AND token_id = OLD.token_id)) THEN "
  424. " RAISE EXCEPTION 'Cannot delete default policy from % table when non-default policy is present', TG_TABLE_NAME; "
  425. "END IF; RETURN OLD;",
  426. ),
  427. )
  428. class TokenDomainPolicy(ExportModelOperationsMixin('TokenDomainPolicy'), models.Model):
  429. token = models.ForeignKey(Token, on_delete=models.CASCADE)
  430. domain = models.ForeignKey(Domain, on_delete=models.CASCADE, null=True)
  431. perm_dyndns = models.BooleanField(default=False)
  432. perm_rrsets = models.BooleanField(default=False)
  433. # Token user, filled via trigger. Used by compound FK constraints to tie domain.owner to token.user (see migration).
  434. token_user = models.ForeignKey(User, on_delete=models.CASCADE, db_constraint=False, related_name='+')
  435. class Meta:
  436. constraints = [
  437. models.UniqueConstraint(fields=['token', 'domain'], name='unique_entry'),
  438. models.UniqueConstraint(fields=['token'], condition=Q(domain__isnull=True), name='unique_entry_null_domain')
  439. ]
  440. def clean(self):
  441. default_policy = self.token.get_policy(domain=None)
  442. if self.pk: # update
  443. # Can't change policy's default status ("domain NULLness") to maintain policy precedence
  444. if (self.domain is None) != (self.pk == default_policy.pk):
  445. raise ValidationError({'domain': 'Policy precedence: Cannot disable default policy when others exist.'})
  446. else: # create
  447. # Can't violate policy precedence (default policy has to be first)
  448. if (self.domain is not None) and (default_policy is None):
  449. raise ValidationError({'domain': 'Policy precedence: The first policy must be the default policy.'})
  450. def delete(self):
  451. # Can't delete default policy when others exist
  452. if (self.domain is None) and self.token.tokendomainpolicy_set.exclude(domain__isnull=True).exists():
  453. raise ValidationError({'domain': "Policy precedence: Can't delete default policy when there exist others."})
  454. return super().delete()
  455. def save(self, *args, **kwargs):
  456. self.clean()
  457. super().save(*args, **kwargs)
  458. class Donation(ExportModelOperationsMixin('Donation'), models.Model):
  459. @staticmethod
  460. def _created_default():
  461. return timezone.now()
  462. @staticmethod
  463. def _due_default():
  464. return timezone.now() + timedelta(days=7)
  465. @staticmethod
  466. def _mref_default():
  467. return "ONDON" + str(time.time())
  468. class Interval(models.IntegerChoices):
  469. ONCE = 0
  470. MONTHLY = 1
  471. QUARTERLY = 3
  472. created = models.DateTimeField(default=_created_default.__func__)
  473. name = models.CharField(max_length=255)
  474. iban = models.CharField(max_length=34)
  475. bic = models.CharField(max_length=11, blank=True)
  476. amount = models.DecimalField(max_digits=8, decimal_places=2)
  477. message = models.CharField(max_length=255, blank=True)
  478. due = models.DateTimeField(default=_due_default.__func__)
  479. mref = models.CharField(max_length=32, default=_mref_default.__func__)
  480. interval = models.IntegerField(choices=Interval.choices, default=Interval.ONCE)
  481. email = models.EmailField(max_length=255, blank=True)
  482. class Meta:
  483. managed = False
  484. @property
  485. def interval_label(self):
  486. return dict(self.Interval.choices)[self.interval]
  487. # RR set types: the good, the bad, and the ugly
  488. # known, but unsupported types
  489. RR_SET_TYPES_UNSUPPORTED = {
  490. 'ALIAS', # Requires signing at the frontend, hence unsupported in desec-stack
  491. 'IPSECKEY', # broken in pdns, https://github.com/PowerDNS/pdns/issues/10589 TODO enable with pdns auth > 4.5.0
  492. 'KEY', # Application use restricted by RFC 3445, DNSSEC use replaced by DNSKEY and handled automatically
  493. 'WKS', # General usage not recommended, "SHOULD NOT" be used in SMTP (RFC 1123)
  494. } | {'NID', 'L32', 'L64', 'LP'} # https://github.com/rthalley/dnspython/issues/674
  495. # restricted types are managed in use by the API, and cannot directly be modified by the API client
  496. RR_SET_TYPES_AUTOMATIC = {
  497. # corresponding functionality is automatically managed:
  498. 'KEY', 'NSEC', 'NSEC3', 'OPT', 'RRSIG',
  499. # automatically managed by the API:
  500. 'NSEC3PARAM', 'SOA'
  501. }
  502. # backend types are types that are the types supported by the backend(s)
  503. RR_SET_TYPES_BACKEND = pdns.SUPPORTED_RRSET_TYPES
  504. # validation types are types supported by the validation backend, currently: dnspython
  505. RR_SET_TYPES_VALIDATION = set(ANY.__all__) | set(IN.__all__) \
  506. | {'HTTPS', 'SVCB'} # https://github.com/rthalley/dnspython/pull/624
  507. # manageable types are directly managed by the API client
  508. RR_SET_TYPES_MANAGEABLE = \
  509. (RR_SET_TYPES_BACKEND & RR_SET_TYPES_VALIDATION) - RR_SET_TYPES_UNSUPPORTED - RR_SET_TYPES_AUTOMATIC
  510. class RRsetManager(Manager):
  511. def create(self, contents=None, **kwargs):
  512. rrset = super().create(**kwargs)
  513. for content in contents or []:
  514. RR.objects.create(rrset=rrset, content=content)
  515. return rrset
  516. class RRset(ExportModelOperationsMixin('RRset'), models.Model):
  517. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  518. created = models.DateTimeField(auto_now_add=True)
  519. touched = models.DateTimeField(auto_now=True, db_index=True)
  520. domain = models.ForeignKey(Domain, on_delete=models.CASCADE)
  521. subname = models.CharField(
  522. max_length=178,
  523. blank=True,
  524. validators=[
  525. validate_lower,
  526. RegexValidator(
  527. regex=r'^([*]|(([*][.])?([a-z0-9_-]{1,63}[.])*[a-z0-9_-]{1,63}))$',
  528. message='Subname can only use (lowercase) a-z, 0-9, ., -, and _, '
  529. 'may start with a \'*.\', or just be \'*\'. Components may not exceed 63 characters.',
  530. code='invalid_subname'
  531. )
  532. ]
  533. )
  534. type = models.CharField(
  535. max_length=10,
  536. validators=[
  537. validate_upper,
  538. RegexValidator(
  539. regex=r'^[A-Z][A-Z0-9]*$',
  540. message='Type must be uppercase alphanumeric and start with a letter.',
  541. code='invalid_type'
  542. )
  543. ]
  544. )
  545. ttl = models.PositiveIntegerField()
  546. objects = RRsetManager()
  547. class Meta:
  548. constraints = [
  549. ExclusionConstraint(
  550. name='cname_exclusivity',
  551. expressions=[
  552. ('domain', RangeOperators.EQUAL),
  553. ('subname', RangeOperators.EQUAL),
  554. (RawSQL("int4(type = 'CNAME')", ()), RangeOperators.NOT_EQUAL),
  555. ],
  556. ),
  557. ]
  558. unique_together = (("domain", "subname", "type"),)
  559. @staticmethod
  560. def construct_name(subname, domain_name):
  561. return '.'.join(filter(None, [subname, domain_name])) + '.'
  562. @property
  563. def name(self):
  564. return self.construct_name(self.subname, self.domain.name)
  565. def save(self, *args, **kwargs):
  566. # TODO Enforce that subname and type aren't changed. https://github.com/desec-io/desec-stack/issues/553
  567. self.full_clean(validate_unique=False)
  568. super().save(*args, **kwargs)
  569. def clean_records(self, records_presentation_format):
  570. """
  571. Validates the records belonging to this set. Validation rules follow the DNS specification; some types may
  572. incur additional validation rules.
  573. Raises ValidationError if violation of DNS specification is found.
  574. Returns a set of records in canonical presentation format.
  575. :param records_presentation_format: iterable of records in presentation format
  576. """
  577. errors = []
  578. # Singletons
  579. if self.type in ('CNAME', 'DNAME',):
  580. if len(records_presentation_format) > 1:
  581. errors.append(f'{self.type} RRset cannot have multiple records.')
  582. # Non-apex
  583. if self.type == 'CNAME':
  584. if self.subname == '':
  585. errors.append('CNAME RRset cannot have empty subname.')
  586. def _error_msg(record, detail):
  587. return f'Record content of {self.type} {self.name} invalid: \'{record}\': {detail}'
  588. records_canonical_format = set()
  589. for r in records_presentation_format:
  590. try:
  591. r_canonical_format = RR.canonical_presentation_format(r, self.type)
  592. except ValueError as ex:
  593. errors.append(_error_msg(r, str(ex)))
  594. else:
  595. if r_canonical_format in records_canonical_format:
  596. errors.append(_error_msg(r, f'Duplicate record content: this is identical to '
  597. f'\'{r_canonical_format}\''))
  598. else:
  599. records_canonical_format.add(r_canonical_format)
  600. if any(errors):
  601. raise ValidationError(errors)
  602. return records_canonical_format
  603. def save_records(self, records):
  604. """
  605. Updates this RR set's resource records, discarding any old values.
  606. Records are expected in presentation format and are converted to canonical
  607. presentation format (e.g., 127.00.0.1 will be converted to 127.0.0.1).
  608. Raises if a invalid set of records is provided.
  609. This method triggers the following database queries:
  610. - one DELETE query
  611. - one SELECT query for comparison of old with new records
  612. - one INSERT query, if one or more records were added
  613. Changes are saved to the database immediately.
  614. :param records: list of records in presentation format
  615. """
  616. new_records = self.clean_records(records)
  617. # Delete RRs that are not in the new record list from the DB
  618. self.records.exclude(content__in=new_records).delete() # one DELETE
  619. # Retrieve all remaining RRs from the DB
  620. unchanged_records = set(r.content for r in self.records.all()) # one SELECT
  621. # Save missing RRs from the new record list to the DB
  622. added_records = new_records - unchanged_records
  623. rrs = [RR(rrset=self, content=content) for content in added_records]
  624. RR.objects.bulk_create(rrs) # One INSERT
  625. def __str__(self):
  626. return '<RRSet %s domain=%s type=%s subname=%s>' % (self.pk, self.domain.name, self.type, self.subname)
  627. class RRManager(Manager):
  628. def bulk_create(self, rrs, **kwargs):
  629. ret = super().bulk_create(rrs, **kwargs)
  630. # For each rrset, save once to set RRset.updated timestamp and trigger signal for post-save processing
  631. rrsets = {rr.rrset for rr in rrs}
  632. for rrset in rrsets:
  633. rrset.save()
  634. return ret
  635. class RR(ExportModelOperationsMixin('RR'), models.Model):
  636. created = models.DateTimeField(auto_now_add=True)
  637. rrset = models.ForeignKey(RRset, on_delete=models.CASCADE, related_name='records')
  638. content = models.TextField()
  639. objects = RRManager()
  640. _type_map = {
  641. dns.rdatatype.AAAA: AAAA, # TODO remove when https://github.com/PowerDNS/pdns/issues/8182 is fixed
  642. dns.rdatatype.CDS: CDS, # TODO remove when https://github.com/rthalley/dnspython/pull/625 is in main codebase
  643. dns.rdatatype.DLV: DLV, # TODO remove when https://github.com/rthalley/dnspython/pull/625 is in main codebase
  644. dns.rdatatype.DS: DS, # TODO remove when https://github.com/rthalley/dnspython/pull/625 is in main codebase
  645. dns.rdatatype.MX: MX, # do DNS name validation the same way as pdns
  646. dns.rdatatype.NS: NS, # do DNS name validation the same way as pdns
  647. dns.rdatatype.SRV: SRV, # do DNS name validation the same way as pdns
  648. dns.rdatatype.TXT: LongQuotedTXT, # we slightly deviate from RFC 1035 and allow tokens longer than 255 bytes
  649. dns.rdatatype.SPF: LongQuotedTXT, # we slightly deviate from RFC 1035 and allow tokens longer than 255 bytes
  650. }
  651. @staticmethod
  652. def canonical_presentation_format(any_presentation_format, type_):
  653. """
  654. Converts any valid presentation format for a RR into it's canonical presentation format.
  655. Raises if provided presentation format is invalid.
  656. """
  657. rdtype = rdatatype.from_text(type_)
  658. try:
  659. # Convert to wire format, ensuring input validation.
  660. cls = RR._type_map.get(rdtype, dns.rdata)
  661. wire = cls.from_text(
  662. rdclass=rdataclass.IN,
  663. rdtype=rdtype,
  664. tok=dns.tokenizer.Tokenizer(any_presentation_format),
  665. relativize=False
  666. ).to_digestable()
  667. if len(wire) > 64000:
  668. raise ValidationError(f'Ensure this value has no more than 64000 byte in wire format (it has {len(wire)}).')
  669. parser = dns.wire.Parser(wire, current=0)
  670. with parser.restrict_to(len(wire)):
  671. rdata = cls.from_wire_parser(rdclass=rdataclass.IN, rdtype=rdtype, parser=parser)
  672. # Convert to canonical presentation format, disable chunking of records.
  673. # Exempt types which have chunksize hardcoded (prevents "got multiple values for keyword argument 'chunksize'").
  674. chunksize_exception_types = (dns.rdatatype.OPENPGPKEY, dns.rdatatype.EUI48, dns.rdatatype.EUI64)
  675. if rdtype in chunksize_exception_types:
  676. return rdata.to_text()
  677. else:
  678. return rdata.to_text(chunksize=0)
  679. except binascii.Error:
  680. # e.g., odd-length string
  681. raise ValueError('Cannot parse hexadecimal or base64 record contents')
  682. except dns.exception.SyntaxError as e:
  683. # e.g., A/127.0.0.999
  684. if 'quote' in e.args[0]:
  685. raise ValueError(f'Data for {type_} records must be given using quotation marks.')
  686. else:
  687. raise ValueError(f'Record content for type {type_} malformed: {",".join(e.args)}')
  688. except dns.name.NeedAbsoluteNameOrOrigin:
  689. raise ValueError('Hostname must be fully qualified (i.e., end in a dot: "example.com.")')
  690. except ValueError as ex:
  691. # e.g., string ("asdf") cannot be parsed into int on base 10
  692. raise ValueError(f'Cannot parse record contents: {ex}')
  693. except Exception as e:
  694. # TODO see what exceptions raise here for faulty input
  695. raise e
  696. def __str__(self):
  697. return '<RR %s %s rr_set=%s>' % (self.pk, self.content, self.rrset.pk)
  698. class AuthenticatedAction(models.Model):
  699. """
  700. Represents a procedure call on a defined set of arguments.
  701. Subclasses can define additional arguments by adding Django model fields and must define the action to be taken by
  702. implementing the `_act` method.
  703. AuthenticatedAction provides the `state` property which by default is a hash of the action type (defined by the
  704. action's class path). Other information such as user state can be included in the state hash by (carefully)
  705. overriding the `_state_fields` property. Instantiation of the model, if given a `state` kwarg, will raise an error
  706. if the given state argument does not match the state computed from `_state_fields` at the moment of instantiation.
  707. The same applies to the `act` method: If called on an object that was instantiated without a `state` kwargs, an
  708. error will be raised.
  709. This effectively allows hash-authenticated procedure calls by third parties as long as the server-side state is
  710. unaltered, according to the following protocol:
  711. (1) Instantiate the AuthenticatedAction subclass representing the action to be taken (no `state` kwarg here),
  712. (2) provide information on how to instantiate the instance, and the state hash, to a third party,
  713. (3) when provided with data that allows instantiation and a valid state hash, take the defined action, possibly with
  714. additional parameters chosen by the third party that do not belong to the verified state.
  715. """
  716. _validated = False
  717. class Meta:
  718. managed = False
  719. def __init__(self, *args, **kwargs):
  720. state = kwargs.pop('state', None)
  721. super().__init__(*args, **kwargs)
  722. if state is not None:
  723. self._validated = self.validate_state(state)
  724. if not self._validated:
  725. raise ValueError
  726. @property
  727. def _state_fields(self):
  728. """
  729. Returns a list that defines the state of this action (used for authentication of this action).
  730. Return value must be JSON-serializable.
  731. Values not included in the return value will not be used for authentication, i.e. those values can be varied
  732. freely and function as unauthenticated action input parameters.
  733. Use caution when overriding this method. You will usually want to append a value to the list returned by the
  734. parent. Overriding the behavior altogether could result in reducing the state to fewer variables, resulting
  735. in valid signatures when they were intended to be invalid. The suggested method for overriding is
  736. @property
  737. def _state_fields:
  738. return super()._state_fields + [self.important_value, self.another_added_value]
  739. :return: List of values to be signed.
  740. """
  741. name = '.'.join([self.__module__, self.__class__.__qualname__])
  742. return [name]
  743. @property
  744. def state(self):
  745. state = json.dumps(self._state_fields).encode()
  746. hash = sha256()
  747. hash.update(state)
  748. return hash.hexdigest()
  749. def validate_state(self, value):
  750. return value == self.state
  751. def _act(self):
  752. """
  753. Conduct the action represented by this class.
  754. :return: None
  755. """
  756. raise NotImplementedError
  757. def act(self):
  758. if not self._validated:
  759. raise RuntimeError('Action state could not be verified.')
  760. return self._act()
  761. class AuthenticatedBasicUserAction(AuthenticatedAction):
  762. """
  763. Abstract AuthenticatedAction involving a user instance.
  764. """
  765. user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
  766. class Meta:
  767. managed = False
  768. @property
  769. def _state_fields(self):
  770. return super()._state_fields + [str(self.user.id)]
  771. class AuthenticatedUserAction(AuthenticatedBasicUserAction):
  772. """
  773. Abstract AuthenticatedBasicUserAction, incorporating the user's id, email, password, and is_active flag into the
  774. Message Authentication Code state.
  775. """
  776. class Meta:
  777. managed = False
  778. @property
  779. def _state_fields(self):
  780. # TODO consider adding a "last change" attribute of the user to the state to avoid code
  781. # re-use after the the state has been changed and changed back.
  782. return super()._state_fields + [self.user.email, self.user.password, self.user.is_active]
  783. class AuthenticatedActivateUserAction(AuthenticatedUserAction):
  784. domain = models.CharField(max_length=191)
  785. class Meta:
  786. managed = False
  787. @property
  788. def _state_fields(self):
  789. return super()._state_fields + [self.domain]
  790. def _act(self):
  791. self.user.activate()
  792. class AuthenticatedChangeEmailUserAction(AuthenticatedUserAction):
  793. new_email = models.EmailField()
  794. class Meta:
  795. managed = False
  796. @property
  797. def _state_fields(self):
  798. return super()._state_fields + [self.new_email]
  799. def _act(self):
  800. self.user.change_email(self.new_email)
  801. class AuthenticatedResetPasswordUserAction(AuthenticatedUserAction):
  802. new_password = models.CharField(max_length=128)
  803. class Meta:
  804. managed = False
  805. def _act(self):
  806. self.user.change_password(self.new_password)
  807. class AuthenticatedDeleteUserAction(AuthenticatedUserAction):
  808. class Meta:
  809. managed = False
  810. def _act(self):
  811. self.user.delete()
  812. class AuthenticatedDomainBasicUserAction(AuthenticatedBasicUserAction):
  813. """
  814. Abstract AuthenticatedUserAction involving an domain instance, incorporating the domain's id, name as well as the
  815. owner ID into the Message Authentication Code state.
  816. """
  817. domain = models.ForeignKey(Domain, on_delete=models.DO_NOTHING)
  818. class Meta:
  819. managed = False
  820. @property
  821. def _state_fields(self):
  822. return super()._state_fields + [
  823. str(self.domain.id), # ensures the domain object is identical
  824. self.domain.name, # exclude renamed domains
  825. str(self.domain.owner.id), # exclude transferred domains
  826. ]
  827. class AuthenticatedRenewDomainBasicUserAction(AuthenticatedDomainBasicUserAction):
  828. class Meta:
  829. managed = False
  830. @property
  831. def _state_fields(self):
  832. return super()._state_fields + [str(self.domain.renewal_changed)]
  833. def _act(self):
  834. self.domain.renewal_state = Domain.RenewalState.FRESH
  835. self.domain.renewal_changed = timezone.now()
  836. self.domain.save(update_fields=['renewal_state', 'renewal_changed'])
  837. def captcha_default_content(kind: str) -> str:
  838. if kind == Captcha.Kind.IMAGE:
  839. alphabet = (string.ascii_uppercase + string.digits).translate({ord(c): None for c in 'IO0'})
  840. length = 5
  841. elif kind == Captcha.Kind.AUDIO:
  842. alphabet = string.digits
  843. length = 8
  844. else:
  845. raise ValueError(f'Unknown Captcha kind: {kind}')
  846. content = ''.join([secrets.choice(alphabet) for _ in range(length)])
  847. metrics.get('desecapi_captcha_content_created').labels(kind).inc()
  848. return content
  849. class Captcha(ExportModelOperationsMixin('Captcha'), models.Model):
  850. class Kind(models.TextChoices):
  851. IMAGE = 'image'
  852. AUDIO = 'audio'
  853. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  854. created = models.DateTimeField(auto_now_add=True)
  855. content = models.CharField(max_length=24, default="")
  856. kind = models.CharField(choices=Kind.choices, default=Kind.IMAGE, max_length=24)
  857. def __init__(self, *args, **kwargs):
  858. super().__init__(*args, **kwargs)
  859. if not self.content:
  860. self.content = captcha_default_content(self.kind)
  861. def verify(self, solution: str):
  862. age = timezone.now() - self.created
  863. self.delete()
  864. return (
  865. str(solution).upper().strip() == self.content # solution correct
  866. and
  867. age <= settings.CAPTCHA_VALIDITY_PERIOD # not expired
  868. )