Debian Codegraph @

examples/send_notify.py

raw
1 #!/usr/bin/python
2 """
3 Minimalistic RFC 1996-like NOTIFY sender.
4 """
5 import argparse
6 import ipaddress
7 import socket
8
9 import dns.flags
10 import dns.inet
11 import dns.message
12 import dns.name
13 import dns.opcode
14 import dns.query
15 import dns.rdataclass
16 import dns.rdatatype
17 import dns.rrset
18
19
20 def main():
21 """Also prints all inputs and intermediate values"""
22 parser = argparse.ArgumentParser(
23 description="Send DNS NOTIFY mesage via UDP, optionally with synthetized SOA RR "
24 "in ANSWER section. No checks. It's not RFC 1996 sect 3.6 compliant sender."
25 )
26 parser.add_argument("--source", type=ipaddress.ip_address, help="source IP address")
27 parser.add_argument("--port", type=int, help="target port", default=53)
28 parser.add_argument("target", type=ipaddress.ip_address, help="target IP address")
29 parser.add_argument("zone", type=dns.name.from_text)
30 parser.add_argument(
31 "serial",
32 nargs="?",
33 type=int,
34 help="optional serial - adds SOA RR into ANSWER section",
35 )
36 parser.add_argument(
37 "--rdclass",
38 default=dns.rdataclass.IN,
39 type=dns.rdataclass.from_text,
40 help="DNS class, defaults to IN",
41 )
42 args = parser.parse_args()
43 if args.source:
44 if dns.inet.af_for_address(str(args.target)) != dns.inet.af_for_address(
45 str(args.source)
46 ):
47 parser.error("address family for source and target must be the same")
48
49 print(args)
50 msg = construct_msg(args)
51 print(msg)
52 udp_send(msg, args)
53
54
55 def construct_msg(args):
56 """if args.serial is specified it creates fake SOA RR with given serial"""
57 msg = dns.message.make_query(
58 args.zone, dns.rdatatype.SOA, rdclass=args.rdclass, flags=dns.flags.AA
59 )
60 msg.set_opcode(dns.opcode.NOTIFY)
61 if args.serial:
62 soa = dns.rrset.from_text_list(
63 name=args.zone,
64 ttl=0,
65 rdclass=args.rdclass,
66 rdtype=dns.rdatatype.SOA,
67 text_rdatas=[f". . {args.serial} 0 0 0 0"],
68 )
69 msg.answer.append(soa)
70 return msg
71
72
73 def udp_send(msg, args):
74 """ignores checks prescribed by RFC 1996 sect 3.6"""
75 afam = dns.inet.af_for_address(str(args.target))
76 sock = socket.socket(afam, socket.SOCK_DGRAM)
77 if args.source:
78 sock.bind((str(args.source), 0))
79 dns.query.send_udp(sock, what=msg, destination=(str(args.target), args.port))
80
81
82 if __name__ == "__main__":
83 main()