blob: 4f9e47c25da1c0ce053a2ac04220667eeba05ee6 [file] [log] [blame]
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +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 string
16import traceback
17
18# Optionally test SSL support, if we have it in the tested platform
19skip_expected = False
20try:
21 import ssl
22except ImportError:
23 skip_expected = True
24
25CERTFILE = None
26GMAIL_POP_CERTFILE = None
27
28class BasicTests(unittest.TestCase):
29
30 def testRudeShutdown(self):
31 # Some random port to connect to.
32 PORT = [9934]
33
34 listener_ready = threading.Event()
35 listener_gone = threading.Event()
36
37 # `listener` runs in a thread. It opens a socket listening on
38 # PORT, and sits in an accept() until the main thread connects.
39 # Then it rudely closes the socket, and sets Event `listener_gone`
40 # to let the main thread know the socket is gone.
41 def listener():
42 s = socket.socket()
43 PORT[0] = test_support.bind_port(s, '', PORT[0])
44 s.listen(5)
45 listener_ready.set()
46 s.accept()
47 s = None # reclaim the socket object, which also closes it
48 listener_gone.set()
49
50 def connector():
51 listener_ready.wait()
52 s = socket.socket()
53 s.connect(('localhost', PORT[0]))
54 listener_gone.wait()
55 try:
56 ssl_sock = socket.ssl(s)
57 except socket.sslerror:
58 pass
59 else:
60 raise test_support.TestFailed(
61 'connecting to closed SSL socket should have failed')
62
63 t = threading.Thread(target=listener)
64 t.start()
65 connector()
66 t.join()
67
68 def testSSLconnect(self):
69 import os
70 with test_support.transient_internet():
71 s = ssl.sslsocket(socket.socket(socket.AF_INET),
72 cert_reqs=ssl.CERT_NONE)
73 s.connect(("pop.gmail.com", 995))
74 c = s.getpeercert()
75 if c:
76 raise test_support.TestFailed("Peer cert %s shouldn't be here!")
77 s.close()
78
79 # this should fail because we have no verification certs
80 s = ssl.sslsocket(socket.socket(socket.AF_INET),
81 cert_reqs=ssl.CERT_REQUIRED)
82 try:
83 s.connect(("pop.gmail.com", 995))
84 except ssl.sslerror:
85 pass
86 finally:
87 s.close()
88
89class ConnectedTests(unittest.TestCase):
90
91 def testTLSecho (self):
92
93 s1 = socket.socket()
94 s1.connect(('127.0.0.1', 10024))
95 c1 = ssl.sslsocket(s1, ssl_version=ssl.PROTOCOL_TLSv1)
96 indata = "FOO\n"
97 c1.write(indata)
98 outdata = c1.read()
99 if outdata != indata.lower():
100 sys.stderr.write("bad data <<%s>> received\n" % data)
101 c1.close()
102
103 def testReadCert(self):
104
105 s2 = socket.socket()
106 s2.connect(('127.0.0.1', 10024))
107 c2 = ssl.sslsocket(s2, ssl_version=ssl.PROTOCOL_TLSv1,
108 cert_reqs=ssl.CERT_REQUIRED, ca_certs=CERTFILE)
109 cert = c2.getpeercert()
110 if not cert:
111 raise test_support.TestFailed("Can't get peer certificate.")
112 if not cert.has_key('subject'):
113 raise test_support.TestFailed(
114 "No subject field in certificate: %s." %
115 pprint.pformat(cert))
116 if not (cert['subject'].has_key('organizationName')):
117 raise test_support.TestFailed(
118 "No 'organizationName' field in certificate subject: %s." %
119 pprint.pformat(cert))
120 if (cert['subject']['organizationName'] !=
121 "Python Software Foundation"):
122 raise test_support.TestFailed(
123 "Invalid 'organizationName' field in certificate subject; "
124 "should be 'Python Software Foundation'.");
125 c2.close()
126
127
128class threadedEchoServer(threading.Thread):
129
130 class connectionHandler(threading.Thread):
131
132 def __init__(self, server, connsock):
133 self.server = server
134 self.running = False
135 self.sock = connsock
136 threading.Thread.__init__(self)
137 self.setDaemon(True)
138
139 def run (self):
140 self.running = True
141 sslconn = ssl.sslsocket(self.sock, server_side=True,
142 certfile=self.server.certificate,
143 ssl_version=self.server.protocol,
144 cert_reqs=self.server.certreqs)
145 while self.running:
146 try:
147 msg = sslconn.read()
148 if not msg:
149 # eof, so quit this handler
150 self.running = False
151 sslconn.close()
152 elif msg.strip() == 'over':
153 sslconn.close()
154 self.server.stop()
155 self.running = False
156 else:
157 # print "server:", msg.strip().lower()
158 sslconn.write(msg.lower())
159 except ssl.sslerror:
160 sys.stderr.write(string.join(
161 traceback.format_exception(*sys.exc_info())))
162 sslconn.close()
163 self.running = False
164 except:
165 sys.stderr.write(string.join(
166 traceback.format_exception(*sys.exc_info())))
167
Neal Norwitzce7fa562007-08-25 16:54:38 +0000168 def __init__(self, port, certificate, ssl_version=None,
169 certreqs=None, cacerts=None):
170 if ssl_version is None:
171 ssl_version = ssl.PROTOCOL_TLSv1
172 if certreqs is None:
173 certreqs = ssl.CERT_NONE
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000174 self.certificate = certificate
175 self.protocol = ssl_version
176 self.certreqs = certreqs
177 self.cacerts = cacerts
178 self.sock = socket.socket()
Neal Norwitz8e58b342007-08-25 17:25:17 +0000179 if hasattr(socket, 'SO_REUSEADDR'):
180 self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
181 if hasattr(socket, 'SO_REUSEPORT'):
182 self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000183 self.sock.bind(('127.0.0.1', port))
184 self.active = False
185 threading.Thread.__init__(self)
186 self.setDaemon(False)
187
188 def run (self):
189 self.sock.settimeout(0.5)
190 self.sock.listen(5)
191 self.active = True
192 while self.active:
193 try:
194 newconn, connaddr = self.sock.accept()
195 # sys.stderr.write('new connection from ' + str(connaddr))
196 handler = self.connectionHandler(self, newconn)
197 handler.start()
198 except socket.timeout:
199 pass
200 except KeyboardInterrupt:
201 self.active = False
202 except:
203 sys.stderr.write(string.join(
204 traceback.format_exception(*sys.exc_info())))
205
206 def stop (self):
207 self.active = False
208
209
210CERTFILE_CONFIG_TEMPLATE = """
211# create RSA certs - Server
212
213[ req ]
214default_bits = 1024
215encrypt_key = yes
216distinguished_name = req_dn
217x509_extensions = cert_type
218
219[ req_dn ]
220countryName = Country Name (2 letter code)
221countryName_default = US
222countryName_min = 2
223countryName_max = 2
224
225stateOrProvinceName = State or Province Name (full name)
226stateOrProvinceName_default = %(state)s
227
228localityName = Locality Name (eg, city)
229localityName_default = %(city)s
230
2310.organizationName = Organization Name (eg, company)
2320.organizationName_default = %(organization)s
233
234organizationalUnitName = Organizational Unit Name (eg, section)
235organizationalUnitName_default = %(unit)s
236
2370.commonName = Common Name (FQDN of your server)
2380.commonName_default = %(common-name)s
239
240# To create a certificate for more than one name uncomment:
241# 1.commonName = DNS alias of your server
242# 2.commonName = DNS alias of your server
243# ...
244# See http://home.netscape.com/eng/security/ssl_2.0_certificate.html
245# to see how Netscape understands commonName.
246
247[ cert_type ]
248nsCertType = server
249"""
250
251def create_cert_files():
252
253 import tempfile, socket, os
254 d = tempfile.mkdtemp()
255 # now create a configuration file for the CA signing cert
256 fqdn = socket.getfqdn()
257 crtfile = os.path.join(d, "cert.pem")
258 conffile = os.path.join(d, "ca.conf")
259 fp = open(conffile, "w")
260 fp.write(CERTFILE_CONFIG_TEMPLATE %
261 {'state': "Delaware",
262 'city': "Wilmington",
263 'organization': "Python Software Foundation",
264 'unit': "SSL",
265 'common-name': fqdn,
266 })
267 fp.close()
Neal Norwitz7fc8e292007-08-26 18:50:39 +0000268 error = os.system(
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000269 "openssl req -batch -new -x509 -days 10 -nodes -config %s "
270 "-keyout \"%s\" -out \"%s\" > /dev/null < /dev/null 2>&1" %
271 (conffile, crtfile, crtfile))
272 # now we have a self-signed server cert in crtfile
273 os.unlink(conffile)
Neal Norwitz7fc8e292007-08-26 18:50:39 +0000274 if error or not os.path.exists(crtfile) or os.path.getsize(crtfile) == 0:
275 raise test_support.TestFailed(
276 "Unable to create certificate for test %d." % error)
277 return d, crtfile
278
279 # XXX(nnorwitz): should this code be removed now?
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000280 #sf_certfile = os.path.join(d, "sourceforge-imap.pem")
281 #sf_cert = ssl.fetch_server_certificate('pop.gmail.com', 995)
282 #open(sf_certfile, 'w').write(sf_cert)
283 #return d, crtfile, sf_certfile
284 # sys.stderr.write(open(crtfile, 'r').read() + '\n')
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000285
286def test_main():
287 if skip_expected:
288 raise test_support.TestSkipped("socket module has no ssl support")
289
290 global CERTFILE
291 tdir, CERTFILE = create_cert_files()
292
293 tests = [BasicTests]
294
295 server = None
296 if test_support.is_resource_enabled('network'):
297 server = threadedEchoServer(10024, CERTFILE)
298 server.start()
299 time.sleep(1)
300 tests.append(ConnectedTests)
301
302 thread_info = test_support.threading_setup()
303
304 try:
305 test_support.run_unittest(*tests)
306 finally:
307 if server is not None and server.active:
308 server.stop()
309 # wait for it to stop
310 server.join()
311
312 shutil.rmtree(tdir)
313 test_support.threading_cleanup(*thread_info)
314
315if __name__ == "__main__":
316 test_main()