models.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. from __future__ import annotations
  2. import binascii
  3. import json
  4. import logging
  5. import re
  6. import secrets
  7. import string
  8. import time
  9. import uuid
  10. from datetime import timedelta
  11. from functools import cached_property
  12. from hashlib import sha256
  13. import dns
  14. import psl_dns
  15. import rest_framework.authtoken.models
  16. from django.conf import settings
  17. from django.contrib.auth.hashers import make_password
  18. from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
  19. from django.contrib.postgres.constraints import ExclusionConstraint
  20. from django.contrib.postgres.fields import CIEmailField, RangeOperators
  21. from django.core.exceptions import ValidationError
  22. from django.core.mail import EmailMessage, get_connection
  23. from django.core.validators import RegexValidator
  24. from django.db import models
  25. from django.db.models import Manager, Q
  26. from django.db.models.expressions import RawSQL
  27. from django.template.loader import get_template
  28. from django.utils import timezone
  29. from django_prometheus.models import ExportModelOperationsMixin
  30. from dns import rdata, rdataclass, rdatatype
  31. from dns.exception import Timeout
  32. from dns.rdtypes import ANY, IN
  33. from dns.resolver import NoNameservers
  34. from rest_framework.exceptions import APIException
  35. from desecapi import metrics
  36. from desecapi import pdns
  37. from desecapi.dns import LongQuotedTXT, OPENPGPKEY
  38. logger = logging.getLogger(__name__)
  39. psl = psl_dns.PSL(resolver=settings.PSL_RESOLVER, timeout=.5)
  40. def validate_lower(value):
  41. if value != value.lower():
  42. raise ValidationError('Invalid value (not lowercase): %(value)s',
  43. code='invalid',
  44. params={'value': value})
  45. def validate_upper(value):
  46. if value != value.upper():
  47. raise ValidationError('Invalid value (not uppercase): %(value)s',
  48. code='invalid',
  49. params={'value': value})
  50. class MyUserManager(BaseUserManager):
  51. def create_user(self, email, password, **extra_fields):
  52. """
  53. Creates and saves a User with the given email, date of
  54. birth and password.
  55. """
  56. if not email:
  57. raise ValueError('Users must have an email address')
  58. email = self.normalize_email(email)
  59. user = self.model(email=email, **extra_fields)
  60. user.set_password(password)
  61. user.save(using=self._db)
  62. return user
  63. def create_superuser(self, email, password):
  64. """
  65. Creates and saves a superuser with the given email, date of
  66. birth and password.
  67. """
  68. user = self.create_user(email, password=password)
  69. user.is_admin = True
  70. user.save(using=self._db)
  71. return user
  72. class User(ExportModelOperationsMixin('User'), AbstractBaseUser):
  73. @staticmethod
  74. def _limit_domains_default():
  75. return settings.LIMIT_USER_DOMAIN_COUNT_DEFAULT
  76. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  77. email = CIEmailField(
  78. verbose_name='email address',
  79. unique=True,
  80. )
  81. is_active = models.BooleanField(default=True)
  82. is_admin = models.BooleanField(default=False)
  83. created = models.DateTimeField(auto_now_add=True)
  84. limit_domains = models.IntegerField(default=_limit_domains_default.__func__, null=True, blank=True)
  85. objects = MyUserManager()
  86. USERNAME_FIELD = 'email'
  87. REQUIRED_FIELDS = []
  88. def get_full_name(self):
  89. return self.email
  90. def get_short_name(self):
  91. return self.email
  92. def __str__(self):
  93. return self.email
  94. # noinspection PyMethodMayBeStatic
  95. def has_perm(self, *_):
  96. """Does the user have a specific permission?"""
  97. # Simplest possible answer: Yes, always
  98. return True
  99. # noinspection PyMethodMayBeStatic
  100. def has_module_perms(self, *_):
  101. """Does the user have permissions to view the app `app_label`?"""
  102. # Simplest possible answer: Yes, always
  103. return True
  104. @property
  105. def is_staff(self):
  106. """Is the user a member of staff?"""
  107. # Simplest possible answer: All admins are staff
  108. return self.is_admin
  109. def activate(self):
  110. self.is_active = True
  111. self.save()
  112. def change_email(self, email):
  113. old_email = self.email
  114. self.email = email
  115. self.validate_unique()
  116. self.save()
  117. self.send_email('change-email-confirmation-old-email', recipient=old_email)
  118. def change_password(self, raw_password):
  119. self.set_password(raw_password)
  120. self.save()
  121. self.send_email('password-change-confirmation')
  122. def delete(self):
  123. pk = self.pk
  124. ret = super().delete()
  125. logger.warning(f'User {pk} deleted')
  126. return ret
  127. def send_email(self, reason, context=None, recipient=None):
  128. fast_lane = 'email_fast_lane'
  129. slow_lane = 'email_slow_lane'
  130. immediate_lane = 'email_immediate_lane'
  131. lanes = {
  132. 'activate': slow_lane,
  133. 'activate-with-domain': slow_lane,
  134. 'change-email': slow_lane,
  135. 'change-email-confirmation-old-email': fast_lane,
  136. 'password-change-confirmation': fast_lane,
  137. 'reset-password': fast_lane,
  138. 'delete-user': fast_lane,
  139. 'domain-dyndns': fast_lane,
  140. 'renew-domain': immediate_lane,
  141. }
  142. if reason not in lanes:
  143. raise ValueError(f'Cannot send email to user {self.pk} without a good reason: {reason}')
  144. context = context or {}
  145. content = get_template(f'emails/{reason}/content.txt').render(context)
  146. content += f'\nSupport Reference: user_id = {self.pk}\n'
  147. footer = get_template('emails/footer.txt').render()
  148. logger.warning(f'Queuing email for user account {self.pk} (reason: {reason}, lane: {lanes[reason]})')
  149. num_queued = EmailMessage(
  150. subject=get_template(f'emails/{reason}/subject.txt').render(context).strip(),
  151. body=content + footer,
  152. from_email=get_template('emails/from.txt').render(),
  153. to=[recipient or self.email],
  154. connection=get_connection(lane=lanes[reason], debug={'user': self.pk, 'reason': reason})
  155. ).send()
  156. metrics.get('desecapi_messages_queued').labels(reason, self.pk, lanes[reason]).observe(num_queued)
  157. return num_queued
  158. class Token(ExportModelOperationsMixin('Token'), rest_framework.authtoken.models.Token):
  159. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  160. key = models.CharField("Key", max_length=128, db_index=True, unique=True)
  161. user = models.ForeignKey(
  162. User, related_name='auth_tokens',
  163. on_delete=models.CASCADE, verbose_name="User"
  164. )
  165. name = models.CharField('Name', blank=True, max_length=64)
  166. last_used = models.DateTimeField(null=True, blank=True)
  167. plain = None
  168. def generate_key(self):
  169. self.plain = secrets.token_urlsafe(21)
  170. self.key = Token.make_hash(self.plain)
  171. return self.key
  172. @staticmethod
  173. def make_hash(plain):
  174. return make_password(plain, salt='static', hasher='pbkdf2_sha256_iter1')
  175. validate_domain_name = [
  176. validate_lower,
  177. RegexValidator(
  178. regex=r'^(([a-z0-9_-]{1,63})\.)*[a-z0-9-]{1,63}$',
  179. message='Domain names must be labels separated by dots. Labels may consist of up to 63 letters, digits, '
  180. 'hyphens, and underscores. The last label may not contain an underscore.',
  181. code='invalid_domain_name',
  182. flags=re.IGNORECASE
  183. )
  184. ]
  185. def get_minimum_ttl_default():
  186. return settings.MINIMUM_TTL_DEFAULT
  187. class Domain(ExportModelOperationsMixin('Domain'), models.Model):
  188. class RenewalState(models.IntegerChoices):
  189. IMMORTAL = 0
  190. FRESH = 1
  191. NOTIFIED = 2
  192. WARNED = 3
  193. created = models.DateTimeField(auto_now_add=True)
  194. name = models.CharField(max_length=191,
  195. unique=True,
  196. validators=validate_domain_name)
  197. owner = models.ForeignKey(User, on_delete=models.PROTECT, related_name='domains')
  198. published = models.DateTimeField(null=True, blank=True)
  199. minimum_ttl = models.PositiveIntegerField(default=get_minimum_ttl_default)
  200. renewal_state = models.IntegerField(choices=RenewalState.choices, default=RenewalState.IMMORTAL)
  201. renewal_changed = models.DateTimeField(auto_now_add=True)
  202. _keys = None
  203. def __init__(self, *args, **kwargs):
  204. super().__init__(*args, **kwargs)
  205. if self.pk is None and kwargs.get('renewal_state') is None and self.is_locally_registrable:
  206. self.renewal_state = Domain.RenewalState.FRESH
  207. @cached_property
  208. def public_suffix(self):
  209. try:
  210. public_suffix = psl.get_public_suffix(self.name)
  211. is_public_suffix = psl.is_public_suffix(self.name)
  212. except (Timeout, NoNameservers):
  213. public_suffix = self.name.rpartition('.')[2]
  214. is_public_suffix = ('.' not in self.name) # TLDs are public suffixes
  215. except psl_dns.exceptions.UnsupportedRule as e:
  216. # It would probably be fine to treat this as a non-public suffix (with the TLD acting as the
  217. # public suffix and setting both public_suffix and is_public_suffix accordingly).
  218. # However, in order to allow to investigate the situation, it's better not catch
  219. # this exception. For web requests, our error handler turns it into a 503 error
  220. # and makes sure admins are notified.
  221. raise e
  222. if is_public_suffix:
  223. return public_suffix
  224. # Take into account that any of the parent domains could be a local public suffix. To that
  225. # end, identify the longest local public suffix that is actually a suffix of domain_name.
  226. for local_public_suffix in settings.LOCAL_PUBLIC_SUFFIXES:
  227. has_local_public_suffix_parent = ('.' + self.name).endswith('.' + local_public_suffix)
  228. if has_local_public_suffix_parent and len(local_public_suffix) > len(public_suffix):
  229. public_suffix = local_public_suffix
  230. return public_suffix
  231. def is_covered_by_foreign_zone(self):
  232. # Generate a list of all domains connecting this one and its public suffix.
  233. # If another user owns a zone with one of these names, then the requested
  234. # domain is unavailable because it is part of the other user's zone.
  235. private_components = self.name.rsplit(self.public_suffix, 1)[0].rstrip('.')
  236. private_components = private_components.split('.') if private_components else []
  237. private_domains = ['.'.join(private_components[i:]) for i in range(0, len(private_components))]
  238. private_domains = [f'{private_domain}.{self.public_suffix}' for private_domain in private_domains]
  239. assert self.name == next(iter(private_domains), self.public_suffix)
  240. # Determine whether domain is covered by other users' zones
  241. return Domain.objects.filter(Q(name__in=private_domains) & ~Q(owner=self._owner_or_none)).exists()
  242. def covers_foreign_zone(self):
  243. # Note: This is not completely accurate: Ideally, we should only consider zones with identical public suffix.
  244. # (If a public suffix lies in between, it's ok.) However, as there could be many descendant zones, the accurate
  245. # check is expensive, so currently not implemented (PSL lookups for each of them).
  246. return Domain.objects.filter(Q(name__endswith=f'.{self.name}') & ~Q(owner=self._owner_or_none)).exists()
  247. def is_registrable(self):
  248. """
  249. Returns False if the domain name is reserved, a public suffix, or covered by / covers another user's domain.
  250. Otherwise, True is returned.
  251. """
  252. self.clean() # ensure .name is a domain name
  253. private_generation = self.name.count('.') - self.public_suffix.count('.')
  254. assert private_generation >= 0
  255. # .internal is reserved
  256. if f'.{self.name}'.endswith('.internal'):
  257. return False
  258. # Public suffixes can only be registered if they are local
  259. if private_generation == 0 and self.name not in settings.LOCAL_PUBLIC_SUFFIXES:
  260. return False
  261. # Disallow _acme-challenge.dedyn.io and the like. Rejects reserved direct children of public suffixes.
  262. reserved_prefixes = ('_', 'autoconfig.', 'autodiscover.',)
  263. if private_generation == 1 and any(self.name.startswith(prefix) for prefix in reserved_prefixes):
  264. return False
  265. # Domains covered by another user's zone can't be registered
  266. if self.is_covered_by_foreign_zone():
  267. return False
  268. # Domains that would cover another user's zone can't be registered
  269. if self.covers_foreign_zone():
  270. return False
  271. return True
  272. @property
  273. def keys(self):
  274. if not self._keys:
  275. self._keys = pdns.get_keys(self)
  276. return self._keys
  277. @property
  278. def touched(self):
  279. try:
  280. rrset_touched = max(updated for updated in self.rrset_set.values_list('touched', flat=True))
  281. # If the domain has not been published yet, self.published is None and max() would fail
  282. return rrset_touched if not self.published else max(rrset_touched, self.published)
  283. except ValueError:
  284. # This can be none if the domain was never published and has no records (but there should be at least NS)
  285. return self.published
  286. @property
  287. def is_locally_registrable(self):
  288. return self.parent_domain_name in settings.LOCAL_PUBLIC_SUFFIXES
  289. @property
  290. def _owner_or_none(self):
  291. try:
  292. return self.owner
  293. except Domain.owner.RelatedObjectDoesNotExist:
  294. return None
  295. @property
  296. def parent_domain_name(self):
  297. return self._partitioned_name[1]
  298. @property
  299. def _partitioned_name(self):
  300. subname, _, parent_name = self.name.partition('.')
  301. return subname, parent_name or None
  302. def save(self, *args, **kwargs):
  303. self.full_clean(validate_unique=False)
  304. super().save(*args, **kwargs)
  305. def update_delegation(self, child_domain: Domain):
  306. child_subname, child_domain_name = child_domain._partitioned_name
  307. if self.name != child_domain_name:
  308. raise ValueError('Cannot update delegation of %s as it is not an immediate child domain of %s.' %
  309. (child_domain.name, self.name))
  310. if child_domain.pk:
  311. # Domain real: set delegation
  312. child_keys = child_domain.keys
  313. if not child_keys:
  314. raise APIException('Cannot delegate %s, as it currently has no keys.' % child_domain.name)
  315. RRset.objects.create(domain=self, subname=child_subname, type='NS', ttl=3600, contents=settings.DEFAULT_NS)
  316. RRset.objects.create(domain=self, subname=child_subname, type='DS', ttl=300,
  317. contents=[ds for k in child_keys for ds in k['ds']])
  318. metrics.get('desecapi_autodelegation_created').inc()
  319. else:
  320. # Domain not real: remove delegation
  321. for rrset in self.rrset_set.filter(subname=child_subname, type__in=['NS', 'DS']):
  322. rrset.delete()
  323. metrics.get('desecapi_autodelegation_deleted').inc()
  324. def delete(self):
  325. ret = super().delete()
  326. logger.warning(f'Domain {self.name} deleted (owner: {self.owner.pk})')
  327. return ret
  328. def __str__(self):
  329. return self.name
  330. class Meta:
  331. ordering = ('created',)
  332. def get_default_value_created():
  333. return timezone.now()
  334. def get_default_value_due():
  335. return timezone.now() + timedelta(days=7)
  336. def get_default_value_mref():
  337. return "ONDON" + str(time.time())
  338. class Donation(ExportModelOperationsMixin('Donation'), models.Model):
  339. created = models.DateTimeField(default=get_default_value_created)
  340. name = models.CharField(max_length=255)
  341. iban = models.CharField(max_length=34)
  342. bic = models.CharField(max_length=11, blank=True)
  343. amount = models.DecimalField(max_digits=8, decimal_places=2)
  344. message = models.CharField(max_length=255, blank=True)
  345. due = models.DateTimeField(default=get_default_value_due)
  346. mref = models.CharField(max_length=32, default=get_default_value_mref)
  347. email = models.EmailField(max_length=255, blank=True)
  348. class Meta:
  349. managed = False
  350. # RR set types: the good, the bad, and the ugly
  351. # known, but unsupported types
  352. RR_SET_TYPES_UNSUPPORTED = {
  353. 'ALIAS', # Requires signing at the frontend, hence unsupported in desec-stack
  354. 'DNAME', # "do not combine with DNSSEC", https://doc.powerdns.com/authoritative/settings.html#dname-processing
  355. 'IPSECKEY', # broken in pdns, https://github.com/PowerDNS/pdns/issues/9055 TODO enable support
  356. 'KEY', # Application use restricted by RFC 3445, DNSSEC use replaced by DNSKEY and handled automatically
  357. 'WKS', # General usage not recommended, "SHOULD NOT" be used in SMTP (RFC 1123)
  358. }
  359. # restricted types are managed in use by the API, and cannot directly be modified by the API client
  360. RR_SET_TYPES_AUTOMATIC = {
  361. # corresponding functionality is automatically managed:
  362. 'CDNSKEY', 'CDS', 'DNSKEY', 'KEY', 'NSEC', 'NSEC3', 'OPT', 'RRSIG',
  363. # automatically managed by the API:
  364. 'NSEC3PARAM', 'SOA'
  365. }
  366. # backend types are types that are the types supported by the backend(s)
  367. RR_SET_TYPES_BACKEND = pdns.SUPPORTED_RRSET_TYPES
  368. # validation types are types supported by the validation backend, currently: dnspython
  369. RR_SET_TYPES_VALIDATION = set(ANY.__all__) | set(IN.__all__)
  370. # manageable types are directly managed by the API client
  371. RR_SET_TYPES_MANAGEABLE = \
  372. (RR_SET_TYPES_BACKEND & RR_SET_TYPES_VALIDATION) - RR_SET_TYPES_UNSUPPORTED - RR_SET_TYPES_AUTOMATIC
  373. class RRsetManager(Manager):
  374. def create(self, contents=None, **kwargs):
  375. rrset = super().create(**kwargs)
  376. for content in contents or []:
  377. RR.objects.create(rrset=rrset, content=content)
  378. return rrset
  379. class RRset(ExportModelOperationsMixin('RRset'), models.Model):
  380. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  381. created = models.DateTimeField(auto_now_add=True)
  382. touched = models.DateTimeField(auto_now=True)
  383. domain = models.ForeignKey(Domain, on_delete=models.CASCADE)
  384. subname = models.CharField(
  385. max_length=178,
  386. blank=True,
  387. validators=[
  388. validate_lower,
  389. RegexValidator(
  390. regex=r'^([*]|(([*][.])?([a-z0-9_-]+[.])*[a-z0-9_-]+))$',
  391. message='Subname can only use (lowercase) a-z, 0-9, ., -, and _, '
  392. 'may start with a \'*.\', or just be \'*\'.',
  393. code='invalid_subname'
  394. )
  395. ]
  396. )
  397. type = models.CharField(
  398. max_length=10,
  399. validators=[
  400. validate_upper,
  401. RegexValidator(
  402. regex=r'^[A-Z][A-Z0-9]*$',
  403. message='Type must be uppercase alphanumeric and start with a letter.',
  404. code='invalid_type'
  405. )
  406. ]
  407. )
  408. ttl = models.PositiveIntegerField()
  409. objects = RRsetManager()
  410. class Meta:
  411. constraints = [
  412. ExclusionConstraint(
  413. name='cname_exclusivity',
  414. expressions=[
  415. ('domain', RangeOperators.EQUAL),
  416. ('subname', RangeOperators.EQUAL),
  417. (RawSQL("int4(type = 'CNAME')", ()), RangeOperators.NOT_EQUAL),
  418. ],
  419. ),
  420. ]
  421. unique_together = (("domain", "subname", "type"),)
  422. @staticmethod
  423. def construct_name(subname, domain_name):
  424. return '.'.join(filter(None, [subname, domain_name])) + '.'
  425. @property
  426. def name(self):
  427. return self.construct_name(self.subname, self.domain.name)
  428. def save(self, *args, **kwargs):
  429. self.full_clean(validate_unique=False)
  430. super().save(*args, **kwargs)
  431. def clean_records(self, records_presentation_format):
  432. """
  433. Validates the records belonging to this set. Validation rules follow the DNS specification; some types may
  434. incur additional validation rules.
  435. Raises ValidationError if violation of DNS specification is found.
  436. Returns a set of records in canonical presentation format.
  437. :param records_presentation_format: iterable of records in presentation format
  438. """
  439. rdtype = rdatatype.from_text(self.type)
  440. errors = []
  441. if self.type == 'CNAME':
  442. if self.subname == '':
  443. errors.append('CNAME RRset cannot have empty subname.')
  444. if len(records_presentation_format) > 1:
  445. errors.append('RRset of type CNAME cannot have multiple records.')
  446. def _error_msg(record, detail):
  447. return f'Record content of {self.type} {self.name} invalid: \'{record}\': {detail}'
  448. records_canonical_format = set()
  449. for r in records_presentation_format:
  450. try:
  451. r_canonical_format = RR.canonical_presentation_format(r, rdtype)
  452. except binascii.Error:
  453. # e.g., odd-length string
  454. errors.append(_error_msg(r, 'Cannot parse hexadecimal or base64 record contents'))
  455. except dns.exception.SyntaxError as e:
  456. # e.g., A/127.0.0.999
  457. if 'quote' in e.args[0]:
  458. errors.append(_error_msg(r, f'Data for {self.type} records must be given using quotation marks.'))
  459. else:
  460. errors.append(_error_msg(r, f'Record content malformed: {",".join(e.args)}'))
  461. except dns.name.NeedAbsoluteNameOrOrigin:
  462. errors.append(_error_msg(r, 'Hostname must be fully qualified (i.e., end in a dot: "example.com.")'))
  463. except ValueError:
  464. # e.g., string ("asdf") cannot be parsed into int on base 10
  465. errors.append(_error_msg(r, 'Cannot parse record contents'))
  466. except Exception as e:
  467. # TODO see what exceptions raise here for faulty input
  468. raise e
  469. else:
  470. if r_canonical_format in records_canonical_format:
  471. errors.append(_error_msg(r, f'Duplicate record content: this is identical to '
  472. f'\'{r_canonical_format}\''))
  473. else:
  474. records_canonical_format.add(r_canonical_format)
  475. if any(errors):
  476. raise ValidationError(errors)
  477. return records_canonical_format
  478. def save_records(self, records):
  479. """
  480. Updates this RR set's resource records, discarding any old values.
  481. Records are expected in presentation format and are converted to canonical
  482. presentation format (e.g., 127.00.0.1 will be converted to 127.0.0.1).
  483. Raises if a invalid set of records is provided.
  484. This method triggers the following database queries:
  485. - one DELETE query
  486. - one SELECT query for comparison of old with new records
  487. - one INSERT query, if one or more records were added
  488. Changes are saved to the database immediately.
  489. :param records: list of records in presentation format
  490. """
  491. new_records = self.clean_records(records)
  492. # Delete RRs that are not in the new record list from the DB
  493. self.records.exclude(content__in=new_records).delete() # one DELETE
  494. # Retrieve all remaining RRs from the DB
  495. unchanged_records = set(r.content for r in self.records.all()) # one SELECT
  496. # Save missing RRs from the new record list to the DB
  497. added_records = new_records - unchanged_records
  498. rrs = [RR(rrset=self, content=content) for content in added_records]
  499. RR.objects.bulk_create(rrs) # One INSERT
  500. def __str__(self):
  501. return '<RRSet %s domain=%s type=%s subname=%s>' % (self.pk, self.domain.name, self.type, self.subname)
  502. class RRManager(Manager):
  503. def bulk_create(self, rrs, **kwargs):
  504. ret = super().bulk_create(rrs, **kwargs)
  505. # For each rrset, save once to set RRset.updated timestamp and trigger signal for post-save processing
  506. rrsets = {rr.rrset for rr in rrs}
  507. for rrset in rrsets:
  508. rrset.save()
  509. return ret
  510. class RR(ExportModelOperationsMixin('RR'), models.Model):
  511. created = models.DateTimeField(auto_now_add=True)
  512. rrset = models.ForeignKey(RRset, on_delete=models.CASCADE, related_name='records')
  513. content = models.TextField()
  514. objects = RRManager()
  515. @staticmethod
  516. def canonical_presentation_format(any_presentation_format, type_):
  517. """
  518. Converts any valid presentation format for a RR into it's canonical presentation format.
  519. Raises if provided presentation format is invalid.
  520. """
  521. if type_ in (dns.rdatatype.TXT, dns.rdatatype.SPF):
  522. # for TXT record, we slightly deviate from RFC 1035 and allow tokens that are longer than 255 byte.
  523. cls = LongQuotedTXT
  524. elif type_ == dns.rdatatype.OPENPGPKEY:
  525. cls = OPENPGPKEY
  526. else:
  527. # For all other record types, let dnspython decide
  528. cls = rdata
  529. wire = cls.from_text(
  530. rdclass=rdataclass.IN,
  531. rdtype=type_,
  532. tok=dns.tokenizer.Tokenizer(any_presentation_format),
  533. relativize=False
  534. ).to_digestable()
  535. # The pdns lmdb backend used on our frontends does not only store the record contents itself, but other metadata
  536. # (such as type etc.) Both together have to fit into the lmdb backend's current total limit of 512 bytes per RR.
  537. # I found the additional data to be 12 bytes (by trial and error). I believe these are the 12 bytes mentioned
  538. # here: https://lists.isc.org/pipermail/bind-users/2008-April/070137.html So we can use 500 bytes for the actual
  539. # content stored in wire format.
  540. # This check can be relaxed as soon as lmdb supports larger records,
  541. # cf. https://github.com/desec-io/desec-slave/issues/34 and https://github.com/PowerDNS/pdns/issues/8012
  542. if len(wire) > 500:
  543. raise ValidationError(f'Ensure this value has no more than 500 byte in wire format (it has {len(wire)}).')
  544. parser = dns.wire.Parser(wire, current=0)
  545. with parser.restrict_to(len(wire)):
  546. return cls.from_wire_parser(
  547. rdclass=rdataclass.IN,
  548. rdtype=type_,
  549. parser=parser,
  550. ).to_text()
  551. def __str__(self):
  552. return '<RR %s %s rr_set=%s>' % (self.pk, self.content, self.rrset.pk)
  553. class AuthenticatedAction(models.Model):
  554. """
  555. Represents a procedure call on a defined set of arguments.
  556. Subclasses can define additional arguments by adding Django model fields and must define the action to be taken by
  557. implementing the `_act` method.
  558. AuthenticatedAction provides the `state` property which by default is a hash of the action type (defined by the
  559. action's class path). Other information such as user state can be included in the state hash by (carefully)
  560. overriding the `_state_fields` property. Instantiation of the model, if given a `state` kwarg, will raise an error
  561. if the given state argument does not match the state computed from `_state_fields` at the moment of instantiation.
  562. The same applies to the `act` method: If called on an object that was instantiated without a `state` kwargs, an
  563. error will be raised.
  564. This effectively allows hash-authenticated procedure calls by third parties as long as the server-side state is
  565. unaltered, according to the following protocol:
  566. (1) Instantiate the AuthenticatedAction subclass representing the action to be taken (no `state` kwarg here),
  567. (2) provide information on how to instantiate the instance, and the state hash, to a third party,
  568. (3) when provided with data that allows instantiation and a valid state hash, take the defined action, possibly with
  569. additional parameters chosen by the third party that do not belong to the verified state.
  570. """
  571. _validated = False
  572. class Meta:
  573. managed = False
  574. def __init__(self, *args, **kwargs):
  575. state = kwargs.pop('state', None)
  576. super().__init__(*args, **kwargs)
  577. if state is not None:
  578. self._validated = self.validate_state(state)
  579. if not self._validated:
  580. raise ValueError
  581. @property
  582. def _state_fields(self):
  583. """
  584. Returns a list that defines the state of this action (used for authentication of this action).
  585. Return value must be JSON-serializable.
  586. Values not included in the return value will not be used for authentication, i.e. those values can be varied
  587. freely and function as unauthenticated action input parameters.
  588. Use caution when overriding this method. You will usually want to append a value to the list returned by the
  589. parent. Overriding the behavior altogether could result in reducing the state to fewer variables, resulting
  590. in valid signatures when they were intended to be invalid. The suggested method for overriding is
  591. @property
  592. def _state_fields:
  593. return super()._state_fields + [self.important_value, self.another_added_value]
  594. :return: List of values to be signed.
  595. """
  596. name = '.'.join([self.__module__, self.__class__.__qualname__])
  597. return [name]
  598. @property
  599. def state(self):
  600. state = json.dumps(self._state_fields).encode()
  601. hash = sha256()
  602. hash.update(state)
  603. return hash.hexdigest()
  604. def validate_state(self, value):
  605. return value == self.state
  606. def _act(self):
  607. """
  608. Conduct the action represented by this class.
  609. :return: None
  610. """
  611. raise NotImplementedError
  612. def act(self):
  613. if not self._validated:
  614. raise RuntimeError('Action state could not be verified.')
  615. return self._act()
  616. class AuthenticatedBasicUserAction(AuthenticatedAction):
  617. """
  618. Abstract AuthenticatedAction involving a user instance.
  619. """
  620. user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
  621. class Meta:
  622. managed = False
  623. @property
  624. def _state_fields(self):
  625. return super()._state_fields + [str(self.user.id)]
  626. class AuthenticatedUserAction(AuthenticatedBasicUserAction):
  627. """
  628. Abstract AuthenticatedBasicUserAction, incorporating the user's id, email, password, and is_active flag into the
  629. Message Authentication Code state.
  630. """
  631. class Meta:
  632. managed = False
  633. @property
  634. def _state_fields(self):
  635. # TODO consider adding a "last change" attribute of the user to the state to avoid code
  636. # re-use after the the state has been changed and changed back.
  637. return super()._state_fields + [self.user.email, self.user.password, self.user.is_active]
  638. class AuthenticatedActivateUserAction(AuthenticatedUserAction):
  639. domain = models.CharField(max_length=191)
  640. class Meta:
  641. managed = False
  642. @property
  643. def _state_fields(self):
  644. return super()._state_fields + [self.domain]
  645. def _act(self):
  646. self.user.activate()
  647. class AuthenticatedChangeEmailUserAction(AuthenticatedUserAction):
  648. new_email = models.EmailField()
  649. class Meta:
  650. managed = False
  651. @property
  652. def _state_fields(self):
  653. return super()._state_fields + [self.new_email]
  654. def _act(self):
  655. self.user.change_email(self.new_email)
  656. class AuthenticatedResetPasswordUserAction(AuthenticatedUserAction):
  657. new_password = models.CharField(max_length=128)
  658. class Meta:
  659. managed = False
  660. def _act(self):
  661. self.user.change_password(self.new_password)
  662. class AuthenticatedDeleteUserAction(AuthenticatedUserAction):
  663. class Meta:
  664. managed = False
  665. def _act(self):
  666. self.user.delete()
  667. class AuthenticatedDomainBasicUserAction(AuthenticatedBasicUserAction):
  668. """
  669. Abstract AuthenticatedUserAction involving an domain instance, incorporating the domain's id, name as well as the
  670. owner ID into the Message Authentication Code state.
  671. """
  672. domain = models.ForeignKey(Domain, on_delete=models.DO_NOTHING)
  673. class Meta:
  674. managed = False
  675. @property
  676. def _state_fields(self):
  677. return super()._state_fields + [
  678. str(self.domain.id), # ensures the domain object is identical
  679. self.domain.name, # exclude renamed domains
  680. str(self.domain.owner.id), # exclude transferred domains
  681. ]
  682. class AuthenticatedRenewDomainBasicUserAction(AuthenticatedDomainBasicUserAction):
  683. class Meta:
  684. managed = False
  685. @property
  686. def _state_fields(self):
  687. return super()._state_fields + [str(self.domain.renewal_changed)]
  688. def _act(self):
  689. self.domain.renewal_state = Domain.RenewalState.FRESH
  690. self.domain.renewal_changed = timezone.now()
  691. self.domain.save(update_fields=['renewal_state', 'renewal_changed'])
  692. def captcha_default_content():
  693. alphabet = (string.ascii_uppercase + string.digits).translate({ord(c): None for c in 'IO0'})
  694. content = ''.join([secrets.choice(alphabet) for _ in range(5)])
  695. metrics.get('desecapi_captcha_content_created').inc()
  696. return content
  697. class Captcha(ExportModelOperationsMixin('Captcha'), models.Model):
  698. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  699. created = models.DateTimeField(auto_now_add=True)
  700. content = models.CharField(
  701. max_length=24,
  702. default=captcha_default_content,
  703. )
  704. def verify(self, solution: str):
  705. age = timezone.now() - self.created
  706. self.delete()
  707. return (
  708. str(solution).upper().strip() == self.content # solution correct
  709. and
  710. age <= settings.CAPTCHA_VALIDITY_PERIOD # not expired
  711. )