-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathHurricaneDNS.py
355 lines (295 loc) · 11.9 KB
/
HurricaneDNS.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
"""
Hurricane Electric DNS library module
Inspired by EveryDNS Python library by Scott Yang:
http://svn.fucoder.com/fucoder/pyeverydns/everydnslib.py
"""
try:
from http.cookiejar import CookieJar
except ImportError:
from cookielib import CookieJar
try:
from urllib.parse import urlencode
from urllib.request import build_opener, HTTPCookieProcessor
except ImportError:
from urllib import urlencode
from urllib2 import build_opener, HTTPCookieProcessor
import pkg_resources
import re
import warnings
import html5lib
import lxml
__version__ = pkg_resources.require("hurricanedns")[0].version
__author__ = "Brian Hartvigsen <[email protected]>"
__copyright__ = "Copyright 2015, Brian Hartvigsen"
__credits__ = ["Scott Yang", "Brian Hartvigsen"]
__license__ = "MIT"
# Basically we just want to make sure it's here. We need lxml because
# ElementTree does not support parent relationships in XPath
assert lxml
HTTP_USER_AGENT = 'PyHurriceDNS/%s' % __version__
HTTP_REQUEST_PATH = 'https://dns.he.net/index.cgi'
class HurricaneError(Exception):
pass
class HurricaneAuthenticationError(HurricaneError):
pass
class HurricaneBadArgumentError(HurricaneError):
pass
class HurricaneDNS(object):
def __init__(self, username, password, totp=None):
self.__account = None
self.__cookie = CookieJar()
self.__opener = build_opener(HTTPCookieProcessor(self.__cookie))
self.__domains = {}
self.login(username, password, totp)
def add_domain(self, domain, master=None, method=None):
domain = domain.lower()
data = {
'retmain': 0,
'submit': 1
}
if master and method:
raise HurricaneBadArgumentError('Domain "%s" can not be both slave and reverse' % domain)
if master:
if isinstance(master, list) or isinstance(master, tuple):
i = 1
for ns in master:
data['master%s' % i] = ns
i += 1
if i == 4:
break
else:
data['master1'] = master
data['add_slave'] = domain
data['action'] = 'add_slave'
elif method:
data['add_reverse'] = domain
data['method'] = method
data['action'] = 'add_reverse'
else:
data['add_domain'] = domain
data['action'] = 'add_zone'
try:
self.__process(data)
except HurricaneError as e:
raise HurricaneBadArgumentError(e)
# HACK: Instead we should just add the domain
self.__domains = None
def __add_or_edit_record(self, domain, record_id, host, rtype, value, mx, ttl):
domain = domain.lower()
d = self.get_domain(domain)
if d['type'] == 'slave':
raise HurricaneBadArgumentError('Domain "%s" is a slave zone, this is a bad idea!' % domain)
try:
res = self.__process({
'account': '', # self.__account,
'menu': 'edit_zone',
'hosted_dns_zoneid': d['id'],
'hosted_dns_recordid': record_id or '',
'hosted_dns_editzone': 1,
'hosted_dns_editrecord': 'Update' if record_id else 'Submit',
'Name': host.lower(),
'Type': rtype,
'Priority': mx or '',
'Content': value,
'TTL': ttl
})
except HurricaneError as e:
raise HurricaneBadArgumentError(e)
if res.find('.//div[@id="dns_err"]') is not None:
# this should mean duplicate records
pass
elif res.find('.//div[@id="dns_status"]') is None:
raise HurricaneBadArgumentError('Record "%s" (%s) not added or modified for domain "%s"' % (host, rtype, domain))
# HACK: Be better to invalidate a single record...
d['records'] = None
def edit_record(self, domain, host, rtype, old_value=None, old_mx=None, old_ttl=None, value=None, mx=None, ttl=None):
if value is None and ttl is None and not (rtype == 'MX' and mx is not None):
raise HurricaneError('You must specify one or more of value, ttl or mx priority')
record = list(self.get_records(domain, host, rtype, old_value, old_mx, old_ttl))
if len(record) > 1:
raise HurricaneBadArgumentError('Criteria matches multiple records, please be more specific')
else:
record = record[0]
if not value:
value = record['value']
if (not mx) and rtype == 'MX':
mx = record['mx']
if not ttl:
ttl = record['ttl']
self.__add_or_edit_record(domain, record['id'], host, rtype, value, mx, ttl)
def add_record(self, domain, host, rtype, value, mx=None, ttl=86400):
self.__add_or_edit_record(domain, None, host, rtype, value, mx, ttl)
def del_record(self, domain, record_id):
d = self.get_domain(domain.lower())
if d['type'] == 'slave':
raise HurricaneBadArgumentError('Domain "%s" is a slave zone, this is a bad idea!' % domain)
self.__process({
'hosted_dns_zoneid': d['id'],
'hosted_dns_recordid': record_id,
'menu': 'edit_zone',
'hosted_dns_delconfirm': 'delete',
'hosted_dns_editzone': 1,
'hosted_dns_delrecord': 1
})
# HACK: Be better to invaldate a single record...
d['records'] = None
def del_records(self, domain, host, rtype=None, value=None, mx=None, ttl=None):
domain = domain.lower()
d = self.get_domain(domain)
if d['type'] == 'slave':
raise HurricaneBadArgumentError('Domain "%s" is a slave zone, this is a bad idea!' % domain)
for r in self.get_records(domain, host, rtype, value, mx, ttl):
if r['status'] == 'locked':
continue
self.del_record(domain, r['id'])
def del_domain(self, domain):
domain = domain.lower()
self.__process({
'delete_id': self.get_domain(domain)['id'],
'account': self.__account,
'remove_domain': 1
})
# HACK: instead we could just remove the one domain
self.__domains = None
def get_domain(self, domain):
domain = domain.lower()
for d in self.cache_domains():
if d['domain'] == domain:
return d
raise HurricaneBadArgumentError('Domain "%s" does not exist' % domain)
def cache_domains(self):
if not self.__domains:
self.__domains = self.list_domains()
return self.__domains
def list_domains(self):
res = self.__process()
domains = {}
the_list = res.findall('.//img[@alt="edit"]')
the_list += res.findall('.//img[@alt="information"]')
for d in the_list:
info = d.findall('./../../td')
info = info[len(info) - 1].find('img')
domain_type = 'zone'
if d.get('menu') is not None:
domain_type = re.match(r'edit_(.*)', d.get('menu')).group(1)
else:
domain_type = re.search(r'menu=edit_([a-z]+)', d.get('onclick')).group(1)
domains[info.get('name')] = {
'domain': info.get('name'),
'id': info.get('value'),
'type': domain_type,
'records': None
}
return domains.values()
def get_record(self, domain, record_id):
records = self.cache_records(domain)
for r in records:
if r['id'] == record_id:
return r
raise HurricaneBadArgumentError('Record %s does not exist for domain "%s"' % (record_id, domain))
def get_records(self, domain, host, rtype=None, value=None, mx=None, ttl=None):
rtype = rtype.lower() if rtype else rtype
records = self.cache_records(domain)
results = []
for r in records:
if (r['host'] == host and
(rtype is None or r['type'].lower() == rtype) and
(value is None or r['value'] == value) and
(mx is None or r['mx'] == mx) and
(ttl is None or r['ttl'] == ttl)):
results.append(r)
return results
def cache_records(self, domain):
d = self.get_domain(domain)
if not d['records']:
d['records'] = self.list_records(domain)
return d['records']
def list_records(self, domain):
d = self.get_domain(domain)
records = []
if d['type'] == 'zone':
res = self.__process({
'hosted_dns_zoneid': d['id'],
'menu': 'edit_zone',
'hosted_dns_editzone': ''
})
# Drop the first row as it's actually headers...
rows = res.findall('.//div[@id="dns_main_content"]/table//tr')[1:]
for r in rows:
data = r.findall('td')
status = re.search(r'dns_tr_(.*)', r.get('class'))
if status:
status = status.group(1)
records.append({
'id': data[1].text,
'status': status,
'host': data[2].text,
'type': data[3].find('span').get('data'),
'ttl': data[4].text,
'mx': data[5].text,
'value': data[6].text,
'extended': data[6].get('data')
})
elif d['type'] == 'slave':
res = self.__process({
'domid': d['id'],
'menu': 'edit_slave',
'action': 'edit'
})
rows = res.findall('.//tr[@class="dns_tr"]')
records = [{
'id': r.get('id'),
'status': 'locked',
'host': r.findall('td')[0].text,
'type': r.findall('td')[1].text,
'ttl': r.findall('td')[2].text,
'mx': r.findall('td')[3].text,
'value': r.findall('td')[4].text
} for r in rows]
return records
def login(self, username, password, totp=None):
# Are we already logged in?
if self.__account is not None:
return True
# Get our CGISESSID cookie
self.__process()
# submit the login form
try:
res = self.__process({
'email': username,
'pass': password,
'submit': 'Login!'
})
except HurricaneError:
raise HurricaneAuthenticationError("Invalid Username/Password")
if res.find('.//input[@type="text"][@name="tfacode"]') is not None:
try:
res = self.__process({
'tfacode': totp,
'submit': 'Submit'
})
except HurricaneError:
raise HurricaneAuthenticationError("Invalid 2FA code")
account = res.find('.//input[@type="hidden"][@name="account"]').get('value')
if account:
self.__account = account
else:
raise HurricaneAuthenticationError('Login failure')
return True
def __process(self, data=None):
if isinstance(data, dict) or isinstance(data, list):
data = urlencode(data).encode("UTF-8")
with warnings.catch_warnings():
warnings.simplefilter("ignore")
res = html5lib.parse(self.__opener.open(HTTP_REQUEST_PATH, data),
namespaceHTMLElements=False, treebuilder="lxml")
error = res.find('.//div[@id="content"]/div/div[@id="dns_err"]')
if error is not None:
# This is not a real error...
if 'properly delegated' in error.text:
pass
elif 'record already exists' in error.text.lower():
pass
else:
raise HurricaneError(error.text)
return res