pdns.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. from hashlib import sha1
  2. import json
  3. import re
  4. import requests
  5. from django.conf import settings
  6. from django.core.exceptions import SuspiciousOperation
  7. from desecapi.exceptions import PDNSException, PDNSValidationError, RequestEntityTooLarge
  8. NSLORD = object()
  9. NSMASTER = object()
  10. _config = {
  11. NSLORD: {
  12. 'base_url': settings.NSLORD_PDNS_API,
  13. 'headers': {
  14. 'Accept': 'application/json',
  15. 'User-Agent': 'desecapi',
  16. 'X-API-Key': settings.NSLORD_PDNS_API_TOKEN,
  17. }
  18. },
  19. NSMASTER: {
  20. 'base_url': settings.NSMASTER_PDNS_API,
  21. 'headers': {
  22. 'Accept': 'application/json',
  23. 'User-Agent': 'desecapi',
  24. 'X-API-Key': settings.NSMASTER_PDNS_API_TOKEN,
  25. }
  26. }
  27. }
  28. def _pdns_request(method, *, server, path, data=None):
  29. if data is not None:
  30. data = json.dumps(data)
  31. if data is not None and len(data) > settings.PDNS_MAX_BODY_SIZE:
  32. raise RequestEntityTooLarge
  33. r = requests.request(method, _config[server]['base_url'] + path, data=data, headers=_config[server]['headers'])
  34. if r.status_code == PDNSValidationError.pdns_code:
  35. raise PDNSValidationError(response=r)
  36. elif r.status_code not in range(200, 300):
  37. raise PDNSException(response=r)
  38. return r
  39. def _pdns_post(server, path, data):
  40. return _pdns_request('post', server=server, path=path, data=data)
  41. def _pdns_patch(server, path, data):
  42. return _pdns_request('patch', server=server, path=path, data=data)
  43. def _pdns_get(server, path):
  44. return _pdns_request('get', server=server, path=path)
  45. def _pdns_put(server, path):
  46. return _pdns_request('put', server=server, path=path)
  47. def _pdns_delete(server, path):
  48. return _pdns_request('delete', server=server, path=path)
  49. def pdns_id(name):
  50. # See also pdns code, apiZoneNameToId() in ws-api.cc (with the exception of forward slash)
  51. if not re.match(r'^[a-zA-Z0-9_.-]+$', name):
  52. raise SuspiciousOperation('Invalid hostname ' + name)
  53. name = name.translate(str.maketrans({'/': '=2F', '_': '=5F'}))
  54. return name.rstrip('.') + '.'
  55. def get_keys(domain):
  56. """
  57. Retrieves a dict representation of the DNSSEC key information
  58. """
  59. r = _pdns_get(NSLORD, '/zones/%s/cryptokeys' % pdns_id(domain.name))
  60. return [{k: key[k] for k in ('dnskey', 'ds', 'flags', 'keytype')}
  61. for key in r.json()
  62. if key['active'] and key['keytype'] in ['csk', 'ksk']]
  63. def get_zone(domain):
  64. """
  65. Retrieves a dict representation of the zone from pdns
  66. """
  67. r = _pdns_get(NSLORD, '/zones/' + pdns_id(domain.name))
  68. return r.json()
  69. def get_rrset_datas(domain):
  70. """
  71. Retrieves a dict representation of the RRsets in a given zone
  72. """
  73. return [{'domain': domain,
  74. 'subname': rrset['name'][:-(len(domain.name) + 2)],
  75. 'type': rrset['type'],
  76. 'records': [record['content'] for record in rrset['records']],
  77. 'ttl': rrset['ttl']}
  78. for rrset in get_zone(domain)['rrsets']]
  79. def construct_catalog_rrset(zone=None, delete=False, subname=None, qtype='PTR', rdata=None):
  80. # subname can be generated from zone for convenience; exactly one needs to be given
  81. assert (zone is None) ^ (subname is None)
  82. # sanity check: one can't delete an rrset and give record data at the same time
  83. assert not (delete and rdata)
  84. if subname is None:
  85. zone = zone.rstrip('.') + '.'
  86. m_unique = sha1(zone.encode()).hexdigest()
  87. subname = f'{m_unique}.zones'
  88. if rdata is None:
  89. rdata = zone
  90. return {
  91. 'name': f'{subname}.{settings.CATALOG_ZONE}'.strip('.') + '.',
  92. 'type': qtype,
  93. 'ttl': 0, # as per the specification
  94. 'changetype': 'REPLACE',
  95. 'records': [] if delete else [{'content': rdata, 'disabled': False}],
  96. }