pdns.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. metrics.get("desecapi_pdns_request_failure").labels(
  95. method, path, r.status_code
  96. ).inc()
  97. raise PDNSException(response=r)
  98. metrics.get("desecapi_pdns_request_success").labels(method, r.status_code).inc()
  99. return r
  100. def _pdns_post(server, path, data, **kwargs):
  101. return _pdns_request("post", server=server, path=path, data=data, **kwargs)
  102. def _pdns_patch(server, path, data, **kwargs):
  103. return _pdns_request("patch", server=server, path=path, data=data, **kwargs)
  104. def _pdns_get(server, path, **kwargs):
  105. return _pdns_request("get", server=server, path=path, **kwargs)
  106. def _pdns_put(server, path, **kwargs):
  107. return _pdns_request("put", server=server, path=path, **kwargs)
  108. def _pdns_delete(server, path, **kwargs):
  109. return _pdns_request("delete", server=server, path=path, **kwargs)
  110. def pdns_id(name):
  111. # See also pdns code, apiZoneNameToId() in ws-api.cc (with the exception of forward slash)
  112. if not re.match(r"^[a-zA-Z0-9_.-]+$", name):
  113. raise SuspiciousOperation("Invalid hostname " + name)
  114. name = name.translate(str.maketrans({"/": "=2F", "_": "=5F"}))
  115. return name.rstrip(".") + "."
  116. def get_keys(domain):
  117. """
  118. Retrieves a dict representation of the DNSSEC key information
  119. """
  120. r = _pdns_get(NSLORD, "/zones/%s/cryptokeys" % pdns_id(domain.name))
  121. metrics.get("desecapi_pdns_keys_fetched").inc()
  122. field_map = {
  123. "dnskey": "dnskey",
  124. "cds": "ds",
  125. "flags": "flags", # deprecated
  126. "keytype": "keytype", # deprecated
  127. }
  128. return [
  129. {v: key.get(k, []) for k, v in field_map.items()}
  130. for key in r.json()
  131. if key["published"]
  132. ]
  133. def get_zone(domain):
  134. """
  135. Retrieves a dict representation of the zone from pdns
  136. """
  137. r = _pdns_get(NSLORD, "/zones/" + pdns_id(domain.name))
  138. return r.json()
  139. def get_zonefile(domain) -> bin:
  140. """
  141. Retrieves the zonefile (presentation format) of a given zone as binary string
  142. """
  143. r = _pdns_get(
  144. NSLORD, "/zones/" + pdns_id(domain.name) + "/export", accept="text/dns"
  145. )
  146. return r.content
  147. def get_rrset_datas(domain):
  148. """
  149. Retrieves a dict representation of the RRsets in a given zone
  150. """
  151. return [
  152. {
  153. "domain": domain,
  154. "subname": rrset["name"][: -(len(domain.name) + 2)],
  155. "type": rrset["type"],
  156. "records": [record["content"] for record in rrset["records"]],
  157. "ttl": rrset["ttl"],
  158. }
  159. for rrset in get_zone(domain)["rrsets"]
  160. ]
  161. def construct_catalog_rrset(
  162. zone=None, delete=False, subname=None, qtype="PTR", rdata=None
  163. ):
  164. # subname can be generated from zone for convenience; exactly one needs to be given
  165. assert (zone is None) ^ (subname is None)
  166. # sanity check: one can't delete an rrset and give record data at the same time
  167. assert not (delete and rdata)
  168. if subname is None:
  169. zone = zone.rstrip(".") + "."
  170. m_unique = sha1(zone.encode()).hexdigest()
  171. subname = f"{m_unique}.zones"
  172. if rdata is None:
  173. rdata = zone
  174. return {
  175. "name": f"{subname}.{settings.CATALOG_ZONE}".strip(".") + ".",
  176. "type": qtype,
  177. "ttl": 0, # as per the specification
  178. "changetype": "REPLACE",
  179. "records": [] if delete else [{"content": rdata, "disabled": False}],
  180. }
  181. def get_serials():
  182. return {
  183. zone["name"]: zone["edited_serial"]
  184. for zone in _pdns_get(NSMASTER, "/zones").json()
  185. }