]> gitweb.michael.orlitzky.com - djbdns-logparse.git/blob - bin/djbdns-logparse.py
e6a6759ad2f3fa73aeb41053731e0c08d9f72d9e
[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 subprocess import Popen, PIPE
9 from time import strftime, gmtime
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) -> str:
86 """
87 Convert a hex string representing an IP address to
88 human-readable form.
89
90 Parameters
91 ----------
92
93 ip : str
94 The hexadecimal representation of either an IPv4 or an IPv6
95 address.
96
97 Returns
98 -------
99
100 The usual decimal dotted-quad representation is returned for an
101 IPv4 address. IPv6 addresses are returned almost as-is, but with
102 colons inserted in the appropriate places, between every four
103 characters.
104
105 Examples
106 --------
107
108 >>> convert_ip("7f000001")
109 '127.0.0.1'
110 >>> convert_ip("00000000000000000000ffff7f000001")
111 '0000:0000:0000:0000:0000:ffff:7f00:0001'
112 """
113 if len(ip) == 8:
114 # IPv4, eg. "7f000001" -> "7f 00 00 01" -> "127.0.0.1"
115 return ".".join(map(str, pack(">L", int(ip, 16))))
116 elif len(ip) == 32:
117 # IPv6 is actually simpler -- it's just a string-slicing operation.
118 return ":".join([ip[(4*i) : (4*i+4)] for i in range(8)])
119
120
121 def decode_client(words : list, i : int):
122 r"""
123 Helper function to decode the client field in a dnscache log
124 entry.
125
126 There are two possible formats for the client field,
127
128 1. clientip:clientport, used by tcpopen/tcpclose entries,
129 2. clientip:clientport:id, used by "query" entries.
130
131 Parameters
132 ----------
133
134 words : list
135 The ``words`` list (a list of fields) from
136 :func:`handle_dnscache_log`.
137
138 i : int
139 The index of the client field within ``words``
140
141 Returns
142 -------
143
144 Nothing; the ``i``th entry in the ``words`` list is modified
145 in-place.
146
147 Examples
148 --------
149
150 >>> words = ["foo", "bar", "7f000001:9253", "quux"]
151 >>> decode_client(words, 2)
152 >>> words
153 ['foo', 'bar', '127.0.0.1:37459', 'quux']
154
155 >>> words = ["foo", "7f000001:a3db:4fb9", "bar", "quux"]
156 >>> decode_client(words, 1)
157 >>> words
158 ['foo', '127.0.0.1:41947 (id 20409)', 'bar', 'quux']
159
160 """
161 chunks = words[i].split(":")
162
163 ip = convert_ip(chunks[0])
164 port = int(chunks[1], 16)
165 words[i] = f"{ip}:{port}"
166
167 if len(chunks) == 3:
168 # For a "query" entry's clientip:clientport:id field.
169 id = int(chunks[2], 16)
170 words[i] += f" (id {id})"
171
172 def decode_ip(words, i):
173 words[i] = convert_ip(words[i])
174
175 def decode_ttl(words, i):
176 words[i] = f"TTL={words[i]}"
177
178 def decode_serial(words, i):
179 serial = int(words[i])
180 words[i] = f"#{serial}"
181
182 def decode_type(words, i):
183 qt = words[i]
184 words[i] = query_type.get(int(qt), qt)
185
186 def handle_dnscache_log(line) -> typing.Optional[str]:
187 """
188 Handle a single log line if it matches the ``dnscache_log_re`` regex.
189
190 Parameters
191 ----------
192
193 line : string
194 The log line that might match ``dnscache_log_re``.
195
196 Returns
197 -------
198
199 Either the human-readable string if the log line was handled (that
200 is, if it was really a dnscache log line), or ``None`` if it was
201 not.
202
203 Examples
204 --------
205
206 >>> line = "2022-09-15 18:37:33.863805500 query 1 7f000001:a3db:4fb9 1 www.example.com."
207 >>> handle_dnscache_log(line)
208 '2022-09-15 18:37:33.863805500 query #1 127.0.0.1:41947 (id 20409) a www.example.com.'
209
210 >>> line = "2022-09-15 18:37:33.863874500 tx 0 1 www.example.com. . c0a80101"
211 >>> handle_dnscache_log(line)
212 '2022-09-15 18:37:33.863874500 tx g=0 a www.example.com. . 192.168.1.1'
213
214 >>> line = "2022-09-15 18:37:33.878529500 rr c0a80101 20865 1 www.example.com. 5db8d822"
215 >>> handle_dnscache_log(line)
216 '2022-09-15 18:37:33.878529500 rr 192.168.1.1 TTL=20865 a www.example.com. 93.184.216.34'
217
218 >>> line = "2022-09-15 18:37:33.878532500 stats 1 43 1 0"
219 >>> handle_dnscache_log(line)
220 '2022-09-15 18:37:33.878532500 stats count=1 motion=43 udp-active=1 tcp-active=0'
221
222 >>> line = "2022-09-15 18:37:33.878602500 sent 1 49"
223 >>> handle_dnscache_log(line)
224 '2022-09-15 18:37:33.878602500 sent #1 49'
225
226 >>> line = "this line is nonsense"
227 >>> handle_dnscache_log(line)
228
229 """
230 match = dnscache_log_re.match(line)
231 if not match:
232 return None
233
234 (timestamp, event, data) = match.groups()
235
236 words = data.split()
237 if event == "cached":
238 if words[0] not in ("cname", "ns", "nxdomain"):
239 decode_type(words, 0)
240
241 elif event == "drop":
242 decode_serial(words, 0)
243
244 elif event == "lame":
245 decode_ip(words, 0)
246
247 elif event == "nodata":
248 decode_ip(words, 0)
249 decode_ttl(words, 1)
250 decode_type(words, 2)
251
252 elif event == "nxdomain":
253 decode_ip(words, 0)
254 decode_ttl(words, 1)
255
256 elif event == "query":
257 decode_serial(words, 0)
258 decode_client(words, 1)
259 decode_type(words, 2)
260
261 elif event == "rr":
262 decode_ip(words, 0)
263 decode_ttl(words, 1)
264 if words[2] not in ("cname", "mx", "ns", "ptr", "soa"):
265 decode_type(words, 2)
266 if words[2] == "a": # decode answer to an A query
267 decode_ip(words, 4)
268 if words[2] == "txt": # text record
269 response = words[4]
270 if response.endswith("..."):
271 ellipsis = "..."
272 response = response[0:-3]
273 else:
274 ellipsis = ""
275 length = int(response[0:2], 16)
276 chars = []
277 for i in range(1, len(response)//2):
278 chars.append(chr(int(response[2*i : (2*i)+2], 16)))
279 txt = "".join(chars)
280 words[4] = f"{length}:\"{txt}{ellipsis}\""
281
282 elif event == "sent":
283 decode_serial(words, 0)
284
285 elif event == "stats":
286 words[0] = f"count={words[0]}"
287 words[1] = f"motion={words[1]}"
288 words[2] = f"udp-active={words[2]}"
289 words[3] = f"tcp-active={words[3]}"
290
291 elif event == "tx":
292 words[0] = f"g={words[0]}"
293 decode_type(words, 1)
294 # words[2] = name
295 # words[3] = control (domain for which these servers are believed
296 # to be authoritative)
297 for i in range(4, len(words)):
298 decode_ip(words, i)
299
300 elif event in ("tcpopen", "tcpclose"):
301 decode_client(words, 0)
302
303 return f"{timestamp} {event} " + " ".join(words)
304
305
306
307 def handle_tinydns_log(line : str) -> typing.Optional[str]:
308 """
309 Handle a single log line if it matches the ``tinydns_log_re`` regex.
310
311 Parameters
312 ----------
313
314 line : string
315 The log line that might match ``tinydns_log_re``.
316
317 Returns
318 -------
319
320 Either the human-readable string if the log line was handled (that
321 is, if it was really a tinydns log line), or ``None`` if it was
322 not.
323
324 Examples
325 --------
326
327 >>> line = "2022-09-14 21:04:40.206516500 7f000001:9d61:be69 - 0001 www.example.com"
328 >>> handle_tinydns_log(line)
329 '2022-09-14 21:04:40.206516500 dropped query (no authority) from 127.0.0.1:40289 (id 48745): a www.example.com'
330
331 >>> line = "this line is nonsense"
332 >>> handle_tinydns_log(line)
333
334 """
335 match = tinydns_log_re.match(line)
336 if not match:
337 return None
338
339 (timestamp, ip, port, id, code, type, name) = match.groups()
340 ip = convert_ip(ip)
341 port = int(port, 16)
342 id = int(id, 16)
343
344 # Convert the "type" field to a human-readable record type name
345 # using the query_type dictionary. If the right name isn't present
346 # in the dictionary, we use the (decimal) type id instead.
347 type = int(type, 16) # "001c" -> 28
348 type = query_type.get(type, type) # 28 -> "aaaa"
349
350 line_tpl = "{timestamp} "
351
352 reason = query_drop_reason[code]
353 if code == "+":
354 line_tpl += "sent response to {ip}:{port} (id {id}): {type} {name}"
355 else:
356 line_tpl += "dropped query ({reason}) from {ip}:{port}"
357 if code != "/":
358 # If the query can actually be parsed, the log line is a
359 # bit more informative than it would have been otherwise.
360 line_tpl += " (id {id}): {type} {name}"
361
362 return line_tpl.format(timestamp=timestamp,
363 reason=reason,
364 ip=ip,
365 port=port,
366 id=id,
367 type=type,
368 name=name)
369
370
371 def parse_logfile(file : typing.TextIO):
372 r"""
373 Process a single log ``file``.
374
375 Parameters
376 ----------
377
378 file : typing.TextIO
379 An open log file, or stdin.
380
381 Examples
382 --------
383
384 >>> line = "@4000000063227a320c4f3114 7f000001:9d61:be69 - 0001 www.example.com\n"
385 >>> from tempfile import NamedTemporaryFile
386 >>> with NamedTemporaryFile(mode="w", delete=False) as f:
387 ... _ = f.write(line)
388 >>> f = open(f.name, 'r')
389 >>> parse_logfile(f)
390 2022-09-14 21:04:40.206516500 dropped query (no authority) from 127.0.0.1:40289 (id 48745): a www.example.com
391 >>> f.close()
392 >>> from os import remove
393 >>> remove(f.name)
394
395 """
396 # Open pipe to tai64nlocal: we will write lines of our input (the
397 # raw log file) to it, and read log lines with readable timestamps
398 # from it.
399 tai = Popen(["tai64nlocal"], stdin=PIPE, stdout=PIPE, text=True, bufsize=0)
400
401 for line in file:
402 tai.stdin.write(line)
403 line = tai.stdout.readline()
404
405 friendly_line = handle_tinydns_log(line)
406 if not friendly_line:
407 friendly_line = handle_dnscache_log(line)
408 if not friendly_line:
409 friendly_line = line
410
411 print(friendly_line)
412
413 def main():
414 r"""
415 The entry point to the program.
416
417 This function is responsible only for parsing any command-line
418 arguments, and then calling :func`parse_logfile` on them.
419 """
420 # Create an argument parser using the file's docsctring as its
421 # description.
422 from argparse import ArgumentParser, FileType
423 parser = ArgumentParser(description = __doc__)
424
425 # Parse zero or more positional arguments into a list of
426 # "logfiles". If none are given, read from stdin instead.
427 from sys import stdin
428 parser.add_argument("logfiles",
429 metavar="LOGFILE",
430 type=FileType("r"),
431 nargs="*",
432 default=[stdin],
433 help="djbdns logfile to process (default: stdin)")
434
435 # Warning: argparse automatically opens its file arguments here,
436 # and they only get closed when the program terminates. There's no
437 # real benefit to closing them one-at-a-time after calling
438 # parse_logfile(), because the "scarce" resource of open file
439 # descriptors gets consumed immediately, before any processing has
440 # happened. In other words, if you're going to run out of file
441 # descriptors, it's going to happen right now.
442 #
443 # So anyway, don't run this on several million logfiles.
444 args = parser.parse_args()
445 for f in args.logfiles:
446 parse_logfile(f)
447
448
449 if __name__ == "__main__":
450 main()