models.py 35 KB

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