blob: 3311f0cab27548a749ce6c6e83c9bce9d6451d1c [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()
179 self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
180 self.sock.bind(('127.0.0.1', port))
181 self.active = False
182 threading.Thread.__init__(self)
183 self.setDaemon(False)
184
185 def run (self):
186 self.sock.settimeout(0.5)
187 self.sock.listen(5)
188 self.active = True
189 while self.active:
190 try:
191 newconn, connaddr = self.sock.accept()
192 # sys.stderr.write('new connection from ' + str(connaddr))
193 handler = self.connectionHandler(self, newconn)
194 handler.start()
195 except socket.timeout:
196 pass
197 except KeyboardInterrupt:
198 self.active = False
199 except:
200 sys.stderr.write(string.join(
201 traceback.format_exception(*sys.exc_info())))
202
203 def stop (self):
204 self.active = False
205
206
207CERTFILE_CONFIG_TEMPLATE = """
208# create RSA certs - Server
209
210[ req ]
211default_bits = 1024
212encrypt_key = yes
213distinguished_name = req_dn
214x509_extensions = cert_type
215
216[ req_dn ]
217countryName = Country Name (2 letter code)
218countryName_default = US
219countryName_min = 2
220countryName_max = 2
221
222stateOrProvinceName = State or Province Name (full name)
223stateOrProvinceName_default = %(state)s
224
225localityName = Locality Name (eg, city)
226localityName_default = %(city)s
227
2280.organizationName = Organization Name (eg, company)
2290.organizationName_default = %(organization)s
230
231organizationalUnitName = Organizational Unit Name (eg, section)
232organizationalUnitName_default = %(unit)s
233
2340.commonName = Common Name (FQDN of your server)
2350.commonName_default = %(common-name)s
236
237# To create a certificate for more than one name uncomment:
238# 1.commonName = DNS alias of your server
239# 2.commonName = DNS alias of your server
240# ...
241# See http://home.netscape.com/eng/security/ssl_2.0_certificate.html
242# to see how Netscape understands commonName.
243
244[ cert_type ]
245nsCertType = server
246"""
247
248def create_cert_files():
249
250 import tempfile, socket, os
251 d = tempfile.mkdtemp()
252 # now create a configuration file for the CA signing cert
253 fqdn = socket.getfqdn()
254 crtfile = os.path.join(d, "cert.pem")
255 conffile = os.path.join(d, "ca.conf")
256 fp = open(conffile, "w")
257 fp.write(CERTFILE_CONFIG_TEMPLATE %
258 {'state': "Delaware",
259 'city': "Wilmington",
260 'organization': "Python Software Foundation",
261 'unit': "SSL",
262 'common-name': fqdn,
263 })
264 fp.close()
265 os.system(
266 "openssl req -batch -new -x509 -days 10 -nodes -config %s "
267 "-keyout \"%s\" -out \"%s\" > /dev/null < /dev/null 2>&1" %
268 (conffile, crtfile, crtfile))
269 # now we have a self-signed server cert in crtfile
270 os.unlink(conffile)
271 #sf_certfile = os.path.join(d, "sourceforge-imap.pem")
272 #sf_cert = ssl.fetch_server_certificate('pop.gmail.com', 995)
273 #open(sf_certfile, 'w').write(sf_cert)
274 #return d, crtfile, sf_certfile
275 # sys.stderr.write(open(crtfile, 'r').read() + '\n')
276 return d, crtfile
277
278def test_main():
279 if skip_expected:
280 raise test_support.TestSkipped("socket module has no ssl support")
281
282 global CERTFILE
283 tdir, CERTFILE = create_cert_files()
284
285 tests = [BasicTests]
286
287 server = None
288 if test_support.is_resource_enabled('network'):
289 server = threadedEchoServer(10024, CERTFILE)
290 server.start()
291 time.sleep(1)
292 tests.append(ConnectedTests)
293
294 thread_info = test_support.threading_setup()
295
296 try:
297 test_support.run_unittest(*tests)
298 finally:
299 if server is not None and server.active:
300 server.stop()
301 # wait for it to stop
302 server.join()
303
304 shutil.rmtree(tdir)
305 test_support.threading_cleanup(*thread_info)
306
307if __name__ == "__main__":
308 test_main()