-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
executable file
·216 lines (174 loc) · 7.22 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#!/usr/bin/python
import BaseHTTPServer
import os
import sys
import json
import re
import logging
from subprocess import Popen, PIPE
from netaddr import IPAddress, IPNetwork
# For a string in the format ftXYZ-aaaa10toto, extract ftXYZ
PREFIX_REGEX_PATTERN = '^(ft\w+)-.+'
prefixToNetwork = {}
noPrefixNetwork = None
prefixRegex = re.compile(PREFIX_REGEX_PATTERN, re.IGNORECASE)
logger = None
class UpdateRejectedError(Exception):
pass
class UpdateFailedError(Exception):
def __init__(self, message, stderr):
super(UpdateFailedError, self).__init__(message)
self.stderr = stderr
class DnsUpdateApiHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def update_name(self, ip, name):
update_input="""
update delete %(name)s.%(zone)s. A
update add %(name)s.%(zone)s. 600 A %(ip)s
send
""" % {"zone": "archinext.local", "name": name, "ip": ip}
print update_input
nsupdate = Popen(["nsupdate", "-l"], stdout=PIPE, stdin=PIPE, stderr=PIPE)
nsupdate_data = nsupdate.communicate(input=update_input)
if nsupdate.returncode != 0:
raise UpdateFailedError("The update failed", nsupdate_data[1])
def delete_name(self, name):
delete_input="""
update delete %(name)s.%(zone)s. A
send
""" % {"zone": "archinext.local", "name": name}
print delete_input
nsupdate = Popen(["nsupdate", "-l"], stdout=PIPE, stdin=PIPE, stderr=PIPE)
nsupdate_data = nsupdate.communicate(input=delete_input)
if nsupdate.returncode != 0:
raise UpdateFailedError("The delete failed", nsupdate_data[1])
def get_name_prefix(self, name):
match = prefixRegex.match(name)
if match:
return match.group(1)
else:
raise UpdateRejectedError("No valid team prefix was found in hostname")
def accept_update(self, ip, name):
parsedIp = IPAddress(ip)
if parsedIp in noPrefixNetwork:
return
namePrefix = self.get_name_prefix(name).lower()
if not namePrefix in prefixToNetwork:
raise UpdateRejectedError("Unknown team prefix " + namePrefix)
networkForPrefix = prefixToNetwork[namePrefix]
if not networkForPrefix:
raise UpdateRejectedError("No valid network found for the team prefix " + namePrefix)
if parsedIp not in networkForPrefix:
raise UpdateRejectedError("This host is not in the allowed network for the team prefix " + namePrefix)
def log_failure(self, exception):
logger.debug("Update failed for " + self.client_address[0] + " on " + self.path + ", error:")
logger.exception(exception)
def do_POST(self):
"""Respond to a POST request."""
self.send_header("Content-type", "text/plain")
shortHostname = os.path.basename(self.path)
print shortHostname
try:
self.accept_update(self.client_address[0], shortHostname)
self.update_name(self.client_address[0], shortHostname)
except UpdateRejectedError as e:
self.log_failure(e)
self.send_response(400)
self.end_headers()
self.wfile.write("Update request rejected.\n")
self.wfile.write("Reason: " + e.args[0])
except UpdateFailedError as e:
self.log_failure(e)
self.send_response(502)
self.end_headers()
self.wfile.write("Update request failed.\n")
self.wfile.write("Error log:\n")
self.wfile.write(e.stderr)
except Exception as e:
self.log_failure(e)
self.send_response(500)
self.end_headers()
self.wfile.write("An unexpected error has occured.\n")
self.wfile.write("Error message: " + e.args[0])
else:
self.send_response(200)
self.end_headers()
self.wfile.write("Update succesful\n")
self.wfile.write(shortHostname)
self.wfile.write(" -> ")
self.wfile.write(self.client_address[0])
def get_ip_for_name(self, name):
dig = Popen(["dig", "+aa", "+short", name + ".archinext.local", "@127.0.0.1"], stdout=PIPE, stdin=None, stderr=PIPE)
dig_data = dig.communicate()
if dig.returncode != 0:
raise UpdateFailedError("Dig check for name failed", dig_data[1])
found_ip = dig_data[0].strip()
if found_ip:
return found_ip
else:
return None
def accept_delete(self, ip, name):
record_ip = self.get_ip_for_name(name)
if not record_ip:
raise UpdateRejectedError("No record found for the given hostname")
record_ip = IPAddress(record_ip)
client_ip = IPAddress(ip)
if not record_ip == client_ip:
raise UpdateRejectedError("Your IP does not match the stored IP for the given name")
def do_DELETE(self):
""" Respond to a DELETE request: delete a record from the DNS server."""
self.send_header("Content-type", "text/plain")
shortHostname = os.path.basename(self.path)
print shortHostname
try:
self.accept_delete(self.client_address[0], shortHostname)
self.delete_name(shortHostname)
except UpdateRejectedError as e:
self.log_failure(e)
self.send_response(400)
self.end_headers()
self.wfile.write("Delete request rejected.\n")
self.wfile.write("Reason: " + e.args[0])
except UpdateFailedError as e:
self.log_failure(e)
self.send_response(502)
self.end_headers()
self.wfile.write("Delete request failed.\n")
self.wfile.write("Error log:\n")
self.wfile.write(e.stderr)
except Exception as e:
self.log_failure(e)
self.send_response(500)
self.end_headers()
self.wfile.write("An unexpected error has occured.\n")
self.wfile.write("Error message: " + e.args[0])
else:
self.send_response(200)
self.end_headers()
self.wfile.write("Delete succesful\n")
self.wfile.write(shortHostname)
self.wfile.write(" -> ")
self.wfile.write(self.client_address[0])
def load_config():
if len(sys.argv) < 2:
sys.stderr.write("usage: " + sys.argv[0] + " config-file-path")
sys.exit(1)
with open(sys.argv[1], 'r') as confStream:
return json.load(confStream)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
config = load_config()
for prefix,ipnet in config['prefixes'].iteritems():
prefixToNetwork[prefix.lower()] = IPNetwork(ipnet)
noPrefixNetwork = IPNetwork(config['noPrefixNetwork'])
logger.debug("Parsed configuration:")
logger.debug(" Prefixless network: " + noPrefixNetwork.__str__())
logger.debug(" Prefixed networks:")
for prefix,ipnet in prefixToNetwork.iteritems():
logger.debug(" " + prefix + ": " + ipnet.__str__())
httpd = BaseHTTPServer.HTTPServer(('', 8080), DnsUpdateApiHandler)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()