models.py 22 KB

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