Return a TLS object to establish a secure connection to a server
162528
def _get_tls_object(self, ssl_params):
        
        if ssl_params is None:
            return None

        if not ssl_params["verify"] and ssl_params["ca_certs"]:
            self.warning(
                "Incorrect configuration: trying to disable server certificate validation, "
                "while also specifying a capath. No validation will be performed. Fix your "
                "configuration to remove this warning"
            )

        validate = ssl.CERT_REQUIRED if ssl_params["verify"] else ssl.CERT_NONE

        if ssl_params["ca_certs"] is None or os.path.isfile(ssl_params["ca_certs"]):
            tls = ldap3.core.tls.Tls(
                local_private_key_file=ssl_params["key"],
                local_certificate_file=ssl_params["cert"],
                ca_certs_file=ssl_params["ca_certs"],
                version=ssl.PROTOCOL_SSLv23,
                validate=validate,
            )
        elif os.path.isdir(ssl_params["ca_certs"]):
            tls = ldap3.core.tls.Tls(
                local_private_key_file=ssl_params["key"],
                local_certificate_file=ssl_params["cert"],
                ca_certs_path=ssl_params["ca_certs"],
                version=ssl.PROTOCOL_SSLv23,
                validate=validate,
            )
        else:
            raise ConfigurationError(
                'Invalid path {} for ssl_ca_certs: no such file or directory'.format(ssl_params['ca_certs'])
            )
        return tls
1147457
def _rest(url, req, data=None):
    """"""
    if url.upper().startswith("HTTPS"):
        print("Secure connection required: Please use HTTPS or https")
        return ""

    req = req.upper()
    if req != "GET" and req != "PUT" and req != "POST" and req != "DELETE":
        return ""

    status, body = _api_action(url, req, data)
    if (int(status) >= 200 and int(status) <= 226):
        return body
    else:
        return body
963540
function getProtocol(req) {
	if (req.raw.socket.encrypted) return 'https';
	const proto = req['X-Forwarded-Proto'] || '';
	return proto ? proto.split(/\s*,\s*/)[0] : 'http';
}
692433
def _get_connection(self, ssl):
        """"""

        # Use SSL/TLS if requested and available.
        connect_string = self.connect_string
        if ssl and self.ssl_connect_string:
            connect_string = self.ssl_connect_string

        return pymongo.MongoClient(connect_string)
481448
private ServerConnector createSSLConnector() {
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(m_keystore);
        sslContextFactory.setKeyStorePassword(m_keystorepassword);
        sslContextFactory.setTrustStorePath(m_truststore);
        sslContextFactory.setTrustStorePassword(m_truststorepassword);
        sslContextFactory.setNeedClientAuth(m_clientauthentication);
        sslContextFactory.setIncludeCipherSuites(m_tls_cipher_suites);

        HttpConfiguration http_config = new HttpConfiguration();
        http_config.setSecureScheme("https");
        HttpConfiguration https_config = new HttpConfiguration(http_config);
        https_config.addCustomizer(new SecureRequestCustomizer());
        SslConnectionFactory sslConnFactory = new SslConnectionFactory(sslContextFactory, "http/1.1");
        HttpConnectionFactory httpConnFactory = new HttpConnectionFactory(https_config);
        ServerConnector sslConnector = new ServerConnector(m_jettyServer, sslConnFactory, httpConnFactory);
        return sslConnector;
    }
126274
def connect_to_mycroft
      if ARGV.include?("--no-tls")
        @client = TCPSocket.open(@host, @port)
      else
        socket = TCPSocket.new(@host, @port)
        ssl_context = OpenSSL::SSL::SSLContext.new
        ssl_context.cert = OpenSSL::X509::Certificate.new(File.open(@cert))
        ssl_context.key = OpenSSL::PKey::RSA.new(File.open(@key))
        @client = OpenSSL::SSL::SSLSocket.new(socket, ssl_context)
        begin
          @client.connect
        rescue
        end
      end
    end
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)
600254
def auth_tls(self, mount_point='cert', use_token=True):
        
        return self.login('/v1/auth/{0}/login'.format(mount_point), use_token=use_token)
273291
def _get_client_and_key(url, user, password, verbose=0):
    '''
    
    '''
    session = {}
    session['client'] = six.moves.xmlrpc_client.Server(url, verbose=verbose, use_datetime=True)
    session['key'] = session['client'].auth.login(user, password)

    return session
564633
def _get_client(self, server):
        
        return Client(
            server=server[0],
            authport=server[1],
            secret=server[2],
            dict=self._get_dictionary(),
        )
805813
def make_tls_config(app_config):
    """"""

    if not app_config['DOCKER_TLS']:
        return False

    cert_path = app_config['DOCKER_TLS_CERT_PATH']
    if cert_path:
        client_cert = '{0}:{1}'.format(
            os.path.join(cert_path, 'cert.pem'),
            os.path.join(cert_path, 'key.pem'))
        ca_cert = os.path.join(cert_path, 'ca.pem')
    else:
        client_cert = app_config['DOCKER_TLS_CLIENT_CERT']
        ca_cert = app_config['DOCKER_TLS_CA_CERT']

    client_cert = parse_client_cert_pair(client_cert)
    return TLSConfig(
        client_cert=client_cert,
        ca_cert=ca_cert,
        verify=app_config['DOCKER_TLS_VERIFY'],
        ssl_version=app_config['DOCKER_TLS_SSL_VERSION'],
        assert_hostname=app_config['DOCKER_TLS_ASSERT_HOSTNAME'])
1238251
def GetRpcServer(options):
	

	rpc_server_class = HttpRpcServer

	def GetUserCredentials():
		"""Prompts the user for a username and password."""
		# Disable status prints so they don't obscure the password prompt.
		global global_status
		st = global_status
		global_status = None

		email = options.email
		if email is None:
			email = GetEmail("Email (login for uploading to %s)" % options.server)
		password = getpass.getpass("Password for %s: " % email)

		# Put status back.
		global_status = st
		return (email, password)

	# If this is the dev_appserver, use fake authentication.
	host = (options.host or options.server).lower()
	if host == "localhost" or host.startswith("localhost:"):
		email = options.email
		if email is None:
			email = "test@example.com"
			logging.info("Using debug user %s.  Override with --email" % email)
		server = rpc_server_class(
				options.server,
				lambda: (email, "password"),
				host_override=options.host,
				extra_headers={"Cookie": 'dev_appserver_login="%s:False"' % email},
				save_cookies=options.save_cookies)
		# Don't try to talk to ClientLogin.
		server.authenticated = True
		return server

	return rpc_server_class(options.server, GetUserCredentials,
		host_override=options.host, save_cookies=options.save_cookies)
516623
def _get_and_verify_certificate_chain(
            server_info: ServerConnectivityInfo,
            trust_store: TrustStore
    ) -> Tuple[List[Certificate], str, Optional[OcspResponse]]:
        
        ssl_connection = server_info.get_preconfigured_ssl_connection(ssl_verify_locations=trust_store.path)

        # Enable OCSP stapling
        ssl_connection.ssl_client.set_tlsext_status_ocsp()

        try:  # Perform the SSL handshake
            ssl_connection.connect()

            ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp()
            x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain()
            (_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result()

        except ClientCertificateRequested:  # The server asked for a client cert
            # We can get the server cert anyway
            ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp()
            x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain()
            (_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result()

        finally:
            ssl_connection.close()

        # Parse the certificates using the cryptography module
        parsed_x509_chain = [load_pem_x509_certificate(x509_cert.as_pem().encode('ascii'), backend=default_backend())
                             for x509_cert in x509_cert_chain]
        return parsed_x509_chain, verify_str, ocsp_response
575597
def _sslobj(sock):
    
    pass
    if isinstance(sock._sslobj, _ssl._SSLSocket):
        return sock._sslobj
    else:
        return sock._sslobj._sslobj
1159641
def bind(self, sock):
        """"""
        if self.context is None:
            self.context = self.get_context()
        conn = SSLConnection(self.context, sock)
        self._environ = self.get_environ()
        return conn
618350
private function connection()
    {
        $url = $this->url;

        if ($this->secure === true) {
            $url = 'ssl://' . $this->url;
        }

        $this->sock = fsockopen($url, $this->port, $errno, $errstr, $this->timeout);

        if ($this->sock == null) {
            throw new SocketException('Impossible to get connected to ' . $this->url . ':' . $this->port, E_USER_ERROR);
        }

        stream_set_timeout($this->sock, $this->timeout, 0);
        $code = $this->read();

        $host = isset($_SERVER['HTTP_HOST']) &&
        preg_match('/^[\w.-]+\z/', $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';

        if ($code == 220) {
            $code = $this->write('EHLO ' . $host, 250, 'HELO');
            if ($code != 250) {
                $this->write('EHLO ' . $host, 250, 'HELO');
            }
        }

        if ($this->tls === true) {
            $this->write('STARTTLS', 220);

            $secured = @stream_socket_enable_crypto($this->sock, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);

            if (!$secured) {
                throw new ErrorException('Can not secure your connection with tls', E_ERROR);
            }
        }

        if ($this->username !== null && $this->password !== null) {
            $this->write('AUTH LOGIN', 334);
            $this->write(base64_encode($this->username), 334, 'username');
            $this->write(base64_encode($this->password), 235, 'password');
        }
    }
1372921
def _init_security(self):
        
        if not self._starttls():
            raise SecurityError("Could not start TLS connection")
        # _ssh_handshake() will throw an exception upon failure
        self._ssl_handshake()
        if not self._auth():
            raise SecurityError("Could not authorize connection")