models.py 21 KB

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