]> gitweb.michael.orlitzky.com - djbdns-logparse.git/blob - bin/djbdns-logparse.py
97182b677c6fe2ff40f854159d7e25b73495a06a
[djbdns-logparse.git] / bin / djbdns-logparse.py
1 #!/usr/bin/python3
2 """
3 Convert tinydns and dnscache logs to human-readable form
4 """
5
6 import re, typing
7 from struct import pack
8 from time import strftime, gmtime
9 from subprocess import Popen, PIPE
10
11
12 ## Regular expressions for matching tinydns/dnscache log lines. We
13 ## compile these once here rather than within the corresponding
14 ## matching functions, because the latter get executed repeatedly.
15
16 # This first pattern is used to match the timestamp format that the
17 # tai64nlocal program produces. It appears in both dnscache and
18 # tinydns lines, after they've been piped through tai64nlocal, of
19 # course.
20 timestamp_pat = r'[\d-]+ [\d:\.]+'
21
22 # The regex to match dnscache log lines.
23 dnscache_log_re = re.compile(fr'({timestamp_pat}) (\w+)(.*)')
24
25 # The "hex4" pattern matches a string of four hexadecimal digits. This
26 # is used, for example, by tinydns to encode the query type
27 # identifier.
28 hex4_pat = r'[0-9a-f]{4}'
29
30 # The IP pattern matches a string of either 8 or 32 hexadecimal
31 # characters, which correspond to IPv4 and IPv6 addresses,
32 # respectively, in tinydns logs.
33 ip_pat = r'[0-9a-f]{8,32}'
34
35 # The regex to match tinydns log lines.
36 tinydns_log_re = re.compile(
37 rf'({timestamp_pat}) ({ip_pat}):({hex4_pat}):({hex4_pat}) ([\+\-IC/]) ({hex4_pat}) (.*)'
38 )
39
40 # A dictionary mapping query type identifiers, in decimal, to their
41 # friendly names for tinydns. Reference:
42 #
43 # https://en.wikipedia.org/wiki/List_of_DNS_record_types
44 #
45 # Note that mapping here is non-exhaustive, and that tinydns will
46 # log responses for record types that it does not know about.
47 query_type = {
48 1: "a",
49 2: "ns",
50 5: "cname",
51 6: "soa",
52 12: "ptr",
53 13: "hinfo",
54 15: "mx",
55 16: "txt",
56 17: "rp",
57 24: "sig",
58 25: "key",
59 28: "aaaa",
60 33: "srv",
61 35: "naptr",
62 38: "a6",
63 48: "dnskey",
64 52: "tlsa",
65 65: "https",
66 252: "axfr",
67 255: "any",
68 257: "caa"
69 }
70
71 # tinydns can drop a query for one of three reasons; this dictionary
72 # maps the symbol that gets logged in each case to a human-readable
73 # reason. We include the "+" case here, indicating that the query was
74 # NOT dropped, to avoid a special case later on when we're formatting
75 # the human-readable output.
76 query_drop_reason = {
77 "+": None,
78 "-": "no authority",
79 "I": "invalid query",
80 "C": "invalid class",
81 "/": "couldn't parse"
82 }
83
84
85 def convert_ip(ip : str):
86 """
87 Convert a hex string representing an IP address to conventional
88 human-readable form, ie. dotted-quad decimal for IPv4, and
89 8 colon-separated hex shorts for IPv6.
90
91 Examples
92 --------
93
94 >>> convert_ip("7f000001")
95 '127.0.0.1'
96 >>> convert_ip("00000000000000000000ffff7f000001")
97 '0000:0000:0000:0000:0000:ffff:7f00:0001'
98
99 """
100 if len(ip) == 8:
101 # IPv4, eg. "7f000001" -> "7f 00 00 01" -> "127.0.0.1"
102 return "%d.%d.%d.%d" % tuple(pack(">L", int(ip, 16)))
103 elif len(ip) == 32:
104 # IPv6 is actually simpler -- it's just a string-slicing operation.
105 return ":".join([ip[(4*i) : (4*i+4)] for i in range(8)])
106
107
108 def decode_client(words, i):
109 chunks = words[i].split(":")
110 if len(chunks) == 2: # ip:port
111 words[i] = "%s:%d" % (convert_ip(chunks[0]), int(chunks[1], 16))
112 elif len(chunks) == 3:
113 words[i] = "%s:%d (id %d)" % (convert_ip(chunks[0]),
114 int(chunks[1], 16),
115 int(chunks[2], 16))
116
117 def decode_ip(words, i):
118 words[i] = convert_ip(words[i])
119
120 def decode_ttl(words, i):
121 words[i] = "TTL=%s" % words[i]
122
123 def decode_serial(words, i):
124 serial = int(words[i])
125 words[i] = "#%d" % serial
126
127 def decode_type(words, i):
128 qt = words[i]
129 words[i] = query_type.get(int(qt), qt)
130
131 def handle_dnscache_log(line) -> bool:
132 """
133 Handle a single log line if it matches the ``dnscache_log_re`` regex.
134
135 Parameters
136 ----------
137
138 line : string
139 The log line that might match ``dnscache_log_re``.
140
141 Returns
142 -------
143
144 ``True`` if the log line was handled (that is, if it was really a
145 dnscache log line), and ``False`` otherwise.
146
147 Examples
148 --------
149
150 >>> line = "2022-09-15 18:37:33.863805500 query 1 7f000001:a3db:4fb9 1 www.example.com."
151 >>> handle_dnscache_log(line)
152 2022-09-15 18:37:33.863805500 query #1 127.0.0.1:41947 (id 20409) a www.example.com.
153 True
154
155 >>> line = "2022-09-15 18:37:33.863874500 tx 0 1 www.example.com. . c0a80101"
156 >>> handle_dnscache_log(line)
157 2022-09-15 18:37:33.863874500 tx g=0 a www.example.com. . 192.168.1.1
158 True
159
160 >>> line = "2022-09-15 18:37:33.878529500 rr c0a80101 20865 1 www.example.com. 5db8d822"
161 >>> handle_dnscache_log(line)
162 2022-09-15 18:37:33.878529500 rr 192.168.1.1 TTL=20865 a www.example.com. 93.184.216.34
163 True
164
165 >>> line = "2022-09-15 18:37:33.878532500 stats 1 43 1 0"
166 >>> handle_dnscache_log(line)
167 2022-09-15 18:37:33.878532500 stats count=1 motion=43 udp-active=1 tcp-active=0
168 True
169
170 >>> line = "2022-09-15 18:37:33.878602500 sent 1 49"
171 >>> handle_dnscache_log(line)
172 2022-09-15 18:37:33.878602500 sent #1 49
173 True
174
175 >>> line = "this line is nonsense"
176 >>> handle_dnscache_log(line)
177 False
178
179 """
180 match = dnscache_log_re.match(line)
181 if not match:
182 return False
183
184 (timestamp, event, data) = match.groups()
185
186 words = data.split()
187 if event == "cached":
188 if words[0] not in ("cname", "ns", "nxdomain"):
189 decode_type(words, 0)
190
191 elif event == "drop":
192 decode_serial(words, 0)
193
194 elif event == "lame":
195 decode_ip(words, 0)
196
197 elif event == "nodata":
198 decode_ip(words, 0)
199 decode_ttl(words, 1)
200 decode_type(words, 2)
201
202 elif event == "nxdomain":
203 decode_ip(words, 0)
204 decode_ttl(words, 1)
205
206 elif event == "query":
207 decode_serial(words, 0)
208 decode_client(words, 1)
209 decode_type(words, 2)
210
211 elif event == "rr":
212 decode_ip(words, 0)
213 decode_ttl(words, 1)
214 if words[2] not in ("cname", "mx", "ns", "ptr", "soa"):
215 decode_type(words, 2)
216 if words[2] == "a": # decode answer to an A query
217 decode_ip(words, 4)
218 if words[2] == "txt": # text record
219 response = words[4]
220 if response.endswith("..."):
221 ellipsis = "..."
222 response = response[0:-3]
223 else:
224 ellipsis = ""
225 length = int(response[0:2], 16)
226 chars = []
227 for i in range(1, len(response)/2):
228 chars.append(chr(int(response[2*i : (2*i)+2], 16)))
229 words[4] = "%d:\"%s%s\"" % (length, "".join(chars), ellipsis)
230
231 elif event == "sent":
232 decode_serial(words, 0)
233
234 elif event == "stats":
235 words[0] = "count=%s" % words[0]
236 words[1] = "motion=%s" % words[1]
237 words[2] = "udp-active=%s" % words[2]
238 words[3] = "tcp-active=%s" % words[3]
239
240 elif event == "tx":
241 words[0] = "g=%s" % words[0]
242 decode_type(words, 1)
243 # words[2] = name
244 # words[3] = control (domain for which these servers are believed
245 # to be authoritative)
246 for i in range(4, len(words)):
247 decode_ip(words, i)
248
249 elif event in ("tcpopen", "tcpclose"):
250 decode_client(words, 0)
251
252 print(timestamp, event, " ".join(words))
253 return True
254
255
256 def handle_tinydns_log(line : str) -> bool:
257 """
258 Handle a single log line if it matches the ``tinydns_log_re`` regex.
259
260 Parameters
261 ----------
262
263 line : string
264 The log line that might match ``tinydns_log_re``.
265
266 Returns
267 -------
268
269 ``True`` if the log line was handled (that is, if it was really a
270 tinydns log line), and ``False`` otherwise.
271
272 Examples
273 --------
274
275 >>> line = "2022-09-14 21:04:40.206516500 7f000001:9d61:be69 - 0001 www.example.com"
276 >>> handle_tinydns_log(line)
277 2022-09-14 21:04:40.206516500 dropped query (no authority) from 127.0.0.1:40289 (id 48745): a www.example.com
278 True
279
280 >>> line = "this line is nonsense"
281 >>> handle_tinydns_log(line)
282 False
283
284 """
285 match = tinydns_log_re.match(line)
286 if not match:
287 return False
288
289 (timestamp, ip, port, id, code, type, name) = match.groups()
290 ip = convert_ip(ip)
291 port = int(port, 16)
292 id = int(id, 16)
293
294 # Convert the "type" field to a human-readable record type name
295 # using the query_type dictionary. If the right name isn't present
296 # in the dictionary, we use the (decimal) type id instead.
297 type = int(type, 16) # "001c" -> 28
298 type = query_type.get(type, type) # 28 -> "aaaa"
299
300 print(timestamp, end=' ')
301
302 reason = query_drop_reason[code]
303 if code == "+":
304 line_tpl = "sent response to {ip}:{port} (id {id}): {type} {name}"
305 else:
306 line_tpl = "dropped query ({reason}) from {ip}:{port}"
307 if code != "/":
308 # If the query can actually be parsed, the log line is a
309 # bit more informative than it would have been otherwise.
310 line_tpl += " (id {id}): {type} {name}"
311
312 print(line_tpl.format(reason=reason,
313 ip=ip,
314 port=port,
315 id=id,
316 type=type,
317 name=name))
318 return True
319
320
321 def parse_logfile(file : typing.TextIO):
322 r"""
323 Process a single log ``file``.
324
325 Parameters
326 ----------
327
328 file : typing.TextIO
329 An open log file, or stdin.
330
331 Examples
332 --------
333
334 >>> line = "@4000000063227a320c4f3114 7f000001:9d61:be69 - 0001 www.example.com\n"
335 >>> from tempfile import NamedTemporaryFile
336 >>> with NamedTemporaryFile(mode="w", delete=False) as f:
337 ... _ = f.write(line)
338 >>> f = open(f.name, 'r')
339 >>> parse_logfile(f)
340 2022-09-14 21:04:40.206516500 dropped query (no authority) from 127.0.0.1:40289 (id 48745): a www.example.com
341 >>> f.close()
342 >>> from os import remove
343 >>> remove(f.name)
344
345 """
346 # Open pipe to tai64nlocal: we will write lines of our input (the
347 # raw log file) to it, and read log lines with readable timestamps
348 # from it.
349 tai = Popen(["tai64nlocal"], stdin=PIPE, stdout=PIPE, text=True, bufsize=0)
350
351 for line in file:
352 tai.stdin.write(line)
353 line = tai.stdout.readline()
354
355 if not handle_tinydns_log(line):
356 if not handle_dnscache_log(line):
357 print(line, end='')
358
359 def main():
360 r"""
361 The entry point to the program.
362
363 This function is responsible only for parsing any command-line
364 arguments, and then calling :func`parse_logfile` on them.
365 """
366 # Create an argument parser using the file's docsctring as its
367 # description.
368 from argparse import ArgumentParser, FileType
369 parser = ArgumentParser(description = __doc__)
370
371 # Parse zero or more positional arguments into a list of
372 # "logfiles". If none are given, read from stdin instead.
373 from sys import stdin
374 parser.add_argument("logfiles",
375 metavar="LOGFILE",
376 type=FileType("r"),
377 nargs="*",
378 default=[stdin],
379 help="djbdns logfile to process (default: stdin)")
380
381 # Warning: argparse automatically opens its file arguments here,
382 # and they only get closed when the program terminates. There's no
383 # real benefit to closing them one-at-a-time after calling
384 # parse_logfile(), because the "scarce" resource of open file
385 # descriptors gets consumed immediately, before any processing has
386 # happened. In other words, if you're going to run out of file
387 # descriptors, it's going to happen right now.
388 #
389 # So anyway, don't run this on several million logfiles.
390 args = parser.parse_args()
391 for f in args.logfiles:
392 parse_logfile(f)
393
394
395 if __name__ == "__main__":
396 main()