dns-hook.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. #!/usr/local/bin/python3
  2. #
  3. # Copyright (c) 2017-2020 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
  30. import re
  31. import requests
  32. from requests.packages.urllib3.exceptions import InsecureRequestWarning
  33. requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
  34. import time
  35. import traceback
  36. import socket
  37. import logging
  38. import CLEUCreds
  39. from cleu.config import Config as C
  40. CNR_HEADERS = {"Accept": "application/json", "Content-Type": "application/json", "Authorization": CLEUCreds.JCLARKE_BASIC}
  41. ALLOWED_TO_CREATE = [
  42. "jclarke@cisco.com",
  43. "ksekula@cisco.com",
  44. "ayourtch@cisco.com",
  45. "rkamerma@cisco.com",
  46. "thulsdau@cisco.com",
  47. "lhercot@cisco.com",
  48. "pweijden@cisco.com",
  49. "udiedric@cisco.com",
  50. ]
  51. spark = Sparker(token=CLEUCreds.SPARK_TOKEN, logit=True)
  52. SPARK_ROOM = "DNS Queries"
  53. def check_for_alias(alias):
  54. global CNR_HEADERS
  55. url = C.DNS_BASE + "CCMRRSet" + "/{}".format(alias)
  56. response = requests.request("GET", url, params={"zoneOrigin": C.DNS_DOMAIN}, headers=CNR_HEADERS, verify=False)
  57. if response.status_code == 404:
  58. return None
  59. res = {}
  60. j = response.json()
  61. hostname = ""
  62. for rr in j["rrs"]["stringItem"]:
  63. m = re.search(r"^IN CNAME (.+)", rr)
  64. if m:
  65. hostname = m.group(1)
  66. break
  67. res["hostname"] = hostname
  68. return res
  69. def create_alias(hostname, alias):
  70. global CNR_HEADERS
  71. url = C.DNS_BASE + "CCMRRSet" + "/{}".format(alias)
  72. if re.search(r"\.", hostname) and not hostname.endswith("."):
  73. hostname += "."
  74. if not hostname.endswith("."):
  75. hostname += "." + C.DNS_DOMAIN + "."
  76. rr_obj = {"name": alias, "zoneOrigin": C.DNS_DOMAIN, "rrs": {"stringItem": ["IN CNAME {}".format(hostname)]}}
  77. response = requests.request("PUT", url, headers=CNR_HEADERS, json=rr_obj, verify=False)
  78. response.raise_for_status()
  79. def delete_alias(alias):
  80. global CNR_HEADERS
  81. url = C.DNS_BASE + "CCMRRSet" + "/{}".format(alias)
  82. response = requests.request("DELETE", url, params={"zoneOrigin": C.DNS_DOMAIN}, headers=CNR_HEADERS, verify=False)
  83. response.raise_for_status()
  84. def delete_record(hostname):
  85. global CNR_HEADERS
  86. url = C.DNS_BASE + "CCMHost" + "/{}".format(hostname)
  87. response = requests.request("DELETE", url, params={"zoneOrigin": C.DNS_DOMAIN}, headers=CNR_HEADERS, verify=False)
  88. response.raise_for_status()
  89. def check_for_record(hostname):
  90. global CNR_HEADERS
  91. url = C.DNS_BASE + "CCMHost" + "/{}".format(hostname)
  92. response = requests.request("GET", url, params={"zoneOrigin": C.DNS_DOMAIN}, 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):
  100. global CNR_HEADERS
  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, json=host_obj, verify=False)
  109. response.raise_for_status()
  110. if __name__ == "__main__":
  111. print("Content-type: application/json\r\n\r\n")
  112. output = sys.stdin.read()
  113. j = json.loads(output)
  114. logging.basicConfig(
  115. format="%(asctime)s - %(name)s - %(levelname)s : %(message)s", filename="/var/log/dns-hook.log", level=logging.DEBUG
  116. )
  117. logging.debug(json.dumps(j, indent=4))
  118. message_from = j["data"]["personEmail"]
  119. if message_from == "livenocbot@sparkbot.io":
  120. logging.debug("Person email is our bot")
  121. print('{"result":"success"}')
  122. sys.exit(0)
  123. tid = spark.get_team_id(C.WEBEX_TEAM)
  124. if tid is None:
  125. logging.error("Failed to get Spark Team ID")
  126. print('{"result":"fail"}')
  127. sys.exit(0)
  128. rid = spark.get_room_id(tid, SPARK_ROOM)
  129. if rid is None:
  130. logging.error("Failed to get Spark Room ID")
  131. print('{"result":"fail"}')
  132. sys.exit(0)
  133. if rid != j["data"]["roomId"]:
  134. logging.error("Spark Room ID is not the same as in the message ({} vs. {})".format(rid, j["data"]["roomId"]))
  135. print('{"result":"fail"}')
  136. sys.exit(0)
  137. mid = j["data"]["id"]
  138. msg = spark.get_message(mid)
  139. if msg is None:
  140. logging.error("Did not get a message")
  141. print('{"result":"error"}')
  142. sys.exit(0)
  143. txt = msg["text"]
  144. found_hit = False
  145. if re.search(r"\bhelp\b", txt, re.I):
  146. spark.post_to_spark(
  147. C.WEBEX_TEAM,
  148. SPARK_ROOM,
  149. "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`",
  150. )
  151. found_hit = True
  152. try:
  153. m = re.search(r"(remove|delete)\s+.*?(alias|cname)\s+([\w\-\.]+)", txt, re.I)
  154. if not found_hit and m:
  155. found_hit = True
  156. if message_from not in ALLOWED_TO_CREATE:
  157. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I'm sorry, {}. I can't do that for you.".format(message_from))
  158. else:
  159. res = check_for_alias(m.group(3))
  160. if res is None:
  161. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I didn't find an alias {}".format(m.group(3)))
  162. else:
  163. try:
  164. delete_alias(m.group(3))
  165. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "Alias {} deleted successfully.".format(m.group(3)), MessageType.GOOD)
  166. except Exception as e:
  167. spark.post_to_spark(
  168. C.WEBEX_TEAM, SPARK_ROOM, "Failed to delete alias {}: {}".format(m.group(3), e), MessageType.BAD
  169. )
  170. m = re.search(r"(remove|delete)\s+.*?for\s+([\w\-\.]+)", txt, re.I)
  171. if not found_hit and m:
  172. found_hit = True
  173. if message_from not in ALLOWED_TO_CREATE:
  174. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I'm sorry, {}. I can't do that for you.".format(message_from))
  175. else:
  176. res = check_for_record(m.group(2))
  177. if res is None:
  178. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I didn't find a DNS record for {}.".format(m.group(2)))
  179. else:
  180. try:
  181. delete_record(m.group(2))
  182. spark.post_to_spark(
  183. C.WEBEX_TEAM, SPARK_ROOM, "DNS record for {} deleted successfully.".format(m.group(2)), MessageType.GOOD
  184. )
  185. except Exception as e:
  186. spark.post_to_spark(
  187. C.WEBEX_TEAM, SPARK_ROOM, "Failed to delete DNS record for {}: {}".format(m.group(2), e), MessageType.BAD
  188. )
  189. m = re.search(
  190. 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]+)?))?",
  191. txt,
  192. re.I,
  193. )
  194. if not found_hit and m:
  195. found_hit = True
  196. if message_from not in ALLOWED_TO_CREATE:
  197. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I'm sorry, {}. I can't do that for you.".format(message_from))
  198. else:
  199. res = check_for_record(m.group(2))
  200. if res is not None:
  201. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "_{}_ is already in DNS as **{}**".format(m.group(2), res["ip"]))
  202. else:
  203. hostname = re.sub(r"\.{}".format(C.DNS_DOMAIN), "", m.group(2))
  204. try:
  205. create_record(m.group(2), m.group(3), m.group(8))
  206. spark.post_to_spark(
  207. C.WEBEX_TEAM, SPARK_ROOM, "Successfully created record for {}.".format(m.group(2)), MessageType.GOOD
  208. )
  209. except Exception as e:
  210. spark.post_to_spark(
  211. C.WEBEX_TEAM, SPARK_ROOM, "Failed to create record for {}: {}".format(m.group(2), e), MessageType.BAD
  212. )
  213. 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)
  214. if not found_hit and m:
  215. found_hit = True
  216. if message_from not in ALLOWED_TO_CREATE:
  217. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I'm sorry, {}. I can't do that for you.".format(message_from))
  218. else:
  219. aliases = m.group(5)
  220. aliases = re.sub(r"\s+", "", aliases)
  221. alist = aliases.split(",")
  222. already_exists = False
  223. for alias in alist:
  224. res = check_for_alias(alias)
  225. if res is not None:
  226. already_exists = True
  227. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "_{}_ is already an alias for **{}**".format(alias, res["hostname"]))
  228. res = check_for_record(alias)
  229. if res is not None:
  230. already_exists = True
  231. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "_{}_ is already a hostname with IP **{}**".format(alias, res["ip"]))
  232. if not already_exists:
  233. success = True
  234. for alias in alist:
  235. try:
  236. create_alias(m.group(8), alias)
  237. except Exception as e:
  238. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "Failed to create alias {}: {}".format(alias, e), MessageType.BAD)
  239. success = False
  240. if success:
  241. spark.post_to_spark(
  242. C.WEBEX_TEAM,
  243. SPARK_ROOM,
  244. "Successfully created alias(es) {} for {}".format(aliases, m.group(8)),
  245. MessageType.GOOD,
  246. )
  247. if not found_hit:
  248. spark.post_to_spark(
  249. C.WEBEX_TEAM,
  250. SPARK_ROOM,
  251. 'Sorry, I didn\'t get that. Please ask me to create or delete a DNS entry; or just ask for "help".',
  252. )
  253. except Exception as e:
  254. logging.error("Error in obtaining data: {}".format(traceback.format_exc()))
  255. spark.post_to_spark(
  256. C.WEBEX_TEAM, SPARK_ROOM, "Whoops, I encountered an error:<br>\n```\n{}\n```".format(traceback.format_exc()), MessageType.BAD
  257. )
  258. print('{"result":"success"}')