-
Notifications
You must be signed in to change notification settings - Fork 2
/
dnstap2passivedns.py
executable file
·339 lines (305 loc) · 11.8 KB
/
dnstap2passivedns.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
#!/usr/bin/env python3
#
# dnstap_reader
# written by Luca Memini (LDO-CERT) - [email protected]
# thx to Davide Arcuri
#
from __future__ import print_function
import io
import os
import sys
import socket
import argparse
import framestream
import ipaddress
import dns.message
import dns.rrset
#import dns.set
import shlex
#import dns.edns, dns.exception, dns.message, dns.name, dns.rdata, dns.rdataclass, dns.rdatatype, dns.rdtypes.ANY.NS, dns.rdtypes.IN.A, dns.rdtypes.IN.AAAA, dns.resolver, dns.rrset
import syslog
import logging
from dnstap_pb2 import Dnstap
from var_dump import var_dump
from daemonize import Daemonize
from datetime import datetime
connection = False
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write("error: %s\n" % message)
self.print_help()
print(
"Default mode parse only Client Response (CR),"
" use -v for show all dns query\n",
"\n",
)
sys.exit(2)
def print_mnemonics():
print(
"Quiet text output format mnemonics\n\n",
"Query Direction:\n",
" AQ: AUTH_QUERY (type: 1)\n",
" AR: AUTH_RESPONSE (type: 2)\n",
" RQ: RESOLVER_QUERY (type: 3)\n",
" RR: RESOLVER_RESPONSE (type: 4)\n",
" CQ: CLIENT_QUERY (type 5)\n",
" CR: CLIENT_RESPONSE (type: 6)\n",
" FQ: FORWARDER_QUERY (type: 7)\n",
" FR: FORWARDER_RESPONSE (type: 8)\n",
" SQ: STUB_QUERY (type: 9)\n",
" SR: STUB_RESPONSE (type: 10)\n",
" TQ: TOOL_QUERY (type: 11)\n",
" TR: TOOL_RESPONSE (type: 12)\n",
"\n",
"Flags description:\n",
" QR: Query Response\n",
" AA: Authoritative Answer\n",
" TT: Truncated Response\n",
" RD: Recursion Desired\n",
" RA: Recursion Avaible\n",
" AD: Authentic Data\n",
" CD: Checking Disabled\n",
"\n",
"RCODE description:\n",
" NOERROR = 0\n",
" FORMERR = 1\n",
" SERVFAIL = 2\n",
" NXDOMAIN = 3\n",
" NOTIMP = 4\n",
" REFUSED = 5\n",
" YXDOMAIN = 6\n",
" YXRRSET = 7\n",
" NXRRSET = 8\n",
" NOTAUTH = 9\n",
" NOTZONE = 10\n",
" BADVERS = 16",
"\n",
)
sys.exit(2)
def log_message(tosyslog, message):
if tosyslog:
syslog.syslog(message)
elif outfile:
logging.info(message)
else:
print(message)
def dnsflag_fromhex(n):
if n & int("0x8000", 16):
return "QR (Query Response)"
if n & int("0x0400", 16):
return "AA (Authoritative Answer)"
if n & int("0x0200", 16):
return "TT (Truncated Response)"
if n & int("0x0100", 16):
return "RD (Recursion Desired)"
if n & int("0x0080", 16):
return "RA (Recursion Avaible)"
if n & int("0x0020", 16):
return "AD (Authentic Data)"
if n & int("0x0010", 16):
return "CD (Checking Disabled)"
def get_query_direction(type):
switcher = {
1: "AQ",
2: "AR",
3: "RQ",
4: "RR",
5: "CQ",
6: "CR",
7: "FQ",
8: "FR",
9: "SQ",
10: "SR",
11: "TQ",
12: "TR",
}
return switcher.get(type, "unknown")
def parse_frame(frame):
dnstap_data = Dnstap()
dnstap_data.ParseFromString(frame)
# https://github.com/dnstap/dnstap.pb/blob/master/dnstap.proto read here!
msg_type = dnstap_data.message.type
if msg_type in [4, 6]: ## 6 CLIENT_RESPONSE - 4 RESOLVER_RESPONSE
query = dns.message.from_wire(dnstap_data.message.response_message)
if msg_type == 6 or (msg_type == 4 and verbose):
json_log = {
'timestamp': dnstap_data.message.response_time_sec,
'query_direction': get_query_direction(msg_type),
'query_address': ipaddress.ip_address(
dnstap_data.message.query_address
),
'query_port': dnstap_data.message.query_port,
'response_address': ipaddress.ip_address(
dnstap_data.message.response_address
),
'response_port': dnstap_data.message.response_port,
'query_id': query.id,
'rcode': dns.rcode.to_text(
dns.rcode.from_flags(query.flags, query.ednsflags)
),
'flags': dns.flags.to_text(query.flags),
'question':[],
'answers': [],
'authorities':[],
}
for question in query.question:
json_log['question'].append(str(question).replace("\n", " | "))
for answer in query.answer:
json_log['answers'].append(str(answer).replace("\n", " | "))
for auth in query.authority:
json_log['authorities'].append(str(auth).replace("\n", " | "))
if verbose:
log_message(tosyslog, json_log)
##timestamp||dns-client ||dns-server||RR class||Query||Query Type||Answer||TTL||Count
msg = "{timestamp}||{query_address}||{response_address}||".format(**json_log)
query_rcode = dns.rcode.from_flags(query.flags,query.ednsflags);
if query_rcode == 0:
for answer in query.answer:
for row in answer.to_text().split("\n"):
r=shlex.split(row)
#print(r) # ['hostupdate.vmware.com.', '14', 'IN', 'CNAME', 'shd-download.vmware.com.edgekey.net.']
if r[3] == 'SOA':
resp =r[2]+"||"+r[0]+"||"+r[3]+"||"+r[4]+"||"+r[-4]+"||"+str(query_rcode) ## use dns.rcode.to_text(query_rcode) to get string
else:
resp =r[2]+"||"+r[0]+"||"+r[3]+"||"+r[-1]+"||"+r[1]+"||"+str(query_rcode) ## use dns.rcode.to_text(query_rcode) to get string
log_message(tosyslog, msg+resp)
else: # RCODE != 0
for question in query.question:
for row in question.to_text().split("\n"):
r=shlex.split(row)
#print(r) #['shajhgajkghajkga.com.', 'IN', 'A']
resp =r[1]+"||"+r[0]+"||"+r[2]+"||""||""||"+str(query_rcode) ## use dns.rcode.to_text(query_rcode) to get string
log_message(tosyslog, msg+resp)
if msg_type == 6 and debug:
logging.debug(dnsflag_fromhex(query.flags))
logging.debug(query)
# OTHER QUERY
else:
if verbose:
query = dns.message.from_wire(dnstap_data.message.query_message)
msg = "{} {} {}:{} -> {}:{} Id: #{}".format(
dnstap_data.message.query_time_sec,
get_query_direction(msg_type),
ipaddress.ip_address(dnstap_data.message.query_address),
dnstap_data.message.query_port,
ipaddress.ip_address(dnstap_data.message.response_address),
dnstap_data.message.response_port,
query.id,
)
log_message(tosyslog, msg)
if debug:
query = dns.message.from_wire(dnstap_data.message.query_message)
log_message(tosyslog, query)
def handshake():
global connection
# Ok, I need Frame Streams handshake code here.
# https://www.nlnetlabs.nl/bugs-script/show_bug.cgi?id=741#c15
log_message(True, ">> Waiting READY FRAME")
data = connection.recv(262144)
log_message(True, "<< Sending ACCEPT FRAME")
connection.sendall(
b"\x00\x00\x00\x00\x00\x00\x00\x22\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x16\x70\x72\x6f\x74\x6f\x62\x75\x66\x3a\x64\x6e\x73\x74\x61\x70\x2e\x44\x6e\x73\x74\x61\x70"
)
log_message(True, ">> Waiting START FRAME")
data = connection.recv(262144)
start = data
return start
def main():
global connection
if socketfile:
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.bind(socketfile)
os.chmod(socketfile,666)
sock.listen(1)
while True:
connection, client_address = sock.accept()
log_message(tosyslog, "New incoming connection...")
try:
connection, client_address = sock.accept()
log_message(True, "New incoming connection...")
start = handshake()
if debug:
var_dump(data)
while True:
data = connection.recv(262144)
if data:
b = io.BytesIO(start + data)
if debug:
var_dump(b.read())
for frame in framestream.reader(b):
parse_frame(frame)
else:
log_message(tosyslog, "error error!!!")
finally:
# Clean up the connection
log_message(tosyslog, "connection lost")
connection.close()
finally:
log_message(tosyslog, "Closing socket")
sock.close()
os.unlink(socketfile)
if tosyslog:
syslog.closelog()
elif tapfile:
log_message(tosyslog, "Reading data from "+tapfile)
for frame in framestream.reader(open(tapfile, "rb")):
parse_frame(frame)
def SIGHUPrecived(signalNumber, frame):
log_message(tosyslog, "(SIGHUP) Restarting handshake")
return handshake()
if __name__ == "__main__":
signal.signal(signal.SIGHUP, SIGHUPrecived)
parser = MyParser(description="DNSTAP reader to passivedns log format")
parser.add_argument("-m", "--mnemonics",
action="store_true", help="Mnemonics datatype (help)")
parser.add_argument("-d", "--debug",
action="store_true", help="Debug mode")
parser.add_argument("-v", "--verbose",
action="store_true", help="Verbose mode")
logdest = parser.add_mutually_exclusive_group(required=False)
logdest.add_argument(
"-l",
"--to-syslog",
action="store_true",
help="Send output to syslog (demonize)",
)
logdest.add_argument(
"-o",
"--outfile",
action="store_true",
help="Send output to file (demonize)",
)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-f", "--file", help="file")
group.add_argument("-s", "--socket", help="socket")
args = parser.parse_args()
tapfile = args.file
debug = args.debug
verbose = args.verbose
socketfile = args.socket
tosyslog = args.to_syslog
outfile = args.outfile
mnemonics = args.mnemonics ## non funziona --todo
if mnemonics:
print_mnemonics()
if outfile:
logging.basicConfig(format='%(message)s', filename="dnstap.log", level=logging.INFO)
if tosyslog:
# Priority: LOG_EMERG, LOG_ALERT, LOG_CRIT,
# LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG.
# Facilities: LOG_KERN, LOG_USER, LOG_MAIL, LOG_DAEMON, LOG_AUTH,
# LOG_LPR, LOG_NEWS, LOG_UUCP, LOG_CRON, LOG_SYSLOG
# and LOG_LOCAL0 to LOG_LOCAL7.
# Options: LOG_PID, LOG_CONS, LOG_NDELAY, LOG_NOWAIT and LOG_PERROR
syslog.openlog(
"DNStap", logoption=syslog.LOG_PID, facility=syslog.LOG_DAEMON
)
pid = "/var/run/dnstap.pid"
daemon = Daemonize(app="DNStap", pid=pid,
action=main, auto_close_fds=True)
# ok, going in to darkness
# https://daemonize.readthedocs.io/en/latest/
daemon.start()
else:
main()