def test_load_verify_locations(self): import _ssl ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) ctx.load_verify_locations(self.keycert) ctx.load_verify_locations(cafile=self.keycert, capath=None) ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) with open(self.keycert) as f: cacert_pem = f.read() ctx.load_verify_locations(cadata=cacert_pem) assert ctx.cert_store_stats()["x509_ca"] == 0
def test_load_verify_locations(self): import _ssl ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) ctx.load_verify_locations(self.keycert) ctx.load_verify_locations(cafile=self.keycert, capath=None) ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) with open(self.keycert) as f: cacert_pem = f.read().decode('ascii') ctx.load_verify_locations(cadata=cacert_pem) assert ctx.cert_store_stats()["x509_ca"] == 0
def test_context(self): import _ssl s = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) raises(ValueError, _ssl._SSLContext, -1) assert type(s.options) is int assert s.options & _ssl.OP_NO_SSLv2 s.options &= ~_ssl.OP_NO_SSLv2 assert not s.options & _ssl.OP_NO_SSLv2 raises(TypeError, "s.options = 2.5") assert not s.check_hostname exc = raises(ValueError, "s.check_hostname = True") assert str(exc.value) == "check_hostname needs a SSL context with " \ "either CERT_OPTIONAL or CERT_REQUIRED" assert s.verify_mode == _ssl.CERT_NONE s.verify_mode = _ssl.CERT_REQUIRED assert s.verify_mode == _ssl.CERT_REQUIRED exc = raises(ValueError, "s.verify_mode = 1234") assert str(exc.value) == "invalid value for verify_mode" assert type(s.verify_flags) is int assert s.verify_flags == _ssl.VERIFY_DEFAULT s.verify_flags = _ssl.VERIFY_CRL_CHECK_LEAF assert s.verify_flags == _ssl.VERIFY_CRL_CHECK_LEAF s.verify_flags = _ssl.VERIFY_DEFAULT assert s.verify_flags == _ssl.VERIFY_DEFAULT s.check_hostname = True assert s.check_hostname exc = raises(ValueError, "s.verify_mode = _ssl.CERT_NONE") assert str(exc.value) == "Cannot set verify_mode to CERT_NONE " \ "when check_hostname is enabled."
def test_server_hostname(self): import socket, _ssl, gc ctx = _ssl._SSLContext(_ssl.PROTOCOL_SSLv23) ss = ctx._wrap_socket(self.s, False, server_hostname="svn.python.org") self.s.close() del ss; gc.collect()
def test_subclass(self): # Check that the appropriate SSLError subclass is raised # (this only tests one of them) import _ssl, _socket ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLS) s = _socket.socket() try: s.bind(("127.0.0.1", 0)) s.listen(5) c = _socket.socket() c.connect(s.getsockname()) c.setblocking(False) c = ctx._wrap_socket(c, False) try: exc = raises(_ssl.SSLWantReadError, c.do_handshake) msg = str(exc.value) assert msg.startswith("The operation did not complete (read)") # For compatibility assert exc.value.errno == _ssl.SSL_ERROR_WANT_READ finally: try: c.shutdown() except _ssl.SSLError: # If the expected exception was raised, the SSLContext # can't be shut down yet pass finally: s.close()
def test_context(self): import _ssl s = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) raises(ValueError, _ssl._SSLContext, -1) assert type(s.options) is long assert s.options & _ssl.OP_NO_SSLv2 s.options &= ~_ssl.OP_NO_SSLv2 assert not s.options & _ssl.OP_NO_SSLv2 raises(TypeError, "s.options = 2.5") assert not s.check_hostname exc = raises(ValueError, "s.check_hostname = True") assert str(exc.value) == "check_hostname needs a SSL context with " \ "either CERT_OPTIONAL or CERT_REQUIRED" assert s.verify_mode == _ssl.CERT_NONE s.verify_mode = _ssl.CERT_REQUIRED assert s.verify_mode == _ssl.CERT_REQUIRED exc = raises(ValueError, "s.verify_mode = 1234") assert str(exc.value) == "invalid value for verify_mode" assert type(s.verify_flags) is long assert s.verify_flags == _ssl.VERIFY_DEFAULT s.verify_flags = _ssl.VERIFY_CRL_CHECK_LEAF assert s.verify_flags == _ssl.VERIFY_CRL_CHECK_LEAF s.verify_flags = _ssl.VERIFY_DEFAULT assert s.verify_flags == _ssl.VERIFY_DEFAULT s.check_hostname = True assert s.check_hostname exc = raises(ValueError, "s.verify_mode = _ssl.CERT_NONE") assert str(exc.value) == "Cannot set verify_mode to CERT_NONE " \ "when check_hostname is enabled."
def test_SSLType_read_and_write(self): #--Positive s = socket.socket(socket.AF_INET) s.connect((SSL_URL, SSL_PORT)) context = _ssl._SSLContext(_ssl.PROTOCOL_SSLv23) ssl_s = context._wrap_socket(s, False) ssl_s.do_handshake() self.assertIn("Writes the string s into the SSL object.", ssl_s.write.__doc__) self.assertIn("Read up to len bytes from the SSL socket.", ssl_s.read.__doc__) #Write self.assertEqual(ssl_s.write(SSL_REQUEST), len(SSL_REQUEST)) #Read self.assertEqual(ssl_s.read(4).lower(), b"http") max_response_length = 5000 response = b'' while len(response) < max_response_length: r = ssl_s.read(max_response_length - len(response)) if not r: break response += r self.assertIn(SSL_RESPONSE, response) #Cleanup ssl_s.shutdown() s.close()
def test_subclass(self): # Check that the appropriate SSLError subclass is raised # (this only tests one of them) import _ssl, _socket ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLS) s = _socket.socket() try: s.bind(("127.0.0.1", 0)) s.listen(5) c = _socket.socket() c.connect(s.getsockname()) c.setblocking(False) c = ctx._wrap_socket(c, False) try: exc = raises(_ssl.SSLWantReadError, c.do_handshake) msg= str(exc.value) assert msg.startswith("The operation did not complete (read)") # For compatibility assert exc.value.errno == _ssl.SSL_ERROR_WANT_READ finally: try: c.shutdown() except _ssl.SSLError: # If the expected exception was raised, the SSLContext # can't be shut down yet pass finally: s.close()
def test_server_hostname(self): import socket, _ssl, gc ctx = _ssl._SSLContext(_ssl.PROTOCOL_SSLv23) ss = ctx._wrap_socket(self.s, False, server_hostname="svn.python.org") self.s.close() del ss gc.collect()
def test_cert_store_stats(self): import _ssl ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) assert ctx.cert_store_stats() == {'x509_ca': 0, 'crl': 0, 'x509': 0} ctx.load_cert_chain(self.keycert) assert ctx.cert_store_stats() == {'x509_ca': 0, 'crl': 0, 'x509': 0} ctx.load_verify_locations(self.keycert) assert ctx.cert_store_stats() == {'x509_ca': 0, 'crl': 0, 'x509': 1}
def test_load_dh_params(self): import _ssl, errno ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) ctx.load_dh_params(self.dh512) raises(TypeError, ctx.load_dh_params) raises(TypeError, ctx.load_dh_params, None) raises(_ssl.SSLError, ctx.load_dh_params, self.keycert) exc = raises(IOError, ctx.load_dh_params, "inexistent.pem") assert exc.value.errno == errno.ENOENT
def test_lib_reason(self): # Test the library and reason attributes import _ssl ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) exc = raises(_ssl.SSLError, ctx.load_dh_params, self.keycert) assert exc.value.library == 'PEM' assert exc.value.reason == 'NO_START_LINE' s = str(exc.value) assert s.startswith("[PEM: NO_START_LINE] no start line")
def test_peer_certificate(self): import _ssl, gc ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLS) ss = ctx._wrap_socket(self.s._sock, False) ss.do_handshake() assert isinstance(ss.peer_certificate(der=True), bytes) assert isinstance(ss.peer_certificate(), dict) self.s.close() del ss; gc.collect()
def test_peer_certificate(self): import _ssl, gc ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLS) ss = ctx._wrap_socket(self.s._sock, False) ss.do_handshake() assert isinstance(ss.peer_certificate(der=True), bytes) assert isinstance(ss.peer_certificate(), dict) self.s.close() del ss gc.collect()
def test_npn_protocol(self): import socket, _ssl, gc if not _ssl.HAS_NPN: skip("NPN requires OpenSSL 1.0.1 or greater") ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) ctx._set_npn_protocols(b'\x08http/1.1\x06spdy/2') ss = ctx._wrap_socket(self.s._sock, True, server_hostname="svn.python.org") self.s.close() del ss; gc.collect()
def test_npn_protocol(self): import socket, _ssl, gc if not _ssl.HAS_NPN: skip("NPN requires OpenSSL 1.0.1 or greater") ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) ctx._set_npn_protocols(b'\x08http/1.1\x06spdy/2') ss = ctx._wrap_socket(self.s, True, server_hostname="svn.python.org") self.s.close() del ss gc.collect()
def test_async_closed(self): import _ssl, _socket, sys, gc s = _socket.socket() s.settimeout(3) if sys.version_info < (2, 7, 9): ss = _ssl.sslwrap(s, 0) else: ss = _ssl._SSLContext(_ssl.PROTOCOL_TLS)._wrap_socket(s, 0) s.close() exc = raises(_ssl.SSLError, ss.write, "data") assert exc.value.message == 'Underlying socket has been closed.' del exc, ss, s gc.collect() # force the destructor() to be called now
def test_get_ca_certs(self): import _ssl ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) ctx.load_verify_locations(self.keycert) assert ctx.get_ca_certs() == [] ctx.load_verify_locations(self.python_org_cert) certs = ctx.get_ca_certs() assert len(certs) == 1 print(certs) assert len(certs[0]['issuer']) == 4 assert certs[0]['version'] == 3 assert certs[0]['crlDistributionPoints'] == ( 'https://www.cacert.org/revoke.crl',)
def test_async_closed(self): import _ssl, _socket, sys, gc s = _socket.socket() s.settimeout(3) if sys.version_info < (2, 7, 9): ss = _ssl.sslwrap(s, 0) else: ss = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1)._wrap_socket(s, 0) s.close() exc = raises(_ssl.SSLError, ss.write, "data") assert exc.value.message == 'Underlying socket has been closed.' del exc, ss, s gc.collect() # force the destructor() to be called now
def test_get_ca_certs(self): import _ssl ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) ctx.load_verify_locations(self.keycert) assert ctx.get_ca_certs() == [] ctx.load_verify_locations(self.python_org_cert) certs = ctx.get_ca_certs() assert len(certs) == 1 print(certs) assert len(certs[0]['issuer']) == 4 assert certs[0]['version'] == 3 assert certs[0]['crlDistributionPoints'] == ( 'https://www.cacert.org/revoke.crl', )
def test_load_cert_chain(self): import _ssl, errno ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) ctx.load_cert_chain(self.keycert) ctx.load_cert_chain(self.cert, self.key) exc = raises(IOError, ctx.load_cert_chain, "inexistent.pem") assert exc.value.errno == errno.ENOENT exc = raises(_ssl.SSLError, ctx.load_cert_chain, self.badcert) raises(_ssl.SSLError, ctx.load_cert_chain, self.emptycert) # Password protected key and cert raises(_ssl.SSLError, ctx.load_cert_chain, self.cert_protected, password="******") ctx.load_cert_chain(self.cert_protected, password="******") ctx.load_cert_chain(self.cert_protected, password=lambda: "somepass") raises(_ssl.SSLError, ctx.load_cert_chain, self.cert_protected, password=lambda: "badpass") raises(TypeError, ctx.load_cert_chain, self.cert_protected, password=lambda: 3)
def test_sslwrap(self): import _ssl, _socket, sys, gc if sys.platform == 'darwin' or 'freebsd' in sys.platform: skip("hangs indefinitely on OSX & FreeBSD (also on CPython)") s = _socket.socket() if sys.version_info < (2, 7, 9): ss = _ssl.sslwrap(s, 0) else: ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) ss = ctx._wrap_socket(s, 0) assert ss.context is ctx exc = raises(_socket.error, ss.do_handshake) if sys.platform == 'win32': assert exc.value.errno == 10057 # WSAENOTCONN else: assert exc.value.errno == 32 # Broken pipe del exc, ss, s gc.collect() # force the destructor() to be called now
def test_SSLType_ssl(self): ''' Should be essentially the same as _ssl.sslwrap. It's not though and will simply be tested as implemented for the time being. ssl(PythonSocket.socket sock, [DefaultParameterValue(null)] string keyfile, [DefaultParameterValue(null)] string certfile) ''' #--Positive #sock s = socket.socket(socket.AF_INET) s.connect((SSL_URL, SSL_PORT)) context = _ssl._SSLContext(_ssl.PROTOCOL_SSLv23) ssl_s = context._wrap_socket(s, False) ssl_s.shutdown() s.close()
def test_SSLType_ssl_neg(self): ''' See comments on test_SSLType_ssl. Basically this needs to be revisited entirely (TODO) after we're more compatible with CPython. ''' s = socket.socket(socket.AF_INET) s.connect((SSL_URL, SSL_PORT)) context = _ssl._SSLContext(_ssl.PROTOCOL_SSLv23) #--Negative #Empty self.assertRaises(TypeError, context._wrap_socket) self.assertRaises(TypeError, context._wrap_socket, False) #None self.assertRaises(TypeError, context._wrap_socket, None, False) #Cleanup s.close()
def test_peer_certificate_verify(self): import _ssl, ssl, gc paths = ssl.get_default_verify_paths() if not paths.capath and not paths.cafile: skip("ssl.get_default_verify_paths() failed to return any path") ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLS) ctx.verify_mode = _ssl.CERT_REQUIRED ctx.load_verify_locations(capath=paths.capath, cafile=paths.cafile) ss = ctx._wrap_socket(self.s._sock, False) try: ss.do_handshake() except _ssl.SSLError as e: if e.reason == 'CERTIFICATE_VERIFY_FAILED': skip("Certificate verification failed. " "Most likely we just don't have any CA certificates.") assert ss.peer_certificate() self.s.close() del ss; gc.collect()
def test_peer_certificate_verify(self): import _ssl, ssl, gc paths = ssl.get_default_verify_paths() if not paths.capath and not paths.cafile: skip("ssl.get_default_verify_paths() failed to return any path") ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLS) ctx.verify_mode = _ssl.CERT_REQUIRED ctx.load_verify_locations(capath=paths.capath, cafile=paths.cafile) ss = ctx._wrap_socket(self.s._sock, False) try: ss.do_handshake() except _ssl.SSLError as e: if e.reason == 'CERTIFICATE_VERIFY_FAILED': skip("Certificate verification failed. " "Most likely we just don't have any CA certificates.") assert ss.peer_certificate() self.s.close() del ss gc.collect()
def test_SSLType_server(self): #--Positive s = socket.socket(socket.AF_INET) s.connect((SSL_URL, SSL_PORT)) context = _ssl._SSLContext(_ssl.PROTOCOL_SSLv23) ssl_s = context._wrap_socket(s, False) self.assertEqual( ssl_s.server(), '' ) #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=24281 ssl_s.do_handshake() if is_cli: #Incompat, but a good one at that self.assertIn( "Returns a string that describes the issuer of the server's certificate", ssl_s.issuer.__doc__) else: self.assertEqual(ssl_s.server.__doc__, None) server = ssl_s.server() #If we can get the server once, we should be able to do it again self.assertEqual(server, ssl_s.server()) self.assertIn(SSL_SERVER, server) #--Negative self.assertRaisesMessage(TypeError, "server() takes no arguments (1 given)", ssl_s.server, None) self.assertRaisesMessage(TypeError, "server() takes no arguments (1 given)", ssl_s.server, 1) self.assertRaisesMessage(TypeError, "server() takes no arguments (2 given)", ssl_s.server, 3.14, "abc") #Cleanup ssl_s.shutdown() s.close()
def test_set_ecdh_curve(self): import _ssl ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) ctx.set_ecdh_curve("prime256v1") raises(ValueError, ctx.set_ecdh_curve, "foo")
def test_options(self): import _ssl ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) assert _ssl.OP_ALL | _ssl.OP_NO_SSLv2 == ctx.options
def test_set_default_verify_paths(self): import _ssl s = _ssl._SSLContext(_ssl.PROTOCOL_TLSv1) s.set_default_verify_paths()
http.client.HTTPConnection.endheaders = endheaders http.client.HTTPConnection.send = send http.client.HTTPConnection.getresponse = getresponse http.client.HTTPConnection.connect = connect http.client.HTTPConnection.set_tunnel = set_tunnel http.client.HTTPConnection.close = close http.client.HTTPSConnection.putrequest = putrequest http.client.HTTPSConnection.putheader = putheader http.client.HTTPSConnection.endheaders = endheaders http.client.HTTPSConnection.send = send http.client.HTTPSConnection.getresponse = getresponse http.client.HTTPSConnection.connect = connect http.client.HTTPSConnection.set_tunnel = set_tunnel http.client.HTTPSConnection.close = close ssl._create_default_https_context = lambda *args, **kwargs: _ssl._SSLContext() ssl.CERT_CERT_REQUIRED = ssl.CERT_REQUIRED def SSLContext__init(self, protocol, *args, **kwargs): self.protocol = protocol self.options = 0 def wrap_socket(self, sock, *args, **kwargs): return sock ssl.SSLContext.__init__ = SSLContext__init ssl.SSLContext.wrap_socket = wrap_socket socket.inet_pton = lambda *args, **kwargs: None
def test(): for _ in range(9999): bio = _ssl.MemoryBIO() for _ in range(fint()): if fint(): try: bio.write(fstr()) except _ssl.SSLError: pass if fint(): bio.read() if fint(): bio.write_eof() bio.pending bio.eof _ssl.RAND_add(fstr(), fdouble()) _ssl.RAND_status() try: _ssl.RAND_bytes(fint()) _ssl.RAND_pseudo_bytes(fint()) except _ssl.SSLError: pass while True: try: ctx = _ssl._SSLContext(rnd.randint(-1,20)) ; break except ValueError: continue try: ctx.set_ciphers(str(fstr())) except _ssl.SSLError: pass try: ctx.set_alpn_protocols(flst()) except (AttributeError, _ssl.SSLError): pass try: ctx.set_npn_protocols(flst()) except (AttributeError, _ssl.SSLError): pass try: ctx.set_ecdh_curve(fstr()) except (ValueError, _ssl.SSLError): pass ctx.get_ciphers() ctx.check_hostname ctx.check_hostname = fbool() ctx._host_flags ctx._host_flags = flong() ctx.minimum_version try: ctx.minimum_version = flong() except (ValueError, _ssl.SSLError): pass ctx.maximum_version try: ctx.maximum_version = flong() except (ValueError, _ssl.SSLError): pass ctx.sni_callback try: ctx.sni_callback = flong except (ValueError, _ssl.SSLError): pass ctx.options ctx.options = flong() ctx.protocol ctx.verify_flags ctx.verify_flags = flong() ctx.verify_mode try: ctx.verify_mode = flong() except (ValueError, _ssl.SSLError): pass sock = socket.socket() sock = ctx._wrap_socket(sock, fbool()) sock.compression() sock.cipher() sock.shared_ciphers() sock.version() sock.selected_alpn_protocol() sock.selected_npn_protocol() try: sock.do_handshake() except _ssl.SSLError: pass try: sock.write(fstr()) except _ssl.SSLError: pass try: sock.read(fint()) except _ssl.SSLError: pass sock.pending() sock.context sock.server_side sock.server_hostname sock.owner sock.session sock.session_reused try: sock.shutdown() except _ssl.SSLError: pass