-
Notifications
You must be signed in to change notification settings - Fork 11
/
dnsreceiver.py
99 lines (73 loc) · 2.44 KB
/
dnsreceiver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/python
import socket
import struct
DNS_QUERY_SECTION_FORMAT = struct.Struct("!2H")
DNS_QUERY_MESSAGE_HEADER = struct.Struct("!6H")
def decode_question_section(message, offset, qdcount):
questions = []
for _ in range(qdcount):
qname, offset = decode_labels(message, offset)
qtype, qclass = DNS_QUERY_SECTION_FORMAT.unpack_from(message, offset)
offset += DNS_QUERY_SECTION_FORMAT.size
question = {"domain_name": qname, "query_type": qtype, "query_class": qclass}
questions.append(question)
return questions, offset
def decode_labels(message, offset):
labels = []
while True:
(length,) = struct.unpack_from("!B", message, offset)
if (length & 0xC0) == 0xC0:
(pointer,) = struct.unpack_from("!H", message, offset)
offset += 2
return labels + decode_labels(message, pointer & 0x3FFF), offset
if (length & 0xC0) != 0x00:
raise Exception("unknown label encoding")
offset += 1
if length == 0:
return labels, offset
labels.append(*struct.unpack_from("!%ds" % length, message, offset))
offset += length
def decode_dns_message(message):
id, misc, qdcount, ancount, nscount, arcount = DNS_QUERY_MESSAGE_HEADER.unpack_from(
message
)
qr = (misc & 0x8000) != 0
opcode = (misc & 0x7800) >> 11
aa = (misc & 0x0400) != 0
tc = (misc & 0x200) != 0
rd = (misc & 0x100) != 0
ra = (misc & 0x80) != 0
z = (misc & 0x70) >> 4
rcode = misc & 0xF
offset = DNS_QUERY_MESSAGE_HEADER.size
questions, offset = decode_question_section(message, offset, qdcount)
return {
"id": id,
"is_response": qr,
"opcode": opcode,
"is_authoritative": aa,
"is_truncated": tc,
"recursion_desired": rd,
"recursion_available": ra,
"reserved": z,
"response_code": rcode,
"question_count": qdcount,
"answer_count": ancount,
"authority_count": nscount,
"additional_count": arcount,
"questions": questions,
}
def save(data):
with open("output.txt", "a") as fp:
fp.write(data + "\n")
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = ""
port = 53
size = 512
s.bind((host, port))
while True:
data, addr = s.recvfrom(size)
ret = decode_dns_message(data)
strlog = str({"addr": addr, "message": ret})
save(strlog)
print(strlog)