models.py 42 KB

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