Choose the SSL mode and optional root cert for the connection.
189946
def choose_connect_args(metadata, config):
    
    if not config.require_ssl and not config.verify_ssl:
        return dict(
            sslmode="prefer",
        )

    if config.require_ssl and not config.verify_ssl:
        return dict(
            sslmode="require",
        )

    if not config.ssl_cert_path:
        raise Exception("SSL certificate path (`ssl_cert_path`) must be configured for verification")

    return dict(
        sslmode="verify-full",
        sslrootcert=config.ssl_cert_path,
    )
1275961
def get_certificate
      uri = URI.parse(URI.escape(@host))
      options = { use_ssl: true, verify_mode: OpenSSL::SSL::VERIFY_NONE }
      Net::HTTP.start(uri.host, uri.port, options) do |http|
        http.peer_cert
      end
    end
1083659
def accept(self):
        
        while 1:
            try:
                sock, addr = self._sock.accept()
                return (type(self)(sock,
                    keyfile=self.keyfile,
                    certfile=self.certfile,
                    server_side=True,
                    cert_reqs=self.cert_reqs,
                    ssl_version=self.ssl_version,
                    ca_certs=self.ca_certs,
                    do_handshake_on_connect=self.do_handshake_on_connect,
                    suppress_ragged_eofs=self.suppress_ragged_eofs,
                    ciphers=self.ciphers), addr)
            except socket.error, exc:
                if exc.args[0] not in (errno.EAGAIN, errno.EWOULDBLOCK):
                    raise
                sys.exc_clear()
                self._wait_event(self.gettimeout())
423017
def connect(self, addr):
        """"""
        # Here we assume that the socket is client-side, and not
        # connected at the time of the call.  We connect it, then wrap it.
        if self._sslobj:
            raise ValueError("attempt to connect already-connected SSLSocket!")
        socket.connect(self, addr)
        if six.PY3:
            self._sslobj = self.context._wrap_socket(self._sock, False, self.server_hostname)
        else:
            if self.ciphers is None:
                self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile,
                                            self.cert_reqs, self.ssl_version,
                                            self.ca_certs)
            else:
                self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile,
                                            self.cert_reqs, self.ssl_version,
                                            self.ca_certs, self.ciphers)
        if self.do_handshake_on_connect:
            self.do_handshake()
715234
def enable_ssl(self, *args, **kwargs):
        
        if self.handshake_sent:
            raise SSLError('can only enable SSL before handshake')

        self.secure = True
        self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)
1366647
def InitHttp(api_endpoint=None,
             page_size=None,
             auth=None,
             proxies=None,
             verify=None,
             cert=None,
             trust_env=True):
  """"""

  connector = http_connector.HttpConnector(
      api_endpoint=api_endpoint,
      page_size=page_size,
      auth=auth,
      proxies=proxies,
      verify=verify,
      cert=cert,
      trust_env=trust_env)

  return GrrApi(connector=connector)
509606
def _configured_socket(address, options):
    
    sock = _create_connection(address, options)
    ssl_context = options.ssl_context

    if ssl_context is not None:
        host = address[0]
        try:
            # According to RFC6066, section 3, IPv4 and IPv6 literals are
            # not permitted for SNI hostname.
            if _HAVE_SNI and not is_ip_address(host):
                sock = ssl_context.wrap_socket(sock, server_hostname=host)
            else:
                sock = ssl_context.wrap_socket(sock)
        except IOError as exc:
            sock.close()
            raise ConnectionFailure("SSL handshake failed: %s" % (str(exc),))
        if ssl_context.verify_mode and options.ssl_match_hostname:
            try:
                match_hostname(sock.getpeercert(), hostname=host)
            except CertificateError:
                sock.close()
                raise

    sock.settimeout(options.socket_timeout)
    return sock
1345236
def _certificate_required(cls, hostname, port=XCLI_DEFAULT_PORT,
                              ca_certs=None, validate=None):
        '''
        
        '''
        if not ca_certs:
            return False

        xlog.debug("CONNECT SSL %s:%s, cert_file=%s",
                   hostname, port, ca_certs)
        certificate = ssl.get_server_certificate((hostname, port),
                                                 ca_certs=None)
        # handle XIV pre-defined certifications
        # if a validation function was given - we let the user check
        # the certificate himself, with the user's own validate function.
        # if the validate returned True - the user checked the cert
        # and we don't need check it, so we return false.
        if validate:
            return not validate(certificate)
        return True
494278
def start():
    '''
    
    '''
    from . import app
    root, apiopts, conf = app.get_app(__opts__)

    if not apiopts.get('disable_ssl', False):
        if 'ssl_crt' not in apiopts or 'ssl_key' not in apiopts:
            logger.error("Not starting '%s'. Options 'ssl_crt' and "
                    "'ssl_key' are required if SSL is not disabled.",
                    __name__)

            return None

        verify_certs(apiopts['ssl_crt'], apiopts['ssl_key'])

        cherrypy.server.ssl_module = 'builtin'
        cherrypy.server.ssl_certificate = apiopts['ssl_crt']
        cherrypy.server.ssl_private_key = apiopts['ssl_key']
        if 'ssl_chain' in apiopts.keys():
            cherrypy.server.ssl_certificate_chain = apiopts['ssl_chain']

    cherrypy.quickstart(root, apiopts.get('root_prefix', '/'), conf)
740520
protected function setConnectionPassiveMode()
    {
        if (is_bool($this->ignorePassiveAddress) && defined('FTP_USEPASVADDRESS')) {
            ftp_set_option($this->connection, FTP_USEPASVADDRESS, ! $this->ignorePassiveAddress);
        }

        if ( ! ftp_pasv($this->connection, $this->passive)) {
            throw new RuntimeException(
                'Could not set passive mode for connection: ' . $this->getHost() . '::' . $this->getPort()
            );
        }
    }
1208762
def get_preconfigured_ssl_connection(
            self,
            override_ssl_version: Optional[OpenSslVersionEnum] = None,
            ssl_verify_locations: Optional[str] = None,
            should_use_legacy_openssl: Optional[bool] = None,
    ) -> SslConnection:
        
        if override_ssl_version is not None:
            # Caller wants to override the ssl version to use for this connection
            final_ssl_version = override_ssl_version
            # Then we don't know which cipher suite is supported by the server for this ssl version
            openssl_cipher_string = None
        else:
            # Use the ssl version and cipher suite that were successful during connectivity testing
            final_ssl_version = self.highest_ssl_version_supported
            openssl_cipher_string = self.openssl_cipher_string_supported

        if should_use_legacy_openssl is not None:
            # Caller wants to override which version of OpenSSL to use
            # Then we don't know which cipher suite is supported by this version of OpenSSL
            openssl_cipher_string = None

        if self.client_auth_credentials is not None:
            # If we have creds for client authentication, go ahead and use them
            should_ignore_client_auth = False
        else:
            # Ignore client auth requests if the server allows optional TLS client authentication
            should_ignore_client_auth = True
            # But do not ignore them is client authentication is required so that the right exceptions get thrown
            # within the plugins, providing a better output
            if self.client_auth_requirement == ClientAuthenticationServerConfigurationEnum.REQUIRED:
                should_ignore_client_auth = False

        ssl_connection = SslConnectionConfigurator.get_connection(
            ssl_version=final_ssl_version,
            server_info=self,
            openssl_cipher_string=openssl_cipher_string,
            ssl_verify_locations=ssl_verify_locations,
            should_use_legacy_openssl=should_use_legacy_openssl,
            should_ignore_client_auth=should_ignore_client_auth,
        )
        return ssl_connection
1316856
def connect(self):
        """"""
        # Standard implementation from HTTPSConnection, which is not
        # designed for extension, unfortunately
        sock = socket.create_connection((self.host, self.port),
                                        self.timeout, self.source_address)
        if getattr(self, '_tunnel_host', None):
            self.sock = sock  # pragma: no cover
            self._tunnel()  # pragma: no cover

        # This is the only difference; default wrap_socket uses SSLv23
        self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
                                    ssl_version=ssl.PROTOCOL_TLSv1_2)
1168580
def redirect_to_ssl(self):
        """"""
        # Should we redirect?
        criteria = [
            request.is_secure,
            current_app.debug,
            current_app.testing,
            request.headers.get('X-Forwarded-Proto', 'http') == 'https'
        ]

        if not any(criteria) and not self.skip:
            if request.url.startswith('http://'):
                url = request.url.replace('http://', 'https://', 1)
                code = 302
                if self.permanent:
                    code = 301
                r = redirect(url, code=code)
                return r
156153
def establish_connection(self):
        """"""
        conninfo = self.connection
        if not conninfo.port:
            conninfo.port = self.default_port
        credentials = pika.PlainCredentials(conninfo.userid,
                                            conninfo.password)
        return self._connection_cls(pika.ConnectionParameters(
                                           conninfo.hostname,
                                           port=conninfo.port,
                                           virtual_host=conninfo.virtual_host,
                                           credentials=credentials))
552003
def connection_options(opts)
      connection_options = {
        logger:                 logger,
        user_known_hosts_file:  '/dev/null',
        hostname:               opts[:host],
        port:                   opts[:port],
        username:               opts[:user],
        compression:            opts[:compression],
        compression_level:      opts[:compression_level],
        keepalive:              opts[:keepalive],
        keepalive_interval:     opts[:keepalive_interval],
        timeout:                opts[:connection_timeout],
        connection_retries:     opts[:connection_retries],
        connection_retry_sleep: opts[:connection_retry_sleep],
        max_wait_until_ready:   opts[:max_wait_until_ready],
        auth_methods:           opts[:auth_methods],
        keys_only:              opts[:keys_only],
        keys:                   opts[:key_files],
        password:               opts[:password],
        forward_agent:          opts[:forward_agent],
        proxy_command:          opts[:proxy_command],
        bastion_host:           opts[:bastion_host],
        bastion_user:           opts[:bastion_user],
        bastion_port:           opts[:bastion_port],
        non_interactive:        opts[:non_interactive],
        transport_options:      opts,
      }
      # disable host key verification. The hash key and value to use
      # depends on the version of net-ssh in use.
      connection_options[verify_host_key_option] = verify_host_key_value(opts[:verify_host_key])

      connection_options
    end
926385
def _verify_cert(self, sock: ssl.SSLSocket):
        ''''''
        # Based on tornado.iostream.SSLIOStream
        # Needed for older OpenSSL (<0.9.8f) versions
        verify_mode = self._ssl_context.verify_mode

        assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED,
                               ssl.CERT_OPTIONAL), \
            'Unknown verify mode {}'.format(verify_mode)

        if verify_mode == ssl.CERT_NONE:
            return

        cert = sock.getpeercert()

        if not cert and verify_mode == ssl.CERT_OPTIONAL:
            return

        if not cert:
            raise SSLVerificationError('No SSL certificate given')

        try:
            ssl.match_hostname(cert, self._hostname)
        except ssl.CertificateError as error:
            raise SSLVerificationError('Invalid SSL certificate') from error
795228
def _helper(
        self,
        host=None,
        port=None,
        debug=False,
        ssl=None,
        sock=None,
        workers=1,
        loop=None,
        protocol=HttpProtocol,
        backlog=100,
        stop_event=None,
        register_sys_signals=True,
        run_async=False,
        auto_reload=False,
    ):
        """"""
        if isinstance(ssl, dict):
            # try common aliaseses
            cert = ssl.get("cert") or ssl.get("certificate")
            key = ssl.get("key") or ssl.get("keyfile")
            if cert is None or key is None:
                raise ValueError("SSLContext or certificate and key required.")
            context = create_default_context(purpose=Purpose.CLIENT_AUTH)
            context.load_cert_chain(cert, keyfile=key)
            ssl = context
        if stop_event is not None:
            if debug:
                warnings.simplefilter("default")
            warnings.warn(
                "stop_event will be removed from future versions.",
                DeprecationWarning,
            )

        self.error_handler.debug = debug
        self.debug = debug

        server_settings = {
            "protocol": protocol,
            "request_class": self.request_class,
            "is_request_stream": self.is_request_stream,
            "router": self.router,
            "host": host,
            "port": port,
            "sock": sock,
            "ssl": ssl,
            "app": self,
            "signal": Signal(),
            "debug": debug,
            "request_handler": self.handle_request,
            "error_handler": self.error_handler,
            "request_timeout": self.config.REQUEST_TIMEOUT,
            "response_timeout": self.config.RESPONSE_TIMEOUT,
            "keep_alive_timeout": self.config.KEEP_ALIVE_TIMEOUT,
            "request_max_size": self.config.REQUEST_MAX_SIZE,
            "request_buffer_queue_size": self.config.REQUEST_BUFFER_QUEUE_SIZE,
            "keep_alive": self.config.KEEP_ALIVE,
            "loop": loop,
            "register_sys_signals": register_sys_signals,
            "backlog": backlog,
            "access_log": self.config.ACCESS_LOG,
            "websocket_max_size": self.config.WEBSOCKET_MAX_SIZE,
            "websocket_max_queue": self.config.WEBSOCKET_MAX_QUEUE,
            "websocket_read_limit": self.config.WEBSOCKET_READ_LIMIT,
            "websocket_write_limit": self.config.WEBSOCKET_WRITE_LIMIT,
            "graceful_shutdown_timeout": self.config.GRACEFUL_SHUTDOWN_TIMEOUT,
        }

        # -------------------------------------------- #
        # Register start/stop events
        # -------------------------------------------- #

        for event_name, settings_name, reverse in (
            ("before_server_start", "before_start", False),
            ("after_server_start", "after_start", False),
            ("before_server_stop", "before_stop", True),
            ("after_server_stop", "after_stop", True),
        ):
            listeners = self.listeners[event_name].copy()
            if reverse:
                listeners.reverse()
            # Prepend sanic to the arguments when listeners are triggered
            listeners = [partial(listener, self) for listener in listeners]
            server_settings[settings_name] = listeners

        if self.configure_logging and debug:
            logger.setLevel(logging.DEBUG)

        if (
            self.config.LOGO
            and os.environ.get("SANIC_SERVER_RUNNING") != "true"
        ):
            logger.debug(
                self.config.LOGO
                if isinstance(self.config.LOGO, str)
                else BASE_LOGO
            )

        if run_async:
            server_settings["run_async"] = True

        # Serve
        if host and port and os.environ.get("SANIC_SERVER_RUNNING") != "true":
            proto = "http"
            if ssl is not None:
                proto = "https"
            logger.info("Goin' Fast @ {}://{}:{}".format(proto, host, port))

        return server_settings