models.py 33 KB

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