Connects to the target server and uses the supplied trust store to validate the server's certificate.
        Returns the server's certificate and OCSP response.
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
340716
private static OkHttpClient getUnsafeOkHttpClient() {
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[] {
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient okHttpClient = new OkHttpClient();
            okHttpClient.setSslSocketFactory(sslSocketFactory);
            okHttpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
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
276978
def INIT_TLS_SESSION(self):
        
        self.cur_session = tlsSession(connection_end="server")
        self.cur_session.server_certs = [self.mycert]
        self.cur_session.server_key = self.mykey
        if isinstance(self.mykey, PrivKeyRSA):
            self.cur_session.server_rsa_key = self.mykey
        # elif isinstance(self.mykey, PrivKeyECDSA):
        #    self.cur_session.server_ecdsa_key = self.mykey
        raise self.WAITING_CLIENTFLIGHT1()
875577
def _init_ssl(self):
        

        if not have_openssl:
            raise ImportError('SSL sockets have been disabled due to missing requirement: pyopenssl.')

        try:
            ctx = SSL.Context(SSL.TLSv1_METHOD)

            if isinstance(self.ssl_key, crypto.PKey):
                ctx.use_privatekey(self.ssl_key)
            else:
                ctx.use_privatekey_file(self.ssl_key)

            if isinstance(self.ssl_certificate, crypto.X509):
                ctx.use_certificate(self.ssl_certificate)
            else:
                ctx.use_certificate_file(self.ssl_certificate)

            if isinstance(self.ssl_ca, crypto.X509):
                store = ctx.get_cert_store()
                store.add_cert(self.ssl_ca)
            else:
                ctx.load_verify_locations(self.ssl_ca, None)

            verify_method = SSL.VERIFY_PEER
            if (self._ssl_allow_self_signed):
                verify_method = SSL.VERIFY_NONE

            ctx.set_verify(verify_method, self._verify_ssl_callback)

            self._device = SSL.Connection(ctx, self._device)

        except SSL.Error as err:
            raise CommError('Error setting up SSL connection.', err)
351627
@RequestMapping(value = "/cert/{hostname:.+}", method = {RequestMethod.GET, RequestMethod.HEAD})
    public
    @ResponseBody
    void getCert(Locale locale, Model model, HttpServletResponse response, @PathVariable String hostname) throws Exception {
        // Set the appropriate headers so the browser thinks this is a file
        response.reset();
        response.setContentType("application/x-x509-ca-cert");
        response.setHeader("Content-Disposition", "attachment;filename=" + hostname + ".cer");

        // special handling for hostname=="root"
        // return the CyberVillians Root Cert in this case
        if (hostname.equals("root")) {
            hostname = "cybervillainsCA";
            response.setContentType("application/pkix-cert ");
        }

        // get the cert for the hostname
        KeyStoreManager keyStoreManager = com.groupon.odo.bmp.Utils.getKeyStoreManager(hostname);

        if (hostname.equals("cybervillainsCA")) {
            // get the cybervillians cert from resources
            File root = new File("seleniumSslSupport" + File.separator + hostname);

            // return the root cert
            Files.copy(new File(root.getAbsolutePath() + File.separator + hostname + ".cer").toPath(), response.getOutputStream());
            response.flushBuffer();
        } else {
            // return the cert for the appropriate alias
            response.getOutputStream().write(keyStoreManager.getCertificateByAlias(hostname).getEncoded());
            response.flushBuffer();
        }


    }
1196780
def processTrustResult(request):
    
    # Get the request from the session so we can construct the
    # appropriate response.
    openid_request = getRequest(request)

    # The identifier that this server can vouch for
    response_identity = getViewURL(request, idPage)

    # If the decision was to allow the verification, respond
    # accordingly.
    allowed = 'allow' in request.POST

    # Generate a response with the appropriate answer.
    openid_response = openid_request.answer(allowed,
                                            identity=response_identity)

    # Send Simple Registration data in the response, if appropriate.
    if allowed:
        sreg_data = {
            'fullname': 'Example User',
            'nickname': 'example',
            'dob': '1970-01-01',
            'email': 'invalid@example.com',
            'gender': 'F',
            'postcode': '12345',
            'country': 'ES',
            'language': 'eu',
            'timezone': 'America/New_York',
            }

        sreg_req = sreg.SRegRequest.fromOpenIDRequest(openid_request)
        sreg_resp = sreg.SRegResponse.extractResponse(sreg_req, sreg_data)
        openid_response.addExtension(sreg_resp)

        pape_response = pape.Response()
        pape_response.setAuthLevel(pape.LEVELS_NIST, 0)
        openid_response.addExtension(pape_response)

    return displayResponse(request, openid_response)
1370806
def validate(cert, ca_name, crl_file):
    '''
    
    '''
    store = OpenSSL.crypto.X509Store()
    cert_obj = _read_cert(cert)
    if cert_obj is None:
        raise CommandExecutionError(
            'Failed to read cert from {0}, see log for details'.format(cert)
        )
    ca_dir = '{0}/{1}'.format(cert_base_path(), ca_name)
    ca_cert = _read_cert('{0}/{1}_ca_cert.crt'.format(ca_dir, ca_name))
    store.add_cert(ca_cert)
    # These flags tell OpenSSL to check the leaf as well as the
    # entire cert chain.
    X509StoreFlags = OpenSSL.crypto.X509StoreFlags
    store.set_flags(X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
    if crl_file is None:
        crl = OpenSSL.crypto.CRL()
    else:
        with salt.utils.files.fopen(crl_file) as fhr:
            crl = OpenSSL.crypto.load_crl(OpenSSL.crypto.FILETYPE_PEM, fhr.read())
    store.add_crl(crl)
    context = OpenSSL.crypto.X509StoreContext(store, cert_obj)
    ret = {}
    try:
        context.verify_certificate()
        ret['valid'] = True
    except OpenSSL.crypto.X509StoreContextError as e:
        ret['error'] = str(e)
        ret['error_cert'] = e.certificate
        ret['valid'] = False
    return ret
1266648
public static CertStore createCertStore(TrustedCertificates tc) throws Exception {

        CertStore store = null;
        if (tc == null) {
            String caCertPattern = "file:" + CoGProperties.getDefault().getCaCertLocations() + "/*.0";
            store = Stores.getCACertStore(caCertPattern);
        } else {
            SimpleMemoryCertStoreParams params = new SimpleMemoryCertStoreParams(tc.getCertificates(), null);
            params.setCerts(tc.getCertificates());
            store = CertStore.getInstance(SimpleMemoryProvider.CERTSTORE_TYPE, params, SimpleMemoryProvider.PROVIDER_NAME);
        }
        return store;
    }
693662
def _build_ocsp_response(self, ocsp_request: OCSPRequest) -> OCSPResponse:
        
        # Get the certificate serial
        tbs_request = ocsp_request['tbs_request']
        request_list = tbs_request['request_list']
        if len(request_list) != 1:
            logger.warning('Received OCSP request with multiple sub requests')
            raise NotImplemented('Combined requests not yet supported')
        single_request = request_list[0]  # TODO: Support more than one request
        req_cert = single_request['req_cert']
        serial = req_cert['serial_number'].native

        # Check certificate status
        try:
            certificate_status, revocation_date = self._validate(serial)
        except Exception as e:
            logger.exception('Could not determine certificate status: %s', e)
            return self._fail(ResponseStatus.internal_error)

        # Retrieve certificate
        try:
            subject_cert_contents = self._cert_retrieve(serial)
        except Exception as e:
            logger.exception('Could not retrieve certificate with serial %s: %s', serial, e)
            return self._fail(ResponseStatus.internal_error)

        # Parse certificate
        try:
            subject_cert = asymmetric.load_certificate(subject_cert_contents.encode('utf8'))
        except Exception as e:
            logger.exception('Returned certificate with serial %s is invalid: %s', serial, e)
            return self._fail(ResponseStatus.internal_error)

        # Build the response
        builder = OCSPResponseBuilder(**{
            'response_status': ResponseStatus.successful.value,
            'certificate': subject_cert,
            'certificate_status': certificate_status.value,
            'revocation_date': revocation_date,
        })

        # Parse extensions
        for extension in tbs_request['request_extensions']:
            extn_id = extension['extn_id'].native
            critical = extension['critical'].native
            value = extension['extn_value'].parsed

            # This variable tracks whether any unknown extensions were encountered
            unknown = False

            # Handle nonce extension
            if extn_id == 'nonce':
                builder.nonce = value.native

            # That's all we know
            else:
                unknown = True

            # If an unknown critical extension is encountered (which should not
            # usually happen, according to RFC 6960 4.1.2), we should throw our
            # hands up in despair and run.
            if unknown is True and critical is True:
                logger.warning('Could not parse unknown critical extension: %r',
                        dict(extension.native))
                return self._fail(ResponseStatus.internal_error)

            # If it's an unknown non-critical extension, we can safely ignore it.
            elif unknown is True:
                logger.info('Ignored unknown non-critical extension: %r', dict(extension.native))

        # Set certificate issuer
        builder.certificate_issuer = self._issuer_cert

        # Set next update date
        builder.next_update = datetime.now(timezone.utc) + timedelta(days=self._next_update_days)

        return builder.build(self._responder_key, self._responder_cert)
563231
def LoadServerCertificate(self, server_certificate=None, ca_certificate=None):
    """"""
    # Check that the server certificate verifies
    try:
      server_certificate.Verify(ca_certificate.GetPublicKey())
    except rdf_crypto.VerificationError as e:
      self.server_name = None
      raise IOError("Server cert is invalid: %s" % e)

    # Make sure that the serial number is higher.
    server_cert_serial = server_certificate.GetSerialNumber()

    if server_cert_serial < config.CONFIG["Client.server_serial_number"]:
      # We can not accept this serial number...
      raise IOError("Server certificate serial number is too old.")
    elif server_cert_serial > config.CONFIG["Client.server_serial_number"]:
      logging.info("Server serial number updated to %s", server_cert_serial)
      config.CONFIG.Set("Client.server_serial_number", server_cert_serial)

      # Save the new data to the config file.
      config.CONFIG.Write()

    self.server_name = server_certificate.GetCN()
    self.server_certificate = server_certificate
    self.ca_certificate = ca_certificate
    self.server_public_key = server_certificate.GetPublicKey()
    # If we still have a cached session key, we need to remove it.
    self._ClearServerCipherCache()
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
1334120
private void initializeHTTPClient() {

    if (_config.isHTTPSConfigured()) {
      try {
        KeyStore trustKeystore = getClientTruststore();
        SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(trustKeystore, new TrustSelfSignedStrategy())
            .build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        // Allow both HTTP and HTTPS connections
        Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory> create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", sslsf)
            .build();

        HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);

        httpClient = HttpClients.custom()
            .setConnectionManager(cm)
            .build();

      } catch (Exception e) {
        LOGGER.error( "Issue creating HTTP client using supplied configuration. Proceeding with default non-SSL client.", e);
        httpClient = HttpClients.createDefault();
      }
    } else {

      httpClient = HttpClients.createDefault();
    }
  }
1049867
private boolean verifySignature(X509Certificate cert)
        throws CertPathValidatorException {

        try {
            Signature respSignature = Signature.getInstance(sigAlgId.getName());
            respSignature.initVerify(cert.getPublicKey());
            respSignature.update(tbsResponseData);

            if (respSignature.verify(signature)) {
                if (debug != null) {
                    debug.println("Verified signature of OCSP Response");
                }
                return true;

            } else {
                if (debug != null) {
                    debug.println(
                        "Error verifying signature of OCSP Response");
                }
                return false;
            }
        } catch (InvalidKeyException | NoSuchAlgorithmException |
                 SignatureException e)
        {
            throw new CertPathValidatorException(e);
        }
    }
696954
private static boolean verifyCertificateChain(X509Certificate cert){
		
		if ( null == cert) {
			LogUtil.writeErrorLog("cert must Not null");
			return false;
		}
		
		X509Certificate middleCert = CertUtil.getMiddleCert();
		if (null == middleCert) {
			LogUtil.writeErrorLog("middleCert must Not null");
			return false;
		}
		
		X509Certificate rootCert = CertUtil.getRootCert();
		if (null == rootCert) {
			LogUtil.writeErrorLog("rootCert or cert must Not null");
			return false;
		}
		
		try {
		
	        X509CertSelector selector = new X509CertSelector();
	        selector.setCertificate(cert);
	        
	        Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
	        trustAnchors.add(new TrustAnchor(rootCert, null));
	        PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(
			        trustAnchors, selector);
	
	        Set<X509Certificate> intermediateCerts = new HashSet<X509Certificate>();
	        intermediateCerts.add(rootCert);
	        intermediateCerts.add(middleCert);
	        intermediateCerts.add(cert);
	        
	        pkixParams.setRevocationEnabled(false);
	
	        CertStore intermediateCertStore = CertStore.getInstance("Collection",
	                new CollectionCertStoreParameters(intermediateCerts), "BC");
	        pkixParams.addCertStore(intermediateCertStore);
	
	        CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
	        
        	@SuppressWarnings("unused")
			PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder
                .build(pkixParams);
			LogUtil.writeLog("verify certificate chain succeed.");
			return true;
        } catch (java.security.cert.CertPathBuilderException e){
			LogUtil.writeErrorLog("verify certificate chain fail.", e);
		} catch (Exception e) {
			LogUtil.writeErrorLog("verify certificate chain exception: ", e);
		}
		return false;
	}
21206
def _custom_validate(self, verify, trust_bundle):
        
        # If we disabled cert validation, just say: cool.
        if not verify:
            return

        # We want data in memory, so load it up.
        if os.path.isfile(trust_bundle):
            with open(trust_bundle, 'rb') as f:
                trust_bundle = f.read()

        cert_array = None
        trust = Security.SecTrustRef()

        try:
            # Get a CFArray that contains the certs we want.
            cert_array = _cert_array_from_pem(trust_bundle)

            # Ok, now the hard part. We want to get the SecTrustRef that ST has
            # created for this connection, shove our CAs into it, tell ST to
            # ignore everything else it knows, and then ask if it can build a
            # chain. This is a buuuunch of code.
            result = Security.SSLCopyPeerTrust(
                self.context, ctypes.byref(trust)
            )
            _assert_no_error(result)
            if not trust:
                raise ssl.SSLError("Failed to copy trust reference")

            result = Security.SecTrustSetAnchorCertificates(trust, cert_array)
            _assert_no_error(result)

            result = Security.SecTrustSetAnchorCertificatesOnly(trust, True)
            _assert_no_error(result)

            trust_result = Security.SecTrustResultType()
            result = Security.SecTrustEvaluate(
                trust, ctypes.byref(trust_result)
            )
            _assert_no_error(result)
        finally:
            if trust:
                CoreFoundation.CFRelease(trust)

            if cert_array is not None:
                CoreFoundation.CFRelease(cert_array)

        # Ok, now we can look at what the result was.
        successes = (
            SecurityConst.kSecTrustResultUnspecified,
            SecurityConst.kSecTrustResultProceed
        )
        if trust_result.value not in successes:
            raise ssl.SSLError(
                "certificate verify failed, error code: %d" %
                trust_result.value
            )
1298459
def _connect(self):
        ""
        sock = super(SSLConnection, self)._connect()
        if hasattr(ssl, "create_default_context"):
            context = ssl.create_default_context()
            context.check_hostname = False
            context.verify_mode = self.cert_reqs
            if self.certfile and self.keyfile:
                context.load_cert_chain(certfile=self.certfile,
                                        keyfile=self.keyfile)
            if self.ca_certs:
                context.load_verify_locations(self.ca_certs)
            sock = context.wrap_socket(sock, server_hostname=self.host)
        else:
            # In case this code runs in a version which is older than 2.7.9,
            # we want to fall back to old code
            sock = ssl.wrap_socket(sock,
                                   cert_reqs=self.cert_reqs,
                                   keyfile=self.keyfile,
                                   certfile=self.certfile,
                                   ca_certs=self.ca_certs)
        return sock