pdns.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. import json
  2. import re
  3. from hashlib import sha1
  4. import requests
  5. from django.conf import settings
  6. from django.core.exceptions import SuspiciousOperation
  7. from desecapi import metrics
  8. from desecapi.exceptions import PDNSException, RequestEntityTooLarge
  9. SUPPORTED_RRSET_TYPES = {
  10. # https://doc.powerdns.com/authoritative/appendices/types.html
  11. # "major" types
  12. "A",
  13. "AAAA",
  14. "AFSDB",
  15. "ALIAS",
  16. "APL",
  17. "CAA",
  18. "CERT",
  19. "CDNSKEY",
  20. "CDS",
  21. "CNAME",
  22. "CSYNC",
  23. "DNSKEY",
  24. "DNAME",
  25. "DS",
  26. "HINFO",
  27. "HTTPS",
  28. "KEY",
  29. "LOC",
  30. "MX",
  31. "NAPTR",
  32. "NS",
  33. "NSEC",
  34. "NSEC3",
  35. "NSEC3PARAM",
  36. "OPENPGPKEY",
  37. "PTR",
  38. "RP",
  39. "RRSIG",
  40. "SOA",
  41. "SPF",
  42. "SSHFP",
  43. "SRV",
  44. "SVCB",
  45. "TLSA",
  46. "SMIMEA",
  47. "TXT",
  48. "URI",
  49. # "additional" types, without obsolete ones
  50. "DHCID",
  51. "DLV",
  52. "EUI48",
  53. "EUI64",
  54. "IPSECKEY",
  55. "KX",
  56. "MINFO",
  57. "MR",
  58. "RKEY",
  59. "WKS",
  60. # https://doc.powerdns.com/authoritative/changelog/4.5.html#change-4.5.0-alpha1-New-Features
  61. "NID",
  62. "L32",
  63. "L64",
  64. "LP",
  65. }
  66. NSLORD = object()
  67. NSMASTER = object()
  68. _config = {
  69. NSLORD: {
  70. "base_url": settings.NSLORD_PDNS_API,
  71. "apikey": settings.NSLORD_PDNS_API_TOKEN,
  72. },
  73. NSMASTER: {
  74. "base_url": settings.NSMASTER_PDNS_API,
  75. "apikey": settings.NSMASTER_PDNS_API_TOKEN,
  76. },
  77. }
  78. def _pdns_request(
  79. method, *, server, path, data=None, accept="application/json", **kwargs
  80. ):
  81. if data is not None:
  82. data = json.dumps(data)
  83. if data is not None and len(data) > settings.PDNS_MAX_BODY_SIZE:
  84. raise RequestEntityTooLarge
  85. headers = {
  86. "Accept": accept,
  87. "User-Agent": "desecapi",
  88. "X-API-Key": _config[server]["apikey"],
  89. }
  90. r = requests.request(
  91. method, _config[server]["base_url"] + path, data=data, headers=headers
  92. )
  93. if r.status_code not in range(200, 300):
  94. raise PDNSException(response=r)
  95. metrics.get("desecapi_pdns_request_success").labels(method, r.status_code).inc()
  96. return r
  97. def _pdns_post(server, path, data, **kwargs):
  98. return _pdns_request("post", server=server, path=path, data=data, **kwargs)
  99. def _pdns_patch(server, path, data, **kwargs):
  100. return _pdns_request("patch", server=server, path=path, data=data, **kwargs)
  101. def _pdns_get(server, path, **kwargs):
  102. return _pdns_request("get", server=server, path=path, **kwargs)
  103. def _pdns_put(server, path, **kwargs):
  104. return _pdns_request("put", server=server, path=path, **kwargs)
  105. def _pdns_delete(server, path, **kwargs):
  106. return _pdns_request("delete", server=server, path=path, **kwargs)
  107. def pdns_id(name):
  108. # See also pdns code, apiZoneNameToId() in ws-api.cc (with the exception of forward slash)
  109. if not re.match(r"^[a-zA-Z0-9_.-]+$", name):
  110. raise SuspiciousOperation("Invalid hostname " + name)
  111. name = name.translate(str.maketrans({"/": "=2F", "_": "=5F"}))
  112. return name.rstrip(".") + "."
  113. def get_keys(domain):
  114. """
  115. Retrieves a dict representation of the DNSSEC key information
  116. """
  117. r = _pdns_get(NSLORD, "/zones/%s/cryptokeys" % pdns_id(domain.name))
  118. metrics.get("desecapi_pdns_keys_fetched").inc()
  119. field_map = {
  120. "dnskey": "dnskey",
  121. "cds": "ds",
  122. "flags": "flags", # deprecated
  123. "keytype": "keytype", # deprecated
  124. }
  125. return [
  126. {v: key.get(k, []) for k, v in field_map.items()}
  127. for key in r.json()
  128. if key["published"]
  129. ]
  130. def get_zone(domain):
  131. """
  132. Retrieves a dict representation of the zone from pdns
  133. """
  134. r = _pdns_get(NSLORD, "/zones/" + pdns_id(domain.name))
  135. return r.json()
  136. def get_rrset_datas(domain):
  137. """
  138. Retrieves a dict representation of the RRsets in a given zone
  139. """
  140. return [
  141. {
  142. "domain": domain,
  143. "subname": rrset["name"][: -(len(domain.name) + 2)],
  144. "type": rrset["type"],
  145. "records": [record["content"] for record in rrset["records"]],
  146. "ttl": rrset["ttl"],
  147. }
  148. for rrset in get_zone(domain)["rrsets"]
  149. ]
  150. def construct_catalog_rrset(
  151. zone=None, delete=False, subname=None, qtype="PTR", rdata=None
  152. ):
  153. # subname can be generated from zone for convenience; exactly one needs to be given
  154. assert (zone is None) ^ (subname is None)
  155. # sanity check: one can't delete an rrset and give record data at the same time
  156. assert not (delete and rdata)
  157. if subname is None:
  158. zone = zone.rstrip(".") + "."
  159. m_unique = sha1(zone.encode()).hexdigest()
  160. subname = f"{m_unique}.zones"
  161. if rdata is None:
  162. rdata = zone
  163. return {
  164. "name": f"{subname}.{settings.CATALOG_ZONE}".strip(".") + ".",
  165. "type": qtype,
  166. "ttl": 0, # as per the specification
  167. "changetype": "REPLACE",
  168. "records": [] if delete else [{"content": rdata, "disabled": False}],
  169. }
  170. def get_serials():
  171. return {
  172. zone["name"]: zone["edited_serial"]
  173. for zone in _pdns_get(NSMASTER, "/zones").json()
  174. }