-
Notifications
You must be signed in to change notification settings - Fork 25
/
dnsdb_query.py
executable file
·328 lines (276 loc) · 10.8 KB
/
dnsdb_query.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
#!/usr/bin/env python
# Copyright (c) 2013 by Farsight Security, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import calendar
import errno
import locale
import optparse
import os
import re
import sys
import time
import urllib
import urllib2
from cStringIO import StringIO
try:
import json
except ImportError:
import simplejson as json
DEFAULT_CONFIG_FILES = filter(os.path.isfile, ('/etc/dnsdb-query.conf', os.path.expanduser('~/.dnsdb-query.conf')))
DEFAULT_DNSDB_SERVER = 'https://api.dnsdb.info'
DEFAULT_HTTP_PROXY = ''
DEFAULT_HTTPS_PROXY = ''
cfg = None
options = None
debug = False # set to True to print raw queries and responses
locale.setlocale(locale.LC_ALL, '')
class QueryError(Exception):
pass
class DnsdbClient(object):
def __init__(self, server, apikey, limit=None, http_proxy=None, https_proxy=None):
self.server = server
self.apikey = apikey
self.limit = limit
self.http_proxy = http_proxy
self.https_proxy = https_proxy
def query_rrset(self, oname, rrtype=None, bailiwick=None, before=None, after=None):
if bailiwick:
if not rrtype:
rrtype = 'ANY'
path = 'rrset/name/%s/%s/%s' % (quote(oname), rrtype, quote(bailiwick))
elif rrtype:
path = 'rrset/name/%s/%s' % (quote(oname), rrtype)
else:
path = 'rrset/name/%s' % quote(oname)
return self._query(path, before, after)
def query_rdata_name(self, rdata_name, rrtype=None, before=None, after=None):
if rrtype:
path = 'rdata/name/%s/%s' % (quote(rdata_name), rrtype)
else:
path = 'rdata/name/%s' % quote(rdata_name)
return self._query(path, before, after)
def query_rdata_ip(self, rdata_ip, before=None, after=None):
path = 'rdata/ip/%s' % rdata_ip.replace('/', ',')
return self._query(path, before, after)
def _query(self, path, before=None, after=None):
res = []
url = '%s/lookup/%s' % (self.server, path)
params = {}
if self.limit:
params['limit'] = self.limit
if before and after:
params['time_first_after'] = after
params['time_last_before'] = before
else:
if before:
params['time_first_before'] = before
if after:
params['time_last_after'] = after
if params:
url += '?{0}'.format(urllib.urlencode(params))
req = urllib2.Request(url)
req.add_header('Accept', 'application/json')
req.add_header('X-Api-Key', self.apikey)
proxy_args = {}
if self.http_proxy:
proxy_args['http'] = self.http_proxy
if self.https_proxy:
proxy_args['https'] = self.https_proxy
proxy_handler = urllib2.ProxyHandler(proxy_args)
opener = urllib2.build_opener(proxy_handler)
if debug:
print >>sys.stderr, ";; query URL =", url
try:
http = opener.open(req)
while True:
line = http.readline()
if not line:
break
if debug:
print >>sys.stderr, ";; response =", line.strip()
yield json.loads(line)
except (urllib2.HTTPError, urllib2.URLError), e:
raise QueryError, str(e), sys.exc_traceback
def quote(path):
return urllib.quote(path, safe='')
def sec_to_text(ts):
return time.strftime('%Y-%m-%d %H:%M:%S -0000', time.gmtime(ts))
def rrset_to_text(m):
s = StringIO()
try:
if 'bailiwick' in m:
s.write(';; bailiwick: %s\n' % m['bailiwick'])
if 'count' in m:
s.write(';; count: %s\n' % locale.format('%d', m['count'], True))
if 'time_first' in m:
s.write(';; first seen: %s\n' % sec_to_text(m['time_first']))
if 'time_last' in m:
s.write(';; last seen: %s\n' % sec_to_text(m['time_last']))
if 'zone_time_first' in m:
s.write(';; first seen in zone file: %s\n' % sec_to_text(m['zone_time_first']))
if 'zone_time_last' in m:
s.write(';; last seen in zone file: %s\n' % sec_to_text(m['zone_time_last']))
if 'rdata' in m:
for rdata in m['rdata']:
s.write('%s IN %s %s\n' % (m['rrname'], m['rrtype'], rdata))
s.seek(0)
return s.read()
finally:
s.close()
def rdata_to_text(m):
return '%s IN %s %s' % (m['rrname'], m['rrtype'], m['rdata'])
def parse_config(cfg_files):
config = {}
if not cfg_files:
raise IOError(errno.ENOENT, 'dnsdb_query: No config files found')
for fname in cfg_files:
for line in open(fname):
key, eq, val = line.strip().partition('=')
val = val.strip('"')
config[key] = val
return config
def time_parse(s):
try:
epoch = int(s)
return epoch
except ValueError:
pass
try:
epoch = int(calendar.timegm(time.strptime(s, '%Y-%m-%d')))
return epoch
except ValueError:
pass
try:
epoch = int(calendar.timegm(time.strptime(s, '%Y-%m-%d %H:%M:%S')))
return epoch
except ValueError:
pass
m = re.match(r'^(?=\d)(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?$', s, re.I)
if m:
return -1*(int(m.group(1) or 0)*604800 + \
int(m.group(2) or 0)*86400+ \
int(m.group(3) or 0)*3600+ \
int(m.group(4) or 0)*60+ \
int(m.group(5) or 0))
raise ValueError('Invalid time: "%s"' % s)
def epipe_wrapper(func):
def f(*args, **kwargs):
try:
return func(*args, **kwargs)
except IOError as e:
if e.errno == errno.EPIPE:
sys.exit(e.errno)
raise
return f
@epipe_wrapper
def main():
global cfg
global options
global debug
parser = optparse.OptionParser(epilog='Time formats are: "%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%d" (UNIX timestamp), "-%d" (Relative time in seconds), BIND format (e.g. 1w1h, (w)eek, (d)ay, (h)our, (m)inute, (s)econd)')
parser.add_option('-c', '--config', dest='config',
help='config file', action='append')
parser.add_option('-r', '--rrset', dest='rrset', type='string',
help='rrset <ONAME>[/<RRTYPE>[/BAILIWICK]]')
parser.add_option('-n', '--rdataname', dest='rdata_name', type='string',
help='rdata name <NAME>[/<RRTYPE>]')
parser.add_option('-i', '--rdataip', dest='rdata_ip', type='string',
help='rdata ip <IPADDRESS|IPRANGE|IPNETWORK>')
parser.add_option('-t', '--rrtype', dest='rrtype', type='string',
help='rrset or rdata rrtype')
parser.add_option('-b', '--bailiwick', dest='bailiwick', type='string',
help='rrset bailiwick')
parser.add_option('-s', '--sort', dest='sort', type='string', help='sort key')
parser.add_option('-R', '--reverse', dest='reverse', action='store_true', default=False,
help='reverse sort')
parser.add_option('-j', '--json', dest='json', action='store_true', default=False,
help='output in JSON format')
parser.add_option('-l', '--limit', dest='limit', type='int', default=0,
help='limit number of results')
parser.add_option('-d', '--debug', dest='debug', action='store_true', default=False,
help='print debug output')
parser.add_option('', '--before', dest='before', type='string', help='only output results seen before this time')
parser.add_option('', '--after', dest='after', type='string', help='only output results seen after this time')
options, args = parser.parse_args()
if args:
parser.print_help()
sys.exit(1)
debug = options.debug
try:
if options.before:
options.before = time_parse(options.before)
except ValueError, e:
print 'Could not parse before: {}'.format(options.before)
try:
if options.after:
options.after = time_parse(options.after)
except ValueError, e:
print 'Could not parse after: {}'.format(options.after)
try:
cfg = parse_config(options.config or DEFAULT_CONFIG_FILES)
except IOError, e:
print >>sys.stderr, str(e)
sys.exit(1)
if not 'DNSDB_SERVER' in cfg:
cfg['DNSDB_SERVER'] = DEFAULT_DNSDB_SERVER
if not 'HTTP_PROXY' in cfg:
cfg['HTTP_PROXY'] = DEFAULT_HTTP_PROXY
if not 'HTTPS_PROXY' in cfg:
cfg['HTTPS_PROXY'] = DEFAULT_HTTPS_PROXY
if not 'APIKEY' in cfg:
sys.stderr.write('dnsdb_query: APIKEY not defined in config file\n')
sys.exit(1)
client = DnsdbClient(cfg['DNSDB_SERVER'], cfg['APIKEY'],
limit=options.limit,
http_proxy=cfg['HTTP_PROXY'],
https_proxy=cfg['HTTPS_PROXY'])
if options.rrset:
if options.rrtype or options.bailiwick:
qargs = (options.rrset, options.rrtype, options.bailiwick)
else:
qargs = (options.rrset.split('/', 2))
results = client.query_rrset(*qargs, before=options.before, after=options.after)
fmt_func = rrset_to_text
elif options.rdata_name:
if options.rrtype:
qargs = (options.rdata_name, options.rrtype)
else:
qargs = (options.rdata_name.split('/', 1))
results = client.query_rdata_name(*qargs, before=options.before, after=options.after)
fmt_func = rdata_to_text
elif options.rdata_ip:
results = client.query_rdata_ip(options.rdata_ip, before=options.before, after=options.after)
fmt_func = rdata_to_text
else:
parser.print_help()
sys.exit(1)
if options.json:
fmt_func = json.dumps
try:
if options.sort:
results = list(results)
if len(results) > 0:
if not options.sort in results[0]:
sort_keys = results[0].keys()
sort_keys.sort()
sys.stderr.write('dnsdb_query: invalid sort key "%s". valid sort keys are %s\n' % (options.sort, ', '.join(sort_keys)))
sys.exit(1)
results.sort(key=lambda r: r[options.sort], reverse=options.reverse)
for res in results:
sys.stdout.write('%s\n' % fmt_func(res))
except QueryError, e:
print >>sys.stderr, e.message
sys.exit(1)
if __name__ == '__main__':
main()