models.py 43 KB

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