dns-hook.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (c) 2017-2023 Joe Clarke <jclarke@cisco.com>
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. # 1. Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. # notice, this list of conditions and the following disclaimer in the
  13. # documentation and/or other materials provided with the distribution.
  14. #
  15. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  16. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  19. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  21. # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  22. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  23. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  24. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  25. # SUCH DAMAGE.
  26. from __future__ import print_function
  27. import sys
  28. import json
  29. from sparker import Sparker, MessageType # type: ignore
  30. import re
  31. import requests
  32. from requests.packages.urllib3.exceptions import InsecureRequestWarning # type: ignore
  33. requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
  34. import traceback
  35. import logging
  36. import CLEUCreds # type: ignore
  37. from cleu.config import Config as C # type: ignore
  38. CNR_HEADERS = {"Accept": "application/json", "Content-Type": "application/json"}
  39. CNR_AUTH = (CLEUCreds.CPNR_USERNAME, CLEUCreds.CPNR_PASSWORD)
  40. ALLOWED_TO_CREATE = [
  41. "jclarke@cisco.com",
  42. "anjesani@cisco.com",
  43. "ayourtch@cisco.com",
  44. "rkamerma@cisco.com",
  45. "lhercot@cisco.com",
  46. "pweijden@cisco.com",
  47. "josterfe@cisco.com",
  48. ]
  49. spark = Sparker(token=CLEUCreds.SPARK_TOKEN, logit=True)
  50. SPARK_ROOM = "DNS Queries"
  51. def check_for_alias(alias):
  52. global CNR_HEADERS, CNR_AUTH
  53. url = C.DNS_BASE + "/CCMRRSet" + "/{}".format(alias)
  54. response = requests.request("GET", url, params={"zoneOrigin": C.DNS_DOMAIN}, auth=CNR_AUTH, headers=CNR_HEADERS, verify=False)
  55. if response.status_code == 404:
  56. return None
  57. res = {}
  58. j = response.json()
  59. hostname = ""
  60. for rr in j["rrs"]["stringItem"]:
  61. m = re.search(r"^IN CNAME (.+)", rr)
  62. if m:
  63. hostname = m.group(1)
  64. break
  65. res["hostname"] = hostname
  66. return res
  67. def create_alias(hostname, alias):
  68. global CNR_HEADERS, CNR_AUTH
  69. url = C.DNS_BASE + "/CCMRRSet" + "/{}".format(alias)
  70. if re.search(r"\.", hostname) and not hostname.endswith("."):
  71. hostname += "."
  72. if not hostname.endswith("."):
  73. hostname += "." + C.DNS_DOMAIN + "."
  74. rr_obj = {"name": alias, "zoneOrigin": C.DNS_DOMAIN, "rrs": {"stringItem": ["IN CNAME {}".format(hostname)]}}
  75. response = requests.request("PUT", url, headers=CNR_HEADERS, auth=CNR_AUTH, json=rr_obj, verify=False)
  76. response.raise_for_status()
  77. def delete_alias(alias):
  78. global CNR_HEADERS, CNR_AUTH
  79. url = C.DNS_BASE + "/CCMRRSet" + "/{}".format(alias)
  80. response = requests.request("DELETE", url, params={"zoneOrigin": C.DNS_DOMAIN}, auth=CNR_AUTH, headers=CNR_HEADERS, verify=False)
  81. response.raise_for_status()
  82. def delete_record(hostname):
  83. global CNR_HEADERS
  84. url = C.DNS_BASE + "/CCMHost" + "/{}".format(hostname)
  85. rrurl = C.DNS_BASE + "/CCMRRSet" + "/{}".format(hostname)
  86. response = requests.request("DELETE", url, params={"zoneOrigin": C.DNS_DOMAIN}, headers=CNR_HEADERS, verify=False)
  87. response.raise_for_status()
  88. response = requests.request("DELETE", rrurl, params={"zoneOrigin": C.DNS_DOMAIN}, headers=CNR_HEADERS, verify=False)
  89. def check_for_record(hostname):
  90. global CNR_HEADERS, CNR_AUTH
  91. url = C.DNS_BASE + "/CCMHost" + "/{}".format(hostname)
  92. response = requests.request("GET", url, params={"zoneOrigin": C.DNS_DOMAIN}, auth=CNR_AUTH, headers=CNR_HEADERS, verify=False)
  93. if response.status_code == 404:
  94. return None
  95. res = {}
  96. j = response.json()
  97. res["ip"] = j["addrs"]["stringItem"][0]
  98. return res
  99. def create_record(hostname, ip, aliases, message_from):
  100. global CNR_HEADERS, CNR_AUTH
  101. url = C.DNS_BASE + "/CCMHost" + "/{}".format(hostname)
  102. host_obj = {"addrs": {"stringItem": [ip]}, "name": hostname, "zoneOrigin": C.DNS_DOMAIN}
  103. if aliases is not None:
  104. aliases = re.sub(r"\s+", "", aliases)
  105. alist = aliases.split(",")
  106. alist = [x + "." + C.DNS_DOMAIN + "." if not x.endswith(".") else x for x in alist]
  107. host_obj["aliases"] = {"stringItem": alist}
  108. response = requests.request("PUT", url, headers=CNR_HEADERS, auth=CNR_AUTH, json=host_obj, verify=False)
  109. response.raise_for_status()
  110. rr_obj = {"name": hostname, "zoneOrigin": C.DNS_DOMAIN, "rrs": {"stringItem": [f'IN TXT "v=_static created by: {message_from}']}}
  111. rrurl = C.DNS_BASE + "/CCMRRSet" + "/{}".format(hostname)
  112. response = requests.request("PUT", rrurl, headers=CNR_HEADERS, auth=CNR_AUTH, json=rr_obj, verify=False)
  113. response.raise_for_status()
  114. if __name__ == "__main__":
  115. print("Content-type: application/json\r\n\r\n")
  116. output = sys.stdin.read()
  117. j = json.loads(output)
  118. logging.basicConfig(
  119. format="%(asctime)s - %(name)s - %(levelname)s : %(message)s", filename="/var/log/dns-hook.log", level=logging.DEBUG
  120. )
  121. logging.debug(json.dumps(j, indent=4))
  122. message_from = j["data"]["personEmail"]
  123. if message_from == "livenocbot@sparkbot.io":
  124. logging.debug("Person email is our bot")
  125. print('{"result":"success"}')
  126. sys.exit(0)
  127. tid = spark.get_team_id(C.WEBEX_TEAM)
  128. if tid is None:
  129. logging.error("Failed to get Spark Team ID")
  130. print('{"result":"fail"}')
  131. sys.exit(0)
  132. rid = spark.get_room_id(tid, SPARK_ROOM)
  133. if rid is None:
  134. logging.error("Failed to get Spark Room ID")
  135. print('{"result":"fail"}')
  136. sys.exit(0)
  137. if rid != j["data"]["roomId"]:
  138. logging.error("Spark Room ID is not the same as in the message ({} vs. {})".format(rid, j["data"]["roomId"]))
  139. print('{"result":"fail"}')
  140. sys.exit(0)
  141. mid = j["data"]["id"]
  142. msg = spark.get_message(mid)
  143. if msg is None:
  144. logging.error("Did not get a message")
  145. print('{"result":"error"}')
  146. sys.exit(0)
  147. txt = msg["text"]
  148. found_hit = False
  149. if re.search(r"\bhelp\b", txt, re.I):
  150. spark.post_to_spark(
  151. C.WEBEX_TEAM,
  152. SPARK_ROOM,
  153. "To create a new DNS entry, tell me things like, `Create record for HOST with IP and alias ALIAS`, `Create entry for HOST with IP`, `Add a DNS record for HOST with IP`",
  154. )
  155. found_hit = True
  156. try:
  157. m = re.search(r"(remove|delete)\s+.*?(alias|cname)\s+([\w\-\.]+)", txt, re.I)
  158. if not found_hit and m:
  159. found_hit = True
  160. if message_from not in ALLOWED_TO_CREATE:
  161. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I'm sorry, {}. I can't do that for you.".format(message_from))
  162. else:
  163. res = check_for_alias(m.group(3))
  164. if res is None:
  165. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I didn't find an alias {}".format(m.group(3)))
  166. else:
  167. try:
  168. delete_alias(m.group(3))
  169. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "Alias {} deleted successfully.".format(m.group(3)), MessageType.GOOD)
  170. except Exception as e:
  171. spark.post_to_spark(
  172. C.WEBEX_TEAM, SPARK_ROOM, "Failed to delete alias {}: {}".format(m.group(3), e), MessageType.BAD
  173. )
  174. m = re.search(r"(remove|delete)\s+.*?for\s+([\w\-\.]+)", txt, re.I)
  175. if not found_hit and m:
  176. found_hit = True
  177. if message_from not in ALLOWED_TO_CREATE:
  178. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I'm sorry, {}. I can't do that for you.".format(message_from))
  179. else:
  180. res = check_for_record(m.group(2))
  181. if res is None:
  182. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I didn't find a DNS record for {}.".format(m.group(2)))
  183. else:
  184. try:
  185. delete_record(m.group(2))
  186. spark.post_to_spark(
  187. C.WEBEX_TEAM, SPARK_ROOM, "DNS record for {} deleted successfully.".format(m.group(2)), MessageType.GOOD
  188. )
  189. except Exception as e:
  190. spark.post_to_spark(
  191. C.WEBEX_TEAM, SPARK_ROOM, "Failed to delete DNS record for {}: {}".format(m.group(2), e), MessageType.BAD
  192. )
  193. m = re.search(
  194. r"(make|create|add)\s+.*?for\s+([\w\-\.]+)\s+.*?([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(\s+.*?(alias(es)?|cname(s)?)\s+([\w\-\.]+(\s*,\s*[\w\-\.,\s]+)?))?",
  195. txt,
  196. re.I,
  197. )
  198. if not found_hit and m:
  199. found_hit = True
  200. if message_from not in ALLOWED_TO_CREATE:
  201. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I'm sorry, {}. I can't do that for you.".format(message_from))
  202. else:
  203. res = check_for_record(m.group(2))
  204. if res is not None:
  205. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "_{}_ is already in DNS as **{}**".format(m.group(2), res["ip"]))
  206. else:
  207. hostname = re.sub(r"\.{}".format(C.DNS_DOMAIN), "", m.group(2))
  208. try:
  209. create_record(m.group(2), m.group(3), m.group(8), message_from)
  210. spark.post_to_spark(
  211. C.WEBEX_TEAM, SPARK_ROOM, "Successfully created record for {}.".format(m.group(2)), MessageType.GOOD
  212. )
  213. except Exception as e:
  214. spark.post_to_spark(
  215. C.WEBEX_TEAM, SPARK_ROOM, "Failed to create record for {}: {}".format(m.group(2), e), MessageType.BAD
  216. )
  217. m = re.search(r"(make|create|add)\s+(alias(es)?|cname(s)?)\s+([\w\-\.]+(\s*,\s*[\w\-\.,\s]+)?)\s+(for|to)\s+([\w\-\.]+)", txt, re.I)
  218. if not found_hit and m:
  219. found_hit = True
  220. if message_from not in ALLOWED_TO_CREATE:
  221. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I'm sorry, {}. I can't do that for you.".format(message_from))
  222. else:
  223. aliases = m.group(5)
  224. aliases = re.sub(r"\s+", "", aliases)
  225. alist = aliases.split(",")
  226. already_exists = False
  227. for alias in alist:
  228. res = check_for_alias(alias)
  229. if res is not None:
  230. already_exists = True
  231. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "_{}_ is already an alias for **{}**".format(alias, res["hostname"]))
  232. res = check_for_record(alias)
  233. if res is not None:
  234. already_exists = True
  235. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "_{}_ is already a hostname with IP **{}**".format(alias, res["ip"]))
  236. if not already_exists:
  237. success = True
  238. for alias in alist:
  239. try:
  240. create_alias(m.group(8), alias)
  241. except Exception as e:
  242. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "Failed to create alias {}: {}".format(alias, e), MessageType.BAD)
  243. success = False
  244. if success:
  245. spark.post_to_spark(
  246. C.WEBEX_TEAM,
  247. SPARK_ROOM,
  248. "Successfully created alias(es) {} for {}".format(aliases, m.group(8)),
  249. MessageType.GOOD,
  250. )
  251. if not found_hit:
  252. spark.post_to_spark(
  253. C.WEBEX_TEAM,
  254. SPARK_ROOM,
  255. 'Sorry, I didn\'t get that. Please ask me to create or delete a DNS entry; or just ask for "help".',
  256. )
  257. except Exception as e:
  258. logging.error("Error in obtaining data: {}".format(traceback.format_exc()))
  259. spark.post_to_spark(
  260. C.WEBEX_TEAM, SPARK_ROOM, "Whoops, I encountered an error:<br>\n```\n{}\n```".format(traceback.format_exc()), MessageType.BAD
  261. )
  262. print('{"result":"success"}')