models.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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 AbstractBaseUser, AnonymousUser, BaseUserManager
  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 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 CDS, DLV, DS, LongQuotedTXT
  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. if isinstance(kwargs.get('owner'), AnonymousUser):
  191. kwargs = {**kwargs, 'owner': None} # make a copy and override
  192. # Avoid super().__init__(owner=None, ...) to not mess up *values instantiation in django.db.models.Model.from_db
  193. super().__init__(*args, **kwargs)
  194. if self.pk is None and kwargs.get('renewal_state') is None and self.is_locally_registrable:
  195. self.renewal_state = Domain.RenewalState.FRESH
  196. @cached_property
  197. def public_suffix(self):
  198. try:
  199. public_suffix = psl.get_public_suffix(self.name)
  200. is_public_suffix = psl.is_public_suffix(self.name)
  201. except (Timeout, NoNameservers):
  202. public_suffix = self.name.rpartition('.')[2]
  203. is_public_suffix = ('.' not in self.name) # TLDs are public suffixes
  204. except psl_dns.exceptions.UnsupportedRule as e:
  205. # It would probably be fine to treat this as a non-public suffix (with the TLD acting as the
  206. # public suffix and setting both public_suffix and is_public_suffix accordingly).
  207. # However, in order to allow to investigate the situation, it's better not catch
  208. # this exception. For web requests, our error handler turns it into a 503 error
  209. # and makes sure admins are notified.
  210. raise e
  211. if is_public_suffix:
  212. return public_suffix
  213. # Take into account that any of the parent domains could be a local public suffix. To that
  214. # end, identify the longest local public suffix that is actually a suffix of domain_name.
  215. for local_public_suffix in settings.LOCAL_PUBLIC_SUFFIXES:
  216. has_local_public_suffix_parent = ('.' + self.name).endswith('.' + local_public_suffix)
  217. if has_local_public_suffix_parent and len(local_public_suffix) > len(public_suffix):
  218. public_suffix = local_public_suffix
  219. return public_suffix
  220. def is_covered_by_foreign_zone(self):
  221. # Generate a list of all domains connecting this one and its public suffix.
  222. # If another user owns a zone with one of these names, then the requested
  223. # domain is unavailable because it is part of the other user's zone.
  224. private_components = self.name.rsplit(self.public_suffix, 1)[0].rstrip('.')
  225. private_components = private_components.split('.') if private_components else []
  226. private_domains = ['.'.join(private_components[i:]) for i in range(0, len(private_components))]
  227. private_domains = [f'{private_domain}.{self.public_suffix}' for private_domain in private_domains]
  228. assert self.name == next(iter(private_domains), self.public_suffix)
  229. # Determine whether domain is covered by other users' zones
  230. return Domain.objects.filter(Q(name__in=private_domains) & ~Q(owner=self._owner_or_none)).exists()
  231. def covers_foreign_zone(self):
  232. # Note: This is not completely accurate: Ideally, we should only consider zones with identical public suffix.
  233. # (If a public suffix lies in between, it's ok.) However, as there could be many descendant zones, the accurate
  234. # check is expensive, so currently not implemented (PSL lookups for each of them).
  235. return Domain.objects.filter(Q(name__endswith=f'.{self.name}') & ~Q(owner=self._owner_or_none)).exists()
  236. def is_registrable(self):
  237. """
  238. Returns False if the domain name is reserved, a public suffix, or covered by / covers another user's domain.
  239. Otherwise, True is returned.
  240. """
  241. self.clean() # ensure .name is a domain name
  242. private_generation = self.name.count('.') - self.public_suffix.count('.')
  243. assert private_generation >= 0
  244. # .internal is reserved
  245. if f'.{self.name}'.endswith('.internal'):
  246. return False
  247. # Public suffixes can only be registered if they are local
  248. if private_generation == 0 and self.name not in settings.LOCAL_PUBLIC_SUFFIXES:
  249. return False
  250. # Disallow _acme-challenge.dedyn.io and the like. Rejects reserved direct children of public suffixes.
  251. reserved_prefixes = ('_', 'autoconfig.', 'autodiscover.',)
  252. if private_generation == 1 and any(self.name.startswith(prefix) for prefix in reserved_prefixes):
  253. return False
  254. # Domains covered by another user's zone can't be registered
  255. if self.is_covered_by_foreign_zone():
  256. return False
  257. # Domains that would cover another user's zone can't be registered
  258. if self.covers_foreign_zone():
  259. return False
  260. return True
  261. @property
  262. def keys(self):
  263. if not self._keys:
  264. self._keys = pdns.get_keys(self)
  265. return self._keys
  266. @property
  267. def touched(self):
  268. try:
  269. rrset_touched = max(updated for updated in self.rrset_set.values_list('touched', flat=True))
  270. # If the domain has not been published yet, self.published is None and max() would fail
  271. return rrset_touched if not self.published else max(rrset_touched, self.published)
  272. except ValueError:
  273. # This can be none if the domain was never published and has no records (but there should be at least NS)
  274. return self.published
  275. @property
  276. def is_locally_registrable(self):
  277. return self.parent_domain_name in settings.LOCAL_PUBLIC_SUFFIXES
  278. @property
  279. def _owner_or_none(self):
  280. try:
  281. return self.owner
  282. except Domain.owner.RelatedObjectDoesNotExist:
  283. return None
  284. @property
  285. def parent_domain_name(self):
  286. return self._partitioned_name[1]
  287. @property
  288. def _partitioned_name(self):
  289. subname, _, parent_name = self.name.partition('.')
  290. return subname, parent_name or None
  291. def save(self, *args, **kwargs):
  292. self.full_clean(validate_unique=False)
  293. super().save(*args, **kwargs)
  294. def update_delegation(self, child_domain: Domain):
  295. child_subname, child_domain_name = child_domain._partitioned_name
  296. if self.name != child_domain_name:
  297. raise ValueError('Cannot update delegation of %s as it is not an immediate child domain of %s.' %
  298. (child_domain.name, self.name))
  299. if child_domain.pk:
  300. # Domain real: set delegation
  301. child_keys = child_domain.keys
  302. if not child_keys:
  303. raise APIException('Cannot delegate %s, as it currently has no keys.' % child_domain.name)
  304. RRset.objects.create(domain=self, subname=child_subname, type='NS', ttl=3600, contents=settings.DEFAULT_NS)
  305. RRset.objects.create(domain=self, subname=child_subname, type='DS', ttl=300,
  306. contents=[ds for k in child_keys for ds in k['ds']])
  307. metrics.get('desecapi_autodelegation_created').inc()
  308. else:
  309. # Domain not real: remove delegation
  310. for rrset in self.rrset_set.filter(subname=child_subname, type__in=['NS', 'DS']):
  311. rrset.delete()
  312. metrics.get('desecapi_autodelegation_deleted').inc()
  313. def delete(self):
  314. ret = super().delete()
  315. logger.warning(f'Domain {self.name} deleted (owner: {self.owner.pk})')
  316. return ret
  317. def __str__(self):
  318. return self.name
  319. class Meta:
  320. ordering = ('created',)
  321. class Token(ExportModelOperationsMixin('Token'), rest_framework.authtoken.models.Token):
  322. @staticmethod
  323. def _allowed_subnets_default():
  324. return [ipaddress.IPv4Network('0.0.0.0/0'), ipaddress.IPv6Network('::/0')]
  325. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  326. key = models.CharField("Key", max_length=128, db_index=True, unique=True)
  327. user = models.ForeignKey(
  328. User, related_name='auth_tokens',
  329. on_delete=models.CASCADE, verbose_name="User"
  330. )
  331. name = models.CharField('Name', blank=True, max_length=64)
  332. last_used = models.DateTimeField(null=True, blank=True)
  333. perm_manage_tokens = models.BooleanField(default=False)
  334. allowed_subnets = ArrayField(CidrAddressField(), default=_allowed_subnets_default.__func__)
  335. max_age = models.DurationField(null=True, default=None, validators=[MinValueValidator(timedelta(0))])
  336. max_unused_period = models.DurationField(null=True, default=None, validators=[MinValueValidator(timedelta(0))])
  337. plain = None
  338. objects = NetManager()
  339. @property
  340. def is_valid(self):
  341. now = timezone.now()
  342. # Check max age
  343. try:
  344. if self.created + self.max_age < now:
  345. return False
  346. except TypeError:
  347. pass
  348. # Check regular usage requirement
  349. try:
  350. if (self.last_used or self.created) + self.max_unused_period < now:
  351. return False
  352. except TypeError:
  353. pass
  354. return True
  355. def generate_key(self):
  356. self.plain = secrets.token_urlsafe(21)
  357. self.key = Token.make_hash(self.plain)
  358. return self.key
  359. @staticmethod
  360. def make_hash(plain):
  361. return make_password(plain, salt='static', hasher='pbkdf2_sha256_iter1')
  362. class Donation(ExportModelOperationsMixin('Donation'), models.Model):
  363. @staticmethod
  364. def _created_default():
  365. return timezone.now()
  366. @staticmethod
  367. def _due_default():
  368. return timezone.now() + timedelta(days=7)
  369. @staticmethod
  370. def _mref_default():
  371. return "ONDON" + str(time.time())
  372. created = models.DateTimeField(default=_created_default.__func__)
  373. name = models.CharField(max_length=255)
  374. iban = models.CharField(max_length=34)
  375. bic = models.CharField(max_length=11, blank=True)
  376. amount = models.DecimalField(max_digits=8, decimal_places=2)
  377. message = models.CharField(max_length=255, blank=True)
  378. due = models.DateTimeField(default=_due_default.__func__)
  379. mref = models.CharField(max_length=32, default=_mref_default.__func__)
  380. email = models.EmailField(max_length=255, blank=True)
  381. class Meta:
  382. managed = False
  383. # RR set types: the good, the bad, and the ugly
  384. # known, but unsupported types
  385. RR_SET_TYPES_UNSUPPORTED = {
  386. 'ALIAS', # Requires signing at the frontend, hence unsupported in desec-stack
  387. 'DNAME', # "do not combine with DNSSEC", https://doc.powerdns.com/authoritative/settings.html#dname-processing
  388. 'IPSECKEY', # broken in pdns, https://github.com/PowerDNS/pdns/issues/9055 TODO enable with pdns auth 4.5.0
  389. 'KEY', # Application use restricted by RFC 3445, DNSSEC use replaced by DNSKEY and handled automatically
  390. 'WKS', # General usage not recommended, "SHOULD NOT" be used in SMTP (RFC 1123)
  391. }
  392. # restricted types are managed in use by the API, and cannot directly be modified by the API client
  393. RR_SET_TYPES_AUTOMATIC = {
  394. # corresponding functionality is automatically managed:
  395. 'KEY', 'NSEC', 'NSEC3', 'OPT', 'RRSIG',
  396. # automatically managed by the API:
  397. 'NSEC3PARAM', 'SOA'
  398. }
  399. # backend types are types that are the types supported by the backend(s)
  400. RR_SET_TYPES_BACKEND = pdns.SUPPORTED_RRSET_TYPES
  401. # validation types are types supported by the validation backend, currently: dnspython
  402. RR_SET_TYPES_VALIDATION = set(ANY.__all__) | set(IN.__all__) \
  403. | {'HTTPS', 'SVCB'} # https://github.com/rthalley/dnspython/pull/624
  404. # manageable types are directly managed by the API client
  405. RR_SET_TYPES_MANAGEABLE = \
  406. (RR_SET_TYPES_BACKEND & RR_SET_TYPES_VALIDATION) - RR_SET_TYPES_UNSUPPORTED - RR_SET_TYPES_AUTOMATIC
  407. class RRsetManager(Manager):
  408. def create(self, contents=None, **kwargs):
  409. rrset = super().create(**kwargs)
  410. for content in contents or []:
  411. RR.objects.create(rrset=rrset, content=content)
  412. return rrset
  413. class RRset(ExportModelOperationsMixin('RRset'), models.Model):
  414. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  415. created = models.DateTimeField(auto_now_add=True)
  416. touched = models.DateTimeField(auto_now=True)
  417. domain = models.ForeignKey(Domain, on_delete=models.CASCADE)
  418. subname = models.CharField(
  419. max_length=178,
  420. blank=True,
  421. validators=[
  422. validate_lower,
  423. RegexValidator(
  424. regex=r'^([*]|(([*][.])?([a-z0-9_-]{1,63}[.])*[a-z0-9_-]{1,63}))$',
  425. message='Subname can only use (lowercase) a-z, 0-9, ., -, and _, '
  426. 'may start with a \'*.\', or just be \'*\'. Components may not exceed 63 characters.',
  427. code='invalid_subname'
  428. )
  429. ]
  430. )
  431. type = models.CharField(
  432. max_length=10,
  433. validators=[
  434. validate_upper,
  435. RegexValidator(
  436. regex=r'^[A-Z][A-Z0-9]*$',
  437. message='Type must be uppercase alphanumeric and start with a letter.',
  438. code='invalid_type'
  439. )
  440. ]
  441. )
  442. ttl = models.PositiveIntegerField()
  443. objects = RRsetManager()
  444. class Meta:
  445. constraints = [
  446. ExclusionConstraint(
  447. name='cname_exclusivity',
  448. expressions=[
  449. ('domain', RangeOperators.EQUAL),
  450. ('subname', RangeOperators.EQUAL),
  451. (RawSQL("int4(type = 'CNAME')", ()), RangeOperators.NOT_EQUAL),
  452. ],
  453. ),
  454. ]
  455. unique_together = (("domain", "subname", "type"),)
  456. @staticmethod
  457. def construct_name(subname, domain_name):
  458. return '.'.join(filter(None, [subname, domain_name])) + '.'
  459. @property
  460. def name(self):
  461. return self.construct_name(self.subname, self.domain.name)
  462. def save(self, *args, **kwargs):
  463. self.full_clean(validate_unique=False)
  464. super().save(*args, **kwargs)
  465. def clean_records(self, records_presentation_format):
  466. """
  467. Validates the records belonging to this set. Validation rules follow the DNS specification; some types may
  468. incur additional validation rules.
  469. Raises ValidationError if violation of DNS specification is found.
  470. Returns a set of records in canonical presentation format.
  471. :param records_presentation_format: iterable of records in presentation format
  472. """
  473. errors = []
  474. if self.type == 'CNAME':
  475. if self.subname == '':
  476. errors.append('CNAME RRset cannot have empty subname.')
  477. if len(records_presentation_format) > 1:
  478. errors.append('CNAME RRset cannot have multiple records.')
  479. def _error_msg(record, detail):
  480. return f'Record content of {self.type} {self.name} invalid: \'{record}\': {detail}'
  481. records_canonical_format = set()
  482. for r in records_presentation_format:
  483. try:
  484. r_canonical_format = RR.canonical_presentation_format(r, self.type)
  485. except ValueError as ex:
  486. errors.append(_error_msg(r, str(ex)))
  487. else:
  488. if r_canonical_format in records_canonical_format:
  489. errors.append(_error_msg(r, f'Duplicate record content: this is identical to '
  490. f'\'{r_canonical_format}\''))
  491. else:
  492. records_canonical_format.add(r_canonical_format)
  493. if any(errors):
  494. raise ValidationError(errors)
  495. return records_canonical_format
  496. def save_records(self, records):
  497. """
  498. Updates this RR set's resource records, discarding any old values.
  499. Records are expected in presentation format and are converted to canonical
  500. presentation format (e.g., 127.00.0.1 will be converted to 127.0.0.1).
  501. Raises if a invalid set of records is provided.
  502. This method triggers the following database queries:
  503. - one DELETE query
  504. - one SELECT query for comparison of old with new records
  505. - one INSERT query, if one or more records were added
  506. Changes are saved to the database immediately.
  507. :param records: list of records in presentation format
  508. """
  509. new_records = self.clean_records(records)
  510. # Delete RRs that are not in the new record list from the DB
  511. self.records.exclude(content__in=new_records).delete() # one DELETE
  512. # Retrieve all remaining RRs from the DB
  513. unchanged_records = set(r.content for r in self.records.all()) # one SELECT
  514. # Save missing RRs from the new record list to the DB
  515. added_records = new_records - unchanged_records
  516. rrs = [RR(rrset=self, content=content) for content in added_records]
  517. RR.objects.bulk_create(rrs) # One INSERT
  518. def __str__(self):
  519. return '<RRSet %s domain=%s type=%s subname=%s>' % (self.pk, self.domain.name, self.type, self.subname)
  520. class RRManager(Manager):
  521. def bulk_create(self, rrs, **kwargs):
  522. ret = super().bulk_create(rrs, **kwargs)
  523. # For each rrset, save once to set RRset.updated timestamp and trigger signal for post-save processing
  524. rrsets = {rr.rrset for rr in rrs}
  525. for rrset in rrsets:
  526. rrset.save()
  527. return ret
  528. class RR(ExportModelOperationsMixin('RR'), models.Model):
  529. created = models.DateTimeField(auto_now_add=True)
  530. rrset = models.ForeignKey(RRset, on_delete=models.CASCADE, related_name='records')
  531. content = models.TextField()
  532. objects = RRManager()
  533. _type_map = {
  534. dns.rdatatype.CDS: CDS, # TODO remove when https://github.com/rthalley/dnspython/pull/625 is in main codebase
  535. dns.rdatatype.DLV: DLV, # TODO remove when https://github.com/rthalley/dnspython/pull/625 is in main codebase
  536. dns.rdatatype.DS: DS, # TODO remove when https://github.com/rthalley/dnspython/pull/625 is in main codebase
  537. dns.rdatatype.TXT: LongQuotedTXT, # we slightly deviate from RFC 1035 and allow tokens longer than 255 bytes
  538. dns.rdatatype.SPF: LongQuotedTXT, # we slightly deviate from RFC 1035 and allow tokens longer than 255 bytes
  539. }
  540. @staticmethod
  541. def canonical_presentation_format(any_presentation_format, type_):
  542. """
  543. Converts any valid presentation format for a RR into it's canonical presentation format.
  544. Raises if provided presentation format is invalid.
  545. """
  546. rdtype = rdatatype.from_text(type_)
  547. try:
  548. # Convert to wire format, ensuring input validation.
  549. cls = RR._type_map.get(rdtype, dns.rdata)
  550. wire = cls.from_text(
  551. rdclass=rdataclass.IN,
  552. rdtype=rdtype,
  553. tok=dns.tokenizer.Tokenizer(any_presentation_format),
  554. relativize=False
  555. ).to_digestable()
  556. if len(wire) > 64000:
  557. raise ValidationError(f'Ensure this value has no more than 64000 byte in wire format (it has {len(wire)}).')
  558. parser = dns.wire.Parser(wire, current=0)
  559. with parser.restrict_to(len(wire)):
  560. rdata = cls.from_wire_parser(rdclass=rdataclass.IN, rdtype=rdtype, parser=parser)
  561. # Convert to canonical presentation format, disable chunking of records.
  562. # Exempt types which have chunksize hardcoded (prevents "got multiple values for keyword argument 'chunksize'").
  563. chunksize_exception_types = (dns.rdatatype.OPENPGPKEY, dns.rdatatype.EUI48, dns.rdatatype.EUI64)
  564. if rdtype in chunksize_exception_types:
  565. return rdata.to_text()
  566. else:
  567. return rdata.to_text(chunksize=0)
  568. except binascii.Error:
  569. # e.g., odd-length string
  570. raise ValueError('Cannot parse hexadecimal or base64 record contents')
  571. except dns.exception.SyntaxError as e:
  572. # e.g., A/127.0.0.999
  573. if 'quote' in e.args[0]:
  574. raise ValueError(f'Data for {type_} records must be given using quotation marks.')
  575. else:
  576. raise ValueError(f'Record content for type {type_} malformed: {",".join(e.args)}')
  577. except dns.name.NeedAbsoluteNameOrOrigin:
  578. raise ValueError('Hostname must be fully qualified (i.e., end in a dot: "example.com.")')
  579. except ValueError as ex:
  580. # e.g., string ("asdf") cannot be parsed into int on base 10
  581. raise ValueError(f'Cannot parse record contents: {ex}')
  582. except Exception as e:
  583. # TODO see what exceptions raise here for faulty input
  584. raise e
  585. def __str__(self):
  586. return '<RR %s %s rr_set=%s>' % (self.pk, self.content, self.rrset.pk)
  587. class AuthenticatedAction(models.Model):
  588. """
  589. Represents a procedure call on a defined set of arguments.
  590. Subclasses can define additional arguments by adding Django model fields and must define the action to be taken by
  591. implementing the `_act` method.
  592. AuthenticatedAction provides the `state` property which by default is a hash of the action type (defined by the
  593. action's class path). Other information such as user state can be included in the state hash by (carefully)
  594. overriding the `_state_fields` property. Instantiation of the model, if given a `state` kwarg, will raise an error
  595. if the given state argument does not match the state computed from `_state_fields` at the moment of instantiation.
  596. The same applies to the `act` method: If called on an object that was instantiated without a `state` kwargs, an
  597. error will be raised.
  598. This effectively allows hash-authenticated procedure calls by third parties as long as the server-side state is
  599. unaltered, according to the following protocol:
  600. (1) Instantiate the AuthenticatedAction subclass representing the action to be taken (no `state` kwarg here),
  601. (2) provide information on how to instantiate the instance, and the state hash, to a third party,
  602. (3) when provided with data that allows instantiation and a valid state hash, take the defined action, possibly with
  603. additional parameters chosen by the third party that do not belong to the verified state.
  604. """
  605. _validated = False
  606. class Meta:
  607. managed = False
  608. def __init__(self, *args, **kwargs):
  609. state = kwargs.pop('state', None)
  610. super().__init__(*args, **kwargs)
  611. if state is not None:
  612. self._validated = self.validate_state(state)
  613. if not self._validated:
  614. raise ValueError
  615. @property
  616. def _state_fields(self):
  617. """
  618. Returns a list that defines the state of this action (used for authentication of this action).
  619. Return value must be JSON-serializable.
  620. Values not included in the return value will not be used for authentication, i.e. those values can be varied
  621. freely and function as unauthenticated action input parameters.
  622. Use caution when overriding this method. You will usually want to append a value to the list returned by the
  623. parent. Overriding the behavior altogether could result in reducing the state to fewer variables, resulting
  624. in valid signatures when they were intended to be invalid. The suggested method for overriding is
  625. @property
  626. def _state_fields:
  627. return super()._state_fields + [self.important_value, self.another_added_value]
  628. :return: List of values to be signed.
  629. """
  630. name = '.'.join([self.__module__, self.__class__.__qualname__])
  631. return [name]
  632. @property
  633. def state(self):
  634. state = json.dumps(self._state_fields).encode()
  635. hash = sha256()
  636. hash.update(state)
  637. return hash.hexdigest()
  638. def validate_state(self, value):
  639. return value == self.state
  640. def _act(self):
  641. """
  642. Conduct the action represented by this class.
  643. :return: None
  644. """
  645. raise NotImplementedError
  646. def act(self):
  647. if not self._validated:
  648. raise RuntimeError('Action state could not be verified.')
  649. return self._act()
  650. class AuthenticatedBasicUserAction(AuthenticatedAction):
  651. """
  652. Abstract AuthenticatedAction involving a user instance.
  653. """
  654. user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
  655. class Meta:
  656. managed = False
  657. @property
  658. def _state_fields(self):
  659. return super()._state_fields + [str(self.user.id)]
  660. class AuthenticatedUserAction(AuthenticatedBasicUserAction):
  661. """
  662. Abstract AuthenticatedBasicUserAction, incorporating the user's id, email, password, and is_active flag into the
  663. Message Authentication Code state.
  664. """
  665. class Meta:
  666. managed = False
  667. @property
  668. def _state_fields(self):
  669. # TODO consider adding a "last change" attribute of the user to the state to avoid code
  670. # re-use after the the state has been changed and changed back.
  671. return super()._state_fields + [self.user.email, self.user.password, self.user.is_active]
  672. class AuthenticatedActivateUserAction(AuthenticatedUserAction):
  673. domain = models.CharField(max_length=191)
  674. class Meta:
  675. managed = False
  676. @property
  677. def _state_fields(self):
  678. return super()._state_fields + [self.domain]
  679. def _act(self):
  680. self.user.activate()
  681. class AuthenticatedChangeEmailUserAction(AuthenticatedUserAction):
  682. new_email = models.EmailField()
  683. class Meta:
  684. managed = False
  685. @property
  686. def _state_fields(self):
  687. return super()._state_fields + [self.new_email]
  688. def _act(self):
  689. self.user.change_email(self.new_email)
  690. class AuthenticatedResetPasswordUserAction(AuthenticatedUserAction):
  691. new_password = models.CharField(max_length=128)
  692. class Meta:
  693. managed = False
  694. def _act(self):
  695. self.user.change_password(self.new_password)
  696. class AuthenticatedDeleteUserAction(AuthenticatedUserAction):
  697. class Meta:
  698. managed = False
  699. def _act(self):
  700. self.user.delete()
  701. class AuthenticatedDomainBasicUserAction(AuthenticatedBasicUserAction):
  702. """
  703. Abstract AuthenticatedUserAction involving an domain instance, incorporating the domain's id, name as well as the
  704. owner ID into the Message Authentication Code state.
  705. """
  706. domain = models.ForeignKey(Domain, on_delete=models.DO_NOTHING)
  707. class Meta:
  708. managed = False
  709. @property
  710. def _state_fields(self):
  711. return super()._state_fields + [
  712. str(self.domain.id), # ensures the domain object is identical
  713. self.domain.name, # exclude renamed domains
  714. str(self.domain.owner.id), # exclude transferred domains
  715. ]
  716. class AuthenticatedRenewDomainBasicUserAction(AuthenticatedDomainBasicUserAction):
  717. class Meta:
  718. managed = False
  719. @property
  720. def _state_fields(self):
  721. return super()._state_fields + [str(self.domain.renewal_changed)]
  722. def _act(self):
  723. self.domain.renewal_state = Domain.RenewalState.FRESH
  724. self.domain.renewal_changed = timezone.now()
  725. self.domain.save(update_fields=['renewal_state', 'renewal_changed'])
  726. def captcha_default_content(kind: str) -> str:
  727. if kind == Captcha.Kind.IMAGE:
  728. alphabet = (string.ascii_uppercase + string.digits).translate({ord(c): None for c in 'IO0'})
  729. length = 5
  730. elif kind == Captcha.Kind.AUDIO:
  731. alphabet = string.digits
  732. length = 8
  733. else:
  734. raise ValueError(f'Unknown Captcha kind: {kind}')
  735. content = ''.join([secrets.choice(alphabet) for _ in range(length)])
  736. metrics.get('desecapi_captcha_content_created').labels(kind).inc()
  737. return content
  738. class Captcha(ExportModelOperationsMixin('Captcha'), models.Model):
  739. class Kind(models.TextChoices):
  740. IMAGE = 'image'
  741. AUDIO = 'audio'
  742. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  743. created = models.DateTimeField(auto_now_add=True)
  744. content = models.CharField(max_length=24, default="")
  745. kind = models.CharField(choices=Kind.choices, default=Kind.IMAGE, max_length=24)
  746. def __init__(self, *args, **kwargs):
  747. super().__init__(*args, **kwargs)
  748. if not self.content:
  749. self.content = captcha_default_content(self.kind)
  750. def verify(self, solution: str):
  751. age = timezone.now() - self.created
  752. self.delete()
  753. return (
  754. str(solution).upper().strip() == self.content # solution correct
  755. and
  756. age <= settings.CAPTCHA_VALIDITY_PERIOD # not expired
  757. )