models.py 18 KB

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