pdns.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import json
  2. import re
  3. import socket
  4. from hashlib import sha1
  5. import requests
  6. from django.conf import settings
  7. from django.core.exceptions import SuspiciousOperation
  8. from desecapi import metrics
  9. from desecapi.exceptions import PDNSException, RequestEntityTooLarge
  10. SUPPORTED_RRSET_TYPES = {
  11. # https://doc.powerdns.com/authoritative/appendices/types.html
  12. # "major" types
  13. "A",
  14. "AAAA",
  15. "AFSDB",
  16. "ALIAS",
  17. "APL",
  18. "CAA",
  19. "CERT",
  20. "CDNSKEY",
  21. "CDS",
  22. "CNAME",
  23. "CSYNC",
  24. "DNSKEY",
  25. "DNAME",
  26. "DS",
  27. "HINFO",
  28. "HTTPS",
  29. "KEY",
  30. "LOC",
  31. "MX",
  32. "NAPTR",
  33. "NS",
  34. "NSEC",
  35. "NSEC3",
  36. "NSEC3PARAM",
  37. "OPENPGPKEY",
  38. "PTR",
  39. "RP",
  40. "RRSIG",
  41. "SOA",
  42. "SPF",
  43. "SSHFP",
  44. "SRV",
  45. "SVCB",
  46. "TLSA",
  47. "SMIMEA",
  48. "TXT",
  49. "URI",
  50. # "additional" types, without obsolete ones
  51. "DHCID",
  52. "DLV",
  53. "EUI48",
  54. "EUI64",
  55. "IPSECKEY",
  56. "KX",
  57. "MINFO",
  58. "MR",
  59. "RKEY",
  60. "WKS",
  61. # https://doc.powerdns.com/authoritative/changelog/4.5.html#change-4.5.0-alpha1-New-Features
  62. "NID",
  63. "L32",
  64. "L64",
  65. "LP",
  66. }
  67. NSLORD = object()
  68. NSMASTER = object()
  69. _config = {
  70. NSLORD: {
  71. "base_url": settings.NSLORD_PDNS_API,
  72. "apikey": settings.NSLORD_PDNS_API_TOKEN,
  73. },
  74. NSMASTER: {
  75. "base_url": settings.NSMASTER_PDNS_API,
  76. "apikey": settings.NSMASTER_PDNS_API_TOKEN,
  77. },
  78. }
  79. _nslord_ip = socket.gethostbyname("nslord")
  80. def _pdns_request(
  81. method, *, server, path, data=None, accept="application/json", **kwargs
  82. ):
  83. if data is not None:
  84. data = json.dumps(data)
  85. if data is not None and len(data) > settings.PDNS_MAX_BODY_SIZE:
  86. raise RequestEntityTooLarge
  87. headers = {
  88. "Accept": accept,
  89. "User-Agent": "desecapi",
  90. "X-API-Key": _config[server]["apikey"],
  91. }
  92. r = requests.request(
  93. method, _config[server]["base_url"] + path, data=data, headers=headers
  94. )
  95. if r.status_code not in range(200, 300):
  96. metrics.get("desecapi_pdns_request_failure").labels(
  97. method, path, r.status_code
  98. ).inc()
  99. raise PDNSException(response=r)
  100. metrics.get("desecapi_pdns_request_success").labels(method, r.status_code).inc()
  101. return r
  102. def _pdns_post(server, path, data, **kwargs):
  103. return _pdns_request("post", server=server, path=path, data=data, **kwargs)
  104. def _pdns_patch(server, path, data, **kwargs):
  105. return _pdns_request("patch", server=server, path=path, data=data, **kwargs)
  106. def _pdns_get(server, path, **kwargs):
  107. return _pdns_request("get", server=server, path=path, **kwargs)
  108. def _pdns_put(server, path, **kwargs):
  109. return _pdns_request("put", server=server, path=path, **kwargs)
  110. def _pdns_delete(server, path, **kwargs):
  111. return _pdns_request("delete", server=server, path=path, **kwargs)
  112. def pdns_id(name):
  113. # See also pdns code, apiZoneNameToId() in ws-api.cc (with the exception of forward slash)
  114. if not re.match(r"^[a-zA-Z0-9_.-]+$", name):
  115. raise SuspiciousOperation("Invalid hostname " + name)
  116. name = name.translate(str.maketrans({"/": "=2F", "_": "=5F"}))
  117. return name.rstrip(".") + "."
  118. def get_keys(domain):
  119. """
  120. Retrieves a dict representation of the DNSSEC key information
  121. """
  122. r = _pdns_get(NSLORD, "/zones/%s/cryptokeys" % pdns_id(domain.name))
  123. metrics.get("desecapi_pdns_keys_fetched").inc()
  124. field_map = {
  125. "dnskey": "dnskey",
  126. "cds": "ds",
  127. "flags": "flags", # deprecated
  128. "keytype": "keytype", # deprecated
  129. }
  130. return [
  131. {v: key.get(k, []) for k, v in field_map.items()}
  132. for key in r.json()
  133. if key["published"]
  134. ]
  135. def get_zone(domain):
  136. """
  137. Retrieves a dict representation of the zone from pdns
  138. """
  139. r = _pdns_get(NSLORD, "/zones/" + pdns_id(domain.name))
  140. return r.json()
  141. def get_zonefile(domain) -> bin:
  142. """
  143. Retrieves the zonefile (presentation format) of a given zone as binary string
  144. """
  145. r = _pdns_get(
  146. NSLORD, "/zones/" + pdns_id(domain.name) + "/export", accept="text/dns"
  147. )
  148. return r.content
  149. def get_rrset_datas(domain):
  150. """
  151. Retrieves a dict representation of the RRsets in a given zone
  152. """
  153. return [
  154. {
  155. "domain": domain,
  156. "subname": rrset["name"][: -(len(domain.name) + 2)],
  157. "type": rrset["type"],
  158. "records": [record["content"] for record in rrset["records"]],
  159. "ttl": rrset["ttl"],
  160. }
  161. for rrset in get_zone(domain)["rrsets"]
  162. ]
  163. def update_catalog(zone, delete=False):
  164. """
  165. Updates the catalog zone information (`settings.CATALOG_ZONE`) for the given zone.
  166. """
  167. content = _pdns_patch(
  168. NSMASTER,
  169. "/zones/" + pdns_id(settings.CATALOG_ZONE),
  170. {"rrsets": [construct_catalog_rrset(zone=zone, delete=delete)]},
  171. )
  172. metrics.get("desecapi_pdns_catalog_updated").inc()
  173. return content
  174. def create_zone_lord(name):
  175. name = name.rstrip(".") + "."
  176. _pdns_post(
  177. NSLORD,
  178. "/zones?rrsets=false",
  179. {
  180. "name": name,
  181. "kind": "MASTER",
  182. "dnssec": True,
  183. "nsec3param": "1 0 0 -",
  184. "nameservers": settings.DEFAULT_NS,
  185. "rrsets": [
  186. {
  187. "name": name,
  188. "type": "SOA",
  189. # SOA RRset TTL: 300 (used as TTL for negative replies including NSEC3 records)
  190. "ttl": 300,
  191. "records": [
  192. {
  193. # SOA refresh: 1 day (only needed for nslord --> nsmaster replication after RRSIG rotation)
  194. # SOA retry = 1h
  195. # SOA expire: 4 weeks (all signatures will have expired anyways)
  196. # SOA minimum: 3600 (for CDS, CDNSKEY, DNSKEY, NSEC3PARAM)
  197. "content": "get.desec.io. get.desec.io. 1 86400 3600 2419200 3600",
  198. "disabled": False,
  199. }
  200. ],
  201. }
  202. ],
  203. },
  204. )
  205. def create_zone_master(name):
  206. name = name.rstrip(".") + "."
  207. _pdns_post(
  208. NSMASTER,
  209. "/zones?rrsets=false",
  210. {
  211. "name": name,
  212. "kind": "SLAVE",
  213. "masters": [_nslord_ip],
  214. "master_tsig_key_ids": ["default"],
  215. },
  216. )
  217. def delete_zone(name, server):
  218. _pdns_delete(server, "/zones/" + pdns_id(name))
  219. def delete_zone_lord(name):
  220. _pdns_delete(NSLORD, "/zones/" + pdns_id(name))
  221. def delete_zone_master(name):
  222. _pdns_delete(NSMASTER, "/zones/" + pdns_id(name))
  223. def update_zone(name, data):
  224. _pdns_patch(NSLORD, "/zones/" + pdns_id(name), data)
  225. def axfr_to_master(zone):
  226. _pdns_put(NSMASTER, "/zones/%s/axfr-retrieve" % pdns_id(zone))
  227. def construct_catalog_rrset(
  228. zone=None, delete=False, subname=None, qtype="PTR", rdata=None
  229. ):
  230. # subname can be generated from zone for convenience; exactly one needs to be given
  231. assert (zone is None) ^ (subname is None)
  232. # sanity check: one can't delete an rrset and give record data at the same time
  233. assert not (delete and rdata)
  234. if subname is None:
  235. zone = zone.rstrip(".") + "."
  236. m_unique = sha1(zone.encode()).hexdigest()
  237. subname = f"{m_unique}.zones"
  238. if rdata is None:
  239. rdata = zone
  240. return {
  241. "name": f"{subname}.{settings.CATALOG_ZONE}".strip(".") + ".",
  242. "type": qtype,
  243. "ttl": 0, # as per the specification
  244. "changetype": "REPLACE",
  245. "records": [] if delete else [{"content": rdata, "disabled": False}],
  246. }
  247. def get_serials():
  248. return {
  249. zone["name"]: zone["edited_serial"]
  250. for zone in _pdns_get(NSMASTER, "/zones").json()
  251. }