models.py 36 KB

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