models.py 36 KB

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