def test_set_default_verify_paths(self): """ L{Context.set_default_verify_paths} causes the platform-specific CA certificate locations to be used for verification purposes. """ # Testing this requires a server with a certificate signed by one of # the CAs in the platform CA location. Getting one of those costs # money. Fortunately (or unfortunately, depending on your # perspective), it's easy to think of a public server on the # internet which has such a certificate. Connecting to the network # in a unit test is bad, but it's the only way I can think of to # really test this. -exarkun # Arg, verisign.com doesn't speak TLSv1 context = Context(SSLv3_METHOD) context.set_default_verify_paths() context.set_verify( VERIFY_PEER, lambda conn, cert, errno, depth, preverify_ok: preverify_ok) client = socket() client.connect(('verisign.com', 443)) clientSSL = Connection(context, client) clientSSL.set_connect_state() clientSSL.do_handshake() clientSSL.send('GET / HTTP/1.0\r\n\r\n') self.assertTrue(clientSSL.recv(1024))
def getServerContext(self): """ Generate a new L{OpenSSL.SSL.Context} object configured to use a certificate signed by C{self.ca} and only accept connections from peers which are also using a certificate signed by C{self.ca}. """ # Generate a new key for the server and have the CA sign a certificate # for it. key = KeyPair.generate(size=512) req = key.certificateRequest(DN(commonName='localhost')) certData = self.ca.signCertificateRequest(req, lambda dn: True, 1) cert = PrivateCertificate.load(certData, key) # Use the new key/certificate context = Context(TLSv1_METHOD) context.use_privatekey(key.original) context.use_certificate(cert.original) context.check_privatekey() # Allow peer certificates signed by the CA store = context.get_cert_store() store.add_cert(self.ca.original) # Verify the peer certificate and require that they have one. def verify(conn, cert, errno, depth, preverify_ok): return preverify_ok context.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify) return context
def test_add_extra_chain_cert(self): """ L{Context.add_extra_chain_cert} accepts an L{X509} instance to add to the certificate chain. """ context = Context(TLSv1_METHOD) context.add_extra_chain_cert(load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
def accept_client_conn(self): context = Context(SSLv23_METHOD) context.set_tlsext_servername_callback(self.prepare_handshake) self.client_ssl_sock = Connection(context, self.client_socket) self.client_ssl_sock.set_accept_state() self.client_ssl_sock.do_handshake()
def go(): def cb(a, b, c): print count.next() return "foobar" c = Context(TLSv1_METHOD) c.set_passwd_cb(cb) while 1: c.use_privatekey_file('pkey.pem')
def getContext(self): """ Create and return an SSL context configured to use L{self._info} as the info callback. """ context = Context(TLSv1_METHOD) context.set_info_callback(self._info) return context
def test_set_client_ca_list_errors(self): """ L{Context.set_client_ca_list} raises a L{TypeError} if called with a non-list or a list that contains objects other than X509Names. """ ctx = Context(TLSv1_METHOD) self.assertRaises(TypeError, ctx.set_client_ca_list, "spam") self.assertRaises(TypeError, ctx.set_client_ca_list, ["spam"]) self.assertIdentical(ctx.set_client_ca_list([]), None)
def test_use_privatekey(self): """ L{Context.use_privatekey} takes an L{OpenSSL.crypto.PKey} instance. """ key = PKey() key.generate_key(TYPE_RSA, 128) ctx = Context(TLSv1_METHOD) ctx.use_privatekey(key) self.assertRaises(TypeError, ctx.use_privatekey, "")
def pick_certificate(connection): try: key, cert = certificates[connection.get_servername()] except KeyError: pass else: new_context = Context(TLSv1_METHOD) new_context.use_privatekey(key) new_context.use_certificate(cert) connection.set_context(new_context)
def __call__(self,connection): try: servername = re.sub('^[^.]*\.(?=\w+\.\w+$)','',connection.get_servername()) key,cert = self.certificates[servername] except KeyError as e: print e except Exception as e: print e new_context = Context(TLSv1_METHOD) new_context.use_privatekey_file(key) new_context.use_certificate_file(cert) connection.set_context(new_context)
def server_ok(serverarg, capath, timeout): "Check if the server is active and responsive" server_ctx = Context(TLSv1_METHOD) server_ctx.load_verify_locations(None, capath) def verify_cb(conn, cert, errnum, depth, ok): return ok server_ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb) serverarg = re.split("/*", serverarg)[1] if ':' in serverarg: serverarg = serverarg.split(':') server = serverarg[0] port = int(serverarg[1] if not '?' in serverarg[1] else serverarg[1].split('?')[0]) else: server = serverarg port = DEFAULT_PORT try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((server, port)) server_conn = Connection(server_ctx, sock) server_conn.set_connect_state() try: def handler(signum, frame): raise socket.error([('Timeout', 'after', str(timeout) + 's')]) signal.signal(signal.SIGALRM, handler) signal.alarm(timeout) server_conn.do_handshake() signal.alarm(0) except socket.timeout as e: nagios_out('Critical', 'Connection error %s - %s' % (server + ':' + str(port), errmsg_from_excp(e)),2) server_conn.shutdown() server_conn.close() except (SSLError, socket.error) as e: if 'sslv3 alert handshake failure' in errmsg_from_excp(e): pass else: nagios_out('Critical', 'Connection error %s - %s' % (server + ':' + str(port), errmsg_from_excp(e)), 2) return True
def prepare_handshake(self, connection): raw_sni = connection.get_servername() if raw_sni is not None: self.sni = str(raw_sni, 'ascii') self.build_server_conn() cert_dict = self.server_ssl_sock.getpeercert() crt_dir = generate_fake_cert(cert_dict) try: key, cert = load(crt_dir) except crypto.Error: raise CertificateRaceCondition new_context = Context(SSLv23_METHOD) new_context.use_privatekey(key) new_context.use_certificate(cert) connection.set_context(new_context)
def getContext(self): ctx = Context(TLSv1_METHOD) store = ctx.get_cert_store() store.add_cert(self.cert) ctx.load_verify_locations(self.certfile) ctx.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, self.verifyHostname) ctx.set_options(OP_NO_SSLv2) return ctx
def __init__(self, HOST='130.236.216.131', PORT = 443): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) context = Context(TLSv1_METHOD) context.use_certificate_file((self.certpath)) context.use_privatekey_file(self.keypath) context.set_timeout(2) conn = Connection(context,s) conn.bind((HOST,PORT)) print 'Server is listening...' conn.listen(5) # self.client_table is a dictionary of clients # where key = unique id and value = socket self.client_table = {} self.id_counter = 0 self.in_q = Queue.Queue() self.out_q = Queue.Queue() threading.Thread(target=self.sendinput).start() threading.Thread(target=self.in_processor).start() threading.Thread(target=self.out_processor).start() try: while True: # Waiting for new client to accept, sslsocket is the socket that will be used for communication with this client after a client sets up a connection with the server sslsocket, addr = conn.accept() self.client_table[self.id_counter] = sslsocket self.id_counter = self.id_counter + 1 threading.Thread(target=self.client_handler,args=(self.id_counter-1,)).start() except KeyboardInterrupt: for key, value in self.client_table.iteritems(): value.shutdown() value.close() sys.exit(0)
def verify_servercert(host, timeout, capath): server_ctx = Context(TLSv1_METHOD) server_ctx.load_verify_locations(None, capath) server_cert_chain = [] def verify_cb(conn, cert, errnum, depth, ok): server_cert_chain.append(cert) return ok server_ctx.set_verify(VERIFY_PEER, verify_cb) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(1) sock.settimeout(timeout) sock.connect((host, 443)) server_conn = Connection(server_ctx, sock) server_conn.set_connect_state() def iosock_try(): ok = True try: server_conn.do_handshake() sleep(0.5) except SSLWantReadError as e: ok = False pass except Exception as e: raise e return ok try: while True: if iosock_try(): break global server_expire server_expire = server_cert_chain[-1].get_notAfter() except PyOpenSSLError as e: raise e finally: server_conn.shutdown() server_conn.close() return True
def test_set_info_callback(self): """ L{Context.set_info_callback} accepts a callable which will be invoked when certain information about an SSL connection is available. """ (server, client) = socket_pair() clientSSL = Connection(Context(TLSv1_METHOD), client) clientSSL.set_connect_state() called = [] def info(conn, where, ret): called.append((conn, where, ret)) context = Context(TLSv1_METHOD) context.set_info_callback(info) context.use_certificate( load_certificate(FILETYPE_PEM, cleartextCertificatePEM)) context.use_privatekey( load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)) serverSSL = Connection(context, server) serverSSL.set_accept_state() while not called: for ssl in clientSSL, serverSSL: try: ssl.do_handshake() except WantReadError: pass # Kind of lame. Just make sure it got called somehow. self.assertTrue(called)
def _load_verify_locations_test(self, *args): port = socket() port.bind(('', 0)) port.listen(1) client = socket() client.setblocking(False) client.connect_ex(port.getsockname()) clientContext = Context(TLSv1_METHOD) clientContext.load_verify_locations(*args) # Require that the server certificate verify properly or the # connection will fail. clientContext.set_verify( VERIFY_PEER, lambda conn, cert, errno, depth, preverify_ok: preverify_ok) clientSSL = Connection(clientContext, client) clientSSL.set_connect_state() server, _ = port.accept() server.setblocking(False) serverContext = Context(TLSv1_METHOD) serverContext.use_certificate( load_certificate(FILETYPE_PEM, cleartextCertificatePEM)) serverContext.use_privatekey( load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)) serverSSL = Connection(serverContext, server) serverSSL.set_accept_state() for i in range(3): for ssl in clientSSL, serverSSL: try: # Without load_verify_locations above, the handshake # will fail: # Error: [('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE', # 'certificate verify failed')] ssl.do_handshake() except WantReadError: pass cert = clientSSL.get_peer_certificate() self.assertEqual(cert.get_subject().CN, 'Testing Root CA')
def main(): """ Run an SNI-enabled server which selects between a few certificates in a C{dict} based on the handshake request it receives from a client. """ port = socket() port.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) port.bind(('', 8443)) port.listen(3) print 'Accepting...', stdout.flush() server, addr = port.accept() print 'accepted', addr server_context = Context(TLSv1_METHOD) server_context.set_tlsext_servername_callback(pick_certificate) server_ssl = Connection(server_context, server) server_ssl.set_accept_state() server_ssl.do_handshake() server.close()
def main(): port = socket() port.bind(('', 0)) port.listen(5) client = socket() client.setblocking(False) client.connect_ex(port.getsockname()) client.setblocking(True) server = port.accept()[0] clientCtx = Context(TLSv1_METHOD) clientCtx.set_cipher_list('ALL:ADH') clientCtx.load_tmp_dh('dhparam.pem') sslClient = Connection(clientCtx, client) sslClient.set_connect_state() serverCtx = Context(TLSv1_METHOD) serverCtx.set_cipher_list('ALL:ADH') serverCtx.load_tmp_dh('dhparam.pem') sslServer = Connection(serverCtx, server) sslServer.set_accept_state() t1 = Thread(target=send, args=(sslClient,)) t2 = Thread(target=send, args=(sslServer,)) t3 = Thread(target=recv, args=(sslClient,)) t4 = Thread(target=recv, args=(sslServer,)) t1.start() t2.start() t3.start() t4.start() t1.join() t2.join() t3.join() t4.join()
def getContext(self): ctx = Context(TLSv1_METHOD) store = ctx.get_cert_store() for value in certificateAuthorityMap.values(): store.add_cert(value) ctx.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, self.verifyHostname) ctx.set_options(OP_NO_SSLv2) return ctx
def __init__(self, server_address, HandlerClass, bind_and_activate=True): socketserver.TCPServer.__init__(self, server_address, HandlerClass) ctx = Context(TLSv1_2_METHOD) ctx.use_privatekey_file (settings.ssl_key_path) ctx.use_certificate_file(settings.ssl_cert_path) # only allow clients with cert: ctx.set_verify(VERIFY_PEER | VERIFY_CLIENT_ONCE | VERIFY_FAIL_IF_NO_PEER_CERT, self._accept) #ctx.set_verify(VERIFY_PEER | VERIFY_CLIENT_ONCE, self._accept) self.socket = Connection(ctx, socket.socket(self.address_family, self.socket_type)) if bind_and_activate: self.server_bind() self.server_activate()
def test_set_passwd_cb(self): """ L{Context.set_passwd_cb} accepts a callable which will be invoked when a private key is loaded from an encrypted PEM. """ key = PKey() key.generate_key(TYPE_RSA, 128) pemFile = self.mktemp() fObj = file(pemFile, 'w') passphrase = "foobar" fObj.write(dump_privatekey(FILETYPE_PEM, key, "blowfish", passphrase)) fObj.close() calledWith = [] def passphraseCallback(maxlen, verify, extra): calledWith.append((maxlen, verify, extra)) return passphrase context = Context(TLSv1_METHOD) context.set_passwd_cb(passphraseCallback) context.use_privatekey_file(pemFile) self.assertTrue(len(calledWith), 1) self.assertTrue(isinstance(calledWith[0][0], int)) self.assertTrue(isinstance(calledWith[0][1], int)) self.assertEqual(calledWith[0][2], None)
def connect(self): print "You are trying to connect..." for x in range(7): if not self.connected: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) context = Context(TLSv1_METHOD) context.use_certificate_file(self.cacertpath) context.set_timeout(2) self.sslsocket = Connection(context,s) self.sslsocket.connect((self.host_addr,self.host_port)) #starting a thread that listen to what server sends which the clients need to be able to send and recive data at the same time t = threading.Thread(target=self.receive) t.daemon = True t.start() if self.sslsocket: self.connected = True print "connection established" #self.authentication("Kalle", "te") t = threading.Thread(target=self.sendinput) t.start() except socket.error: print "You failed to connect, retrying......." time.sleep(5)
def verify_cert(host, ca, timeout): server_ctx = Context(TLSv1_METHOD) server_cert_chain = [] if os.path.isdir(ca): server_ctx.load_verify_locations(None, ca) else: server_ctx.load_verify_locations(ca, None) def verify_cb(conn, cert, errnum, depth, ok): server_cert_chain.append(cert) return ok server_ctx.set_verify(VERIFY_PEER, verify_cb) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(1) sock.settimeout(timeout) sock.connect((host, 443)) server_conn = Connection(server_ctx, sock) server_conn.set_connect_state() def iosock_try(): ok = True try: server_conn.do_handshake() sleep(0.5) except SSLWantReadError as e: ok = False pass except Exception as e: raise e return ok try: while True: if iosock_try(): break server_subject = server_cert_chain[-1].get_subject() if host != server_subject.CN: raise SSLError('Server certificate CN does not match %s' % host) except SSLError as e: raise e finally: server_conn.shutdown() server_conn.close() return True
def getContext(self, hostname=None, port=None): ''' Returns a context pre-populated with x509 decoded root certs to validate against. ''' context = Context(TLSv1_METHOD) store = context.get_cert_store() for cert in self.root_certs: store.add_cert(cert) context.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, self.check_cn) context.set_options(OP_NO_SSLv2) return context
def go(): port = socket() port.bind(('', 0)) port.listen(1) called = [] def info(*args): print count.next() called.append(None) return 1 context = Context(TLSv1_METHOD) context.set_verify(VERIFY_PEER, info) context.use_certificate( load_certificate(FILETYPE_PEM, cleartextCertificatePEM)) context.use_privatekey( load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)) while 1: client = socket() client.setblocking(False) client.connect_ex(port.getsockname()) clientSSL = Connection(context, client) clientSSL.set_connect_state() server, ignored = port.accept() server.setblocking(False) serverSSL = Connection(context, server) serverSSL.set_accept_state() del called[:] while not called: for ssl in clientSSL, serverSSL: try: ssl.send('foo') except WantReadError, e: pass
def go(): port = socket() port.bind(('', 0)) port.listen(1) called = [] def info(conn, where, ret): print count.next() called.append(None) context = Context(TLSv1_METHOD) context.set_info_callback(info) context.use_certificate( load_certificate(FILETYPE_PEM, cleartextCertificatePEM)) context.use_privatekey( load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)) while 1: client = socket() client.setblocking(False) client.connect_ex(port.getsockname()) clientSSL = Connection(Context(TLSv1_METHOD), client) clientSSL.set_connect_state() server, ignored = port.accept() server.setblocking(False) serverSSL = Connection(context, server) serverSSL.set_accept_state() del called[:] while not called: for ssl in clientSSL, serverSSL: try: ssl.do_handshake() except WantReadError: pass
def getContext(self): ctx = Context(SSLv3_METHOD) ctx.set_options(0x00004000L) return ctx
def do_GET(self): get_params = parse.urlparse(self.path).query get_url = input_target_url if get_params: get_url = '%s?%s' % (get_url, get_params) new_headers = dict(self.headers) if 'Host' in new_headers: del new_headers['Host'] new_request = request.Request(url=get_url, data=None, headers=new_headers, method='GET') # TU ZACINA GRCKA SORRY. certificate_common_names = None certificate_is_valid = None if get_url.startswith('https://'): client = None try: client = socket.socket() # print('Connecting...') client.connect((parse.urlparse(get_url).netloc, 443)) client_ssl = Connection(Context(TLSv1_2_METHOD), client) client_ssl.set_connect_state() client_ssl.set_tlsext_host_name( parse.urlparse(get_url).netloc.encode('UTF-8')) client_ssl.do_handshake() # print('Server subject is', dict(client_ssl.get_peer_certificate().get_subject().get_components())) certificate_common_names = get_certificate_san( client_ssl.get_peer_certificate()) except: pass finally: if client: client.close() try: with request.urlopen(new_request, timeout=1) as response: certificate_is_valid = True except: certificate_is_valid = False # TU KONCI GRCKA. try: ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE with request.urlopen(new_request, timeout=1, context=ctx) as response: res_content = response.read().decode('UTF-8') output = prepare_output(response.status, response.getheaders(), res_content, certificate_is_valid, certificate_common_names) self.send_result(200, output) except HTTPError as err: self.send_result(200, prepare_output(err.code, None, None)) except: return self.send_result(200, prepare_output('timeout', None, None))
def getContext(self): """Create an SSL context. This is a sample implementation that loads a certificate from a file called 'server.pem'.""" ctx = SSL_Context(SSLv23_METHOD) ctx.use_certificate_file(self.certificateFileName) ctx.use_privatekey_file(self.privateKeyFileName) ctx.load_client_ca(self.certificateChainFile) ctx.load_verify_locations(self.certificateChainFile) ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT, self._verify) ctx.set_verify_depth(10) return ctx
def getContext(self): ctx = Context(TLSv1_METHOD) ctx.use_certificate(self.flocker_credential.certificate.original) ctx.use_privatekey(self.flocker_credential.keypair.keypair.original) return ctx
msg[0]) + ' , Error message : ' + msg[1] sys.exit() print 'Socket Created' host = 'www.google.com' port = 80 try: remote_ip = socket.gethostbyname(host) except socket.gaierror: #could not resolve print 'Hostname could not be resolved. Exiting' sys.exit() client.connect((remote_ip, port)) print 'connected', client.getpeername() client_ssl = Connection(Context(SSLv3_METHOD), client) client_ssl.set_connect_state() #client_ssl.set_tlsext_host_name(argv[1]) client_ssl.do_handshake() print 'Server subject is', client_ssl.get_peer_certificate().get_subject() client_ssl.close() if __name__ == '__main__': import client raise SystemExit(client.main())
host = argv[1] + '.' + argv[2] port = argv[3] print '\nChecking DNS for CAA records . . .\n' answers = dns.resolver.query(domain, 'CAA') print 'The following records were found:\n' for rdata in answers: print domain, 'in CAA', rdata.flags, rdata.value print '\nNow checking certificate . . . \n' print 'Using server name:', host, 'on port', port, 'for SNI ...' client = socket() stdout.flush() client.connect(('{0}'.format(host), int(port))) print 'Connected to', client.getpeername(), '\n' client_ssl = Connection(Context(TLSv1_METHOD), client) client_ssl.set_connect_state() client_ssl.set_tlsext_host_name(host) client_ssl.do_handshake() issuer = client_ssl.get_peer_certificate().get_issuer() issr = str(issuer) issr = issr.strip('<>') issr = issr.replace('X509Name object', 'Certificate Information: ') issr = issr.replace('C=', 'Country: ') issr = issr.replace('O=', 'Organization: ') issr = issr.replace('CN=', 'Common Name: ') issr = issr.split('/') for issr in issr: print issr print '\n' client_ssl.close()
def getContext(self): ctx = Context(SSLv23_METHOD) ctx.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, self.fetch) return ctx
Created by PyCharm. File: LinuxBashShellScriptForOps:pyGetCertsInfo.py User: Guodong Create Date: 2016/12/1 Create Time: 13:58 """ import datetime import time from socket import socket from OpenSSL.SSL import Connection, Context, SSLv3_METHOD, TLSv1_2_METHOD host = 'www.baidu.com' try: ssl_connection_setting = Context(SSLv3_METHOD) except ValueError: ssl_connection_setting = Context(TLSv1_2_METHOD) ssl_connection_setting.set_timeout(30) s = socket() s.connect((host, 443)) c = Connection(ssl_connection_setting, s) c.set_connect_state() c.do_handshake() cert = c.get_peer_certificate() print "Issuer: ", cert.get_issuer() print "Subject: ", cert.get_subject().get_components() subject_list = cert.get_subject().get_components() print "Common Name:", dict(subject_list).get("CN") print "notAfter(UTC time): ", cert.get_notAfter()
tlsFactory = TLSMemoryBIOFactory(contextFactory, False, serverFactory) reactor.listenTCP(12345, tlsFactory) reactor.run() This API offers somewhat more flexibility than L{twisted.internet.interfaces.IReactorSSL}; for example, a L{TLSMemoryBIOProtocol} instance can use another instance of L{TLSMemoryBIOProtocol} as its transport, yielding TLS over TLS - useful to implement onion routing. It can also be used to run TLS over unusual transports, such as UNIX sockets and stdio. """ from OpenSSL.SSL import Error, ZeroReturnError, WantReadError from OpenSSL.SSL import TLSv1_METHOD, Context, Connection try: Connection(Context(TLSv1_METHOD), None) except TypeError, e: if str(e) != "argument must be an int, or have a fileno() method.": raise raise ImportError( "twisted.protocols.tls requires pyOpenSSL 0.10 or newer.") from zope.interface import implements from twisted.python.failure import Failure from twisted.python import log from twisted.python.reflect import safe_str from twisted.internet.interfaces import ISystemHandle, ISSLTransport from twisted.internet.interfaces import IPushProducer, ILoggingContext from twisted.internet.main import CONNECTION_LOST from twisted.internet.protocol import Protocol
def do_POST(self): content_len = int(self.headers.get('Content-Length', 0)) post_body = self.rfile.read(content_len) try: json_body = json.loads(post_body) request_type = 'GET' if 'type' in json_body: request_type = json_body['type'] if 'url' not in json_body or (request_type == 'POST' and 'content' not in json_body): self.send_result(200, prepare_output('invalid json')) request_url = json_body['url'] request_headers = json_body[ 'headers'] if 'headers' in json_body else dict() request_content = json_body[ 'content'] if request_type == 'POST' else None request_timeout = json_body[ 'timeout'] if 'timeout' in json_body else 1 request_headers = { k.lower(): v for k, v in request_headers.items() } if 'content-type' not in request_headers: request_headers['content-type'] = 'text/plain' new_request = request.Request( url=request_url, data=bytes(request_content, 'UTF-8') if request_content else None, headers=request_headers, method=request_type) # TU ZACINA GRCKA SORRY. # cert_raw = ssl.get_server_certificate(('google.com', 443)) # cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_raw) # print(dict(cert.get_subject().get_components())) certificate_common_names = None certificate_is_valid = None if request_url.startswith('https://'): client = None try: client = socket.socket() # print('Connecting...') client.connect( (parse.urlparse(request_url).netloc, 443)) client_ssl = Connection(Context(TLSv1_2_METHOD), client) client_ssl.set_connect_state() client_ssl.set_tlsext_host_name( parse.urlparse(request_url).netloc.encode('UTF-8')) client_ssl.do_handshake() # print('Server subject is', dict(client_ssl.get_peer_certificate().get_subject().get_components())) certificate_common_names = get_certificate_san( client_ssl.get_peer_certificate()) except: pass finally: if client: client.close() try: with request.urlopen( new_request, timeout=request_timeout) as response: certificate_is_valid = True except: certificate_is_valid = False # TU KONCI GRCKA. try: ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE with request.urlopen(new_request, timeout=request_timeout, context=ctx) as response: res_content = response.read().decode('UTF-8') output = prepare_output(response.status, response.getheaders(), res_content, certificate_is_valid, certificate_common_names) self.send_result(200, output) except HTTPError as err: self.send_result(200, prepare_output(err.code, None, None)) except: return self.send_result( 200, prepare_output('timeout', None, None)) except ValueError: # import traceback # traceback.print_exc() self.send_result(200, prepare_output('invalid json'))
def verify_cert(host, capath, timeout, cncheck=True): server_ctx = Context(TLSv1_METHOD) server_cert_chain = [] server_ctx.load_verify_locations(None, capath) host = re.split("/*", host)[1] if ':' in host: host = host.split(':') server = host[0] port = int(host[1] if not '?' in host[1] else host[1].split('?')[0]) else: server = host port = 443 def verify_cb(conn, cert, errnum, depth, ok): server_cert_chain.append(cert) return ok server_ctx.set_verify(VERIFY_PEER, verify_cb) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(1) sock.settimeout(timeout) sock.connect((server, port)) except (socket.error, socket.timeout) as e: nagios_out( 'Critical', 'Connection error %s - %s' % (server + ':' + str(port), errmsg_from_excp(e)), 2) server_conn = Connection(server_ctx, sock) server_conn.set_connect_state() def iosock_try(): ok = True try: server_conn.do_handshake() sleep(0.5) except SSLWantReadError as e: ok = False pass except Exception as e: raise e return ok try: while True: if iosock_try(): break if cncheck: server_subject = server_cert_chain[-1].get_subject() if server != server_subject.CN: nagios_out( 'Critical', 'Server certificate CN %s does not match %s' % (server_subject.CN, server), 2) except SSLError as e: if 'sslv3 alert handshake failure' in errmsg_from_excp(e): pass else: nagios_out( 'Critical', 'Connection error %s - %s' % (server + ':' + str(port), errmsg_from_excp(e, level=1)), 2) finally: server_conn.shutdown() server_conn.close() return True
def getContext(self): # log.msg(self.connection.get_protocol_version_name()) server_context = Context(SSL.TLSv1_2_METHOD) server_context.set_tlsext_servername_callback(self) #server_context.sni_callback=self.server_name return server_context
def Sockets(addresses, **args): ssl_private_key = args.get('ssl_private_key', args.get('key_file')) ssl_certificate = args.get('ssl_certificate', args.get('cert_file')) ssl = ssl_certificate and ssl_private_key if ssl: if not SSL: raise ImportError('you must install pyOpenSSL to use https') ctx = SSLContext(SSLv23_METHOD) ctx.use_privatekey_file(ssl_private_key) ctx.use_certificate_file(ssl_certificate) cert = load_certificate(FILETYPE_PEM, open(ssl_certificate, 'rb').read()) base_environ = dict(HTTPS='on', SSL_SERVER_M_SERIAL=cert.get_serial_number(), SSL_SERVER_M_VERSION=cert.get_version()) for prefix, dn in [("I", cert.get_issuer()), ("S", cert.get_subject())]: dnstr = str(dn)[18:-2] wsgikey = 'SSL_SERVER_%s_DN' % prefix base_environ[wsgikey] = dnstr while dnstr: pos = dnstr.rfind('=') dnstr, value = dnstr[:pos], dnstr[pos + 1:] pos = dnstr.rfind('/') dnstr, key = dnstr[:pos], dnstr[pos + 1:] if key and value: wsgikey = 'SSL_SERVER_%s_DN_%s' % (prefix, key) base_environ[wsgikey] = value socket_func = lambda family, socktype: \ SSL(SSLConnection(ctx, Socket(family, socktype))) fromfd_func = lambda fileno, family, socktype: \ SSL(SSLConnection(ctx, fromfd(fileno, family, socktype))) else: fromfd_func, socket_func, base_environ = fromfd, Socket, {} if isinstance(addresses, basestring): addresses, addrs = [], [ i for i in str(addresses).split(',') if i.strip() ] for addr in addrs: is_ipv6 = R_IPV6(addr) if is_ipv6: addresses.append((AF_INET6, is_ipv6.groups())) continue seq = [i.strip() for i in addr.split(':')] if len(seq) == 2: if seq[0].lower() in ('fromfd', 'fileno'): addresses.append((AF_INET, int(seq[1]))) continue addresses.append((AF_INET, seq)) continue if len(seq) == 3 and seq[0].lower() in ('fromfd', 'fileno'): family = seq[1].lower() if family in ('inet', 'af_inet', 'ipv4'): addresses.append((AF_INET, int(seq[2]))) continue elif family in ('inet6', 'af_inet6', 'ipv6', '6'): addresses.append((AF_INET, int(seq[2]))) continue elif family in ('unix', 'af_unix', 's', 'socket', 'unix_socket', 'unixsocket', 'unixsock'): addresses.append((_socket.AF_UNIX, int(seq[2]))) continue addresses.append((_socket.AF_UNIX, addr.strip())) else: addresses, addrs = [], addresses for addr in addrs: if isinstance(addr, (int, long)): addresses.append((AF_INET, addr)) continue if isinstance(addr, (list, tuple)) and len(addr) == 2: if isinstance(addr[0], (int, long)): address.append(addr) continue if isinstance(addr[0], basestring): addresses.append((AF_INET6, addr) if ':' in addr[0] \ else (AF_INET , addr)) continue if isinstance(addr, basestring): addresses.append((_socket.AF_UNIX, addr)) continue raise ValueError('bad address %r' % addr) sockets = [] for family, addr in addresses: if isinstance(addr, (int, long)): sock = fromfd_func(addr, family, SOCK_STREAM) sock.setblocking(0) environ = dict(SERVER_NAME='fileno:%d' % addr, SERVER_PORT='') environ.update(base_environ) sockets.append((sock, environ)) continue if family == AF_UNIX: sock = socket_func(_socket.AF_UNIX, SOCK_STREAM) sock.setblocking(0) try: sock.bind(addr) except SocketError, address_already_in_use: if address_already_in_use.args[0] != 98: raise ping = socket_func(_socket.AF_UNIX, SOCK_STREAM) try: ping.connect(addr) except SocketError, e: if e.args[0] == 111: os.unlink(addr) sock.bind(addr) else: ping.close() raise address_already_in_use sock.listen(4194304) environ = dict(SERVER_NAME='s:%s' % addr, SERVER_PORT='') environ.update(base_environ) sockets.append((sock, environ)) continue
def test_create_self_signed_cert(): cert_a, _ = cssc(join(getcwd(), "data"), "a.pem", "a.key") cert_b, _ = cssc(join(getcwd(), "data"), "b.pem", "b.key") key_a = load_privatekey(FP, open(join(getcwd(), "data", "a.key")).read()) cert_a = load_certificate(FP, open(join(getcwd(), "data", "a.pem")).read()) cert_b = load_certificate(FP, open(join(getcwd(), "data", "b.pem")).read()) ctx = Context(TLSv1_METHOD) ctx.use_privatekey(key_a) ctx.use_certificate(cert_a) ctx.check_privatekey() ctx.use_certificate(cert_b) with pytest.raises(Error): ctx.check_privatekey() remove(join(getcwd(), "data", "a.pem")) remove(join(getcwd(), "data", "a.key")) remove(join(getcwd(), "data", "b.pem")) remove(join(getcwd(), "data", "b.key"))
def cacheContext(self): # Unfortunate code duplication. ctx = SSLContext(self.sslmethod) if self.ciphers is not None: ctx.set_cipher_list(self.ciphers) if self.passwdCallback is not None: ctx.set_passwd_cb(self.passwdCallback) ctx.use_certificate_file(self.certificateFileName) ctx.use_privatekey_file(self.privateKeyFileName) if self.certificateChainFile != "": ctx.use_certificate_chain_file(self.certificateChainFile) self._context = ctx
def cacheContext(self): # Unfortunate code duplication. ctx = SSLContext(self.sslmethod) # Always disable SSLv2/SSLv3 ctx.set_options(OP_NO_SSLv2) ctx.set_options(OP_NO_SSLv3) if self.ciphers is not None: ctx.set_cipher_list(self.ciphers) ctx.set_options(OP_CIPHER_SERVER_PREFERENCE) if self.passwdCallback is not None: ctx.set_passwd_cb(self.passwdCallback) ctx.use_certificate_file(self.certificateFileName) ctx.use_privatekey_file(self.privateKeyFileName) if self.certificateChainFile != "": ctx.use_certificate_chain_file(self.certificateChainFile) verifyFlags = VERIFY_NONE if self.verifyClient: verifyFlags = VERIFY_PEER if self.requireClientCertificate: verifyFlags |= VERIFY_FAIL_IF_NO_PEER_CERT if self.verifyClientOnce: verifyFlags |= VERIFY_CLIENT_ONCE if self.clientCACertFileNames: store = ctx.get_cert_store() for cert in self.clientCACertFileNames: with open(cert) as f: certpem = f.read() cert = Certificate.loadPEM(certpem) store.add_cert(cert.original) if self.sendCAsToClient: ctx.add_client_ca(cert.original) # When a client certificate is used we also need to set a session context id # to avoid openssl SSL_F_SSL_GET_PREV_SESSION,SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED # errors ctx.set_session_id(str(uuid.uuid4()).replace("-", "")) # It'd be nice if pyOpenSSL let us pass None here for this behavior (as # the underlying OpenSSL API call allows NULL to be passed). It # doesn't, so we'll supply a function which does the same thing. def _verifyCallback(conn, cert, errno, depth, preverify_ok): return preverify_ok ctx.set_verify(verifyFlags, _verifyCallback) if self.verifyClientDepth is not None: ctx.set_verify_depth(self.verifyClientDepth) self._context = ctx