]>
gitweb.michael.orlitzky.com - djbdns-logparse.git/blob - bin/djbdns-logparse.py
3 Convert tinydns and dnscache logs to human-readable form
7 from struct
import pack
8 from subprocess
import Popen
, PIPE
9 from time
import strftime
, gmtime
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.
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
20 timestamp_pat
= r
'[\d-]+ [\d:\.]+'
22 # The regex to match dnscache log lines.
23 dnscache_log_re
= re
.compile(fr
'({timestamp_pat}) (\w+)(.*)')
25 # The "hex4" pattern matches a string of four hexadecimal digits. This
26 # is used, for example, by tinydns to encode the query type
28 hex4_pat
= r
'[0-9a-f]{4}'
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}'
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}) (.*)'
40 # A dictionary mapping query type identifiers, in decimal, to their
41 # friendly names for tinydns. Reference:
43 # https://en.wikipedia.org/wiki/List_of_DNS_record_types
45 # Note that mapping here is non-exhaustive, and that tinydns will
46 # log responses for record types that it does not know about.
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.
85 def convert_ip(ip
: str):
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.
94 >>> convert_ip("7f000001")
96 >>> convert_ip("00000000000000000000ffff7f000001")
97 '0000:0000:0000:0000:0000:ffff:7f00:0001'
101 # IPv4, eg. "7f000001" -> "7f 00 00 01" -> "127.0.0.1"
102 return ".".join(map(str, pack(">L", int(ip
, 16))))
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)])
108 def decode_client(words
, i
):
109 chunks
= words
[i
].split(":")
111 ip
= convert_ip(chunks
[0])
112 port
= int(chunks
[1], 16)
113 words
[i
] = f
"{ip}:{port}"
116 # For a "query" entry's clientip:clientport:id field.
117 id = int(chunks
[2], 16)
118 words
[i
] += f
" (id {id})"
120 def decode_ip(words
, i
):
121 words
[i
] = convert_ip(words
[i
])
123 def decode_ttl(words
, i
):
124 words
[i
] = f
"TTL={words[i]}"
126 def decode_serial(words
, i
):
127 serial
= int(words
[i
])
128 words
[i
] = f
"#{serial}"
130 def decode_type(words
, i
):
132 words
[i
] = query_type
.get(int(qt
), qt
)
134 def handle_dnscache_log(line
) -> typing
.Optional
[str]:
136 Handle a single log line if it matches the ``dnscache_log_re`` regex.
142 The log line that might match ``dnscache_log_re``.
147 Either the human-readable string if the log line was handled (that
148 is, if it was really a dnscache log line), or ``None`` if it was
154 >>> line = "2022-09-15 18:37:33.863805500 query 1 7f000001:a3db:4fb9 1 www.example.com."
155 >>> handle_dnscache_log(line)
156 '2022-09-15 18:37:33.863805500 query #1 127.0.0.1:41947 (id 20409) a www.example.com.'
158 >>> line = "2022-09-15 18:37:33.863874500 tx 0 1 www.example.com. . c0a80101"
159 >>> handle_dnscache_log(line)
160 '2022-09-15 18:37:33.863874500 tx g=0 a www.example.com. . 192.168.1.1'
162 >>> line = "2022-09-15 18:37:33.878529500 rr c0a80101 20865 1 www.example.com. 5db8d822"
163 >>> handle_dnscache_log(line)
164 '2022-09-15 18:37:33.878529500 rr 192.168.1.1 TTL=20865 a www.example.com. 93.184.216.34'
166 >>> line = "2022-09-15 18:37:33.878532500 stats 1 43 1 0"
167 >>> handle_dnscache_log(line)
168 '2022-09-15 18:37:33.878532500 stats count=1 motion=43 udp-active=1 tcp-active=0'
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'
174 >>> line = "this line is nonsense"
175 >>> handle_dnscache_log(line)
178 match
= dnscache_log_re
.match(line
)
182 (timestamp
, event
, data
) = match
.groups()
185 if event
== "cached":
186 if words
[0] not in ("cname", "ns", "nxdomain"):
187 decode_type(words
, 0)
189 elif event
== "drop":
190 decode_serial(words
, 0)
192 elif event
== "lame":
195 elif event
== "nodata":
198 decode_type(words
, 2)
200 elif event
== "nxdomain":
204 elif event
== "query":
205 decode_serial(words
, 0)
206 decode_client(words
, 1)
207 decode_type(words
, 2)
212 if words
[2] not in ("cname", "mx", "ns", "ptr", "soa"):
213 decode_type(words
, 2)
214 if words
[2] == "a": # decode answer to an A query
216 if words
[2] == "txt": # text record
218 if response
.endswith("..."):
220 response
= response
[0:-3]
223 length
= int(response
[0:2], 16)
225 for i
in range(1, len(response
)//2):
226 chars
.append(chr(int(response
[2*i
: (2*i
)+2], 16)))
228 words
[4] = f
"{length}:\"{txt}{ellipsis}\""
230 elif event
== "sent":
231 decode_serial(words
, 0)
233 elif event
== "stats":
234 words
[0] = f
"count={words[0]}"
235 words
[1] = f
"motion={words[1]}"
236 words
[2] = f
"udp-active={words[2]}"
237 words
[3] = f
"tcp-active={words[3]}"
240 words
[0] = f
"g={words[0]}"
241 decode_type(words
, 1)
243 # words[3] = control (domain for which these servers are believed
244 # to be authoritative)
245 for i
in range(4, len(words
)):
248 elif event
in ("tcpopen", "tcpclose"):
249 decode_client(words
, 0)
251 return f
"{timestamp} {event} " + " ".join(words
)
255 def handle_tinydns_log(line
: str) -> typing
.Optional
[str]:
257 Handle a single log line if it matches the ``tinydns_log_re`` regex.
263 The log line that might match ``tinydns_log_re``.
268 Either the human-readable string if the log line was handled (that
269 is, if it was really a tinydns log line), or ``None`` if it was
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'
279 >>> line = "this line is nonsense"
280 >>> handle_tinydns_log(line)
283 match
= tinydns_log_re
.match(line
)
287 (timestamp
, ip
, port
, id, code
, type, name
) = match
.groups()
292 # Convert the "type" field to a human-readable record type name
293 # using the query_type dictionary. If the right name isn't present
294 # in the dictionary, we use the (decimal) type id instead.
295 type = int(type, 16) # "001c" -> 28
296 type = query_type
.get(type, type) # 28 -> "aaaa"
298 line_tpl
= "{timestamp} "
300 reason
= query_drop_reason
[code
]
302 line_tpl
+= "sent response to {ip}:{port} (id {id}): {type} {name}"
304 line_tpl
+= "dropped query ({reason}) from {ip}:{port}"
306 # If the query can actually be parsed, the log line is a
307 # bit more informative than it would have been otherwise.
308 line_tpl
+= " (id {id}): {type} {name}"
310 return line_tpl
.format(timestamp
=timestamp
,
319 def parse_logfile(file : typing
.TextIO
):
321 Process a single log ``file``.
327 An open log file, or stdin.
332 >>> line = "@4000000063227a320c4f3114 7f000001:9d61:be69 - 0001 www.example.com\n"
333 >>> from tempfile import NamedTemporaryFile
334 >>> with NamedTemporaryFile(mode="w", delete=False) as f:
335 ... _ = f.write(line)
336 >>> f = open(f.name, 'r')
338 2022-09-14 21:04:40.206516500 dropped query (no authority) from 127.0.0.1:40289 (id 48745): a www.example.com
340 >>> from os import remove
344 # Open pipe to tai64nlocal: we will write lines of our input (the
345 # raw log file) to it, and read log lines with readable timestamps
347 tai
= Popen(["tai64nlocal"], stdin
=PIPE
, stdout
=PIPE
, text
=True, bufsize
=0)
350 tai
.stdin
.write(line
)
351 line
= tai
.stdout
.readline()
353 friendly_line
= handle_tinydns_log(line
)
354 if not friendly_line
:
355 friendly_line
= handle_dnscache_log(line
)
356 if not friendly_line
:
363 The entry point to the program.
365 This function is responsible only for parsing any command-line
366 arguments, and then calling :func`parse_logfile` on them.
368 # Create an argument parser using the file's docsctring as its
370 from argparse
import ArgumentParser
, FileType
371 parser
= ArgumentParser(description
= __doc__
)
373 # Parse zero or more positional arguments into a list of
374 # "logfiles". If none are given, read from stdin instead.
375 from sys
import stdin
376 parser
.add_argument("logfiles",
381 help="djbdns logfile to process (default: stdin)")
383 # Warning: argparse automatically opens its file arguments here,
384 # and they only get closed when the program terminates. There's no
385 # real benefit to closing them one-at-a-time after calling
386 # parse_logfile(), because the "scarce" resource of open file
387 # descriptors gets consumed immediately, before any processing has
388 # happened. In other words, if you're going to run out of file
389 # descriptors, it's going to happen right now.
391 # So anyway, don't run this on several million logfiles.
392 args
= parser
.parse_args()
393 for f
in args
.logfiles
:
397 if __name__
== "__main__":