check server identify against hostnames. This method is used to enhance X509TrustManager to provide standard identity check.

This method can be applied to both clients and servers.

@param session
@param cert
@throws CertificateException
428754
private void checkIdentity(SSLSession session, X509Certificate cert) throws CertificateException {
		if (session == null) {
			throw new CertificateException("No handshake session");
		}

		if (EndpointIdentificationAlgorithm.HTTPS == identityAlg) {
			String hostname = session.getPeerHost();
			APINameChecker.verifyAndThrow(hostname, cert);
		}
	}
945078
public static void setTlsExtHostName(long ssl, String hostname) {
        if (hostname != null && hostname.endsWith(".")) {
            // Strip trailing dot if included.
            // See https://github.com/netty/netty-tcnative/issues/400
            hostname = hostname.substring(0, hostname.length() - 1);
        }
        setTlsExtHostName0(ssl, hostname);
    }
183613
@Override
	public void engineSetCertificateEntry(String alias, Certificate certificate)
			throws KeyStoreException {

		if (!(certificate instanceof X509Certificate)) {
			throw new KeyStoreException(
					"Certificate must be instance of X509Certificate");
		}
		File file;
		ResourceTrustAnchor trustAnchor = getCertificateEntry(alias);
		if (trustAnchor != null) {
			file = trustAnchor.getFile();
		} else {
			file = new File(defaultDirectory, alias);
		}
		X509Certificate x509Cert = (X509Certificate) certificate;
		try {
			if(!inMemoryOnly){
				writeCertificate(x509Cert, file);
			}
			ResourceTrustAnchor anchor = new ResourceTrustAnchor(inMemoryOnly,
					new GlobusResource(file.getAbsolutePath()), new TrustAnchor(x509Cert,
							null));
			this.aliasObjectMap.put(alias, anchor);
			this.certFilenameMap.put(x509Cert, alias);
		} catch (ResourceStoreException e) {
			throw new KeyStoreException(e);
		} catch (IOException e) {
			throw new KeyStoreException(e);
		} catch (CertificateEncodingException e) {
			throw new KeyStoreException(e);
		}
	}
588806
private static void disableSSLCertificateChecking() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // Not implemented
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // Not implemented
            }
        } };

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());

            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // Create all-trusting host name verifier
            HostnameVerifier allHostsValid = new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };

            // Install the all-trusting host verifier
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        } catch (KeyManagementException e) {
            throw new IllegalArgumentException("Disabling SSL certificate failed: " + e,e);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("Disabling SSL certificate failed: " + e,e);
        }
    }
220363
public void checkKeyStore() {
        if (sslContext != null)
            return; //nothing to check if using preconfigured context
        
        if (keyStoreInputStream == null &&
	    sslConfig.getKeyStorePath() == null) {
            throw new IllegalStateException("SSL doesn't have a valid keystore");
        }
        // if the keystore has been configured but there is no
        // truststore configured, use the keystore as the truststore
        if (trustStoreInputStream == null && sslConfig.getTrustStorePath() == null) {
            trustStoreInputStream = keyStoreInputStream;
            sslConfig.setTrustStorePath(sslConfig.getKeyStorePath());
            sslConfig.setTrustStoreType(sslConfig.getKeyStoreType());
            sslConfig.setTrustStoreProvider(sslConfig.getKeyStoreProvider());
            sslConfig.setTrustStorePassword(sslConfig.getKeyStorePassword());
            sslConfig.setTrustManagerFactoryAlgorithm(sslConfig.getKeyManagerFactoryAlgorithm());
        }

        // It's the same stream we cannot read it twice, so read it once in memory
        if (keyStoreInputStream != null && keyStoreInputStream == trustStoreInputStream) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
		streamCopy(keyStoreInputStream, baos, null, false);
                keyStoreInputStream.close();
                keyStoreInputStream = new ByteArrayInputStream(baos.toByteArray());
                trustStoreInputStream = new ByteArrayInputStream(baos.toByteArray());
            } catch (Exception ex) {
                throw new IllegalStateException(ex);
            }
        }
    }
155790
private void checkPair() throws CertificateException {

        /* if either of pair is missing, return w/o error */
        if (forward == null || reverse == null) {
            return;
        }
        /*
         * If both elements of the pair are present, check that they
         * are a valid pair.
         */
        X500Principal fwSubject = forward.getSubjectX500Principal();
        X500Principal fwIssuer = forward.getIssuerX500Principal();
        X500Principal rvSubject = reverse.getSubjectX500Principal();
        X500Principal rvIssuer = reverse.getIssuerX500Principal();
        if (!fwIssuer.equals(rvSubject) || !rvIssuer.equals(fwSubject)) {
            throw new CertificateException("subject and issuer names in "
                + "forward and reverse certificates do not match");
        }

        /* check signatures unless key parameters are missing */
        try {
            PublicKey pk = reverse.getPublicKey();
            if (!(pk instanceof DSAPublicKey) ||
                        ((DSAPublicKey)pk).getParams() != null) {
                forward.verify(pk);
            }
            pk = forward.getPublicKey();
            if (!(pk instanceof DSAPublicKey) ||
                        ((DSAPublicKey)pk).getParams() != null) {
                reverse.verify(pk);
            }
        } catch (GeneralSecurityException e) {
            throw new CertificateException("invalid signature: "
                + e.getMessage());
        }
    }
754344
@Beta
  public static SSLContext trustAllSSLContext() throws GeneralSecurityException {
    TrustManager[] trustAllCerts =
        new TrustManager[] {
          new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {}

            public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {}

            public X509Certificate[] getAcceptedIssuers() {
              return null;
            }
          }
        };
    SSLContext context = getTlsSslContext();
    context.init(null, trustAllCerts, null);
    return context;
  }
979252
private void indexCertificate(X509Certificate cert) {
        X500Principal subject = cert.getSubjectX500Principal();
        Object oldEntry = certSubjects.put(subject, cert);
        if (oldEntry != null) { // assume this is unlikely
            if (oldEntry instanceof X509Certificate) {
                if (cert.equals(oldEntry)) {
                    return;
                }
                List<X509Certificate> list = new ArrayList<>(2);
                list.add(cert);
                list.add((X509Certificate)oldEntry);
                certSubjects.put(subject, list);
            } else {
                @SuppressWarnings("unchecked") // See certSubjects javadoc.
                List<X509Certificate> list = (List<X509Certificate>)oldEntry;
                if (list.contains(cert) == false) {
                    list.add(cert);
                }
                certSubjects.put(subject, list);
            }
        }
    }
338406
@Beta
  public static HostnameVerifier trustAllHostnameVerifier() {
    return new HostnameVerifier() {

      public boolean verify(String arg0, SSLSession arg1) {
        return true;
      }
    };
  }
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;
	}
700967
@Override
    public void check(Certificate cert, Collection<String> unresCritExts)
        throws CertPathValidatorException
    {
        X509Certificate currCert = (X509Certificate)cert;

        remainingCerts--;

        // if final certificate, check that target constraints are satisfied
        if (remainingCerts == 0) {
            if (targetConstraints != null &&
                targetConstraints.match(currCert) == false) {
                throw new CertPathValidatorException("target certificate " +
                    "constraints check failed");
            }
        } else {
            // otherwise, verify that keyCertSign bit is set in CA certificate
            verifyCAKeyUsage(currCert);
        }

        // remove the extensions that we have checked
        if (unresCritExts != null && !unresCritExts.isEmpty()) {
            unresCritExts.remove(KeyUsage_Id.toString());
            unresCritExts.remove(ExtendedKeyUsage_Id.toString());
            unresCritExts.remove(SubjectAlternativeName_Id.toString());
        }
    }
730901
public void removeSession(Session session) {
		InetSocketAddress remoteSocketAddress = session
				.getRemoteSocketAddress();
		log.warn("Remove a session: "
				+ SystemUtils.getRawAddress(remoteSocketAddress) + ":"
				+ remoteSocketAddress.getPort());
		this.sessionList.remove(session);
	}
351351
public static void verifyAndThrow(final String name, final X509Certificate cert) throws CertificateException{
		if (!verify(name, cert)) {
			throw new CertificateException("No name matching " + name + " found");
		}		
	}
415184
@Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "checkServerTrusted");

        Map<String, Object> currentConnectionInfo = ThreadManager.getInstance().getOutboundConnectionInfoInternal();
        if (currentConnectionInfo != null) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "original peerHost: " + peerHost);
                Tr.debug(tc, "currentConnectionInfo: " + currentConnectionInfo);
            }
            peerHost = (String) currentConnectionInfo.get(Constants.CONNECTION_INFO_REMOTE_HOST);
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "current peerHost: " + peerHost);
        } else {
            currentConnectionInfo = extendedInfo;
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "currentConnectionInfo from extendedInfo: " + currentConnectionInfo);
        }

        extendedInfo = JSSEHelper.getInstance().getOutboundConnectionInfo();
        if (extendedInfo != null)
            peerHost = (String) extendedInfo.get(Constants.CONNECTION_INFO_REMOTE_HOST);

        // if we do not have host and port just go ahead and default it to unknown
        // to avoid null's
        if (peerHost == null || 0 == peerHost.length()) {
            peerHost = "unknown";
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Target host: " + peerHost);
            for (int j = 0; j < chain.length; j++) {
                Tr.debug(tc, "Certificate information:");
                Tr.debug(tc, "  Subject DN: " + chain[j].getSubjectDN());
                Tr.debug(tc, "  Issuer DN: " + chain[j].getIssuerDN());
                Tr.debug(tc, "  Serial number: " + chain[j].getSerialNumber());
            }
        }

        for (int i = 0; i < tm.length; i++) {
            if (tm[i] != null && tm[i] instanceof X509TrustManager) {
                // skip the default trust manager if configured to do so.
                try {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                        Tr.debug(tc, "Delegating to X509TrustManager: " + tm[i].getClass().getName());
                    ((X509TrustManager) tm[i]).checkServerTrusted(chain, authType);
                } catch (CertificateException e) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                        Tr.debug(tc, "Certificate Exception occurred: " + e.getMessage());

                    // if the reason for the CertificateException is due to
                    // an expired date, don't accept it.
                    boolean dateValid = checkIfExpiredBeforeOrAfter(chain);
                    if (!dateValid) {
                        throw e;
                    }

                    try {
                        // If this is a client process then we may prompt the user to accept the signer certificate
                        if (!isServer) {
                            if (!autoAccept) {
                                // prompt user
                                if (userAcceptedPrompt(chain)) {
                                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                                        Tr.debug(tc, "prompt user - adding certificate to the truststore.");
                                    setCertificateToTruststore(chain);
                                } else {
                                    printClientHandshakeError(config, tsFile, e, chain);
                                    throw e;
                                }

                            } else {
                                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                                    Tr.debug(tc, "autoacceptsigner - adding certificate to the truststore.");
                                setCertificateToTruststore(chain);
                            }
                        } else {
                            // IBM JDK will throw the exception in obfuscated code, get the cause
                            Exception excpt = e;
                            if (excpt.getClass().toString().startsWith("class com.ibm.jsse2")) {
                                excpt = (Exception) excpt.getCause();
                            }

                            // This the server print a message and rethrow the exception
                            FFDCFilter.processException(excpt, getClass().getName(), "checkServerTrusted", this, new Object[] { chain, authType });
                            printClientHandshakeError(config, tsFile, e, chain);
                            throw excpt;
                        }
                    } catch (Exception ex)
                    {
                        throw new CertificateException(ex.getMessage());
                    }
                }
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, "Server is trusted by all X509TrustManagers.");
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "checkServerTrusted");
    }
48998
public static boolean isSelfSigned(X509Certificate cert) {
        try {
            cert.verify(cert.getPublicKey());
            return true;
        } catch (SignatureException e) {
            return false;
        } catch (InvalidKeyException e) {
            return false;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
18925
public final X509Certificate retrieveCertificate(KeyStore keyStore, String certificateName) {
        try {
            logger.entry();
            X509Certificate certificate = (X509Certificate) keyStore.getCertificate(certificateName);
            logger.exit();
            return certificate;
        } catch (KeyStoreException e) {
            RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to retrieve a certificate.", e);
            logger.error(exception.toString());
            throw exception;
        }
    }
1080656
@Override
    public void updateState(X509Certificate cert)
        throws CertificateException, IOException, CertPathValidatorException {

        if (cert == null)
            return;

        X509CertImpl icert = X509CertImpl.toImpl(cert);

        /* see if certificate key has null parameters */
        if (PKIX.isDSAPublicKeyWithoutParams(icert.getPublicKey())) {
            keyParamsNeededFlag = true;
        }

        /* update certificate */
        this.cert = icert;

        /* update issuer DN */
        issuerDN = cert.getIssuerX500Principal();

        if (!X509CertImpl.isSelfIssued(cert)) {

            /*
             * update traversedCACerts only if this is a non-self-issued
             * intermediate CA cert
             */
            if (!init && cert.getBasicConstraints() != -1) {
                traversedCACerts++;
            }
        }

        /* update subjectNamesTraversed only if this is the EE cert or if
           this cert is not self-issued */
        if (init || !X509CertImpl.isSelfIssued(cert)){
            X500Principal subjName = cert.getSubjectX500Principal();
            subjectNamesTraversed.add(X500Name.asX500Name(subjName));

            try {
                SubjectAlternativeNameExtension subjAltNameExt
                    = icert.getSubjectAlternativeNameExtension();
                if (subjAltNameExt != null) {
                    GeneralNames gNames = subjAltNameExt.get(
                            SubjectAlternativeNameExtension.SUBJECT_NAME);
                    for (GeneralName gName : gNames.names()) {
                        subjectNamesTraversed.add(gName.getName());
                    }
                }
            } catch (IOException e) {
                if (debug != null) {
                    debug.println("ForwardState.updateState() unexpected "
                        + "exception");
                    e.printStackTrace();
                }
                throw new CertPathValidatorException(e);
            }
        }

        init = false;
    }