2007-08-25 12:08:43 -03:00
|
|
|
# Test the support for SSL and sockets
|
|
|
|
|
|
|
|
import sys
|
|
|
|
import unittest
|
|
|
|
from test import test_support
|
|
|
|
import socket
|
|
|
|
import errno
|
|
|
|
import threading
|
|
|
|
import subprocess
|
|
|
|
import time
|
|
|
|
import os
|
|
|
|
import pprint
|
|
|
|
import urllib
|
|
|
|
import shutil
|
|
|
|
import traceback
|
|
|
|
|
|
|
|
# Optionally test SSL support, if we have it in the tested platform
|
|
|
|
skip_expected = False
|
|
|
|
try:
|
|
|
|
import ssl
|
|
|
|
except ImportError:
|
|
|
|
skip_expected = True
|
|
|
|
|
|
|
|
CERTFILE = None
|
|
|
|
|
2007-08-26 22:03:18 -03:00
|
|
|
|
|
|
|
def handle_error(prefix):
|
|
|
|
exc_format = ' '.join(traceback.format_exception(*sys.exc_info()))
|
|
|
|
sys.stdout.write(prefix + exc_format)
|
|
|
|
|
|
|
|
|
2007-08-25 12:08:43 -03:00
|
|
|
class BasicTests(unittest.TestCase):
|
|
|
|
|
|
|
|
def testRudeShutdown(self):
|
|
|
|
# Some random port to connect to.
|
|
|
|
PORT = [9934]
|
|
|
|
|
|
|
|
listener_ready = threading.Event()
|
|
|
|
listener_gone = threading.Event()
|
|
|
|
|
|
|
|
# `listener` runs in a thread. It opens a socket listening on
|
|
|
|
# PORT, and sits in an accept() until the main thread connects.
|
|
|
|
# Then it rudely closes the socket, and sets Event `listener_gone`
|
|
|
|
# to let the main thread know the socket is gone.
|
|
|
|
def listener():
|
|
|
|
s = socket.socket()
|
|
|
|
PORT[0] = test_support.bind_port(s, '', PORT[0])
|
|
|
|
s.listen(5)
|
|
|
|
listener_ready.set()
|
|
|
|
s.accept()
|
|
|
|
s = None # reclaim the socket object, which also closes it
|
|
|
|
listener_gone.set()
|
|
|
|
|
|
|
|
def connector():
|
|
|
|
listener_ready.wait()
|
|
|
|
s = socket.socket()
|
|
|
|
s.connect(('localhost', PORT[0]))
|
|
|
|
listener_gone.wait()
|
|
|
|
try:
|
|
|
|
ssl_sock = socket.ssl(s)
|
|
|
|
except socket.sslerror:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
raise test_support.TestFailed(
|
|
|
|
'connecting to closed SSL socket should have failed')
|
|
|
|
|
|
|
|
t = threading.Thread(target=listener)
|
|
|
|
t.start()
|
|
|
|
connector()
|
|
|
|
t.join()
|
|
|
|
|
|
|
|
def testSSLconnect(self):
|
|
|
|
import os
|
|
|
|
with test_support.transient_internet():
|
|
|
|
s = ssl.sslsocket(socket.socket(socket.AF_INET),
|
|
|
|
cert_reqs=ssl.CERT_NONE)
|
|
|
|
s.connect(("pop.gmail.com", 995))
|
|
|
|
c = s.getpeercert()
|
|
|
|
if c:
|
|
|
|
raise test_support.TestFailed("Peer cert %s shouldn't be here!")
|
|
|
|
s.close()
|
|
|
|
|
|
|
|
# this should fail because we have no verification certs
|
|
|
|
s = ssl.sslsocket(socket.socket(socket.AF_INET),
|
|
|
|
cert_reqs=ssl.CERT_REQUIRED)
|
|
|
|
try:
|
|
|
|
s.connect(("pop.gmail.com", 995))
|
|
|
|
except ssl.sslerror:
|
|
|
|
pass
|
|
|
|
finally:
|
|
|
|
s.close()
|
|
|
|
|
|
|
|
class ConnectedTests(unittest.TestCase):
|
|
|
|
|
|
|
|
def testTLSecho (self):
|
|
|
|
|
|
|
|
s1 = socket.socket()
|
2007-08-26 16:35:09 -03:00
|
|
|
try:
|
|
|
|
s1.connect(('127.0.0.1', 10024))
|
|
|
|
except:
|
2007-08-26 22:03:18 -03:00
|
|
|
handle_error("connection failure:\n")
|
2007-08-26 16:35:09 -03:00
|
|
|
raise test_support.TestFailed("Can't connect to test server")
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
c1 = ssl.sslsocket(s1, ssl_version=ssl.PROTOCOL_TLSv1)
|
|
|
|
except:
|
2007-08-26 22:03:18 -03:00
|
|
|
handle_error("SSL handshake failure:\n")
|
2007-08-26 16:35:09 -03:00
|
|
|
raise test_support.TestFailed("Can't SSL-handshake with test server")
|
|
|
|
else:
|
|
|
|
if not c1:
|
|
|
|
raise test_support.TestFailed("Can't SSL-handshake with test server")
|
|
|
|
indata = "FOO\n"
|
|
|
|
c1.write(indata)
|
|
|
|
outdata = c1.read()
|
|
|
|
if outdata != indata.lower():
|
|
|
|
raise test_support.TestFailed("bad data <<%s>> received; expected <<%s>>\n" % (data, indata.lower()))
|
|
|
|
c1.close()
|
2007-08-25 12:08:43 -03:00
|
|
|
|
|
|
|
def testReadCert(self):
|
|
|
|
|
|
|
|
s2 = socket.socket()
|
2007-08-26 16:35:09 -03:00
|
|
|
try:
|
|
|
|
s2.connect(('127.0.0.1', 10024))
|
|
|
|
except:
|
2007-08-26 22:03:18 -03:00
|
|
|
handle_error("connection failure:\n")
|
2007-08-26 16:35:09 -03:00
|
|
|
raise test_support.TestFailed("Can't connect to test server")
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
c2 = ssl.sslsocket(s2, ssl_version=ssl.PROTOCOL_TLSv1,
|
|
|
|
cert_reqs=ssl.CERT_REQUIRED, ca_certs=CERTFILE)
|
|
|
|
except:
|
2007-08-26 22:03:18 -03:00
|
|
|
handle_error("SSL handshake failure:\n")
|
2007-08-26 16:35:09 -03:00
|
|
|
raise test_support.TestFailed("Can't SSL-handshake with test server")
|
|
|
|
else:
|
|
|
|
if not c2:
|
|
|
|
raise test_support.TestFailed("Can't SSL-handshake with test server")
|
|
|
|
cert = c2.getpeercert()
|
|
|
|
if not cert:
|
|
|
|
raise test_support.TestFailed("Can't get peer certificate.")
|
2007-09-04 21:46:27 -03:00
|
|
|
if test_support.verbose:
|
|
|
|
sys.stdout.write(pprint.pformat(cert) + '\n')
|
2007-08-26 16:35:09 -03:00
|
|
|
if not cert.has_key('subject'):
|
|
|
|
raise test_support.TestFailed(
|
|
|
|
"No subject field in certificate: %s." %
|
|
|
|
pprint.pformat(cert))
|
2007-09-04 21:46:27 -03:00
|
|
|
if not ('organizationName', 'Python Software Foundation') in cert['subject']:
|
2007-08-26 16:35:09 -03:00
|
|
|
raise test_support.TestFailed(
|
2007-09-04 21:46:27 -03:00
|
|
|
"Missing or invalid 'organizationName' field in certificate subject; "
|
2007-08-26 16:35:09 -03:00
|
|
|
"should be 'Python Software Foundation'.");
|
|
|
|
c2.close()
|
2007-08-25 12:08:43 -03:00
|
|
|
|
|
|
|
|
2007-08-26 19:20:03 -03:00
|
|
|
class ThreadedEchoServer(threading.Thread):
|
2007-08-25 12:08:43 -03:00
|
|
|
|
2007-08-26 19:20:03 -03:00
|
|
|
class ConnectionHandler(threading.Thread):
|
2007-08-25 12:08:43 -03:00
|
|
|
|
|
|
|
def __init__(self, server, connsock):
|
|
|
|
self.server = server
|
|
|
|
self.running = False
|
|
|
|
self.sock = connsock
|
|
|
|
threading.Thread.__init__(self)
|
|
|
|
self.setDaemon(True)
|
|
|
|
|
|
|
|
def run (self):
|
|
|
|
self.running = True
|
2007-08-26 16:35:09 -03:00
|
|
|
try:
|
|
|
|
sslconn = ssl.sslsocket(self.sock, server_side=True,
|
|
|
|
certfile=self.server.certificate,
|
|
|
|
ssl_version=self.server.protocol,
|
|
|
|
cert_reqs=self.server.certreqs)
|
|
|
|
except:
|
|
|
|
# here, we want to stop the server, because this shouldn't
|
|
|
|
# happen in the context of our test case
|
2007-08-26 22:03:18 -03:00
|
|
|
handle_error("Test server failure:\n")
|
2007-08-26 16:35:09 -03:00
|
|
|
self.running = False
|
|
|
|
# normally, we'd just stop here, but for the test
|
|
|
|
# harness, we want to stop the server
|
|
|
|
self.server.stop()
|
|
|
|
return
|
|
|
|
|
2007-08-25 12:08:43 -03:00
|
|
|
while self.running:
|
|
|
|
try:
|
|
|
|
msg = sslconn.read()
|
|
|
|
if not msg:
|
|
|
|
# eof, so quit this handler
|
|
|
|
self.running = False
|
|
|
|
sslconn.close()
|
|
|
|
elif msg.strip() == 'over':
|
|
|
|
sslconn.close()
|
|
|
|
self.server.stop()
|
|
|
|
self.running = False
|
|
|
|
else:
|
2007-08-26 22:15:33 -03:00
|
|
|
if test_support.verbose:
|
|
|
|
sys.stdout.write("\nserver: %s\n" % msg.strip().lower())
|
2007-08-25 12:08:43 -03:00
|
|
|
sslconn.write(msg.lower())
|
|
|
|
except ssl.sslerror:
|
2007-08-26 22:03:18 -03:00
|
|
|
handle_error("Test server failure:\n")
|
2007-08-25 12:08:43 -03:00
|
|
|
sslconn.close()
|
|
|
|
self.running = False
|
2007-08-26 16:35:09 -03:00
|
|
|
# normally, we'd just stop here, but for the test
|
|
|
|
# harness, we want to stop the server
|
|
|
|
self.server.stop()
|
2007-08-25 12:08:43 -03:00
|
|
|
except:
|
2007-08-26 22:03:18 -03:00
|
|
|
handle_error('')
|
2007-08-25 12:08:43 -03:00
|
|
|
|
2007-08-25 13:54:38 -03:00
|
|
|
def __init__(self, port, certificate, ssl_version=None,
|
|
|
|
certreqs=None, cacerts=None):
|
|
|
|
if ssl_version is None:
|
|
|
|
ssl_version = ssl.PROTOCOL_TLSv1
|
|
|
|
if certreqs is None:
|
|
|
|
certreqs = ssl.CERT_NONE
|
2007-08-25 12:08:43 -03:00
|
|
|
self.certificate = certificate
|
|
|
|
self.protocol = ssl_version
|
|
|
|
self.certreqs = certreqs
|
|
|
|
self.cacerts = cacerts
|
|
|
|
self.sock = socket.socket()
|
2007-08-26 19:20:03 -03:00
|
|
|
self.flag = None
|
2007-08-25 14:25:17 -03:00
|
|
|
if hasattr(socket, 'SO_REUSEADDR'):
|
|
|
|
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
|
|
if hasattr(socket, 'SO_REUSEPORT'):
|
|
|
|
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
|
2007-08-25 12:08:43 -03:00
|
|
|
self.sock.bind(('127.0.0.1', port))
|
|
|
|
self.active = False
|
|
|
|
threading.Thread.__init__(self)
|
|
|
|
self.setDaemon(False)
|
|
|
|
|
2007-08-26 19:20:03 -03:00
|
|
|
def start (self, flag=None):
|
|
|
|
self.flag = flag
|
|
|
|
threading.Thread.start(self)
|
|
|
|
|
2007-08-25 12:08:43 -03:00
|
|
|
def run (self):
|
|
|
|
self.sock.settimeout(0.5)
|
|
|
|
self.sock.listen(5)
|
|
|
|
self.active = True
|
2007-08-26 19:20:03 -03:00
|
|
|
if self.flag:
|
|
|
|
# signal an event
|
|
|
|
self.flag.set()
|
2007-08-25 12:08:43 -03:00
|
|
|
while self.active:
|
|
|
|
try:
|
|
|
|
newconn, connaddr = self.sock.accept()
|
2007-08-26 22:15:33 -03:00
|
|
|
if test_support.verbose:
|
|
|
|
sys.stdout.write('\nserver: new connection from ' + str(connaddr) + '\n')
|
2007-08-26 19:20:03 -03:00
|
|
|
handler = self.ConnectionHandler(self, newconn)
|
2007-08-25 12:08:43 -03:00
|
|
|
handler.start()
|
|
|
|
except socket.timeout:
|
|
|
|
pass
|
|
|
|
except KeyboardInterrupt:
|
2007-08-26 16:35:09 -03:00
|
|
|
self.stop()
|
2007-08-25 12:08:43 -03:00
|
|
|
except:
|
2007-08-26 22:03:18 -03:00
|
|
|
handle_error("Test server failure:\n")
|
2007-08-25 12:08:43 -03:00
|
|
|
|
|
|
|
def stop (self):
|
|
|
|
self.active = False
|
2007-08-26 16:35:09 -03:00
|
|
|
self.sock.close()
|
2007-08-25 12:08:43 -03:00
|
|
|
|
|
|
|
CERTFILE_CONFIG_TEMPLATE = """
|
|
|
|
# create RSA certs - Server
|
|
|
|
|
|
|
|
[ req ]
|
|
|
|
default_bits = 1024
|
|
|
|
encrypt_key = yes
|
|
|
|
distinguished_name = req_dn
|
|
|
|
x509_extensions = cert_type
|
|
|
|
|
|
|
|
[ req_dn ]
|
|
|
|
countryName = Country Name (2 letter code)
|
|
|
|
countryName_default = US
|
|
|
|
countryName_min = 2
|
|
|
|
countryName_max = 2
|
|
|
|
|
|
|
|
stateOrProvinceName = State or Province Name (full name)
|
|
|
|
stateOrProvinceName_default = %(state)s
|
|
|
|
|
|
|
|
localityName = Locality Name (eg, city)
|
|
|
|
localityName_default = %(city)s
|
|
|
|
|
|
|
|
0.organizationName = Organization Name (eg, company)
|
|
|
|
0.organizationName_default = %(organization)s
|
|
|
|
|
|
|
|
organizationalUnitName = Organizational Unit Name (eg, section)
|
|
|
|
organizationalUnitName_default = %(unit)s
|
|
|
|
|
|
|
|
0.commonName = Common Name (FQDN of your server)
|
|
|
|
0.commonName_default = %(common-name)s
|
|
|
|
|
|
|
|
# To create a certificate for more than one name uncomment:
|
|
|
|
# 1.commonName = DNS alias of your server
|
|
|
|
# 2.commonName = DNS alias of your server
|
|
|
|
# ...
|
|
|
|
# See http://home.netscape.com/eng/security/ssl_2.0_certificate.html
|
|
|
|
# to see how Netscape understands commonName.
|
|
|
|
|
|
|
|
[ cert_type ]
|
|
|
|
nsCertType = server
|
|
|
|
"""
|
|
|
|
|
2007-08-27 14:19:42 -03:00
|
|
|
def create_cert_files(hostname=None):
|
|
|
|
|
|
|
|
"""This is the routine that was run to create the certificate
|
|
|
|
and private key contained in keycert.pem."""
|
2007-08-25 12:08:43 -03:00
|
|
|
|
|
|
|
import tempfile, socket, os
|
|
|
|
d = tempfile.mkdtemp()
|
|
|
|
# now create a configuration file for the CA signing cert
|
2007-08-27 14:19:42 -03:00
|
|
|
fqdn = hostname or socket.getfqdn()
|
2007-08-25 12:08:43 -03:00
|
|
|
crtfile = os.path.join(d, "cert.pem")
|
|
|
|
conffile = os.path.join(d, "ca.conf")
|
|
|
|
fp = open(conffile, "w")
|
|
|
|
fp.write(CERTFILE_CONFIG_TEMPLATE %
|
|
|
|
{'state': "Delaware",
|
|
|
|
'city': "Wilmington",
|
|
|
|
'organization': "Python Software Foundation",
|
|
|
|
'unit': "SSL",
|
|
|
|
'common-name': fqdn,
|
|
|
|
})
|
|
|
|
fp.close()
|
2007-08-26 15:50:39 -03:00
|
|
|
error = os.system(
|
2007-08-27 14:19:42 -03:00
|
|
|
"openssl req -batch -new -x509 -days 2000 -nodes -config %s "
|
2007-08-25 12:08:43 -03:00
|
|
|
"-keyout \"%s\" -out \"%s\" > /dev/null < /dev/null 2>&1" %
|
|
|
|
(conffile, crtfile, crtfile))
|
|
|
|
# now we have a self-signed server cert in crtfile
|
|
|
|
os.unlink(conffile)
|
2007-08-26 21:58:33 -03:00
|
|
|
if (os.WEXITSTATUS(error) or
|
|
|
|
not os.path.exists(crtfile) or os.path.getsize(crtfile) == 0):
|
2007-08-26 22:15:33 -03:00
|
|
|
if test_support.verbose:
|
2007-08-27 14:19:42 -03:00
|
|
|
sys.stdout.write("Unable to create certificate for test, "
|
|
|
|
+ "error status %d\n" % (error >> 8))
|
2007-08-26 22:15:33 -03:00
|
|
|
crtfile = None
|
|
|
|
elif test_support.verbose:
|
|
|
|
sys.stdout.write(open(crtfile, 'r').read() + '\n')
|
2007-08-26 15:50:39 -03:00
|
|
|
return d, crtfile
|
|
|
|
|
2007-08-25 12:08:43 -03:00
|
|
|
|
2007-08-26 22:15:33 -03:00
|
|
|
def test_main(verbose=False):
|
2007-08-25 12:08:43 -03:00
|
|
|
if skip_expected:
|
2007-09-04 21:46:27 -03:00
|
|
|
raise test_support.TestSkipped("No SSL support")
|
2007-08-25 12:08:43 -03:00
|
|
|
|
|
|
|
global CERTFILE
|
2007-08-27 14:19:42 -03:00
|
|
|
CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir,
|
|
|
|
"keycert.pem")
|
2007-08-26 22:15:33 -03:00
|
|
|
if not CERTFILE:
|
|
|
|
sys.__stdout__.write("Skipping test_ssl ConnectedTests; "
|
|
|
|
"couldn't create a certificate.\n")
|
2007-08-25 12:08:43 -03:00
|
|
|
|
|
|
|
tests = [BasicTests]
|
|
|
|
|
|
|
|
server = None
|
2007-08-26 22:15:33 -03:00
|
|
|
if CERTFILE and test_support.is_resource_enabled('network'):
|
2007-08-26 19:20:03 -03:00
|
|
|
server = ThreadedEchoServer(10024, CERTFILE)
|
|
|
|
flag = threading.Event()
|
|
|
|
server.start(flag)
|
|
|
|
# wait for it to start
|
|
|
|
flag.wait()
|
2007-08-25 12:08:43 -03:00
|
|
|
tests.append(ConnectedTests)
|
|
|
|
|
|
|
|
thread_info = test_support.threading_setup()
|
|
|
|
|
|
|
|
try:
|
|
|
|
test_support.run_unittest(*tests)
|
|
|
|
finally:
|
|
|
|
if server is not None and server.active:
|
|
|
|
server.stop()
|
|
|
|
# wait for it to stop
|
|
|
|
server.join()
|
|
|
|
|
|
|
|
test_support.threading_cleanup(*thread_info)
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
test_main()
|