models.py 44 KB

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