models.py 20 KB

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