Python ssl.SSLContext() Examples
The following are 30
code examples of ssl.SSLContext().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
ssl
, or try the search function
.
Example #1
Source File: client.py From verge3d-blender-addon with GNU General Public License v3.0 | 7 votes |
def __init__(self, host, port=None, key_file=None, cert_file=None, strict=_strict_sentinel, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, **_3to2kwargs): if 'check_hostname' in _3to2kwargs: check_hostname = _3to2kwargs['check_hostname']; del _3to2kwargs['check_hostname'] else: check_hostname = None if 'context' in _3to2kwargs: context = _3to2kwargs['context']; del _3to2kwargs['context'] else: context = None super(HTTPSConnection, self).__init__(host, port, strict, timeout, source_address) self.key_file = key_file self.cert_file = cert_file if context is None: # Some reasonable defaults context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.options |= ssl.OP_NO_SSLv2 will_verify = context.verify_mode != ssl.CERT_NONE if check_hostname is None: check_hostname = will_verify elif check_hostname and not will_verify: raise ValueError("check_hostname needs a SSL context with " "either CERT_OPTIONAL or CERT_REQUIRED") if key_file or cert_file: context.load_cert_chain(cert_file, key_file) self._context = context self._check_hostname = check_hostname
Example #2
Source File: test_ssl.py From workload-collocation-agent with Apache License 2.0 | 6 votes |
def test_good_certificate(): # Disable due to https://github.com/urllib3/urllib3/issues/497 requests.packages.urllib3.disable_warnings( requests.packages.urllib3.exceptions.SubjectAltNameWarning) ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) ssl_context.load_cert_chain('tests/ssl/goodkey.crt', 'tests/ssl/goodkey.key') server = Process(target=run_simple_https_server, args=(ssl_context,)) server.start() time.sleep(0.5) try: s = requests.Session() s.mount('https://localhost:8080/', HTTPSAdapter()) r = s.get('https://localhost:8080/', verify='tests/ssl/rootCA.crt') assert r.text == 'Passed' server.terminate() except Exception: server.terminate() raise
Example #3
Source File: request.py From verge3d-blender-addon with GNU General Public License v3.0 | 6 votes |
def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, **_3to2kwargs): if 'cadefault' in _3to2kwargs: cadefault = _3to2kwargs['cadefault']; del _3to2kwargs['cadefault'] else: cadefault = False if 'capath' in _3to2kwargs: capath = _3to2kwargs['capath']; del _3to2kwargs['capath'] else: capath = None if 'cafile' in _3to2kwargs: cafile = _3to2kwargs['cafile']; del _3to2kwargs['cafile'] else: cafile = None global _opener if cafile or capath or cadefault: if not _have_ssl: raise ValueError('SSL support not available') context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.options |= ssl.OP_NO_SSLv2 context.verify_mode = ssl.CERT_REQUIRED if cafile or capath: context.load_verify_locations(cafile, capath) else: context.set_default_verify_paths() https_handler = HTTPSHandler(context=context, check_hostname=True) opener = build_opener(https_handler) elif _opener is None: _opener = opener = build_opener() else: opener = _opener return opener.open(url, data, timeout)
Example #4
Source File: test_httplib.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_local_bad_hostname(self): # The (valid) cert doesn't validate the HTTP hostname import ssl server = self.make_server(CERT_fakehostname) context = ssl.SSLContext(ssl.PROTOCOL_TLS) context.verify_mode = ssl.CERT_REQUIRED context.check_hostname = True context.load_verify_locations(CERT_fakehostname) h = httplib.HTTPSConnection('localhost', server.port, context=context) with self.assertRaises(ssl.CertificateError): h.request('GET', '/') h.close() # With context.check_hostname=False, the mismatching is ignored context.check_hostname = False h = httplib.HTTPSConnection('localhost', server.port, context=context) h.request('GET', '/nonexistent') resp = h.getresponse() self.assertEqual(resp.status, 404)
Example #5
Source File: connections.py From python-gvm with GNU General Public License v3.0 | 6 votes |
def _new_socket(self): transport_socket = socketlib.socket( socketlib.AF_INET, socketlib.SOCK_STREAM ) if self.certfile and self.cafile and self.keyfile: context = ssl.create_default_context( ssl.Purpose.SERVER_AUTH, cafile=self.cafile ) context.check_hostname = False context.load_cert_chain( certfile=self.certfile, keyfile=self.keyfile, password=self.password, ) sock = context.wrap_socket(transport_socket, server_side=False) else: context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) sock = context.wrap_socket(transport_socket) sock.settimeout(self._timeout) return sock
Example #6
Source File: ssl_servers.py From verge3d-blender-addon with GNU General Public License v3.0 | 6 votes |
def make_https_server(case, certfile=CERTFILE, host=HOST, handler_class=None): # we assume the certfile contains both private key and certificate context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.load_cert_chain(certfile) server = HTTPSServerThread(context, host, handler_class) flag = threading.Event() server.start(flag) flag.wait() def cleanup(): if support.verbose: sys.stdout.write('stopping HTTPS server\n') server.stop() if support.verbose: sys.stdout.write('joining HTTPS thread\n') server.join() case.addCleanup(cleanup) return server
Example #7
Source File: XAsyncSockets.py From MicroWebSrv2 with MIT License | 6 votes |
def StartSSLContext(self, sslContext, serverSide=False) : if not hasattr(ssl, 'SSLContext') : raise XAsyncTCPClientException('StartSSLContext : This SSL implementation is not supported.') if not isinstance(sslContext, ssl.SSLContext) : raise XAsyncTCPClientException('StartSSLContext : "sslContext" is incorrect.') if self.IsSSL : raise XAsyncTCPClientException('StartSSLContext : SSL already started.') try : self._asyncSocketsPool.NotifyNextReadyForWriting(self, False) self._asyncSocketsPool.NotifyNextReadyForReading(self, False) self._socket = sslContext.wrap_socket( self._socket, server_side = serverSide, do_handshake_on_connect = False ) except Exception as ex : raise XAsyncTCPClientException('StartSSLContext : %s' % ex) self._doSSLHandshake() # ------------------------------------------------------------------------
Example #8
Source File: XAsyncSockets.py From MicroWebSrv2 with MIT License | 6 votes |
def StartSSL( self, keyfile = None, certfile = None, server_side = False, cert_reqs = 0, ca_certs = None ) : if not hasattr(ssl, 'SSLContext') : raise XAsyncTCPClientException('StartSSL : This SSL implementation is not supported.') if self.IsSSL : raise XAsyncTCPClientException('StartSSL : SSL already started.') try : self._asyncSocketsPool.NotifyNextReadyForWriting(self, False) self._asyncSocketsPool.NotifyNextReadyForReading(self, False) self._socket = ssl.wrap_socket( self._socket, keyfile = keyfile, certfile = certfile, server_side = server_side, cert_reqs = cert_reqs, ca_certs = ca_certs, do_handshake_on_connect = False ) except Exception as ex : raise XAsyncTCPClientException('StartSSL : %s' % ex) self._doSSLHandshake() # ------------------------------------------------------------------------
Example #9
Source File: test_ftplib.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_context(self): self.client.quit() ctx = ssl.SSLContext(ssl.PROTOCOL_TLS) self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE, context=ctx) self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE, context=ctx) self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE, keyfile=CERTFILE, context=ctx) self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT) self.client.connect(self.server.host, self.server.port) self.assertNotIsInstance(self.client.sock, ssl.SSLSocket) self.client.auth() self.assertIs(self.client.sock.context, ctx) self.assertIsInstance(self.client.sock, ssl.SSLSocket) self.client.prot_p() sock = self.client.transfercmd('list') try: self.assertIs(sock.context, ctx) self.assertIsInstance(sock, ssl.SSLSocket) finally: sock.close()
Example #10
Source File: connections.py From ServerlessCrawler-VancouverRealState with MIT License | 6 votes |
def _create_ssl_ctx(self, sslp): if isinstance(sslp, ssl.SSLContext): return sslp ca = sslp.get('ca') capath = sslp.get('capath') hasnoca = ca is None and capath is None ctx = ssl.create_default_context(cafile=ca, capath=capath) ctx.check_hostname = not hasnoca and sslp.get('check_hostname', True) ctx.verify_mode = ssl.CERT_NONE if hasnoca else ssl.CERT_REQUIRED if 'cert' in sslp: ctx.load_cert_chain(sslp['cert'], keyfile=sslp.get('key')) if 'cipher' in sslp: ctx.set_ciphers(sslp['cipher']) ctx.options |= ssl.OP_NO_SSLv2 ctx.options |= ssl.OP_NO_SSLv3 return ctx
Example #11
Source File: serving.py From recruit with Apache License 2.0 | 6 votes |
def load_ssl_context(cert_file, pkey_file=None, protocol=None): """Loads SSL context from cert/private key files and optional protocol. Many parameters are directly taken from the API of :py:class:`ssl.SSLContext`. :param cert_file: Path of the certificate to use. :param pkey_file: Path of the private key to use. If not given, the key will be obtained from the certificate file. :param protocol: One of the ``PROTOCOL_*`` constants in the stdlib ``ssl`` module. Defaults to ``PROTOCOL_SSLv23``. """ if protocol is None: protocol = ssl.PROTOCOL_SSLv23 ctx = _SSLContext(protocol) ctx.load_cert_chain(cert_file, pkey_file) return ctx
Example #12
Source File: archive.py From bob with GNU General Public License v3.0 | 6 votes |
def _getConnection(self): if self.__connection is not None: return self.__connection url = self.__url if url.scheme == 'http': connection = http.client.HTTPConnection(url.hostname, url.port) elif url.scheme == 'https': ctx = None if self.__sslVerify else ssl.SSLContext(ssl.PROTOCOL_SSLv23) connection = http.client.HTTPSConnection(url.hostname, url.port, context=ctx) else: raise BuildError("Unsupported URL scheme: '{}'".format(url.schema)) self.__connection = connection return connection
Example #13
Source File: client.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def __init__(self, host, port=None, key_file=None, cert_file=None, strict=_strict_sentinel, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, **_3to2kwargs): if 'check_hostname' in _3to2kwargs: check_hostname = _3to2kwargs['check_hostname']; del _3to2kwargs['check_hostname'] else: check_hostname = None if 'context' in _3to2kwargs: context = _3to2kwargs['context']; del _3to2kwargs['context'] else: context = None super(HTTPSConnection, self).__init__(host, port, strict, timeout, source_address) self.key_file = key_file self.cert_file = cert_file if context is None: # Some reasonable defaults context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.options |= ssl.OP_NO_SSLv2 will_verify = context.verify_mode != ssl.CERT_NONE if check_hostname is None: check_hostname = will_verify elif check_hostname and not will_verify: raise ValueError("check_hostname needs a SSL context with " "either CERT_OPTIONAL or CERT_REQUIRED") if key_file or cert_file: context.load_cert_chain(cert_file, key_file) self._context = context self._check_hostname = check_hostname
Example #14
Source File: request.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, **_3to2kwargs): if 'cadefault' in _3to2kwargs: cadefault = _3to2kwargs['cadefault']; del _3to2kwargs['cadefault'] else: cadefault = False if 'capath' in _3to2kwargs: capath = _3to2kwargs['capath']; del _3to2kwargs['capath'] else: capath = None if 'cafile' in _3to2kwargs: cafile = _3to2kwargs['cafile']; del _3to2kwargs['cafile'] else: cafile = None global _opener if cafile or capath or cadefault: if not _have_ssl: raise ValueError('SSL support not available') context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.options |= ssl.OP_NO_SSLv2 context.verify_mode = ssl.CERT_REQUIRED if cafile or capath: context.load_verify_locations(cafile, capath) else: context.set_default_verify_paths() https_handler = HTTPSHandler(context=context, check_hostname=True) opener = build_opener(https_handler) elif _opener is None: _opener = opener = build_opener() else: opener = _opener return opener.open(url, data, timeout)
Example #15
Source File: client.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def __init__(self, host, port=None, key_file=None, cert_file=None, strict=_strict_sentinel, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, **_3to2kwargs): if 'check_hostname' in _3to2kwargs: check_hostname = _3to2kwargs['check_hostname']; del _3to2kwargs['check_hostname'] else: check_hostname = None if 'context' in _3to2kwargs: context = _3to2kwargs['context']; del _3to2kwargs['context'] else: context = None super(HTTPSConnection, self).__init__(host, port, strict, timeout, source_address) self.key_file = key_file self.cert_file = cert_file if context is None: # Some reasonable defaults context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.options |= ssl.OP_NO_SSLv2 will_verify = context.verify_mode != ssl.CERT_NONE if check_hostname is None: check_hostname = will_verify elif check_hostname and not will_verify: raise ValueError("check_hostname needs a SSL context with " "either CERT_OPTIONAL or CERT_REQUIRED") if key_file or cert_file: context.load_cert_chain(cert_file, key_file) self._context = context self._check_hostname = check_hostname
Example #16
Source File: iostream.py From tornado-zh with MIT License | 6 votes |
def __init__(self, *args, **kwargs): """The ``ssl_options`` keyword argument may either be an `ssl.SSLContext` object or a dictionary of keywords arguments for `ssl.wrap_socket` """ self._ssl_options = kwargs.pop('ssl_options', _client_ssl_defaults) super(SSLIOStream, self).__init__(*args, **kwargs) self._ssl_accepting = True self._handshake_reading = False self._handshake_writing = False self._ssl_connect_callback = None self._server_hostname = None # If the socket is already connected, attempt to start the handshake. try: self.socket.getpeername() except socket.error: pass else: # Indirectly start the handshake, which will run on the next # IOLoop iteration and then the real IO state will be set in # _handle_events. self._add_io_state(self.io_loop.WRITE)
Example #17
Source File: netutil.py From tornado-zh with MIT License | 6 votes |
def ssl_wrap_socket(socket, ssl_options, server_hostname=None, **kwargs): """Returns an ``ssl.SSLSocket`` wrapping the given socket. ``ssl_options`` may be either an `ssl.SSLContext` object or a dictionary (as accepted by `ssl_options_to_context`). Additional keyword arguments are passed to ``wrap_socket`` (either the `~ssl.SSLContext` method or the `ssl` module function as appropriate). """ context = ssl_options_to_context(ssl_options) if hasattr(ssl, 'SSLContext') and isinstance(context, ssl.SSLContext): if server_hostname is not None and getattr(ssl, 'HAS_SNI'): # Python doesn't have server-side SNI support so we can't # really unittest this, but it can be manually tested with # python3.2 -m tornado.httpclient https://sni.velox.ch return context.wrap_socket(socket, server_hostname=server_hostname, **kwargs) else: return context.wrap_socket(socket, **kwargs) else: return ssl.wrap_socket(socket, **dict(context, **kwargs))
Example #18
Source File: serving.py From jbox with MIT License | 6 votes |
def load_ssl_context(cert_file, pkey_file=None, protocol=None): """Loads SSL context from cert/private key files and optional protocol. Many parameters are directly taken from the API of :py:class:`ssl.SSLContext`. :param cert_file: Path of the certificate to use. :param pkey_file: Path of the private key to use. If not given, the key will be obtained from the certificate file. :param protocol: One of the ``PROTOCOL_*`` constants in the stdlib ``ssl`` module. Defaults to ``PROTOCOL_SSLv23``. """ if protocol is None: protocol = ssl.PROTOCOL_SSLv23 ctx = _SSLContext(protocol) ctx.load_cert_chain(cert_file, pkey_file) return ctx
Example #19
Source File: client.py From python-slackclient with MIT License | 6 votes |
def __init__( self, url: str, timeout: int = 30, ssl: Optional[SSLContext] = None, proxy: Optional[str] = None, default_headers: Dict[str, str] = {}, ): """API client for Incoming Webhooks and response_url :param url: a complete URL to send data (e.g., https://hooks.slack.com/XXX) :param timeout: request timeout (in seconds) :param ssl: ssl.SSLContext to use for requests :param proxy: proxy URL (e.g., localhost:9000, http://localhost:9000) :param default_headers: request headers to add to all requests """ self.url = url self.timeout = timeout self.ssl = ssl self.proxy = proxy self.default_headers = default_headers
Example #20
Source File: iostream.py From tornado-zh with MIT License | 6 votes |
def __init__(self, *args, **kwargs): """The ``ssl_options`` keyword argument may either be an `ssl.SSLContext` object or a dictionary of keywords arguments for `ssl.wrap_socket` """ self._ssl_options = kwargs.pop('ssl_options', _client_ssl_defaults) super(SSLIOStream, self).__init__(*args, **kwargs) self._ssl_accepting = True self._handshake_reading = False self._handshake_writing = False self._ssl_connect_callback = None self._server_hostname = None # If the socket is already connected, attempt to start the handshake. try: self.socket.getpeername() except socket.error: pass else: # Indirectly start the handshake, which will run on the next # IOLoop iteration and then the real IO state will be set in # _handle_events. self._add_io_state(self.io_loop.WRITE)
Example #21
Source File: netutil.py From tornado-zh with MIT License | 6 votes |
def ssl_wrap_socket(socket, ssl_options, server_hostname=None, **kwargs): """Returns an ``ssl.SSLSocket`` wrapping the given socket. ``ssl_options`` may be either an `ssl.SSLContext` object or a dictionary (as accepted by `ssl_options_to_context`). Additional keyword arguments are passed to ``wrap_socket`` (either the `~ssl.SSLContext` method or the `ssl` module function as appropriate). """ context = ssl_options_to_context(ssl_options) if hasattr(ssl, 'SSLContext') and isinstance(context, ssl.SSLContext): if server_hostname is not None and getattr(ssl, 'HAS_SNI'): # Python doesn't have server-side SNI support so we can't # really unittest this, but it can be manually tested with # python3.2 -m tornado.httpclient https://sni.velox.ch return context.wrap_socket(socket, server_hostname=server_hostname, **kwargs) else: return context.wrap_socket(socket, **kwargs) else: return ssl.wrap_socket(socket, **dict(context, **kwargs))
Example #22
Source File: httprelayclient.py From CVE-2017-7494 with GNU General Public License v3.0 | 6 votes |
def __init__(self, target): # Target comes as protocol://target:port/path self.target = target proto, host, path = target.split(':') host = host[2:] self.path = '/' + path.split('/', 1)[1] if proto.lower() == 'https': #Create unverified (insecure) context try: uv_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) self.session = HTTPSConnection(host,context=uv_context) except AttributeError: #This does not exist on python < 2.7.11 self.session = HTTPSConnection(host) else: self.session = HTTPConnection(host) self.lastresult = None
Example #23
Source File: serving.py From lambda-packs with MIT License | 6 votes |
def load_ssl_context(cert_file, pkey_file=None, protocol=None): """Loads SSL context from cert/private key files and optional protocol. Many parameters are directly taken from the API of :py:class:`ssl.SSLContext`. :param cert_file: Path of the certificate to use. :param pkey_file: Path of the private key to use. If not given, the key will be obtained from the certificate file. :param protocol: One of the ``PROTOCOL_*`` constants in the stdlib ``ssl`` module. Defaults to ``PROTOCOL_SSLv23``. """ if protocol is None: protocol = ssl.PROTOCOL_SSLv23 ctx = _SSLContext(protocol) ctx.load_cert_chain(cert_file, pkey_file) return ctx
Example #24
Source File: request.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, **_3to2kwargs): if 'cadefault' in _3to2kwargs: cadefault = _3to2kwargs['cadefault']; del _3to2kwargs['cadefault'] else: cadefault = False if 'capath' in _3to2kwargs: capath = _3to2kwargs['capath']; del _3to2kwargs['capath'] else: capath = None if 'cafile' in _3to2kwargs: cafile = _3to2kwargs['cafile']; del _3to2kwargs['cafile'] else: cafile = None global _opener if cafile or capath or cadefault: if not _have_ssl: raise ValueError('SSL support not available') context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.options |= ssl.OP_NO_SSLv2 context.verify_mode = ssl.CERT_REQUIRED if cafile or capath: context.load_verify_locations(cafile, capath) else: context.set_default_verify_paths() https_handler = HTTPSHandler(context=context, check_hostname=True) opener = build_opener(https_handler) elif _opener is None: _opener = opener = build_opener() else: opener = _opener return opener.open(url, data, timeout)
Example #25
Source File: _gaiohttp.py From jbox with MIT License | 5 votes |
def _create_ssl_context(cfg): """ Creates SSLContext instance for usage in asyncio.create_server. See ssl.SSLSocket.__init__ for more details. """ ctx = ssl.SSLContext(cfg.ssl_version) ctx.load_cert_chain(cfg.certfile, cfg.keyfile) ctx.verify_mode = cfg.cert_reqs if cfg.ca_certs: ctx.load_verify_locations(cfg.ca_certs) if cfg.ciphers: ctx.set_ciphers(cfg.ciphers) return ctx
Example #26
Source File: cli.py From recruit with Apache License 2.0 | 5 votes |
def _validate_key(ctx, param, value): """The ``--key`` option must be specified when ``--cert`` is a file. Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed. """ cert = ctx.params.get('cert') is_adhoc = cert == 'adhoc' if sys.version_info < (2, 7): is_context = cert and not isinstance(cert, (text_type, bytes)) else: is_context = isinstance(cert, ssl.SSLContext) if value is not None: if is_adhoc: raise click.BadParameter( 'When "--cert" is "adhoc", "--key" is not used.', ctx, param) if is_context: raise click.BadParameter( 'When "--cert" is an SSLContext object, "--key is not used.', ctx, param) if not cert: raise click.BadParameter( '"--cert" must also be specified.', ctx, param) ctx.params['cert'] = cert, value else: if cert and not (is_adhoc or is_context): raise click.BadParameter( 'Required when using "--cert".', ctx, param) return value
Example #27
Source File: util.py From recruit with Apache License 2.0 | 5 votes |
def connect(self): sock = socket.create_connection((self.host, self.port), self.timeout) if getattr(self, '_tunnel_host', False): self.sock = sock self._tunnel() if not hasattr(ssl, 'SSLContext'): # For 2.x if self.ca_certs: cert_reqs = ssl.CERT_REQUIRED else: cert_reqs = ssl.CERT_NONE self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, cert_reqs=cert_reqs, ssl_version=ssl.PROTOCOL_SSLv23, ca_certs=self.ca_certs) else: # pragma: no cover context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.options |= ssl.OP_NO_SSLv2 if self.cert_file: context.load_cert_chain(self.cert_file, self.key_file) kwargs = {} if self.ca_certs: context.verify_mode = ssl.CERT_REQUIRED context.load_verify_locations(cafile=self.ca_certs) if getattr(ssl, 'HAS_SNI', False): kwargs['server_hostname'] = self.host self.sock = context.wrap_socket(sock, **kwargs) if self.ca_certs and self.check_domain: try: match_hostname(self.sock.getpeercert(), self.host) logger.debug('Host verified: %s', self.host) except CertificateError: # pragma: no cover self.sock.shutdown(socket.SHUT_RDWR) self.sock.close() raise
Example #28
Source File: config.py From aiobotocore with Apache License 2.0 | 5 votes |
def _validate_connector_args(connector_args): if connector_args is None: return for k, v in connector_args.items(): # verify_ssl is handled by verify parameter to create_client if k == 'use_dns_cache': if not isinstance(v, bool): raise ParamValidationError( report='{} value must be a boolean'.format(k)) elif k in ['keepalive_timeout']: if not isinstance(v, (float, int)): raise ParamValidationError( report='{} value must be a float/int'.format(k)) elif k == 'force_close': if not isinstance(v, bool): raise ParamValidationError( report='{} value must be a boolean'.format(k)) # limit is handled by max_pool_connections elif k == 'ssl_context': import ssl if not isinstance(v, ssl.SSLContext): raise ParamValidationError( report='{} must be an SSLContext instance'.format(k)) else: raise ParamValidationError( report='invalid connector_arg:{}'.format(k))
Example #29
Source File: util.py From jbox with MIT License | 5 votes |
def connect(self): sock = socket.create_connection((self.host, self.port), self.timeout) if getattr(self, '_tunnel_host', False): self.sock = sock self._tunnel() if not hasattr(ssl, 'SSLContext'): # For 2.x if self.ca_certs: cert_reqs = ssl.CERT_REQUIRED else: cert_reqs = ssl.CERT_NONE self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, cert_reqs=cert_reqs, ssl_version=ssl.PROTOCOL_SSLv23, ca_certs=self.ca_certs) else: context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.options |= ssl.OP_NO_SSLv2 if self.cert_file: context.load_cert_chain(self.cert_file, self.key_file) kwargs = {} if self.ca_certs: context.verify_mode = ssl.CERT_REQUIRED context.load_verify_locations(cafile=self.ca_certs) if getattr(ssl, 'HAS_SNI', False): kwargs['server_hostname'] = self.host self.sock = context.wrap_socket(sock, **kwargs) if self.ca_certs and self.check_domain: try: match_hostname(self.sock.getpeercert(), self.host) logger.debug('Host verified: %s', self.host) except CertificateError: self.sock.shutdown(socket.SHUT_RDWR) self.sock.close() raise
Example #30
Source File: tls.py From heralding with GNU General Public License v3.0 | 5 votes |
def __init__(self, writer, reader, pem_file): """@param: writer and reader are asyncio stream writer and reader objects""" self._tlsInBuff = ssl.MemoryBIO() self._tlsOutBuff = ssl.MemoryBIO() ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_1) ctx.set_ciphers('RSA:!aNULL') ctx.check_hostname = False ctx.load_cert_chain(pem_file) self._tlsObj = ctx.wrap_bio( self._tlsInBuff, self._tlsOutBuff, server_side=True) self.writer = writer self.reader = reader