models.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. from django.conf import settings
  2. from django.db import models, transaction
  3. from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
  4. from django.utils import timezone
  5. from django.core.exceptions import SuspiciousOperation, ValidationError
  6. from desecapi import pdns, mixins
  7. import datetime, uuid
  8. from django.core.validators import MinValueValidator
  9. from collections import OrderedDict
  10. import rest_framework.authtoken.models
  11. from time import time
  12. import random
  13. from os import urandom
  14. from base64 import b64encode
  15. class MyUserManager(BaseUserManager):
  16. def create_user(self, email, password=None, registration_remote_ip=None, lock=False, dyn=False):
  17. """
  18. Creates and saves a User with the given email, date of
  19. birth and password.
  20. """
  21. if not email:
  22. raise ValueError('Users must have an email address')
  23. user = self.model(
  24. email=self.normalize_email(email),
  25. registration_remote_ip=registration_remote_ip,
  26. locked=timezone.now() if lock else None,
  27. dyn=dyn,
  28. )
  29. user.set_password(password)
  30. user.save(using=self._db)
  31. return user
  32. def create_superuser(self, email, password):
  33. """
  34. Creates and saves a superuser with the given email, date of
  35. birth and password.
  36. """
  37. user = self.create_user(email,
  38. password=password
  39. )
  40. user.is_admin = True
  41. user.save(using=self._db)
  42. return user
  43. class Token(rest_framework.authtoken.models.Token):
  44. key = models.CharField("Key", max_length=40, db_index=True, unique=True)
  45. # relation to user is a ForeignKey, so each user can have more than one token
  46. user = models.ForeignKey(
  47. settings.AUTH_USER_MODEL, related_name='auth_tokens',
  48. on_delete=models.CASCADE, verbose_name="User"
  49. )
  50. name = models.CharField("Name", max_length=64, default="")
  51. user_specific_id = models.BigIntegerField("User-Specific ID")
  52. def save(self, *args, **kwargs):
  53. if not self.user_specific_id:
  54. self.user_specific_id = random.randrange(16**8)
  55. super().save(*args, **kwargs) # Call the "real" save() method.
  56. def generate_key(self):
  57. return b64encode(urandom(21)).decode('utf-8').replace('/', '-').replace('=', '_').replace('+', '.')
  58. class Meta:
  59. abstract = False
  60. unique_together = (('user', 'user_specific_id'),)
  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. registration_remote_ip = models.CharField(max_length=1024, blank=True)
  70. locked = models.DateTimeField(null=True,blank=True)
  71. created = models.DateTimeField(auto_now_add=True)
  72. limit_domains = models.IntegerField(default=settings.LIMIT_USER_DOMAIN_COUNT_DEFAULT,null=True,blank=True)
  73. dyn = models.BooleanField(default=False)
  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 get_token(self):
  82. token, created = Token.objects.get_or_create(user=self)
  83. return token.key
  84. def __str__(self):
  85. return self.email
  86. def has_perm(self, perm, obj=None):
  87. "Does the user have a specific permission?"
  88. # Simplest possible answer: Yes, always
  89. return True
  90. def has_module_perms(self, app_label):
  91. "Does the user have permissions to view the app `app_label`?"
  92. # Simplest possible answer: Yes, always
  93. return True
  94. @property
  95. def is_staff(self):
  96. "Is the user a member of staff?"
  97. # Simplest possible answer: All admins are staff
  98. return self.is_admin
  99. def unlock(self):
  100. # self.locked is used by domain.sync_to_pdns(), so call that first
  101. for domain in self.domains.all():
  102. domain.sync_to_pdns()
  103. self.locked = None
  104. self.save()
  105. class Domain(models.Model, mixins.SetterMixin):
  106. created = models.DateTimeField(auto_now_add=True)
  107. name = models.CharField(max_length=191, unique=True)
  108. owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='domains')
  109. published = models.DateTimeField(null=True)
  110. _dirtyName = False
  111. def setter_name(self, val):
  112. if val != self.name:
  113. self._dirtyName = True
  114. return val
  115. def clean(self):
  116. if self._dirtyName:
  117. raise ValidationError('You must not change the domain name')
  118. @property
  119. def keys(self):
  120. return pdns.get_keys(self)
  121. @property
  122. def pdns_id(self):
  123. if '/' in self.name or '?' in self.name:
  124. raise SuspiciousOperation('Invalid hostname ' + self.name)
  125. # Transform to be valid pdns API identifiers (:id in their docs). The
  126. # '/' case here is just a safety measure (this case should never occur due
  127. # to the above check).
  128. # See also pdns code, apiZoneNameToId() in ws-api.cc
  129. name = self.name.translate(str.maketrans({'/': '=2F', '_': '=5F'}))
  130. if not name.endswith('.'):
  131. name += '.'
  132. return name
  133. def sync_to_pdns(self):
  134. """
  135. Make sure that pdns gets the latest information about this domain/zone.
  136. Re-syncing is relatively expensive and should not happen routinely.
  137. This method should only be called for new domains or on user unlocking.
  138. For unlocked users, it assumes that the domain is a new one.
  139. """
  140. # Determine if this domain is expected to be new on pdns. This is the
  141. # case if the user is not locked (by assumption) or if the domain was
  142. # created after the user was locked. (If the user had this domain
  143. # before locking, it is not new on pdns.)
  144. new = self.owner.locked is None or self.owner.locked < self.created
  145. if new:
  146. # Create zone
  147. # Throws exception if pdns already knows this zone for some reason
  148. # which means that it is not ours and we should not mess with it.
  149. # We escalate the exception to let the next level deal with the
  150. # response.
  151. pdns.create_zone(self, settings.DEFAULT_NS)
  152. # Send RRsets to pdns that may have been created (e.g. during lock).
  153. self._publish()
  154. # Make our RRsets consistent with pdns (specifically, NS may exist)
  155. self.sync_from_pdns()
  156. # For dedyn.io domains, propagate NS and DS delegation RRsets
  157. subname, parent_pdns_id = self.pdns_id.split('.', 1)
  158. if parent_pdns_id == 'dedyn.io.':
  159. try:
  160. parent = Domain.objects.get(name='dedyn.io')
  161. except Domain.DoesNotExist:
  162. pass
  163. else:
  164. rrsets = RRset.plain_to_RRsets([
  165. {'subname': subname, 'type': 'NS', 'ttl': 3600,
  166. 'contents': settings.DEFAULT_NS},
  167. {'subname': subname, 'type': 'DS', 'ttl': 60,
  168. 'contents': [ds for k in self.keys for ds in k['ds']]}
  169. ], domain=parent)
  170. parent.write_rrsets(rrsets)
  171. else:
  172. # Zone exists. For the case that pdns knows records that we do not
  173. # (e.g. if a locked account has deleted an RRset), it is necessary
  174. # to purge all records here. However, there is currently no way to
  175. # do this through the pdns API (not to mention doing it atomically
  176. # with setting the new RRsets). So for now, we have disabled RRset
  177. # deletion for locked accounts.
  178. self._publish()
  179. @transaction.atomic
  180. def sync_from_pdns(self):
  181. self.rrset_set.all().delete()
  182. rrsets = []
  183. rrs = []
  184. for rrset_data in pdns.get_rrset_datas(self):
  185. if rrset_data['type'] in RRset.RESTRICTED_TYPES:
  186. continue
  187. records = rrset_data.pop('records')
  188. rrset = RRset(**rrset_data)
  189. rrsets.append(rrset)
  190. rrs.extend([RR(rrset=rrset, content=record) for record in records])
  191. RRset.objects.bulk_create(rrsets)
  192. RR.objects.bulk_create(rrs)
  193. @transaction.atomic
  194. def write_rrsets(self, rrsets):
  195. # Base queryset for all RRsets of the current domain
  196. rrset_qs = RRset.objects.filter(domain=self)
  197. # Set to check RRset uniqueness
  198. rrsets_seen = set()
  199. # We want to return all new, changed, and unchanged RRsets (but not
  200. # deleted ones). We store them here, indexed by (subname, type).
  201. rrsets_to_return = OrderedDict()
  202. # Record contents to send to pdns, indexed by their RRset
  203. rrsets_for_pdns = {}
  204. # Always-false Q object: https://stackoverflow.com/a/35894246/6867099
  205. q_meaty = models.Q(pk__isnull=True)
  206. q_empty = models.Q(pk__isnull=True)
  207. # Determine which RRsets need to be updated or deleted
  208. for rrset, rrs in rrsets.items():
  209. if rrset.domain != self:
  210. raise ValueError('RRset has wrong domain')
  211. if (rrset.subname, rrset.type) in rrsets_seen:
  212. raise ValueError('RRset repeated with same subname and type')
  213. if rrs is not None and not all(rr.rrset is rrset for rr in rrs):
  214. raise ValueError('RR has wrong parent RRset')
  215. rrsets_seen.add((rrset.subname, rrset.type))
  216. q = models.Q(subname=rrset.subname, type=rrset.type)
  217. if rrs or rrs is None:
  218. rrsets_to_return[(rrset.subname, rrset.type)] = rrset
  219. q_meaty |= q
  220. else:
  221. # Set TTL so that pdns does not get confused if missing
  222. rrset.ttl = 1
  223. rrsets_for_pdns[rrset] = []
  224. q_empty |= q
  225. # Construct querysets representing RRsets that do (not) have RR
  226. # contents and lock them
  227. qs_meaty = rrset_qs.filter(q_meaty).select_for_update()
  228. qs_empty = rrset_qs.filter(q_empty).select_for_update()
  229. # For existing RRsets, execute TTL updates and/or mark for RR update.
  230. # First, let's create a to-do dict; we'll need it later for new RRsets.
  231. rrsets_with_new_rrs = []
  232. rrsets_meaty_todo = dict(rrsets_to_return)
  233. for rrset in qs_meaty.all():
  234. rrsets_to_return[(rrset.subname, rrset.type)] = rrset
  235. rrset_temp = rrsets_meaty_todo.pop((rrset.subname, rrset.type))
  236. rrs = {rr.content for rr in rrset.records.all()}
  237. partial = rrsets[rrset_temp] is None
  238. if partial:
  239. rrs_temp = rrs
  240. else:
  241. rrs_temp = {rr.content for rr in rrsets[rrset_temp]}
  242. # Take current TTL if none was given
  243. rrset_temp.ttl = rrset_temp.ttl or rrset.ttl
  244. changed_ttl = (rrset_temp.ttl != rrset.ttl)
  245. changed_rrs = not partial and (rrs_temp != rrs)
  246. if changed_ttl:
  247. rrset.ttl = rrset_temp.ttl
  248. rrset.save()
  249. if changed_rrs:
  250. rrsets_with_new_rrs.append(rrset)
  251. if changed_ttl or changed_rrs:
  252. rrsets_for_pdns[rrset] = [RR(rrset=rrset, content=rr_content)
  253. for rr_content in rrs_temp]
  254. # At this point, rrsets_meaty_todo contains new RRsets only, with
  255. # a list of RRs or with None associated.
  256. for key, rrset in list(rrsets_meaty_todo.items()):
  257. if rrsets[rrset] is None:
  258. # None means "don't change RRs". In the context of a new RRset,
  259. # this really is no-op, and we do not need to return the RRset.
  260. rrsets_to_return.pop((rrset.subname, rrset.type))
  261. else:
  262. # If there are associated RRs, let's save the RRset. This does
  263. # not save the RRs yet.
  264. rrsets_with_new_rrs.append(rrset)
  265. rrset.save()
  266. # In either case, send a request to pdns so that we can take
  267. # advantage of pdns' type validation check (even if no RRs given).
  268. rrsets_for_pdns[rrset] = rrsets[rrset]
  269. # Repeat lock to make sure new RRsets are also locked
  270. rrset_qs.filter(q_meaty).select_for_update()
  271. # Delete empty RRsets
  272. qs_empty.delete()
  273. # Update contents of modified RRsets
  274. RR.objects.filter(rrset__in=rrsets_with_new_rrs).delete()
  275. RR.objects.bulk_create([rr
  276. for (rrset, rrs) in rrsets_for_pdns.items()
  277. if rrs and rrset in rrsets_with_new_rrs
  278. for rr in rrs])
  279. # Send RRsets to pdns
  280. if not self.owner.locked:
  281. self._publish(rrsets_for_pdns)
  282. # Return RRsets
  283. return list(rrsets_to_return.values())
  284. @transaction.atomic
  285. def _publish(self, rrsets = None):
  286. if rrsets is None:
  287. rrsets = self.rrset_set.all()
  288. self.published = timezone.now()
  289. self.save()
  290. if rrsets:
  291. pdns.set_rrsets(self, rrsets)
  292. @transaction.atomic
  293. def delete(self, *args, **kwargs):
  294. # Delete delegation for dynDNS domains (direct child of dedyn.io)
  295. subname, parent_pdns_id = self.pdns_id.split('.', 1)
  296. if parent_pdns_id == 'dedyn.io.':
  297. try:
  298. parent = Domain.objects.get(name='dedyn.io')
  299. except Domain.DoesNotExist:
  300. pass
  301. else:
  302. rrsets = parent.rrset_set.filter(subname=subname,
  303. type__in=['NS', 'DS']).all()
  304. parent.write_rrsets({rrset: [] for rrset in rrsets})
  305. # Delete domain
  306. super().delete(*args, **kwargs)
  307. pdns.delete_zone(self)
  308. @transaction.atomic
  309. def save(self, *args, **kwargs):
  310. new = self.pk is None
  311. self.clean()
  312. super().save(*args, **kwargs)
  313. if new and not self.owner.locked:
  314. self.sync_to_pdns()
  315. def __str__(self):
  316. """
  317. Return domain name. Needed for serialization via StringRelatedField.
  318. (Must be unique.)
  319. """
  320. return self.name
  321. class Meta:
  322. ordering = ('created',)
  323. def get_default_value_created():
  324. return timezone.now()
  325. def get_default_value_due():
  326. return timezone.now() + datetime.timedelta(days=7)
  327. def get_default_value_mref():
  328. return "ONDON" + str((timezone.now() - timezone.datetime(1970,1,1,tzinfo=timezone.utc)).total_seconds())
  329. class Donation(models.Model):
  330. created = models.DateTimeField(default=get_default_value_created)
  331. name = models.CharField(max_length=255)
  332. iban = models.CharField(max_length=34)
  333. bic = models.CharField(max_length=11)
  334. amount = models.DecimalField(max_digits=8,decimal_places=2)
  335. message = models.CharField(max_length=255, blank=True)
  336. due = models.DateTimeField(default=get_default_value_due)
  337. mref = models.CharField(max_length=32,default=get_default_value_mref)
  338. email = models.EmailField(max_length=255, blank=True)
  339. def save(self, *args, **kwargs):
  340. self.iban = self.iban[:6] + "xxx" # do NOT save account details
  341. super().save(*args, **kwargs) # Call the "real" save() method.
  342. class Meta:
  343. ordering = ('created',)
  344. def validate_upper(value):
  345. if value != value.upper():
  346. raise ValidationError('Invalid value (not uppercase): %(value)s',
  347. code='invalid',
  348. params={'value': value})
  349. class RRset(models.Model, mixins.SetterMixin):
  350. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  351. created = models.DateTimeField(auto_now_add=True)
  352. updated = models.DateTimeField(null=True)
  353. domain = models.ForeignKey(Domain, on_delete=models.CASCADE)
  354. subname = models.CharField(max_length=178, blank=True)
  355. type = models.CharField(max_length=10, validators=[validate_upper])
  356. ttl = models.PositiveIntegerField(validators=[MinValueValidator(1)])
  357. _dirty = False
  358. DEAD_TYPES = ('ALIAS', 'DNAME')
  359. RESTRICTED_TYPES = ('SOA', 'RRSIG', 'DNSKEY', 'NSEC3PARAM', 'OPT')
  360. class Meta:
  361. unique_together = (("domain","subname","type"),)
  362. def __init__(self, *args, **kwargs):
  363. self._dirties = set()
  364. super().__init__(*args, **kwargs)
  365. def setter_domain(self, val):
  366. if val != self.domain:
  367. self._dirties.add('domain')
  368. return val
  369. def setter_subname(self, val):
  370. # On PUT, RRsetSerializer sends None, denoting the unchanged value
  371. if val is None:
  372. return self.subname
  373. if val != self.subname:
  374. self._dirties.add('subname')
  375. return val
  376. def setter_type(self, val):
  377. if val != self.type:
  378. self._dirties.add('type')
  379. return val
  380. def setter_ttl(self, val):
  381. if val != self.ttl:
  382. self._dirties.add('ttl')
  383. return val
  384. def clean(self):
  385. errors = {}
  386. for field in (self._dirties & {'domain', 'subname', 'type'}):
  387. errors[field] = ValidationError(
  388. 'You cannot change the `%s` field.' % field)
  389. if errors:
  390. raise ValidationError(errors)
  391. def get_dirties(self):
  392. return self._dirties
  393. @property
  394. def name(self):
  395. return '.'.join(filter(None, [self.subname, self.domain.name])) + '.'
  396. @transaction.atomic
  397. def delete(self, *args, **kwargs):
  398. # For locked users, we can't easily sync deleted RRsets to pdns later,
  399. # so let's forbid it for now.
  400. assert not self.domain.owner.locked
  401. self.domain.write_rrsets({self: []})
  402. self._dirties = {}
  403. def save(self, *args, **kwargs):
  404. # If not new, the only thing that can change is the TTL
  405. if self.created is None or 'ttl' in self.get_dirties():
  406. self.updated = timezone.now()
  407. self.full_clean()
  408. # Tell Django to not attempt an update, although the pk is not None
  409. kwargs['force_insert'] = (self.created is None)
  410. super().save(*args, **kwargs)
  411. self._dirties = {}
  412. @staticmethod
  413. def plain_to_RRsets(datas, *, domain):
  414. rrsets = {}
  415. for data in datas:
  416. rrset = RRset(domain=domain, subname=data['subname'],
  417. type=data['type'], ttl=data['ttl'])
  418. rrsets[rrset] = [RR(rrset=rrset, content=content)
  419. for content in data['contents']]
  420. return rrsets
  421. class RR(models.Model):
  422. created = models.DateTimeField(auto_now_add=True)
  423. rrset = models.ForeignKey(RRset, on_delete=models.CASCADE, related_name='records')
  424. # max_length is determined based on the calculation in
  425. # https://lists.isc.org/pipermail/bind-users/2008-April/070148.html
  426. content = models.CharField(max_length=4092)