]> gitweb.michael.orlitzky.com - djbdns-logparse.git/blob - bin/djbdns-logparse.py
bin/djbdns-logparse.py: add .py extension and doctests for convert_ip().
[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
7 from struct import pack
8 from time import strftime, gmtime
9 from subprocess import Popen, PIPE
10
11
12 # common components of line-matching regexes
13 timestamp_pat = r'[\d-]+ [\d:\.]+' # output of tai64nlocal
14 hex4_pat = r'[0-9a-f]{4}'
15 ip_pat = r'[0-9a-f]{8,32}' # IPv4 or IPv6 addresses in hex
16
17 # discriminate between dnscache and tinydns log lines
18 tinydns_log_re = re.compile(
19 r'(%s) (%s):(%s):(%s) ([\+\-IC/]) (%s) (.*)'
20 % (timestamp_pat, ip_pat, hex4_pat, hex4_pat, hex4_pat))
21 dnscache_log_re = re.compile(r'(%s) (\w+)(.*)' % timestamp_pat)
22
23 query_type = {
24 1: "a",
25 2: "ns",
26 5: "cname",
27 6: "soa",
28 12: "ptr",
29 13: "hinfo",
30 15: "mx",
31 16: "txt",
32 17: "rp",
33 24: "sig",
34 25: "key",
35 28: "aaaa",
36 38: "a6",
37 252: "axfr",
38 255: "any",
39 }
40
41 # for tinydns only
42 query_drop_reason = {
43 "-": "no authority",
44 "I": "invalid query",
45 "C": "invalid class",
46 }
47
48
49 def convert_ip(ip : str):
50 """
51 Convert a hex string representing an IP address to conventional
52 human-readable form, ie. dotted-quad decimal for IPv4, and
53 8 colon-separated hex shorts for IPv6.
54
55 Examples
56 --------
57
58 >>> convert_ip("7f000001")
59 '127.0.0.1'
60 >>> convert_ip("00000000000000000000ffff7f000001")
61 '0000:0000:0000:0000:0000:ffff:7f00:0001'
62
63 """
64 if len(ip) == 8:
65 # IPv4, eg. "7f000001" -> "127.0.0.1"
66 return "%d.%d.%d.%d" % tuple(pack(">L", int(ip, 16)))
67 elif len(ip) == 32:
68 # IPv6 is actually simpler -- it's just a string-slicing operation,
69 # eg. "00000000000000000000ffff7f000001" ->
70 # "0000:0000:0000:0000:0000:ffff:7f00:0001"
71 return ":".join([ip[(4*i) : (4*i+4)] for i in range(8)])
72
73
74 def _cvt_ip(match):
75 return convert_ip(match.group(1))
76
77 def _cvt_port(match):
78 return ":" + str(int(match.group(1), 16))
79
80 def decode_client(words, i):
81 chunks = words[i].split(":")
82 if len(chunks) == 2: # ip:port
83 words[i] = "%s:%d" % (convert_ip(chunks[0]), int(chunks[1], 16))
84 elif len(chunks) == 3:
85 words[i] = "%s:%d (id %d)" % (convert_ip(chunks[0]),
86 int(chunks[1], 16),
87 int(chunks[2], 16))
88
89 def decode_ip(words, i):
90 words[i] = convert_ip(words[i])
91
92 def decode_ttl(words, i):
93 words[i] = "TTL=%s" % words[i]
94
95 def decode_serial(words, i):
96 serial = int(words[i])
97 words[i] = "#%d" % serial
98
99 def decode_type(words, i):
100 qt = words[i]
101 words[i] = query_type.get(int(qt), qt)
102
103 def handle_dnscache_log(line, match):
104 (timestamp, event, data) = match.groups()
105
106 words = data.split()
107 if event == "cached":
108 if words[0] not in ("cname", "ns", "nxdomain"):
109 decode_type(words, 0)
110
111 elif event == "drop":
112 decode_serial(words, 0)
113
114 elif event == "lame":
115 decode_ip(words, 0)
116
117 elif event == "nodata":
118 decode_ip(words, 0)
119 decode_ttl(words, 1)
120 decode_type(words, 2)
121
122 elif event == "nxdomain":
123 decode_ip(words, 0)
124 decode_ttl(words, 1)
125
126 elif event == "query":
127 decode_serial(words, 0)
128 decode_client(words, 1)
129 decode_type(words, 2)
130
131 elif event == "rr":
132 decode_ip(words, 0)
133 decode_ttl(words, 1)
134 if words[2] not in ("cname", "mx", "ns", "ptr", "soa"):
135 decode_type(words, 2)
136 if words[2] == "a": # decode answer to an A query
137 decode_ip(words, 4)
138 if words[2] == "txt": # text record
139 response = words[4]
140 if response.endswith("..."):
141 ellipsis = "..."
142 response = response[0:-3]
143 else:
144 ellipsis = ""
145 length = int(response[0:2], 16)
146 chars = []
147 for i in range(1, len(response)/2):
148 chars.append(chr(int(response[2*i : (2*i)+2], 16)))
149 words[4] = "%d:\"%s%s\"" % (length, "".join(chars), ellipsis)
150
151 elif event == "sent":
152 decode_serial(words, 0)
153
154 elif event == "stats":
155 words[0] = "count=%s" % words[0]
156 words[1] = "motion=%s" % words[1]
157 words[2] = "udp-active=%s" % words[2]
158 words[3] = "tcp-active=%s" % words[3]
159
160 elif event == "tx":
161 words[0] = "g=%s" % words[0]
162 decode_type(words, 1)
163 # words[2] = name
164 # words[3] = control (domain for which these servers are believed
165 # to be authoritative)
166 for i in range(4, len(words)):
167 decode_ip(words, i)
168
169 elif event in ("tcpopen", "tcpclose"):
170 decode_client(words, 0)
171
172 print(timestamp, event, " ".join(words))
173
174
175 def handle_tinydns_log(line, match):
176 (timestamp, ip, port, id, code, type, name) = match.groups()
177 ip = convert_ip(ip)
178 port = int(port, 16)
179 id = int(id, 16)
180 type = int(type, 16) # "001c" -> 28
181 type = query_type.get(type, type) # 28 -> "aaaa"
182
183 print(timestamp, end=' ')
184
185 if code == "+":
186 print ("sent response to %s:%s (id %s): %s %s"
187 % (ip, port, id, type, name))
188 elif code in ("-", "I", "C"):
189 reason = query_drop_reason[code]
190 print ("dropped query (%s) from %s:%s (id %s): %s %s"
191 % (reason, ip, port, id, type, name))
192 elif code == "/":
193 print ("dropped query (couldn't parse) from %s:%s"
194 % (ip, port))
195 else:
196 print ("%s from %s:%s (id %s): %s %s"
197 % (code, ip, port, id, type, name))
198
199
200 def parse_logfile(file):
201 # Open pipe to tai64nlocal: we will write lines of our input (the
202 # raw log file) to it, and read log lines with readable timestamps
203 # from it.
204 tai = Popen(["tai64nlocal"], stdin=PIPE, stdout=PIPE, text=True, bufsize=0)
205
206 for line in file:
207 tai.stdin.write(line)
208 line = tai.stdout.readline()
209
210 match = tinydns_log_re.match(line)
211 if match:
212 handle_tinydns_log(line, match)
213 continue
214
215 match = dnscache_log_re.match(line)
216 if match:
217 handle_dnscache_log(line, match)
218 continue
219
220 print(line)
221
222 def main():
223 # Create an argument parser using the file's docsctring as its
224 # description.
225 from argparse import ArgumentParser, FileType
226 parser = ArgumentParser(description = __doc__)
227
228 # Parse zero or more positional arguments into a list of
229 # "logfiles". If none are given, read from stdin instead.
230 from sys import stdin
231 parser.add_argument("logfiles",
232 metavar="LOGFILE",
233 type=FileType("r"),
234 nargs="*",
235 default=[stdin],
236 help="djbdns logfile to process (default: stdin)")
237
238 args = parser.parse_args()
239 for f in args.logfiles:
240 parse_logfile(f)
241
242
243
244
245 if __name__ == "__main__":
246 main()