models.py 43 KB

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