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