models.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. from __future__ import annotations
  2. import json
  3. import logging
  4. import secrets
  5. import string
  6. import time
  7. import uuid
  8. from base64 import urlsafe_b64encode
  9. from datetime import timedelta
  10. from hashlib import sha256
  11. import psl_dns
  12. import rest_framework.authtoken.models
  13. from django.conf import settings
  14. from django.contrib.auth.hashers import make_password
  15. from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, AnonymousUser
  16. from django.core.exceptions import ValidationError
  17. from django.core.mail import EmailMessage, get_connection
  18. from django.core.validators import RegexValidator
  19. from django.db import models
  20. from django.db.models import Manager, Q
  21. from django.template.loader import get_template
  22. from django.utils import timezone
  23. from django_prometheus.models import ExportModelOperationsMixin
  24. from dns.exception import Timeout
  25. from dns.resolver import NoNameservers
  26. from rest_framework.exceptions import APIException
  27. from desecapi import metrics
  28. from desecapi import pdns
  29. logger = logging.getLogger(__name__)
  30. psl = psl_dns.PSL(resolver=settings.PSL_RESOLVER, timeout=.5)
  31. def validate_lower(value):
  32. if value != value.lower():
  33. raise ValidationError('Invalid value (not lowercase): %(value)s',
  34. code='invalid',
  35. params={'value': value})
  36. def validate_upper(value):
  37. if value != value.upper():
  38. raise ValidationError('Invalid value (not uppercase): %(value)s',
  39. code='invalid',
  40. params={'value': value})
  41. class MyUserManager(BaseUserManager):
  42. def create_user(self, email, password, **extra_fields):
  43. """
  44. Creates and saves a User with the given email, date of
  45. birth and password.
  46. """
  47. if not email:
  48. raise ValueError('Users must have an email address')
  49. email = self.normalize_email(email)
  50. user = self.model(email=email, **extra_fields)
  51. user.set_password(password)
  52. user.save(using=self._db)
  53. return user
  54. def create_superuser(self, email, password):
  55. """
  56. Creates and saves a superuser with the given email, date of
  57. birth and password.
  58. """
  59. user = self.create_user(email, password=password)
  60. user.is_admin = True
  61. user.save(using=self._db)
  62. return user
  63. class User(ExportModelOperationsMixin('User'), AbstractBaseUser):
  64. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  65. email = models.EmailField(
  66. verbose_name='email address',
  67. max_length=191,
  68. unique=True,
  69. )
  70. is_active = models.BooleanField(default=True)
  71. is_admin = models.BooleanField(default=False)
  72. created = models.DateTimeField(auto_now_add=True)
  73. limit_domains = models.IntegerField(default=settings.LIMIT_USER_DOMAIN_COUNT_DEFAULT, null=True, blank=True)
  74. objects = MyUserManager()
  75. USERNAME_FIELD = 'email'
  76. REQUIRED_FIELDS = []
  77. def get_full_name(self):
  78. return self.email
  79. def get_short_name(self):
  80. return self.email
  81. def __str__(self):
  82. return self.email
  83. # noinspection PyMethodMayBeStatic
  84. def has_perm(self, *_):
  85. """Does the user have a specific permission?"""
  86. # Simplest possible answer: Yes, always
  87. return True
  88. # noinspection PyMethodMayBeStatic
  89. def has_module_perms(self, *_):
  90. """Does the user have permissions to view the app `app_label`?"""
  91. # Simplest possible answer: Yes, always
  92. return True
  93. @property
  94. def is_staff(self):
  95. """Is the user a member of staff?"""
  96. # Simplest possible answer: All admins are staff
  97. return self.is_admin
  98. def activate(self):
  99. self.is_active = True
  100. self.save()
  101. def change_email(self, email):
  102. old_email = self.email
  103. self.email = email
  104. self.validate_unique()
  105. self.save()
  106. self.send_email('change-email-confirmation-old-email', recipient=old_email)
  107. def change_password(self, raw_password):
  108. self.set_password(raw_password)
  109. self.save()
  110. self.send_email('password-change-confirmation')
  111. def send_email(self, reason, context=None, recipient=None):
  112. fast_lane = 'email_fast_lane'
  113. slow_lane = 'email_slow_lane'
  114. lanes = {
  115. 'activate': slow_lane,
  116. 'activate-with-domain': slow_lane,
  117. 'change-email': slow_lane,
  118. 'change-email-confirmation-old-email': fast_lane,
  119. 'password-change-confirmation': fast_lane,
  120. 'reset-password': fast_lane,
  121. 'delete-user': fast_lane,
  122. 'domain-dyndns': fast_lane,
  123. }
  124. if reason not in lanes:
  125. raise ValueError(f'Cannot send email to user {self.pk} without a good reason: {reason}')
  126. context = context or {}
  127. context.setdefault('link_expiration_hours',
  128. settings.VALIDITY_PERIOD_VERIFICATION_SIGNATURE // timedelta(hours=1))
  129. content = get_template(f'emails/{reason}/content.txt').render(context)
  130. content += f'\nSupport Reference: user_id = {self.pk}\n'
  131. footer = get_template('emails/footer.txt').render()
  132. logger.warning(f'Queuing email for user account {self.pk} (reason: {reason})')
  133. num_queued = EmailMessage(
  134. subject=get_template(f'emails/{reason}/subject.txt').render(context).strip(),
  135. body=content + footer,
  136. from_email=get_template('emails/from.txt').render(),
  137. to=[recipient or self.email],
  138. connection=get_connection(lane=lanes[reason], debug={'user': self.pk, 'reason': reason})
  139. ).send()
  140. metrics.get('desecapi_messages_queued').labels(reason, self.pk, lanes[reason]).observe(num_queued)
  141. return num_queued
  142. class Token(ExportModelOperationsMixin('Token'), rest_framework.authtoken.models.Token):
  143. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  144. key = models.CharField("Key", max_length=128, db_index=True, unique=True)
  145. user = models.ForeignKey(
  146. User, related_name='auth_tokens',
  147. on_delete=models.CASCADE, verbose_name="User"
  148. )
  149. name = models.CharField("Name", max_length=64, default="")
  150. plain = None
  151. def generate_key(self):
  152. self.plain = secrets.token_urlsafe(21)
  153. self.key = Token.make_hash(self.plain)
  154. return self.key
  155. @staticmethod
  156. def make_hash(plain):
  157. return make_password(plain, salt='static', hasher='pbkdf2_sha256_iter1')
  158. validate_domain_name = [
  159. validate_lower,
  160. RegexValidator(
  161. # TODO See how far this validation can be relaxed
  162. regex=r'^(([a-z0-9][a-z0-9-]{0,61}[a-z0-9]|[a-z0-9])\.)*[a-z]{1,63}$',
  163. message='Domain names must be labels separated dots. Labels may only use hyphens, digits, and lowercase '
  164. 'letters, must not start or end with a hyphen, and must not exceed 63 byte. The last label may only '
  165. 'have lowercase letters.',
  166. code='invalid_domain_name'
  167. )
  168. ]
  169. def get_minimum_ttl_default():
  170. return settings.MINIMUM_TTL_DEFAULT
  171. class Domain(ExportModelOperationsMixin('Domain'), models.Model):
  172. created = models.DateTimeField(auto_now_add=True)
  173. name = models.CharField(max_length=191,
  174. unique=True,
  175. validators=validate_domain_name)
  176. owner = models.ForeignKey(User, on_delete=models.PROTECT, related_name='domains')
  177. published = models.DateTimeField(null=True, blank=True)
  178. minimum_ttl = models.PositiveIntegerField(default=get_minimum_ttl_default)
  179. _keys = None
  180. @classmethod
  181. def is_registrable(cls, domain_name: str, user: User):
  182. """
  183. Returns False in any of the following cases:
  184. (a) the domain name is under .internal,
  185. (b) the domain_name appears on the public suffix list,
  186. (c) the domain is descendant to a zone that belongs to any user different from the given one,
  187. unless it's parent is a public suffix, either through the Internet PSL or local settings.
  188. Otherwise, True is returned.
  189. """
  190. if domain_name != domain_name.lower():
  191. raise ValueError
  192. if f'.{domain_name}'.endswith('.internal'):
  193. return False
  194. try:
  195. public_suffix = psl.get_public_suffix(domain_name)
  196. is_public_suffix = psl.is_public_suffix(domain_name)
  197. except (Timeout, NoNameservers):
  198. public_suffix = domain_name.rpartition('.')[2]
  199. is_public_suffix = ('.' not in domain_name) # TLDs are public suffixes
  200. except psl_dns.exceptions.UnsupportedRule as e:
  201. # It would probably be fine to treat this as a non-public suffix (with the TLD acting as the
  202. # public suffix and setting both public_suffix and is_public_suffix accordingly).
  203. # However, in order to allow to investigate the situation, it's better not catch
  204. # this exception. For web requests, our error handler turns it into a 503 error
  205. # and makes sure admins are notified.
  206. raise e
  207. if not is_public_suffix:
  208. # Take into account that any of the parent domains could be a local public suffix. To that
  209. # end, identify the longest local public suffix that is actually a suffix of domain_name.
  210. # Then, override the global PSL result.
  211. for local_public_suffix in settings.LOCAL_PUBLIC_SUFFIXES:
  212. has_local_public_suffix_parent = ('.' + domain_name).endswith('.' + local_public_suffix)
  213. if has_local_public_suffix_parent and len(local_public_suffix) > len(public_suffix):
  214. public_suffix = local_public_suffix
  215. is_public_suffix = (public_suffix == domain_name)
  216. if is_public_suffix and domain_name not in settings.LOCAL_PUBLIC_SUFFIXES:
  217. return False
  218. # Generate a list of all domains connecting this one and its public suffix.
  219. # If another user owns a zone with one of these names, then the requested
  220. # domain is unavailable because it is part of the other user's zone.
  221. private_components = domain_name.rsplit(public_suffix, 1)[0].rstrip('.')
  222. private_components = private_components.split('.') if private_components else []
  223. private_components += [public_suffix]
  224. private_domains = ['.'.join(private_components[i:]) for i in range(0, len(private_components) - 1)]
  225. assert is_public_suffix or domain_name == private_domains[0]
  226. # Deny registration for non-local public suffixes and for domains covered by other users' zones
  227. user = user if not isinstance(user, AnonymousUser) else None
  228. return not cls.objects.filter(Q(name__in=private_domains) & ~Q(owner=user)).exists()
  229. @property
  230. def keys(self):
  231. if not self._keys:
  232. self._keys = pdns.get_keys(self)
  233. return self._keys
  234. @property
  235. def is_locally_registrable(self):
  236. return self.parent_domain_name in settings.LOCAL_PUBLIC_SUFFIXES
  237. @property
  238. def parent_domain_name(self):
  239. return self._partitioned_name[1]
  240. @property
  241. def _partitioned_name(self):
  242. subname, _, parent_name = self.name.partition('.')
  243. return subname, parent_name or None
  244. def save(self, *args, **kwargs):
  245. self.full_clean(validate_unique=False)
  246. super().save(*args, **kwargs)
  247. def update_delegation(self, child_domain: Domain):
  248. child_subname, child_domain_name = child_domain._partitioned_name
  249. if self.name != child_domain_name:
  250. raise ValueError('Cannot update delegation of %s as it is not an immediate child domain of %s.' %
  251. (child_domain.name, self.name))
  252. if child_domain.pk:
  253. # Domain real: set delegation
  254. child_keys = child_domain.keys
  255. if not child_keys:
  256. raise APIException('Cannot delegate %s, as it currently has no keys.' % child_domain.name)
  257. RRset.objects.create(domain=self, subname=child_subname, type='NS', ttl=3600, contents=settings.DEFAULT_NS)
  258. RRset.objects.create(domain=self, subname=child_subname, type='DS', ttl=300,
  259. contents=[ds for k in child_keys for ds in k['ds']])
  260. metrics.get('desecapi_autodelegation_created').inc()
  261. else:
  262. # Domain not real: remove delegation
  263. for rrset in self.rrset_set.filter(subname=child_subname, type__in=['NS', 'DS']):
  264. rrset.delete()
  265. metrics.get('desecapi_autodelegation_deleted').inc()
  266. def delete(self):
  267. ret = super().delete()
  268. logger.warning(f'Domain {self.name} deleted (owner: {self.owner.pk})')
  269. return ret
  270. def __str__(self):
  271. return self.name
  272. class Meta:
  273. ordering = ('created',)
  274. def get_default_value_created():
  275. return timezone.now()
  276. def get_default_value_due():
  277. return timezone.now() + timedelta(days=7)
  278. def get_default_value_mref():
  279. return "ONDON" + str(time.time())
  280. class Donation(ExportModelOperationsMixin('Donation'), models.Model):
  281. created = models.DateTimeField(default=get_default_value_created)
  282. name = models.CharField(max_length=255)
  283. iban = models.CharField(max_length=34)
  284. bic = models.CharField(max_length=11, blank=True)
  285. amount = models.DecimalField(max_digits=8, decimal_places=2)
  286. message = models.CharField(max_length=255, blank=True)
  287. due = models.DateTimeField(default=get_default_value_due)
  288. mref = models.CharField(max_length=32, default=get_default_value_mref)
  289. email = models.EmailField(max_length=255, blank=True)
  290. class Meta:
  291. managed = False
  292. class RRsetManager(Manager):
  293. def create(self, contents=None, **kwargs):
  294. rrset = super().create(**kwargs)
  295. for content in contents or []:
  296. RR.objects.create(rrset=rrset, content=content)
  297. return rrset
  298. class RRset(ExportModelOperationsMixin('RRset'), models.Model):
  299. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  300. created = models.DateTimeField(auto_now_add=True)
  301. updated = models.DateTimeField(null=True) # undocumented, used for debugging only
  302. domain = models.ForeignKey(Domain, on_delete=models.CASCADE)
  303. subname = models.CharField(
  304. max_length=178,
  305. blank=True,
  306. validators=[
  307. validate_lower,
  308. RegexValidator(
  309. regex=r'^([*]|(([*][.])?[a-z0-9_.-]*))$',
  310. message='Subname can only use (lowercase) a-z, 0-9, ., -, and _, '
  311. 'may start with a \'*.\', or just be \'*\'.',
  312. code='invalid_subname'
  313. )
  314. ]
  315. )
  316. type = models.CharField(
  317. max_length=10,
  318. validators=[
  319. validate_upper,
  320. RegexValidator(
  321. regex=r'^[A-Z][A-Z0-9]*$',
  322. message='Type must be uppercase alphanumeric and start with a letter.',
  323. code='invalid_type'
  324. )
  325. ]
  326. )
  327. ttl = models.PositiveIntegerField()
  328. objects = RRsetManager()
  329. DEAD_TYPES = ('ALIAS', 'DNAME')
  330. RESTRICTED_TYPES = ('SOA', 'RRSIG', 'DNSKEY', 'NSEC3PARAM', 'OPT')
  331. class Meta:
  332. unique_together = (("domain", "subname", "type"),)
  333. @staticmethod
  334. def construct_name(subname, domain_name):
  335. return '.'.join(filter(None, [subname, domain_name])) + '.'
  336. @property
  337. def name(self):
  338. return self.construct_name(self.subname, self.domain.name)
  339. def save(self, *args, **kwargs):
  340. self.updated = timezone.now()
  341. self.full_clean(validate_unique=False)
  342. super().save(*args, **kwargs)
  343. def __str__(self):
  344. return '<RRSet %s domain=%s type=%s subname=%s>' % (self.pk, self.domain.name, self.type, self.subname)
  345. class RRManager(Manager):
  346. def bulk_create(self, rrs, **kwargs):
  347. ret = super().bulk_create(rrs, **kwargs)
  348. # For each rrset, save once to set RRset.updated timestamp and trigger signal for post-save processing
  349. rrsets = {rr.rrset for rr in rrs}
  350. for rrset in rrsets:
  351. rrset.save()
  352. return ret
  353. class RR(ExportModelOperationsMixin('RR'), models.Model):
  354. created = models.DateTimeField(auto_now_add=True)
  355. rrset = models.ForeignKey(RRset, on_delete=models.CASCADE, related_name='records')
  356. # The pdns lmdb backend used on our slaves does not only store the record contents itself, but other metadata (such
  357. # as type etc.) Both together have to fit into the lmdb backend's current total limit of 512 bytes per RR, see
  358. # https://github.com/PowerDNS/pdns/issues/8012
  359. # I found the additional data to be 12 bytes (by trial and error). I believe these are the 12 bytes mentioned here:
  360. # https://lists.isc.org/pipermail/bind-users/2008-April/070137.html So we can use 500 bytes for the actual content.
  361. # Note: This is a conservative estimate, as record contents may be stored more efficiently depending on their type,
  362. # effectively allowing a longer length in "presentation format". For example, A record contents take up 4 bytes,
  363. # although the presentation format (usual IPv4 representation) takes up to 15 bytes. Similarly, OPENPGPKEY contents
  364. # are base64-decoded before storage in binary format, so a "presentation format" value (which is the value our API
  365. # sees) can have up to 668 bytes. Instead of introducing per-type limits, setting it to 500 should always work.
  366. content = models.CharField(max_length=500) #
  367. objects = RRManager()
  368. def __str__(self):
  369. return '<RR %s %s rr_set=%s>' % (self.pk, self.content, self.rrset.pk)
  370. class AuthenticatedAction(ExportModelOperationsMixin('AuthenticatedAction'), models.Model):
  371. """
  372. Represents a procedure call on a defined set of arguments.
  373. Subclasses can define additional arguments by adding Django model fields and must define the action to be taken by
  374. implementing the `_act` method.
  375. AuthenticatedAction provides the `state` property which by default is a hash of the action type (defined by the
  376. action's class path). Other information such as user state can be included in the state hash by (carefully)
  377. overriding the `_state_fields` property. Instantiation of the model, if given a `state` kwarg, will raise an error
  378. if the given state argument does not match the state computed from `_state_fields` at the moment of instantiation.
  379. The same applies to the `act` method: If called on an object that was instantiated without a `state` kwargs, an
  380. error will be raised.
  381. This effectively allows hash-authenticated procedure calls by third parties as long as the server-side state is
  382. unaltered, according to the following protocol:
  383. (1) Instantiate the AuthenticatedAction subclass representing the action to be taken (no `state` kwarg here),
  384. (2) provide information on how to instantiate the instance, and the state hash, to a third party,
  385. (3) when provided with data that allows instantiation and a valid state hash, take the defined action, possibly with
  386. additional parameters chosen by the third party that do not belong to the verified state.
  387. """
  388. _validated = False
  389. class Meta:
  390. managed = False
  391. def __init__(self, *args, **kwargs):
  392. state = kwargs.pop('state', None)
  393. super().__init__(*args, **kwargs)
  394. if state is not None:
  395. self._validated = self.validate_state(state)
  396. if not self._validated:
  397. raise ValueError
  398. @property
  399. def _state_fields(self):
  400. """
  401. Returns a list that defines the state of this action (used for authentication of this action).
  402. Return value must be JSON-serializable.
  403. Values not included in the return value will not be used for authentication, i.e. those values can be varied
  404. freely and function as unauthenticated action input parameters.
  405. Use caution when overriding this method. You will usually want to append a value to the list returned by the
  406. parent. Overriding the behavior altogether could result in reducing the state to fewer variables, resulting
  407. in valid signatures when they were intended to be invalid. The suggested method for overriding is
  408. @property
  409. def _state_fields:
  410. return super()._state_fields + [self.important_value, self.another_added_value]
  411. :return: List of values to be signed.
  412. """
  413. # TODO consider adding a "last change" attribute of the user to the state to avoid code
  414. # re-use after the the state has been changed and changed back.
  415. name = '.'.join([self.__module__, self.__class__.__qualname__])
  416. return [name]
  417. @property
  418. def state(self):
  419. state = json.dumps(self._state_fields).encode()
  420. hash = sha256()
  421. hash.update(state)
  422. return hash.hexdigest()
  423. def validate_state(self, value):
  424. return value == self.state
  425. def _act(self):
  426. """
  427. Conduct the action represented by this class.
  428. :return: None
  429. """
  430. raise NotImplementedError
  431. def act(self):
  432. if not self._validated:
  433. raise RuntimeError('Action state could not be verified.')
  434. return self._act()
  435. class AuthenticatedUserAction(ExportModelOperationsMixin('AuthenticatedUserAction'), AuthenticatedAction):
  436. """
  437. Abstract AuthenticatedAction involving an user instance, incorporating the user's id, email, password, and
  438. is_active flag into the Message Authentication Code state.
  439. """
  440. user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
  441. class Meta:
  442. managed = False
  443. @property
  444. def _state_fields(self):
  445. return super()._state_fields + [str(self.user.id), self.user.email, self.user.password, self.user.is_active]
  446. def _act(self):
  447. raise NotImplementedError
  448. class AuthenticatedActivateUserAction(ExportModelOperationsMixin('AuthenticatedActivateUserAction'), AuthenticatedUserAction):
  449. domain = models.CharField(max_length=191)
  450. class Meta:
  451. managed = False
  452. @property
  453. def _state_fields(self):
  454. return super()._state_fields + [self.domain]
  455. def _act(self):
  456. self.user.activate()
  457. class AuthenticatedChangeEmailUserAction(ExportModelOperationsMixin('AuthenticatedChangeEmailUserAction'), AuthenticatedUserAction):
  458. new_email = models.EmailField()
  459. class Meta:
  460. managed = False
  461. @property
  462. def _state_fields(self):
  463. return super()._state_fields + [self.new_email]
  464. def _act(self):
  465. self.user.change_email(self.new_email)
  466. class AuthenticatedResetPasswordUserAction(ExportModelOperationsMixin('AuthenticatedResetPasswordUserAction'), AuthenticatedUserAction):
  467. new_password = models.CharField(max_length=128)
  468. class Meta:
  469. managed = False
  470. def _act(self):
  471. self.user.change_password(self.new_password)
  472. class AuthenticatedDeleteUserAction(ExportModelOperationsMixin('AuthenticatedDeleteUserAction'), AuthenticatedUserAction):
  473. class Meta:
  474. managed = False
  475. def _act(self):
  476. self.user.delete()
  477. def captcha_default_content():
  478. alphabet = (string.ascii_uppercase + string.digits).translate({ord(c): None for c in 'IO0'})
  479. content = ''.join([secrets.choice(alphabet) for _ in range(5)])
  480. metrics.get('desecapi_captcha_content_created').inc()
  481. return content
  482. class Captcha(ExportModelOperationsMixin('Captcha'), models.Model):
  483. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  484. created = models.DateTimeField(auto_now_add=True)
  485. content = models.CharField(
  486. max_length=24,
  487. default=captcha_default_content,
  488. )
  489. def verify(self, solution: str):
  490. age = timezone.now() - self.created
  491. self.delete()
  492. return (
  493. str(solution).upper().strip() == self.content # solution correct
  494. and
  495. age <= settings.CAPTCHA_VALIDITY_PERIOD # not expired
  496. )