models.py 32 KB

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