protected boolean verify(String hostname, SSLSession session, boolean interactive) { LOGGER.log( Level.FINE, "hostname verifier for " + hostname + ", trying default verifier first"); // if the default verifier accepts the hostname, we are done if (defaultVerifier.verify(hostname, session)) { LOGGER.log(Level.FINE, "default verifier accepted " + hostname); return true; } // otherwise, we check if the hostname is an alias for this cert in our keystore try { X509Certificate cert = (X509Certificate) session.getPeerCertificates()[0]; // Log.d(TAG, "cert: " + cert); if (cert.equals(appKeyStore.getCertificate(hostname.toLowerCase(Locale.US)))) { LOGGER.log(Level.FINE, "certificate for " + hostname + " is in our keystore. accepting."); return true; } else { LOGGER.log( Level.FINE, "server " + hostname + " provided wrong certificate, asking user."); if (interactive) { return interactHostname(cert, hostname); } else { return false; } } } catch (Exception e) { e.printStackTrace(); return false; } }
public int compare(Object o1, Object o2) { X509Certificate c1 = (X509Certificate) o1; X509Certificate c2 = (X509Certificate) o2; if (c1 == c2) // this deals with case where both are null { return 0; } if (c1 == null) // non-null is always bigger than null { return -1; } if (c2 == null) { return 1; } if (c1.equals(c2)) { return 0; } Date d1 = c1.getNotAfter(); Date d2 = c2.getNotAfter(); int c = d1.compareTo(d2); if (c == 0) { String s1 = JavaImpl.getSubjectX500(c1); String s2 = JavaImpl.getSubjectX500(c2); c = s1.compareTo(s2); if (c == 0) { s1 = JavaImpl.getIssuerX500(c1); s2 = JavaImpl.getIssuerX500(c2); c = s1.compareTo(s2); if (c == 0) { BigInteger big1 = c1.getSerialNumber(); BigInteger big2 = c2.getSerialNumber(); c = big1.compareTo(big2); if (c == 0) { try { byte[] b1 = c1.getEncoded(); byte[] b2 = c2.getEncoded(); int len1 = b1.length; int len2 = b2.length; int i = 0; for (; i < len1 && i < len2; i++) { c = ((int) b1[i]) - ((int) b2[i]); if (c != 0) { break; } } if (c == 0) { c = b1.length - b2.length; } } catch (CertificateEncodingException cee) { // I give up. They can be equal if they // really want to be this badly. c = 0; } } } } } return c; }
public boolean checkCertificate(X509Certificate certificate, String hostname) { try { return certificate.equals(appKeyStore.getCertificate(hostname.toLowerCase(Locale.US))) || interactHostname(certificate, hostname); } catch (KeyStoreException e) { LOGGER.error("error while checking certificate", e); return false; } }
/** * Find the index of the token corresponding to either the X509Certificate or PublicKey used to * sign the "signatureResult" argument. */ private int findCorrespondingTokenIndex( WSSecurityEngineResult signatureResult, List<WSSecurityEngineResult> results) { // See what was used to sign this result X509Certificate cert = (X509Certificate) signatureResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE); PublicKey publicKey = (PublicKey) signatureResult.get(WSSecurityEngineResult.TAG_PUBLIC_KEY); for (int i = 0; i < results.size(); i++) { WSSecurityEngineResult token = results.get(i); Integer actInt = (Integer) token.get(WSSecurityEngineResult.TAG_ACTION); if (actInt == WSConstants.SIGN) { continue; } BinarySecurity binarySecurity = (BinarySecurity) token.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN); PublicKey foundPublicKey = (PublicKey) token.get(WSSecurityEngineResult.TAG_PUBLIC_KEY); if (binarySecurity instanceof X509Security || binarySecurity instanceof PKIPathSecurity) { X509Certificate foundCert = (X509Certificate) token.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE); if (foundCert.equals(cert)) { return i; } } else if (actInt.intValue() == WSConstants.ST_SIGNED || actInt.intValue() == WSConstants.ST_UNSIGNED) { SamlAssertionWrapper assertionWrapper = (SamlAssertionWrapper) token.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); SAMLKeyInfo samlKeyInfo = assertionWrapper.getSubjectKeyInfo(); if (samlKeyInfo != null) { X509Certificate[] subjectCerts = samlKeyInfo.getCerts(); PublicKey subjectPublicKey = samlKeyInfo.getPublicKey(); if ((cert != null && subjectCerts != null && cert.equals(subjectCerts[0])) || (subjectPublicKey != null && subjectPublicKey.equals(publicKey))) { return i; } } } else if (publicKey != null && publicKey.equals(foundPublicKey)) { return i; } } return -1; }
protected static void processAttrCert4( X509Certificate acIssuerCert, ExtendedPKIXParameters pkixParams) throws CertPathValidatorException { Set set = pkixParams.getTrustedACIssuers(); boolean trusted = false; for (Iterator it = set.iterator(); it.hasNext(); ) { TrustAnchor anchor = (TrustAnchor) it.next(); if (acIssuerCert.getSubjectX500Principal().getName("RFC2253").equals(anchor.getCAName()) || acIssuerCert.equals(anchor.getTrustedCert())) { trusted = true; } } if (!trusted) { throw new CertPathValidatorException("Attribute certificate issuer is not directly trusted."); } }
public synchronized boolean isCertificateAcceptedForHostname( String hostname, X509Certificate cert) { String prefix = hostname.toLowerCase() + ":"; try { for (Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements(); ) { String alias = aliases.nextElement(); if (alias.startsWith(prefix)) { X509Certificate c = (X509Certificate) keyStore.getCertificate(alias); if (c != null && c.equals(cert)) return true; } } } catch (KeyStoreException x) { ZimbraLog.security.warn(x); } return false; }
public void testAutoCredentialCreationNoRenewal() { AssertionCredentialsManager cm = null; try { IdentityProviderProperties props = Utils.getIdentityProviderProperties(); props.setAutoRenewAssertingCredentials(false); cm = new AssertionCredentialsManager(props, ca, db); X509Certificate cert = cm.getIdPCertificate(); assertNotNull(cert); assertNotNull(cm.getIdPKey()); String expectedSub = Utils.CA_SUBJECT_PREFIX + ",CN=" + AssertionCredentialsManager.CERT_DN; assertEquals(expectedSub, cert.getSubjectDN().toString()); String subject = cert.getSubjectDN().toString(); KeyPair pair = KeyUtil.generateRSAKeyPair1024(); GregorianCalendar cal = new GregorianCalendar(); Date start = cal.getTime(); cal.add(Calendar.SECOND, 2); Date end = cal.getTime(); cm.deleteAssertingCredentials(); X509Certificate shortCert = ca.signCertificate(subject, pair.getPublic(), start, end); cm.storeCredentials(shortCert, pair.getPrivate()); if (cert.equals(shortCert)) { assertTrue(false); } Thread.sleep(2500); assertTrue(CertUtil.isExpired(shortCert)); try { cm.getIdPCertificate(); assertTrue(false); } catch (DorianInternalFault fault) { } } catch (Exception e) { FaultUtil.printFault(e); assertTrue(false); } finally { try { cm.clearDatabase(); } catch (Exception e) { e.printStackTrace(); } } }
/** * Liefert alle Schluessel, die von diesem signiert wurden. * * @return Liste aller Schluessel, die von diesem signiert wurden. Die Funktion liefert nie NULL * sondern hoechstens eine leere Liste. * @throws Exception */ public List<Entry> getClients() throws Exception { if (this.clients != null) return this.clients; this.clients = new ArrayList<Entry>(); if (CHECK_CA && !this.isCA()) return this.clients; X509Certificate x = this.getCertificate(); byte[] sig = x.getPublicKey().getEncoded(); X500Principal self = x.getSubjectX500Principal(); // 2. Wir sind ein CA-Zertifikat, jetzt holen wir alle // Zertifikate, bei denen wir als CA eingetragen sind. List<Entry> all = this.store.getEntries(); for (Entry e : all) { X509Certificate c = e.getCertificate(); // sind wir selbst if (c.equals(x)) continue; // Checken, ob die Aussteller-Signatur angegeben ist byte[] issuerSig = x.getExtensionValue(Extension.authorityKeyIdentifier.getId()); if (issuerSig != null && issuerSig.length > 0) { // Issuer-Signatur angegeben. Mal checken, ob es unsere ist if (Arrays.equals(issuerSig, sig)) { // jepp, passt this.clients.add(e); continue; } } // Checken, ob der DN uebereinstimmt. X500Principal p = c.getIssuerX500Principal(); // passt, nehmen wir auch if (p != null && p.equals(self)) { this.clients.add(e); continue; } } Collections.sort(this.clients); return this.clients; }
/* * Initializes the signerInfo and the VerifierInfo from the Certificate Pair */ private void initializeCertificates() { X509Certificate certRoot = null; X509Certificate certIssuer = null; CertificatePair trustedCertificate; if (getFoundCertificate() == null) { CertificatePair[] certs = getRootCertificates(); if (certs.length == 0) return; trustedCertificate = certs[0]; } else { trustedCertificate = getFoundCertificate(); } certRoot = (X509Certificate) trustedCertificate.getRoot(); certIssuer = (X509Certificate) trustedCertificate.getIssuer(); StringBuffer strb = new StringBuffer(); strb.append(issuerString(certIssuer.getSubjectDN())); strb.append("\r\n"); // $NON-NLS-1$ strb.append( NLS.bind( Messages.JarVerificationResult_ValidBetween, (new String[] { dateString(certIssuer.getNotBefore()), dateString(certIssuer.getNotAfter()) }))); strb.append(checkValidity(certIssuer)); signerInfo = strb.toString(); if (certIssuer != null && !certIssuer.equals(certRoot)) { strb = new StringBuffer(); strb.append(issuerString(certIssuer.getIssuerDN())); strb.append("\r\n"); // $NON-NLS-1$ strb.append( NLS.bind( Messages.JarVerificationResult_ValidBetween, (new String[] { dateString(certRoot.getNotBefore()), dateString(certRoot.getNotAfter()) }))); strb.append(checkValidity(certRoot)); verifierInfo = strb.toString(); } }
public void testAutoCredentialCreationRenew() { AssertionCredentialsManager cm = null; try { cm = Utils.getAssertionCredentialsManager(); X509Certificate cert = cm.getIdPCertificate(); assertNotNull(cert); assertNotNull(cm.getIdPKey()); String expectedSub = Utils.CA_SUBJECT_PREFIX + ",CN=" + AssertionCredentialsManager.CERT_DN; assertEquals(expectedSub, cert.getSubjectDN().toString()); String subject = cert.getSubjectDN().toString(); KeyPair pair = KeyUtil.generateRSAKeyPair1024(); GregorianCalendar cal = new GregorianCalendar(); Date start = cal.getTime(); cal.add(Calendar.SECOND, 6); Date end = cal.getTime(); cm.deleteAssertingCredentials(); X509Certificate shortCert = ca.signCertificate(subject, pair.getPublic(), start, end); cm.storeCredentials(shortCert, pair.getPrivate()); X509Certificate idpShortCert = cm.getIdPCertificate(); assertEquals(shortCert, idpShortCert); if (cert.equals(idpShortCert)) { assertTrue(false); } Thread.sleep(6500); assertTrue(CertUtil.isExpired(idpShortCert)); X509Certificate renewedCert = cm.getIdPCertificate(); assertNotNull(renewedCert); PrivateKey renewedKey = cm.getIdPKey(); assertNotNull(renewedKey); assertTrue(!CertUtil.isExpired(renewedCert)); if (renewedCert.equals(idpShortCert)) { assertTrue(false); } if (renewedKey.equals(pair.getPrivate())) { assertTrue(false); } SAMLAssertion saml = cm.getAuthenticationAssertion(TEST_UID, TEST_FIRST_NAME, TEST_LAST_NAME, TEST_EMAIL); verifySAMLAssertion(saml, cm); String xml = SAMLUtils.samlAssertionToString(saml); SAMLAssertion saml2 = SAMLUtils.stringToSAMLAssertion(xml); verifySAMLAssertion(saml2, cm); } catch (Exception e) { FaultUtil.printFault(e); assertTrue(false); } finally { try { cm.clearDatabase(); } catch (Exception e) { e.printStackTrace(); } } }
/** * Verifies a matching certificate. * * <p>This method executes any of the validation steps in the PKIX path validation algorithm which * were not satisfied via filtering out non-compliant certificates with certificate matching * rules. * * <p>If the last certificate is being verified (the one whose subject matches the target subject, * then the steps in Section 6.1.4 of the Certification Path Validation algorithm are NOT * executed, regardless of whether or not the last cert is an end-entity cert or not. This allows * callers to certify CA certs as well as EE certs. * * @param cert the certificate to be verified * @param currentState the current state against which the cert is verified * @param certPathList the certPathList generated thus far */ void verifyCert(X509Certificate cert, State currState, List certPathList) throws GeneralSecurityException { if (debug != null) debug.println( "ReverseBuilder.verifyCert(SN: " + Debug.toHexString(cert.getSerialNumber()) + "\n Subject: " + cert.getSubjectX500Principal() + ")"); ReverseState currentState = (ReverseState) currState; /* we don't perform any validation of the trusted cert */ if (currentState.isInitial()) { return; } /* * check for looping - abort a loop if * ((we encounter the same certificate twice) AND * ((policyMappingInhibited = true) OR (no policy mapping * extensions can be found between the occurences of the same * certificate))) * in order to facilitate the check to see if there are * any policy mapping extensions found between the occurences * of the same certificate, we reverse the certpathlist first */ if ((certPathList != null) && (!certPathList.isEmpty())) { List reverseCertList = new ArrayList(); Iterator iter = certPathList.iterator(); while (iter.hasNext()) { reverseCertList.add(0, iter.next()); } Iterator cpListIter = reverseCertList.iterator(); boolean policyMappingFound = false; while (cpListIter.hasNext()) { X509Certificate cpListCert = (X509Certificate) cpListIter.next(); X509CertImpl cpListCertImpl = X509CertImpl.toImpl(cpListCert); PolicyMappingsExtension policyMappingsExt = cpListCertImpl.getPolicyMappingsExtension(); if (policyMappingsExt != null) { policyMappingFound = true; } if (debug != null) debug.println("policyMappingFound = " + policyMappingFound); if (cert.equals(cpListCert)) { if ((buildParams.isPolicyMappingInhibited()) || (!policyMappingFound)) { if (debug != null) debug.println("loop detected!!"); throw new CertPathValidatorException("loop detected"); } } } } /* check if target cert */ boolean finalCert = cert.getSubjectX500Principal().equals(targetSubjectDN); /* check if CA cert */ boolean caCert = (cert.getBasicConstraints() != -1 ? true : false); /* if there are more certs to follow, verify certain constraints */ if (!finalCert) { /* check if CA cert */ if (!caCert) throw new CertPathValidatorException("cert is NOT a CA cert"); /* If the certificate was not self-issued, verify that * remainingCerts is greater than zero */ if ((currentState.remainingCACerts <= 0) && !X509CertImpl.isSelfIssued(cert)) { throw new CertPathValidatorException("pathLenConstraint violated, path too long"); } /* * Check keyUsage extension (only if CA cert and not final cert) */ KeyChecker.verifyCAKeyUsage(cert); } else { /* * If final cert, check that it satisfies specified target * constraints */ if (targetCertSelector.match(cert) == false) { throw new CertPathValidatorException("target certificate " + "constraints check failed"); } } /* * Check revocation. */ if (buildParams.isRevocationEnabled()) { boolean crlSign = currentState.crlChecker.check(cert, currentState.pubKey, true); // if this cert can't vouch for the CRL on the next cert, and // if this wasn't the last cert in the chain, then we can't // keep going from here! // NOTE: if we ever add indirect/idp support, this will have // to change... if ((!crlSign) && (!finalCert)) throw new CertPathValidatorException("cert can't vouch for crl"); } /* Check name constraints if this is not a self-issued cert */ if (finalCert || !X509CertImpl.isSelfIssued(cert)) { if (currentState.nc != null) { try { if (!currentState.nc.verify(cert)) { throw new CertPathValidatorException("name constraints check failed"); } } catch (IOException ioe) { throw new CertPathValidatorException(ioe); } } } /* * Check policy */ X509CertImpl certImpl = X509CertImpl.toImpl(cert); currentState.rootNode = PolicyChecker.processPolicies( currentState.certIndex, initPolicies, currentState.explicitPolicy, currentState.policyMapping, currentState.inhibitAnyPolicy, buildParams.getPolicyQualifiersRejected(), currentState.rootNode, certImpl, finalCert); /* * Check CRITICAL private extensions */ Set unresolvedCritExts = cert.getCriticalExtensionOIDs(); if (unresolvedCritExts == null) { unresolvedCritExts = Collections.EMPTY_SET; } Iterator i = currentState.userCheckers.iterator(); while (i.hasNext()) { PKIXCertPathChecker checker = (PKIXCertPathChecker) i.next(); checker.check(cert, unresolvedCritExts); } /* * Look at the remaining extensions and remove any ones we have * already checked. If there are any left, throw an exception! */ if (!unresolvedCritExts.isEmpty()) { unresolvedCritExts.remove(PKIXExtensions.BasicConstraints_Id.toString()); unresolvedCritExts.remove(PKIXExtensions.NameConstraints_Id.toString()); unresolvedCritExts.remove(PKIXExtensions.CertificatePolicies_Id.toString()); unresolvedCritExts.remove(PKIXExtensions.PolicyMappings_Id.toString()); unresolvedCritExts.remove(PKIXExtensions.PolicyConstraints_Id.toString()); unresolvedCritExts.remove(PKIXExtensions.InhibitAnyPolicy_Id.toString()); unresolvedCritExts.remove(PKIXExtensions.SubjectAlternativeName_Id.toString()); unresolvedCritExts.remove(PKIXExtensions.KeyUsage_Id.toString()); unresolvedCritExts.remove(PKIXExtensions.ExtendedKeyUsage_Id.toString()); if (!unresolvedCritExts.isEmpty()) throw new CertificateException("Unrecognized critical extension(s)"); } /* * Check signature. */ if (buildParams.getSigProvider() != null) { cert.verify(currentState.pubKey, buildParams.getSigProvider()); } else { cert.verify(currentState.pubKey); } }
@Override protected Object _doExecute() throws Exception { X509ChangeCAEntry ey = getChangeCAEntry(); String caName = ey.getName(); out("checking CA" + caName); CAEntry entry = caManager.getCA(caName); if (entry == null) { throw new UnexpectedException("could not find CA '" + caName + "'"); } if (entry instanceof X509CAEntry == false) { throw new UnexpectedException("CA '" + caName + "' is not an X509-CA"); } X509CAEntry ca = (X509CAEntry) entry; // CA cert uris if (ey.getCaCertUris() != null) { List<String> ex = ey.getCaCertUris(); List<String> is = ca.getCacertUris(); MgmtQAShellUtil.assertEquals("CA cert uris", ex, is); } // CA certificate if (ey.getCert() != null) { X509Certificate ex = ey.getCert(); X509Certificate is = ca.getCertificate(); if (ex.equals(is) == false) { throw new CmdFailure("CA cert is not as expected"); } } // CMP control name if (ey.getCmpControlName() != null) { String ex = ey.getCmpControlName(); String is = ca.getCmpControlName(); MgmtQAShellUtil.assertEquals("CMP control name", ex, is); } // CRL signer name if (ey.getCrlSignerName() != null) { String ex = ey.getCrlSignerName(); String is = ca.getCrlSignerName(); MgmtQAShellUtil.assertEquals("CRL signer name", ex, is); } // CRL uris if (ey.getCrlUris() != null) { List<String> ex = ey.getCrlUris(); List<String> is = ca.getCrlUris(); MgmtQAShellUtil.assertEquals("CRL uris", ex, is); } // DeltaCRL uris if (ey.getDeltaCrlUris() != null) { List<String> ex = ey.getDeltaCrlUris(); List<String> is = ca.getDeltaCrlUris(); MgmtQAShellUtil.assertEquals("Delta CRL uris", ex, is); } // Duplicate key mode if (ey.getDuplicateKeyMode() != null) { DuplicationMode ex = ey.getDuplicateKeyMode(); DuplicationMode is = ca.getDuplicateKeyMode(); if (ex.equals(is) == false) { throw new CmdFailure("Duplicate key mode: is '" + is + "', but expected '" + ex + "'"); } } // Duplicate subject mode if (ey.getDuplicateSubjectMode() != null) { DuplicationMode ex = ey.getDuplicateSubjectMode(); DuplicationMode is = ca.getDuplicateSubjectMode(); if (ex.equals(is) == false) { throw new CmdFailure("Duplicate subject mode: is '" + is + "', but expected '" + ex + "'"); } } // Expiration period if (ey.getExpirationPeriod() != null) { Integer ex = ey.getExpirationPeriod(); Integer is = ca.getExpirationPeriod(); if (ex.equals(is) == false) { throw new CmdFailure("Expiration period: is '" + is + "', but expected '" + ex + "'"); } } // Extra control if (ey.getExtraControl() != null) { String ex = ey.getExtraControl(); String is = ca.getExtraControl(); if (ex.equals(is) == false) { throw new CmdFailure("Extra control: is '" + is + "', but expected '" + ex + "'"); } } // Max validity if (ey.getMaxValidity() != null) { CertValidity ex = ey.getMaxValidity(); CertValidity is = ca.getMaxValidity(); if (ex.equals(is) == false) { throw new CmdFailure("Max validity: is '" + is + "', but expected '" + ex + "'"); } } // Num CRLs if (ey.getNumCrls() != null) { int ex = ey.getNumCrls(); int is = ca.getNumCrls(); if (ex != is) { throw new CmdFailure("num CRLs: is '" + is + "', but expected '" + ex + "'"); } } // OCSP uris if (ey.getOcspUris() != null) { List<String> ex = ey.getOcspUris(); List<String> is = ca.getOcspUris(); MgmtQAShellUtil.assertEquals("OCSP uris", ex, is); } // Permissions if (ey.getPermissions() != null) { Set<Permission> ex = ey.getPermissions(); Set<Permission> is = ca.getPermissions(); MgmtQAShellUtil.assertEquals("permissions", ex, is); } // Responder name if (ey.getResponderName() != null) { String ex = ey.getResponderName(); String is = ca.getResponderName(); MgmtQAShellUtil.assertEquals("responder name", ex, is); } // Signer Type if (ey.getSignerType() != null) { String ex = ey.getSignerType(); String is = ca.getSignerType(); MgmtQAShellUtil.assertEquals("signer type", ex, is); } if (ey.getSignerConf() != null) { CmpUtf8Pairs ex = new CmpUtf8Pairs(ey.getSignerConf()); ex.removeUtf8Pair("keystore"); CmpUtf8Pairs is = new CmpUtf8Pairs(ca.getSignerConf()); is.removeUtf8Pair("keystore"); if (ex.equals(is) == false) { throw new CmdFailure("signer conf: is '" + is + "', but expected '" + ex + "'"); } } // Status if (ey.getStatus() != null) { CAStatus ex = ey.getStatus(); CAStatus is = ca.getStatus(); if (ex.equals(is) == false) { throw new CmdFailure("status: is '" + is + "', but expected '" + ex + "'"); } } // validity mode if (ey.getValidityMode() != null) { ValidityMode ex = ey.getValidityMode(); ValidityMode is = ca.getValidityMode(); if (ex.equals(is) == false) { throw new CmdFailure("validity mode: is '" + is + "', but expected '" + ex + "'"); } } out(" checked CA" + caName); return null; }