def test_verify_cb_new_function(self): pid = self.start_server(self.args) try: ctx = SSL.Context() ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 9, verify_cb_new_function) s = SSL.Connection(ctx) try: s.connect(self.srv_addr) except SSL.SSLError as e: self.fail(e) data = self.http_get(s) s.close() finally: self.stop_server(pid) self.assertIn('s_server -quiet -www', data)
def test_HTTPSConnection_secure_context(self): pid = self.start_server(self.args) try: ctx = SSL.Context() ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 9) ctx.load_verify_locations('tests/ca.pem') c = httpslib.HTTPSConnection(srv_host, self.srv_port, ssl_context=ctx) c.request('GET', '/') data = c.getresponse().read() c.close() finally: self.stop_server(pid) self.assertIn('s_server -quiet -www', data)
def test_urllib2_secure_context(self): pid = self.start_server(self.args) try: ctx = SSL.Context() ctx.set_verify( SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 9) ctx.load_verify_locations('tests/ca.pem') opener = m2urllib2.build_opener(ctx) opener.addheaders = [('Connection', 'close')] u = opener.open('https://%s:%s/' % (srv_host, self.srv_port)) data = u.read() u.close() finally: self.stop_server(pid) self.assertIn(b's_server -quiet -www', data)
def test_z_urllib2_opener(self): pid = self.start_server(self.args) try: ctx = SSL.Context() opener = m2urllib2.build_opener( ctx, m2urllib2.HTTPBasicAuthHandler()) m2urllib2.install_opener(opener) req = m2urllib2.Request('https://%s:%s/' % (srv_host, self.srv_port)) u = m2urllib2.urlopen(req) data = u.read() u.close() finally: self.stop_server(pid) self.assertIn(b's_server -quiet -www', data)
def test_makefile(self): pid = self.start_server(self.args) try: ctx = SSL.Context() s = SSL.Connection(ctx) try: s.connect(self.srv_addr) except SSL.SSLError, e: assert 0, e bio = s.makefile('rw') #s.close() # XXX bug 6628? bio.write('GET / HTTP/1.0\n\n') bio.flush() data = bio.read() bio.close() s.close()
def test_verify_cert_mutual_auth_servernbio(self): self.args.extend(['-Verify', '2', '-CAfile', 'ca.pem', '-nbio']) pid = self.start_server(self.args) try: ctx = SSL.Context() ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 9) ctx.load_verify_locations('tests/ca.pem') ctx.load_cert('tests/x509.pem') s = SSL.Connection(ctx) try: s.connect(self.srv_addr) except SSL.SSLError, e: assert 0, e data = self.http_get(s) s.close()
def test_HTTPS_secure_context_fail(self): pid = self.start_server(self.args) try: from M2Crypto import httpslib ctx = SSL.Context() ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 9) ctx.load_verify_locations('tests/server.pem') c = httpslib.HTTPS(srv_host, srv_port, ssl_context=ctx) c.putrequest('GET', '/') c.putheader('Accept', 'text/html') c.putheader('Accept', 'text/plain') self.assertRaises(SSL.SSLError, c.endheaders) c.close() finally: self.stop_server(pid)
def reportIP(self, IPaddress, port): """ Shamesly copied from: http://phreakmonkey.com/index.php/archives/100 A quick hack to probe for SSL Certificate Information Requres python & m2crypto 2007.09.26 - phreakmonkey.com / phreakmonkey at gmail """ ctx = SSL.Context() ctx.set_allow_unknown_ca(True) ctx.set_verify(SSL.verify_none, 1) conn = SSL.Connection(ctx) conn.postConnectionCheck = None timeout = SSL.timeout(15) conn.set_socket_read_timeout(timeout) conn.set_socket_write_timeout(timeout) try: if self.verbose: sys.stderr.write('Connecting ' + IPaddress + '.\n') sys.stderr.flush() conn.connect((IPaddress, port)) except KeyboardInterrupt: raise KeyboardInterrupt except TypeError: raise MyException('connect: Malformed address specified') except socket.gaierror: raise MyException('connect: No address associated with hostname') except socket.error: raise MyException('timeout connecting with hostname.') except SSL.SSLError: raise MyException('SSL_HANDSHAKE_FAILED.') if self.verbose: sys.stderr.write('Retrieving cert info.\n') sys.stderr.flush() cert = conn.get_peer_cert() try: cissuer = cert.get_issuer().as_text() except SSL.SSLError: raise MyException('Error: No Valid Cert Presented.') conn.close return cert
def __init__(self, port, host='', threaded=_has_threading,prtcol='PYRO'): self._ssl_server = 0 self.connections = [] # connection threads self.initTLS=lambda tls: None # default do-nothing func if host: socket.gethostbyname(host) # validate hostname try: if prtcol=='PYROSSL': try: from M2Crypto import SSL except ImportError: raise ProtocolError('SSL not available') try: self.ctx = SSL.Context('sslv23') if Pyro.config.PYROSSL_KEY: keyfile = os.path.join(Pyro.config.PYROSSL_CERTDIR, Pyro.config.PYROSSL_KEY) else: keyfile = None self.ctx.load_cert(os.path.join(Pyro.config.PYROSSL_CERTDIR, Pyro.config.PYROSSL_CERT), keyfile) self.ctx.load_client_ca(os.path.join(Pyro.config.PYROSSL_CERTDIR, Pyro.config.PYROSSL_CA_CERT)) self.ctx.load_verify_info(os.path.join(Pyro.config.PYROSSL_CERTDIR, Pyro.config.PYROSSL_CA_CERT)) self.ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert,10) self.ctx.set_allow_unknown_ca(1) self._ssl_server = 1 Log.msg('TCPServer','SSL Context initialized') except: Log.warn('TCPServer','SSL Context could not be initialized !!!') self.setNewConnectionValidator(BasicSSLValidator()) else: self.setNewConnectionValidator(DefaultConnValidator()) # create server socket for new connections self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) set_reuse_addr(self.sock) set_sock_no_inherit(self.sock) self.sock.bind((host,port)) self.sock.listen(Pyro.config.PYRO_TCP_LISTEN_BACKLOG) if self._ssl_server: self.sock = SSL.Connection(self.ctx,self.sock) # wrap server socket as SSL socket # rest of members self.threaded = threaded self.mustShutdown=0 # global shutdown self.localStorage=LocalStorage() # TLS for systems that don't have threads return except socket.error,msg: raise ProtocolError(msg)
def test_cipher_ok(self): if OPENSSL111: TCIPHER = 'TLS_AES_256_GCM_SHA384' else: TCIPHER = 'AES128-SHA' self.args = self.args + ['-cipher', TCIPHER] pid = self.start_server(self.args) try: ctx = SSL.Context() s = SSL.Connection(ctx) s.set_cipher_list(TCIPHER) s.connect(self.srv_addr) data = self.http_get(s) self.assertEqual(s.get_cipher().name(), TCIPHER, s.get_cipher().name()) cipher_stack = s.get_ciphers() self.assertEqual(cipher_stack[0].name(), TCIPHER, cipher_stack[0].name()) if not OPENSSL111: with self.assertRaises(IndexError): cipher_stack.__getitem__(2) # For some reason there are 2 entries in the stack # self.assertEqual(len(cipher_stack), 1, len(cipher_stack)) self.assertEqual(s.get_cipher_list(), TCIPHER, s.get_cipher_list()) # Test Cipher_Stack iterator i = 0 for cipher in cipher_stack: i += 1 if not OPENSSL111: cipname = cipher.name() self.assertEqual(cipname, 'AES128-SHA', '"%s" (%s)' % (cipname, type(cipname))) self.assertEqual('AES128-SHA-128', str(cipher)) # For some reason there are 2 entries in the stack # self.assertEqual(i, 1, i) self.assertEqual(i, len(cipher_stack)) s.close() finally: self.stop_server(pid) self.assertIn('s_server -quiet -www', data)
def _secureConnect(self): addr = self._getLocalVdsName(self.trust_store_path) from M2Crypto.m2xmlrpclib import SSL_Transport from M2Crypto import SSL KEYFILE = self.trust_store_path + '/keys/vdsmkey.pem' CERTFILE = self.trust_store_path + '/certs/vdsmcert.pem' CACERT = self.trust_store_path + '/certs/cacert.pem' ctx = SSL.Context('sslv3') ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 16) ctx.load_verify_locations(CACERT) ctx.load_cert(CERTFILE, KEYFILE) return xmlrpclib.Server('https://%s:%s' % (addr, self.management_port), SSL_Transport(ctx))
def get_ssl_information(self, hostname): ssl_context = SSL.Context() # I am enabling unknown CA's to deal with self-signed certs ssl_context.set_allow_unknown_ca(True) ssl_context.set_verify(SSL.verify_none, 1) connect_to_server_over_https = SSL.Connection(ssl_context) connect_to_server_over_https.postConnectionCheck = None timeout = SSL.timeout(15) connect_to_server_over_https.set_socket_read_timeout(timeout) connect_to_server_over_https.set_socket_write_timeout(timeout) try: connect_to_server_over_https.connect((hostname, 443)) except Exception, err: print("%s: %s" % (hostname, err)) self.cert_expiration_date = "Error getting Expiration date" return
def build_ssl_ctx(options): log.debug("creating SSL Context") ssl_ctx = SSL.Context("tlsv1") ssl_ctx.load_verify_locations(capath=options.capath) ssl_ctx.set_verify(SSL.verify_peer, 10) try: if options.use_proxy: ssl_ctx.load_cert_chain(options.proxy, options.proxy, lambda prompt: askpass(prompt, options)) else: ssl_ctx.load_cert(options.usercert, options.userkey, lambda prompt: askpass(prompt, options)) except SSL.SSLError, exc: errmsg("Failed to load certificate: %s", str(exc)) sys.exit(exit_codes.proxy_error)
def setup_server_ctx(): ctx = SSL.Context('sslv23') if ctx.load_verify_locations('ca.pem') != 1: print "***No CA file" #if ctx.set_default_verify_paths() != 1: # print "***No default verify paths" ctx.load_cert_chain('server.pem') ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 10, verify_callback) ctx.set_options(SSL.op_all | SSL.op_no_sslv2) ctx.set_tmp_dh_callback(tmp_dh_callback) #ctx.set_tmp_dh('dh1024.pem') if ctx.set_cipher_list('ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH') != 1: print "***No valid ciphers" if verbose_debug: ctx.set_info_callback() return ctx
def connect(server): if server.has_key('SSL') and server['SSL'].upper() in yesList: ctx = SSL.Context('sslv3') if server.has_key('TRUSTSTORE'): ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, depth=9) if ctx.load_verify_locations(server['TRUSTSTORE']) != 1: raise Exception('No CA certs') if server.has_key('KEYSTORE'): ctx.load_cert_chain(server['KEYSTORE']) soc = SSL.Connection(ctx) else: soc = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: soc.connect((server['HOST'],int(server['PORT']))) except: raise Exception('ConnectError') return soc
def test_z_urllib2_opener(self): pid = self.start_server(self.args) try: ctx = SSL.Context() from M2Crypto import m2urllib2 opener = m2urllib2.build_opener( ctx, m2urllib2.HTTPBasicAuthHandler()) m2urllib2.install_opener(opener) req = m2urllib2.Request('https://%s:%s/' % (srv_host, srv_port)) u = m2urllib2.urlopen(req) data = u.read() u.close() finally: self.stop_server(pid) self.failIf(string.find(data, 's_server -quiet -www') == -1)
def reportIP(IPaddress): ctx = SSL.Context() ctx.set_allow_unknown_ca(True) ctx.set_verify(SSL.verify_none, 1) conn = SSL.Connection(ctx) conn.postConnectionCheck = None timeout = SSL.timeout(15) conn.set_socket_read_timeout(timeout) conn.set_socket_write_timeout(timeout) try: sys.stderr.flush() conn.connect((IPaddress, 443)) except: print IPaddress + "|{SSL_HANDSHAKE_FAILED}|" + "|" + "|" + "|" sys.stderr.write('failed.\n') sys.stderr.flush() return sys.stderr.flush() cert = conn.get_peer_cert() try: cissuer = cert.get_issuer().as_text() except: sys.stderr.write("Error: No Valid Cert Presented\n") print IPaddress + "|{NO_CERT_PRESENTED}|" + "|" + "|" + "|" sys.stderr.flush conn.close return sys.stderr.flush() csubject = cert.get_subject().as_text() try: cAltName = cert.get_ext('subjectAltName').get_value() except LookupError: cAltName = "" try: cCN = cert.get_subject().CN except AttributeError: cCN = "" try: cExpiry = str(cert.get_not_after()) except AttributeError: cExpiry = "" conn.close print cExpiry
def test_HTTPSConnection_SNI_support(self): args = [ 's_server', '-servername', srv_host, '-debug', '-www', '-cert', 'server.pem', '-key', 'server_key.pem', '-cert2', 'server.pem', '-key2', 'server_key.pem', '-accept', str(self.srv_port) ] pid = self.start_server(args) try: ctx = SSL.Context() c = httpslib.HTTPSConnection(srv_host, self.srv_port, ssl_context=ctx) c.request('GET', '/') c.close() finally: out, err = self.stop_server(pid) self.assertIn('Hostname in TLS extension: "%s"' % srv_host, out)
def __init__(self, url, bofh_client, cacert_file=None, rand_cmd=None): self.__bc = bofh_client if url.startswith("https"): from M2Crypto.m2xmlrpclib import Server, SSL_Transport from M2Crypto import SSL if not os.path.exists('/dev/random') and rand_cmd is not None: from M2Crypto.Rand import rand_add rand_file = os.popen(rand_cmd, 'r') rand_string = rand_file.read() rand_file.close() rand_add(rand_string, len(rand_string)) ctx = SSL.Context('sslv3') if cacert_file is not None: ctx.load_verify_info(cacert_file) ctx.set_verify(SSL.verify_peer, 10) self.conn = Server(url, SSL_Transport(ctx), encoding='iso8859-1') else: self.conn = xmlrpclib.Server(url, encoding='iso8859-1')
def test_verify_allow_unknown_old(self): pid = self.start_server(self.args) try: ctx = SSL.Context() ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 9, SSL.cb.ssl_verify_callback_allow_unknown_ca) ctx.set_allow_unknown_ca(1) s = SSL.Connection(ctx) try: s.connect(self.srv_addr) except SSL.SSLError: log.error('Failed to connect to %s', self.srv_addr) raise data = self.http_get(s) s.close() finally: self.stop_server(pid) self.assertIn('s_server -quiet -www', data)
def test_sslv23_weak_crypto(self): self.args = self.args + ['-ssl2'] pid = self.start_server(self.args) try: ctx = SSL.Context('sslv23', weak_crypto=1) s = SSL.Connection(ctx) # SSLv2 ciphers disabled by default in newer OpenSSL if plat_fedora and m2.OPENSSL_VERSION_NUMBER < 0x10000000: s.connect(self.srv_addr) self.assertEqual(s.get_version(), 'SSLv2') else: self.assertRaises(SSL.SSLError, s.connect, self.srv_addr) s.close() except Exception as ex: print('Caught exception %s' % ex) raise finally: self.stop_server(pid)
def test_makefile_err(self): pid = self.start_server(self.args) try: ctx = SSL.Context() s = SSL.Connection(ctx) try: s.connect(self.srv_addr) except SSL.SSLError, e: assert 0, e f = s.makefile() data = self.http_get(s) s.close() del f del s err_code = Err.peek_error_code() assert not err_code, 'Unexpected error: %s' % err_code err = Err.get_error() assert not err, 'Unexpected error: %s' % err
def create_pywbem_ssl_context(): """ Create an SSL context based on what is commonly accepted as the required limitations. This code attempts to create the same context for Python 2 and Python 3 except for the ciphers This list is based on what is currently defined in the Python SSL module create_default_context function This includes: * Disallow SSLV2 and SSLV3 * Allow TLSV1 TLSV1.1, TLSV1.2 * No compression * Single DH Use and Single ECDH use cacerts info is set independently so is not part of our context setter. """ if six.PY2: context = SSL.Context('sslv23') # Many of the flags are not in the M2Crypto source so they were taken # from OpenSSL SSL.h module as flags. SSL.context.set_options(SSL.SSL_OP_NO_SSLv2 | 0x02000000 | # OP_NO_SSLV3 0x00020000 | # OP_NO_COMPRESSION 0x00100000 | # OP_SINGLE_DH_USE 0x00400000 | # OP_CIPHER_SERVER_PREFERENCE 0x00080000) # OP_SINGLE_ECDH_USE else: # The choice for the Python SSL module is whether to use the # create_default directly and possibly have different limits depending # on which version of Python you use or to set the attributes # directly based on a currently used SSL context = SSL.create_default_context(purpose=SSL.Purpose.CLIENT_AUTH) # Variable settings per SSL create_default_context. These are what # the function above sets for Python 3.4 # context = SSLContext(PROTOCOL_SSLv23) # context.options |= OP_NO_SSLv2 # context.options |= OP_NO_SSLv3 # context.options |= getattr(SSL, "OP_NO_COMPRESSION", 0) # context.options |= getattr(SSL, "OP_CIPHER_SERVER_PREFERENCE", 0) # context.options |= getattr(SSL, "OP_SINGLE_DH_USE", 0) # context.options |= getattr(SSL, "OP_SINGLE_ECDH_USE", 0) # context.set_ciphers(_RESTRICTED_SERVER_CIPHERS) return context
def test_makefile(self): pid = self.start_server(self.args) try: ctx = SSL.Context() s = SSL.Connection(ctx) try: s.connect(self.srv_addr) except SSL.SSLError as e: self.fail(e) bio = s.makefile('rwb') # s.close() # XXX bug 6628? bio.write(b'GET / HTTP/1.0\n\n') bio.flush() data = bio.read() bio.close() s.close() finally: self.stop_server(pid) self.assertIn('s_server -quiet -www', data)
def test_verify_cert_mutual_auth(self): self.args.extend(['-Verify', '2', '-CAfile', 'ca.pem']) pid = self.start_server(self.args) try: ctx = SSL.Context() ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 9) ctx.load_verify_locations('tests/ca.pem') ctx.load_cert('tests/x509.pem') s = SSL.Connection(ctx) try: s.connect(self.srv_addr) except SSL.SSLError as e: self.fail(e) data = self.http_get(s) s.close() finally: self.stop_server(pid) self.assertIn('s_server -quiet -www', data)
def __call__(self, hostname, get_cert_from, port): val_results = ValidationResults() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) cxt = SSL.Context() cxt.set_verify(SSL.verify_none, depth=1) SSL.Connection.clientPostConnectionCheck = None # we'll verify things later manually! try: c = SSL.Connection(cxt, sock) c.connect((get_cert_from, port)) cert = c.get_peer_cert() except Exception, e: # socket connection val_results.connection_error = True val_results.inner_exception = e return val_results
def get_ec2_cert(self): if not self._ec2_cert: cnf = bus.cnf cert_path = cnf.key_path(CLOUD_CERT, private=False) if not os.path.exists(cert_path): ec2_url = cnf.rawini.get(self.name, OPT_EC2_URL) url = urlparse(ec2_url) if url.schema == 'https': # Open SSL connection and retrieve certificate addr = (url.hostname, url.port if url.port else 443) ctx = SSL.Context() conn = SSL.Connection(ctx) conn.set_post_connection_check_callback(None) conn.connect(addr) cert = conn.get_peer_cert() cert.save_pem(cert_path) self._ec2_cert = cnf.read_key(CLOUD_CERT, private=False) return self._ec2_cert
def test_verify_cb_old(self): with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) pid = self.start_server(self.args) try: ctx = SSL.Context() ctx.set_verify( SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 9, self.verify_cb_old) s = SSL.Connection(ctx) try: s.connect(self.srv_addr) except SSL.SSLError as e: self.fail(e) data = self.http_get(s) s.close() finally: self.stop_server(pid) self.assertIn('s_server -quiet -www', data)
def __init__(self): PYROAdapter.__init__(self) try: from M2Crypto import SSL except ImportError: raise ProtocolError('SSL not available') self.ctx = SSL.Context('sslv23') if Pyro.config.PYROSSL_KEY: keyfile = os.path.join(Pyro.config.PYROSSL_CERTDIR, Pyro.config.PYROSSL_KEY) else: keyfile = None self.ctx.load_cert(os.path.join(Pyro.config.PYROSSL_CERTDIR, Pyro.config.PYROSSL_CERT), keyfile) self.ctx.load_client_ca(os.path.join(Pyro.config.PYROSSL_CERTDIR, Pyro.config.PYROSSL_CA_CERT)) self.ctx.load_verify_info(os.path.join(Pyro.config.PYROSSL_CERTDIR, Pyro.config.PYROSSL_CA_CERT)) self.ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert,10) self.ctx.set_allow_unknown_ca(1) Log.msg('PYROSSLAdapter','SSL Context initialized')
def test_HTTPSConnection_resume_session(self): pid = self.start_server(self.args) try: self.ctx.load_verify_locations(cafile='tests/ca.pem') self.ctx.load_cert('tests/x509.pem') self.ctx.set_verify( SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 1) self.ctx.set_session_cache_mode(m2.SSL_SESS_CACHE_CLIENT) c = httpslib.HTTPSConnection(srv_host, self.srv_port, ssl_context=self.ctx) c.request('GET', '/') ses = c.get_session() t = ses.as_text() data = c.getresponse().read() # Appearently closing connection here screws session; Ali Polatel? # c.close() ctx2 = SSL.Context() ctx2.load_verify_locations(cafile='tests/ca.pem') ctx2.load_cert('tests/x509.pem') ctx2.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 1) ctx2.set_session_cache_mode(m2.SSL_SESS_CACHE_CLIENT) c2 = httpslib.HTTPSConnection(srv_host, self.srv_port, ssl_context=ctx2) c2.set_session(ses) c2.request('GET', '/') ses2 = c2.get_session() t2 = ses2.as_text() data = six.ensure_text(c2.getresponse().read()) c.close() c2.close() self.assertEqual( t, t2, "Sessions did not match: t = %s, t2 = %s" % ( t, t2, )) finally: self.stop_server(pid) self.assertIn('s_server -quiet -www', data)