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