models.py 43 KB

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