Python ssl.get_default_verify_paths() Examples

The following are 13 code examples of ssl.get_default_verify_paths(). 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: deribit_ws.py    From archon with MIT License 6 votes vote down vote up
def connect(self):
        self.logger.info("connect ws")
        websocket.enableTrace(True)
        self.ws = websocket.WebSocketApp("wss://www.deribit.com/ws/api/v1/",
                                  on_message = lambda ws,msg: self.on_message(ws, msg),
                                  on_error   = lambda ws,msg: self.on_error(ws, msg),
                                  on_open    = lambda ws:  self.on_open(ws),
                                  #on_open = self.on_open,                                  
                                  on_close = self.on_close)
        ssl_defaults = ssl.get_default_verify_paths()
        sslopt_ca_certs = {'ca_certs': ssl_defaults.cafile}
        self.wst = threading.Thread(target=lambda: self.ws.run_forever(sslopt=sslopt_ca_certs))
        self.wst.daemon = True
        self.wst.start()
        self.logger.info("Started thread")
        #TOOD subscribe later
        #self.ws.run_forever() 
Example #2
Source File: websocket.py    From jellyfin-kodi with GNU General Public License v3.0 6 votes vote down vote up
def _wrap_sni_socket(sock, sslopt, hostname):
    context = ssl.SSLContext(sslopt.get('ssl_version', ssl.PROTOCOL_TLS))
    context.options |= ssl.OP_NO_SSLv2  # Explicitly disable SSLv2
    context.options |= ssl.OP_NO_SSLv3  # Explicitly disable SSLv3
    context.options |= ssl.OP_NO_TLSv1  # Explicitly disable TLSv1.0
    context.options |= ssl.OP_NO_TLSv1_1  # Explicitly disable TLSv1.1

    if sslopt.get('cert_reqs', ssl.CERT_NONE) != ssl.CERT_NONE:
        capath = ssl.get_default_verify_paths().capath
        context.load_verify_locations(
            cafile=sslopt.get('ca_certs', None),
            capath=sslopt.get('ca_cert_path', capath)
        )

    return context.wrap_socket(
        sock,
        do_handshake_on_connect=sslopt.get('do_handshake_on_connect', True),
        suppress_ragged_eofs=sslopt.get('suppress_ragged_eofs', True),
        server_hostname=hostname,
    ) 
Example #3
Source File: websocket.py    From python-graphenelib with MIT License 6 votes vote down vote up
def connect(self):
        log.debug("Trying to connect to node %s" % self.url)
        self._request_id = 0
        if self.url[:3] == "wss":
            ssl_defaults = ssl.get_default_verify_paths()
            sslopt_ca_certs = {"ca_certs": ssl_defaults.cafile}
            self.ws = websocket.WebSocket(sslopt=sslopt_ca_certs)
        else:  # pragma: no cover
            self.ws = websocket.WebSocket()

        self.ws.connect(
            self.url,
            http_proxy_host=self.proxy_host,
            http_proxy_port=self.proxy_port,
            http_proxy_auth=(self.proxy_user, self.proxy_pass)
            if self.proxy_user
            else None,
            proxy_type=self.proxy_type,
        )

        if self.user and self.password:
            self.login(self.user, self.password, api_id=1) 
Example #4
Source File: websocket.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def _wrap_sni_socket(sock, sslopt, hostname):
    context = ssl.SSLContext(sslopt.get('ssl_version', ssl.PROTOCOL_SSLv23))

    if sslopt.get('cert_reqs', ssl.CERT_NONE) != ssl.CERT_NONE:
        capath = ssl.get_default_verify_paths().capath
        context.load_verify_locations(cafile=sslopt.get('ca_certs', None),
                capath=sslopt.get('ca_cert_path', capath))

    return context.wrap_socket(
        sock,
        do_handshake_on_connect=sslopt.get('do_handshake_on_connect', True),
        suppress_ragged_eofs=sslopt.get('suppress_ragged_eofs', True),
        server_hostname=hostname,
    ) 
Example #5
Source File: wss.py    From hitbtc with MIT License 5 votes vote down vote up
def _connect(self):
        """Create a websocket connection.

        Automatically reconnects connection if it was severed unintentionally.
        """
        self.conn = websocket.WebSocketApp(
            self.url,
            on_open=self._on_open,
            on_message=self._on_message,
            on_error=self._on_error,
            on_close=self._on_close
        )

        ssl_defaults = ssl.get_default_verify_paths()
        sslopt_ca_certs = {'ca_certs': ssl_defaults.cafile}
        self.conn.run_forever(sslopt=sslopt_ca_certs)

        while self.reconnect_required:
            if not self.disconnect_called:
                self.log.info("Attempting to connect again in %s seconds.", self.reconnect_interval)
                time.sleep(self.reconnect_interval)

                # We need to set this flag since closing the socket will
                # set it to False
                self.conn.keep_running = True
                self.conn.run_forever(sslopt=sslopt_ca_certs) 
Example #6
Source File: ws_thread.py    From BitmexBot with MIT License 5 votes vote down vote up
def __connect(self, wsURL):
        '''Connect to the websocket in a thread.'''
        self.logger.debug("Starting thread")

        ssl_defaults = ssl.get_default_verify_paths()
        sslopt_ca_certs = {'ca_certs': ssl_defaults.cafile}
        self.ws = websocket.WebSocketApp(wsURL,
                                         on_message=self.__on_message,
                                         on_close=self.__on_close,
                                         on_open=self.__on_open,
                                         on_error=self.__on_error,
                                         header=self.__get_auth()
                                         )

        setup_custom_logger('websocket', log_level=settings.LOG_LEVEL)
        self.wst = threading.Thread(target=lambda: self.ws.run_forever(sslopt=sslopt_ca_certs))
        self.wst.daemon = True
        self.wst.start()
        self.logger.info("Started thread")

        # Wait for connect before continuing
        conn_timeout = 5
        while (not self.ws.sock or not self.ws.sock.connected) and conn_timeout and not self._error:
            sleep(1)
            conn_timeout -= 1

        if not conn_timeout or self._error:
            self.logger.error("Couldn't connect to WS! Exiting.")
            self.exit()
            sys.exit(1) 
Example #7
Source File: ws_thread.py    From stocklook with MIT License 5 votes vote down vote up
def __connect(self, wsURL):
        '''Connect to the websocket in a thread.'''
        self.logger.debug("Starting thread")

        ssl_defaults = ssl.get_default_verify_paths()
        sslopt_ca_certs = {'ca_certs': ssl_defaults.cafile}
        self.ws = websocket.WebSocketApp(wsURL,
                                         on_message=self.__on_message,
                                         on_close=self.__on_close,
                                         on_open=self.__on_open,
                                         on_error=self.__on_error,
                                         header=self.__get_auth()
                                         )

        setup_custom_logger('websocket', log_level=settings.LOG_LEVEL)
        self.wst = threading.Thread(target=lambda: self.ws.run_forever(sslopt=sslopt_ca_certs))
        self.wst.daemon = True
        self.wst.start()
        self.logger.info("Started thread")

        # Wait for connect before continuing
        conn_timeout = 5
        while (not self.ws.sock or not self.ws.sock.connected) and conn_timeout and not self._error:
            sleep(1)
            conn_timeout -= 1

        if not conn_timeout or self._error:
            self.logger.error("Couldn't connect to WS! Exiting.")
            self.exit()
            sys.exit(1) 
Example #8
Source File: screepsapi.py    From python-screeps with MIT License 5 votes vote down vote up
def connect(self):
        screepsConnection = API(u=self.user,p=self.password,ptr=self.ptr,host=self.host,secure=self.secure, token=self.atoken)
        me = screepsConnection.me()
        self.user_id = me['_id']
        self.token = screepsConnection.token

        if self.logging:
            logging.getLogger('websocket').addHandler(logging.StreamHandler())
            websocket.enableTrace(True)
        else:
            logging.getLogger('websocket').addHandler(logging.NullHandler())
            websocket.enableTrace(False)

        if self.host:
            url = 'wss://' if self.secure else 'ws://'
            url += self.host + '/socket/websocket'
        elif not self.ptr:
            url = 'wss://screeps.com/socket/websocket'
        else:
            url = 'wss://screeps.com/ptr/socket/websocket'

        self.ws = websocket.WebSocketApp(url=url,
                                    on_message=lambda ws, message: self.on_message(ws,message),
                                    on_error=lambda ws, error: self.on_error(ws,error),
                                    on_close=lambda ws: self.on_close(ws),
                                    on_open=lambda ws: self.on_open(ws))

        ssl_defaults = ssl.get_default_verify_paths()
        sslopt_ca_certs = {'ca_certs': ssl_defaults.cafile}
        if 'http_proxy' in self.settings and self.settings['http_proxy'] is not None:
            http_proxy_port = self.settings['http_proxy_port'] if 'http_proxy_port' in self.settings else 8080
            self.ws.run_forever(http_proxy_host=self.settings['http_proxy'], http_proxy_port=http_proxy_port, ping_interval=1, sslopt=sslopt_ca_certs)
        else:
            self.ws.run_forever(ping_interval=1, sslopt=sslopt_ca_certs) 
Example #9
Source File: ssl.py    From geofront-cli with GNU General Public License v3.0 5 votes vote down vote up
def get_https_context_factory():
    if not hasattr(ssl, 'Purpose'):
        return lambda *_, **__: None
    if not hasattr(ssl, '_create_default_https_context') or \
       hasattr(ssl, 'get_default_verify_paths') and \
       ssl.get_default_verify_paths()[0] is None:
        m = re.match(r'(Open|Libre)SSL (\d+)\.(\d+)\.(\d+)',
                     ssl.OPENSSL_VERSION)
        openssl_version = int(m.group(2)), int(m.group(3)), int(m.group(4))
        if openssl_version < (1, 0, 2) and hasattr(certifi, 'old_where'):
            # https://github.com/certifi/python-certifi/issues/26
            where = certifi.old_where
        else:
            where = certifi.where

        def get_https_context(purpose=ssl.Purpose.SERVER_AUTH,
                              cafile=None, capath=None, cadata=None):
            return ssl.create_default_context(
                purpose=purpose,
                cafile=cafile or where(),
                capath=capath,
                cadata=cadata
            )
        return get_https_context
    if hasattr(ssl, '_create_default_https_context'):
        return ssl._create_default_https_context
    if hasattr(ssl, 'create_default_context'):
        return ssl.create_default_context
    return lambda *_, **__: None 
Example #10
Source File: ssl_utils.py    From ansible-kafka-admin with Apache License 2.0 4 votes vote down vote up
def generate_ssl_context(ssl_check_hostname,
                         ssl_cafile,
                         ssl_certfile,
                         ssl_keyfile,
                         ssl_password,
                         ssl_crlfile,
                         ssl_supported_protocols,
                         ssl_ciphers):
    """
    Generate SSLContext for kafka client.
    """
    log.debug('Configuring default SSL Context')
    ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    ssl_context.options |= ssl.OP_NO_SSLv2
    ssl_context.options |= ssl.OP_NO_SSLv3
    ssl_context.verify_mode = ssl.CERT_OPTIONAL
    if ssl_supported_protocols:
        if 'TLSv1' not in ssl_supported_protocols:
            ssl_context.options |= ssl.OP_NO_TLSv1
        if 'TLSv1.1' not in ssl_supported_protocols:
            ssl_context.options |= ssl.OP_NO_TLSv1_1
        if 'TLSv1.2' not in ssl_supported_protocols:
            ssl_context.options |= ssl.OP_NO_TLSv1_2
    if ssl_check_hostname:
        ssl_context.check_hostname = True
    if ssl_cafile:
        log.info('Loading SSL CA from %s', ssl_cafile)
        ssl_context.load_verify_locations(ssl_cafile)
        ssl_context.verify_mode = ssl.CERT_REQUIRED
    else:
        log.info('Loading system default SSL CAs from %s',
                 ssl.get_default_verify_paths())
        ssl_context.load_default_certs()
    if ssl_certfile and ssl_keyfile:
        log.info('Loading SSL Cert from %s', ssl_certfile)
        log.info('Loading SSL Key from %s', ssl_keyfile)
        ssl_context.load_cert_chain(
            certfile=ssl_certfile,
            keyfile=ssl_keyfile,
            password=ssl_password)
    if ssl_crlfile:
        if not hasattr(ssl, 'VERIFY_CRL_CHECK_LEAF'):
            raise RuntimeError('This version of Python does not'
                               ' support ssl_crlfile!')
        log.info('Loading SSL CRL from %s', ssl_crlfile)
        ssl_context.load_verify_locations(ssl_crlfile)
        ssl_context.verify_flags |= ssl.VERIFY_CRL_CHECK_LEAF
    if ssl_ciphers:
        log.info('Setting SSL Ciphers: %s', ssl_ciphers)
        ssl_context.set_ciphers(ssl_ciphers)
    return ssl_context 
Example #11
Source File: __init__.py    From flask-ldapconn with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def init_app(self, app):
        ssl_defaults = ssl.get_default_verify_paths()

        # Default config
        app.config.setdefault('LDAP_SERVER', 'localhost')
        app.config.setdefault('LDAP_PORT', 389)
        app.config.setdefault('LDAP_BINDDN', None)
        app.config.setdefault('LDAP_SECRET', None)
        app.config.setdefault('LDAP_CONNECT_TIMEOUT', 10)
        app.config.setdefault('LDAP_READ_ONLY', False)
        app.config.setdefault('LDAP_VALID_NAMES', None)
        app.config.setdefault('LDAP_PRIVATE_KEY_PASSWORD', None)
        app.config.setdefault('LDAP_RAISE_EXCEPTIONS', False)

        app.config.setdefault('LDAP_CONNECTION_STRATEGY', SYNC)

        app.config.setdefault('LDAP_USE_SSL', False)
        app.config.setdefault('LDAP_USE_TLS', True)
        app.config.setdefault('LDAP_TLS_VERSION', ssl.PROTOCOL_TLSv1)
        app.config.setdefault('LDAP_REQUIRE_CERT', ssl.CERT_REQUIRED)

        app.config.setdefault('LDAP_CLIENT_PRIVATE_KEY', None)
        app.config.setdefault('LDAP_CLIENT_CERT', None)

        app.config.setdefault('LDAP_CA_CERTS_FILE', ssl_defaults.cafile)
        app.config.setdefault('LDAP_CA_CERTS_PATH', ssl_defaults.capath)
        app.config.setdefault('LDAP_CA_CERTS_DATA', None)

        app.config.setdefault('FORCE_ATTRIBUTE_VALUE_AS_LIST', False)

        self.tls = Tls(
            local_private_key_file=app.config['LDAP_CLIENT_PRIVATE_KEY'],
            local_certificate_file=app.config['LDAP_CLIENT_CERT'],
            validate=app.config['LDAP_REQUIRE_CERT'],
            version=app.config['LDAP_TLS_VERSION'],
            ca_certs_file=app.config['LDAP_CA_CERTS_FILE'],
            valid_names=app.config['LDAP_VALID_NAMES'],
            ca_certs_path=app.config['LDAP_CA_CERTS_PATH'],
            ca_certs_data=app.config['LDAP_CA_CERTS_DATA'],
            local_private_key_password=app.config['LDAP_PRIVATE_KEY_PASSWORD']
        )

        self.ldap_server = Server(
            host=app.config['LDAP_SERVER'],
            port=app.config['LDAP_PORT'],
            use_ssl=app.config['LDAP_USE_SSL'],
            connect_timeout=app.config['LDAP_CONNECT_TIMEOUT'],
            tls=self.tls,
            get_info=ALL
        )

        # Store ldap_conn object to extensions
        app.extensions['ldap_conn'] = self

        # Teardown appcontext
        app.teardown_appcontext(self.teardown) 
Example #12
Source File: ssl_tools.py    From DeepPavlov with Apache License 2.0 4 votes vote down vote up
def verify_certs_chain(certs_chain: List[crypto.X509], amazon_cert: crypto.X509) -> bool:
    """Verifies if Amazon and additional certificates creates chain of trust to a root CA.

    Args:
        certs_chain: List of pycrypto X509 intermediate certificates from signature chain URL.
        amazon_cert: Pycrypto X509 Amazon certificate.

    Returns:
        result: True if verification was successful, False if not.
    """
    store = crypto.X509Store()

    # add certificates from Amazon provided certs chain
    for cert in certs_chain:
        store.add_cert(cert)

    # add CA certificates
    default_verify_paths = ssl.get_default_verify_paths()

    default_verify_file = default_verify_paths.cafile
    default_verify_file = Path(default_verify_file).resolve() if default_verify_file else None

    default_verify_path = default_verify_paths.capath
    default_verify_path = Path(default_verify_path).resolve() if default_verify_path else None

    ca_files = [ca_file for ca_file in default_verify_path.iterdir()] if default_verify_path else []
    if default_verify_file:
        ca_files.append(default_verify_file)

    for ca_file in ca_files:
        ca_file: Path
        if ca_file.is_file():
            with ca_file.open('r', encoding='ascii') as crt_f:
                ca_certs_txt = crt_f.read()
                ca_certs = extract_certs(ca_certs_txt)
                for cert in ca_certs:
                    store.add_cert(cert)

    # add CA certificates (Windows)
    ssl_context = ssl.create_default_context()
    der_certs = ssl_context.get_ca_certs(binary_form=True)
    pem_certs = '\n'.join([ssl.DER_cert_to_PEM_cert(der_cert) for der_cert in der_certs])
    ca_certs = extract_certs(pem_certs)
    for ca_cert in ca_certs:
        store.add_cert(ca_cert)

    store_context = crypto.X509StoreContext(store, amazon_cert)

    try:
        store_context.verify_certificate()
        result = True
    except crypto.X509StoreContextError:
        result = False

    return result 
Example #13
Source File: connection.py    From btfxwss with MIT License 4 votes vote down vote up
def _connect(self):
        """Creates a websocket connection.

        :return:
        """
        self.log.debug("_connect(): Initializing Connection..")
        self.socket = websocket.WebSocketApp(
            self.url,
            on_open=self._on_open,
            on_message=self._on_message,
            on_error=self._on_error,
            on_close=self._on_close
        )

        if 'ca_certs' not in self.sslopt.keys():
            ssl_defaults = ssl.get_default_verify_paths()
            self.sslopt['ca_certs'] = ssl_defaults.cafile

        self.log.debug("_connect(): Starting Connection..")
        self.socket.run_forever(sslopt=self.sslopt,
                        http_proxy_host=self.http_proxy_host,
                        http_proxy_port=self.http_proxy_port,
                        http_proxy_auth=self.http_proxy_auth,
                        http_no_proxy=self.http_no_proxy)

        # stop outstanding ping/pong timers
        self._stop_timers()
        while self.reconnect_required.is_set():
            if not self.disconnect_called.is_set():
                self.log.info("Attempting to connect again in %s seconds."
                              % self.reconnect_interval)
                self.state = "unavailable"
                time.sleep(self.reconnect_interval)

                # We need to set this flag since closing the socket will
                # set it to False
                self.socket.keep_running = True
                self.socket.sock = None
                self.socket.run_forever(sslopt=self.sslopt,
                                http_proxy_host=self.http_proxy_host,
                                http_proxy_port=self.http_proxy_port,
                                http_proxy_auth=self.http_proxy_auth,
                                http_no_proxy=self.http_no_proxy)
            else:
                break