models.py 33 KB

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