blob: 04daab2f36141b173d7142a868b32df032393896 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001# Test the support for SSL and sockets
2
3import sys
4import unittest
5from test import test_support
6import socket
7import errno
8import threading
9import subprocess
10import time
11import os
12import pprint
13import urllib
14import shutil
15import traceback
16
17# Optionally test SSL support, if we have it in the tested platform
18skip_expected = False
19try:
20 import ssl
21except ImportError:
22 skip_expected = True
23
24CERTFILE = None
25
26
27def handle_error(prefix):
28 exc_format = ' '.join(traceback.format_exception(*sys.exc_info()))
29 sys.stdout.write(prefix + exc_format)
30
31
32class BasicTests(unittest.TestCase):
33
34 def testRudeShutdown(self):
35 # Some random port to connect to.
36 PORT = [9934]
37
38 listener_ready = threading.Event()
39 listener_gone = threading.Event()
40
41 # `listener` runs in a thread. It opens a socket listening on
42 # PORT, and sits in an accept() until the main thread connects.
43 # Then it rudely closes the socket, and sets Event `listener_gone`
44 # to let the main thread know the socket is gone.
45 def listener():
46 s = socket.socket()
47 PORT[0] = test_support.bind_port(s, '', PORT[0])
48 s.listen(5)
49 listener_ready.set()
50 s.accept()
51 s = None # reclaim the socket object, which also closes it
52 listener_gone.set()
53
54 def connector():
55 listener_ready.wait()
56 s = socket.socket()
57 s.connect(('localhost', PORT[0]))
58 listener_gone.wait()
59 try:
60 ssl_sock = socket.ssl(s)
61 except socket.sslerror:
62 pass
63 else:
64 raise test_support.TestFailed(
65 'connecting to closed SSL socket should have failed')
66
67 t = threading.Thread(target=listener)
68 t.start()
69 connector()
70 t.join()
71
72 def testSSLconnect(self):
73 import os
74 with test_support.transient_internet():
75 s = ssl.sslsocket(socket.socket(socket.AF_INET),
76 cert_reqs=ssl.CERT_NONE)
77 s.connect(("pop.gmail.com", 995))
78 c = s.getpeercert()
79 if c:
80 raise test_support.TestFailed("Peer cert %s shouldn't be here!")
81 s.close()
82
83 # this should fail because we have no verification certs
84 s = ssl.sslsocket(socket.socket(socket.AF_INET),
85 cert_reqs=ssl.CERT_REQUIRED)
86 try:
87 s.connect(("pop.gmail.com", 995))
88 except ssl.sslerror:
89 pass
90 finally:
91 s.close()
92
93class ConnectedTests(unittest.TestCase):
94
95 def testTLSecho (self):
96
97 s1 = socket.socket()
98 try:
99 s1.connect(('127.0.0.1', 10024))
100 except:
101 handle_error("connection failure:\n")
102 raise test_support.TestFailed("Can't connect to test server")
103 else:
104 try:
105 c1 = ssl.sslsocket(s1, ssl_version=ssl.PROTOCOL_TLSv1)
106 except:
107 handle_error("SSL handshake failure:\n")
108 raise test_support.TestFailed("Can't SSL-handshake with test server")
109 else:
110 if not c1:
111 raise test_support.TestFailed("Can't SSL-handshake with test server")
112 indata = "FOO\n"
113 c1.write(indata)
114 outdata = c1.read()
115 if outdata != indata.lower():
116 raise test_support.TestFailed("bad data <<%s>> received; expected <<%s>>\n" % (data, indata.lower()))
117 c1.close()
118
119 def testReadCert(self):
120
121 s2 = socket.socket()
122 try:
123 s2.connect(('127.0.0.1', 10024))
124 except:
125 handle_error("connection failure:\n")
126 raise test_support.TestFailed("Can't connect to test server")
127 else:
128 try:
129 c2 = ssl.sslsocket(s2, ssl_version=ssl.PROTOCOL_TLSv1,
130 cert_reqs=ssl.CERT_REQUIRED, ca_certs=CERTFILE)
131 except:
132 handle_error("SSL handshake failure:\n")
133 raise test_support.TestFailed("Can't SSL-handshake with test server")
134 else:
135 if not c2:
136 raise test_support.TestFailed("Can't SSL-handshake with test server")
137 cert = c2.getpeercert()
138 if not cert:
139 raise test_support.TestFailed("Can't get peer certificate.")
Thomas Wouters89d996e2007-09-08 17:39:28 +0000140 if test_support.verbose:
141 sys.stdout.write(pprint.pformat(cert) + '\n')
Thomas Woutersed03b412007-08-28 21:37:11 +0000142 if not cert.has_key('subject'):
143 raise test_support.TestFailed(
144 "No subject field in certificate: %s." %
145 pprint.pformat(cert))
Thomas Wouters89d996e2007-09-08 17:39:28 +0000146 if not ('organizationName', 'Python Software Foundation') in cert['subject']:
Thomas Woutersed03b412007-08-28 21:37:11 +0000147 raise test_support.TestFailed(
Thomas Wouters89d996e2007-09-08 17:39:28 +0000148 "Missing or invalid 'organizationName' field in certificate subject; "
Thomas Woutersed03b412007-08-28 21:37:11 +0000149 "should be 'Python Software Foundation'.");
150 c2.close()
151
152
153class ThreadedEchoServer(threading.Thread):
154
155 class ConnectionHandler(threading.Thread):
156
157 def __init__(self, server, connsock):
158 self.server = server
159 self.running = False
160 self.sock = connsock
161 threading.Thread.__init__(self)
162 self.setDaemon(True)
163
164 def run (self):
165 self.running = True
166 try:
167 sslconn = ssl.sslsocket(self.sock, server_side=True,
168 certfile=self.server.certificate,
169 ssl_version=self.server.protocol,
170 cert_reqs=self.server.certreqs)
171 except:
172 # here, we want to stop the server, because this shouldn't
173 # happen in the context of our test case
174 handle_error("Test server failure:\n")
175 self.running = False
176 # normally, we'd just stop here, but for the test
177 # harness, we want to stop the server
178 self.server.stop()
179 return
180
181 while self.running:
182 try:
183 msg = sslconn.read()
184 if not msg:
185 # eof, so quit this handler
186 self.running = False
187 sslconn.close()
188 elif msg.strip() == 'over':
189 sslconn.close()
190 self.server.stop()
191 self.running = False
192 else:
193 if test_support.verbose:
194 sys.stdout.write("\nserver: %s\n" % msg.strip().lower())
195 sslconn.write(msg.lower())
196 except ssl.sslerror:
197 handle_error("Test server failure:\n")
198 sslconn.close()
199 self.running = False
200 # normally, we'd just stop here, but for the test
201 # harness, we want to stop the server
202 self.server.stop()
203 except:
204 handle_error('')
205
206 def __init__(self, port, certificate, ssl_version=None,
207 certreqs=None, cacerts=None):
208 if ssl_version is None:
209 ssl_version = ssl.PROTOCOL_TLSv1
210 if certreqs is None:
211 certreqs = ssl.CERT_NONE
212 self.certificate = certificate
213 self.protocol = ssl_version
214 self.certreqs = certreqs
215 self.cacerts = cacerts
216 self.sock = socket.socket()
217 self.flag = None
218 if hasattr(socket, 'SO_REUSEADDR'):
219 self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
220 if hasattr(socket, 'SO_REUSEPORT'):
221 self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
222 self.sock.bind(('127.0.0.1', port))
223 self.active = False
224 threading.Thread.__init__(self)
225 self.setDaemon(False)
226
227 def start (self, flag=None):
228 self.flag = flag
229 threading.Thread.start(self)
230
231 def run (self):
232 self.sock.settimeout(0.5)
233 self.sock.listen(5)
234 self.active = True
235 if self.flag:
236 # signal an event
237 self.flag.set()
238 while self.active:
239 try:
240 newconn, connaddr = self.sock.accept()
241 if test_support.verbose:
242 sys.stdout.write('\nserver: new connection from ' + str(connaddr) + '\n')
243 handler = self.ConnectionHandler(self, newconn)
244 handler.start()
245 except socket.timeout:
246 pass
247 except KeyboardInterrupt:
248 self.stop()
249 except:
250 handle_error("Test server failure:\n")
251
252 def stop (self):
253 self.active = False
254 self.sock.close()
255
256CERTFILE_CONFIG_TEMPLATE = """
257# create RSA certs - Server
258
259[ req ]
260default_bits = 1024
261encrypt_key = yes
262distinguished_name = req_dn
263x509_extensions = cert_type
264
265[ req_dn ]
266countryName = Country Name (2 letter code)
267countryName_default = US
268countryName_min = 2
269countryName_max = 2
270
271stateOrProvinceName = State or Province Name (full name)
272stateOrProvinceName_default = %(state)s
273
274localityName = Locality Name (eg, city)
275localityName_default = %(city)s
276
2770.organizationName = Organization Name (eg, company)
2780.organizationName_default = %(organization)s
279
280organizationalUnitName = Organizational Unit Name (eg, section)
281organizationalUnitName_default = %(unit)s
282
2830.commonName = Common Name (FQDN of your server)
2840.commonName_default = %(common-name)s
285
286# To create a certificate for more than one name uncomment:
287# 1.commonName = DNS alias of your server
288# 2.commonName = DNS alias of your server
289# ...
290# See http://home.netscape.com/eng/security/ssl_2.0_certificate.html
291# to see how Netscape understands commonName.
292
293[ cert_type ]
294nsCertType = server
295"""
296
297def create_cert_files(hostname=None):
298
299 """This is the routine that was run to create the certificate
300 and private key contained in keycert.pem."""
301
302 import tempfile, socket, os
303 d = tempfile.mkdtemp()
304 # now create a configuration file for the CA signing cert
305 fqdn = hostname or socket.getfqdn()
306 crtfile = os.path.join(d, "cert.pem")
307 conffile = os.path.join(d, "ca.conf")
308 fp = open(conffile, "w")
309 fp.write(CERTFILE_CONFIG_TEMPLATE %
310 {'state': "Delaware",
311 'city': "Wilmington",
312 'organization': "Python Software Foundation",
313 'unit': "SSL",
314 'common-name': fqdn,
315 })
316 fp.close()
317 error = os.system(
318 "openssl req -batch -new -x509 -days 2000 -nodes -config %s "
319 "-keyout \"%s\" -out \"%s\" > /dev/null < /dev/null 2>&1" %
320 (conffile, crtfile, crtfile))
321 # now we have a self-signed server cert in crtfile
322 os.unlink(conffile)
323 if (os.WEXITSTATUS(error) or
324 not os.path.exists(crtfile) or os.path.getsize(crtfile) == 0):
325 if test_support.verbose:
326 sys.stdout.write("Unable to create certificate for test, "
327 + "error status %d\n" % (error >> 8))
328 crtfile = None
329 elif test_support.verbose:
330 sys.stdout.write(open(crtfile, 'r').read() + '\n')
331 return d, crtfile
332
333
334def test_main(verbose=False):
335 if skip_expected:
Thomas Wouters89d996e2007-09-08 17:39:28 +0000336 raise test_support.TestSkipped("No SSL support")
Thomas Woutersed03b412007-08-28 21:37:11 +0000337
Thomas Woutersed03b412007-08-28 21:37:11 +0000338 global CERTFILE
339 CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir,
340 "keycert.pem")
341 if not CERTFILE:
342 sys.__stdout__.write("Skipping test_ssl ConnectedTests; "
343 "couldn't create a certificate.\n")
344
345 tests = [BasicTests]
346
347 server = None
348 if CERTFILE and test_support.is_resource_enabled('network'):
349 server = ThreadedEchoServer(10024, CERTFILE)
350 flag = threading.Event()
351 server.start(flag)
352 # wait for it to start
353 flag.wait()
354 tests.append(ConnectedTests)
355
356 thread_info = test_support.threading_setup()
357
358 try:
359 test_support.run_unittest(*tests)
360 finally:
361 if server is not None and server.active:
362 server.stop()
363 # wait for it to stop
364 server.join()
365
366 test_support.threading_cleanup(*thread_info)
367
368if __name__ == "__main__":
369 test_main()