homer.py 8.13 KB
Newer Older
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
1
2
3
4
5
6
7
8
#!/usr/bin/env python3

# http://pycurl.io/docs/latest
import pycurl

# http://www.dnspython.org/
import dns.message

9
10
11
12
13
# Octobre 2019: the Python GnuTLS bindings don't work with Python 3. So we use OpenSSL.
# https://www.pyopenssl.org/
# https://pyopenssl.readthedocs.io/
import OpenSSL

Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
14
15
16
17
18
19
import io
import sys
import base64
import getopt
import urllib.parse
import time
20
21
import socket
import ctypes
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
22

23
# Values that can be changed from the command line
24
dot = False # DoH by default
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
25
26
27
28
29
30
post = False
verbose = False
insecure = False
head = False
rtype = 'AAAA'
tests = 1 # Number of repeated tests
31
ifile = None # Input file
32
delay = None
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
33
34
35
36
37
38
39
40
41
42
43
44

def error(msg=None):
    if msg is None:
        msg = "Unknown error"
    print(msg,file=sys.stderr)
    sys.exit(1)
    
def usage(msg=None):
    if msg:
        print(msg,file=sys.stderr)
    print("Usage: %s [-P] [-k] url domain-name [DNS type]" % sys.argv[0], file=sys.stderr)

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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
class Connection:
    def __init__(self, server, dot=False, verbose=verbose, insecure=insecure, post=post, head=head):
        # TODO test that server is a hostname is dot is True and an URL otherwise?
        self.server = server
        self.dot = dot
        if not self.dot:
            self.post = post
            self.head = head
        self.verbose = verbose
        self.insecure = insecure
        if self.dot:
            # TODO family-independant sockets
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            # With typical DoT servers, we *must* use TLS 1.2 (otherwise,
            # do_handshake fails with "OpenSSL.SSL.SysCallError: (-1, 'Unexpected
            # EOF')" Typical HTTP servers are more lax.
            self.context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD)
            self.session = OpenSSL.SSL.Connection(self.context, self.sock)
            self.session.connect((self.server, 853)) 
            self.session.do_handshake()
            # TODO is certificate checked by default? If yes, disable it if insecure
            self.cert = self.session.get_peer_certificate()
        else: # DoH
            self.curl = pycurl.Curl()
            self.url = server
            # Does not work if pycurl was not compiled with nghttp2 (recent Debian
            # packages are OK) https://github.com/pycurl/pycurl/issues/477
            self.curl.setopt(pycurl.HTTP_VERSION, pycurl.CURL_HTTP_VERSION_2)
            self.curl.setopt(pycurl.HTTPHEADER, ["Content-type: application/dns-message"])
            if self.verbose:
                self.curl.setopt(self.curl.VERBOSE, True)
            if self.insecure:
                self.curl.setopt(pycurl.SSL_VERIFYPEER, False)   
                self.curl.setopt(pycurl.SSL_VERIFYHOST, False)
            if self.head:
                self.curl.setopt(pycurl.NOBODY, True)
            if self.post:
                 self.curl.setopt(pycurl.POST, True)
    def __str__(self):
        return self.server
    def end(self):
        if self.dot:
            self.session.shutdown()
            self.session.close()
        else: # DoH
            self.curl.close()
            
# Routine doing one actual test. Returns a tuple, first member is a
# result (boolean for DoT, HTTP status code for DoH), second member is
# a DNS message (or a string if there is an error).
def do_test(connection, qname, qtype=rtype):
    print("Test of \"%s\" to %s" % (qname, connection))
    message = dns.message.make_query(qname, dns.rdatatype.from_text(qtype))
    if connection.dot:
        # TODO Check what the Query ID is. Really random?
        messagew = message.to_wire() 
        length = len(messagew)
        n = connection.session.send(length.to_bytes(2, byteorder='big') + messagew)
        buf = connection.session.recv(2) 
        received = int.from_bytes(buf, byteorder='big')
        buf = connection.session.recv(received)
        response = dns.message.from_wire(buf) # TODO check the Query ID
        return (True, response)
    else: # DoH
        message.id = 0 # DoH requests that
        if connection.post:
            data = message.to_wire()
            connection.curl.setopt(pycurl.POSTFIELDS, data)
        else:
            dns_req = base64.urlsafe_b64encode(message.to_wire()).decode('UTF8').rstrip('=')
            connection.curl.setopt(connection.curl.URL, connection.server + ("?dns=%s" % dns_req))
        buffer = io.BytesIO()
        connection.curl.setopt(connection.curl.WRITEDATA, buffer)
        connection.curl.perform()
        rcode = connection.curl.getinfo(pycurl.RESPONSE_CODE)
        ok = True
        if rcode == 200:
            if not head:
                body = buffer.getvalue()
                try:
                    response = dns.message.from_wire(body)
                except dns.message.TrailingJunk: # Not DNS. 
                    response = "ERROR Not proper DNS data \"%s\"" % body
                    ok = False
            else:
                response = "HEAD successful"
        else:
            body =  buffer.getvalue()
            if len(body) == 0:
                body = b"[No details]"
                ok = False
        buffer.close()
        return (rcode, response)
    
139
140
141
# Main program
name = None
message = None
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
142
try:
143
144
    optlist, args = getopt.getopt (sys.argv[1:], "hvPker:f:d:t",
                                   ["help", "verbose", "dot", "head", "insecure", "POST", "repeat=", "file=", "delay="])
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
145
146
147
148
149
150
151
152
    for option, value in optlist:
        if option == "--help" or option == "-h":
            usage()
            sys.exit(0)
        elif option == "--verbose" or option == "-v":
            verbose = True
        elif option == "--head" or option == "-e":
            head = True
153
154
        elif option == "--dot" or option == "-t":
            dot = True
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
155
156
157
158
159
160
161
162
        elif option == "--insecure" or option == "-k":
            insecure = True
        elif option == "--POST" or option == "-P":
            post = True
        elif option == "--repeat" or option == "-r":
            tests = int(value)
            if tests <= 1:
                error("--repeat needs a value > 1")
163
164
165
166
        elif option == "--delay" or option == "-d":
            delay = float(value)
            if delay <= 0:
                error("--delay needs a value > 0")
167
168
        elif option == "--file" or option == "-f":
            ifile = value
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
169
170
171
172
173
        else:
            error("Unknown option %s" % option)
except getopt.error as reason:
    usage(reason)
    sys.exit(1)
174
175
if tests <= 1 and delay is not None:
    error("--delay makes no sense if there is no repetition")
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
176
177
178
if post and head:
    usage("POST or HEAD but not both")
    sys.exit(1)
179
180
181
if dot and (post or head):
    usage("POST or HEAD makes non sense for DoT")
    sys.exit(1)    
182
if ifile is None and (len(args) != 2 and len(args) != 3):
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
183
184
    usage("Wrong number of arguments")
    sys.exit(1)
185
186
187
if ifile is not None and len(args) != 1:
    usage("Wrong number of arguments (if --file is used, do not indicate the domain name)")
    sys.exit(1)
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
188
url = args[0]
189
190
191
192
if ifile is None:
    name = args[1]
    if len(args) == 3:
        rtype = args[2]
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
193
ok = True
194
195
conn = Connection(url, dot=dot)
start = time.time() 
196
197
if ifile is not None:
    input = open(ifile)
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
198
for i in range (0, tests):
199
200
201
202
203
204
205
206
207
208
209
    if tests > 1:
        print("\nTest %i" % i)
    if ifile is not None:
        line = input.readline()
        if line[:-1] == "":
            error("Not enough data in %s for the %i tests" % (ifile, tests))
        if line.find(' ') == -1:
            name = line[:-1]
            rtype = 'AAAA'
        else:
            (name, rtype) = line.split()
210
211
212
    (rcode, msg) = do_test(conn, name, rtype)
    if (dot and rcode) or (not dot and rcode == 200):
        print(msg)
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
213
    else:
214
215
216
217
        if dot:
            print("Error: %s" % msg, file=sys.stderr)
        else:
            print("HTTP error %i: %s" % (rcode, msg), file=sys.stderr)
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
218
        ok = False
219
220
    if tests > 1 and i == 0:
        start2 = time.time()
221
222
    if delay is not None:
        time.sleep(delay)
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
223
stop = time.time()
224
225
226
227
228
229
230
if tests > 1:
    extra = ", %.2f ms/request if we ignore the first one" % ((stop-start2)*1000/(tests-1))
else:
    extra = ""
print("\nTotal elapsed time: %.2f seconds (%.2f ms/request %s)" % (stop-start, (stop-start)*1000/tests, extra))
if ifile is not None:
    input.close()
231
conn.end()
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
232
233
234
235
236
if ok:
    sys.exit(0)
else:
    sys.exit(1)