List of usage examples for java.security.cert X509CRL getIssuerX500Principal
public X500Principal getIssuerX500Principal()
From source file:mitm.common.security.crl.PKIXRevocationChecker.java
private boolean checkDeltaCRL_6_3_3_b(X509Certificate targetCertificate, X509CRL deltaCRL, X509CRL baseCRL) throws IOException { if (!X509CRLInspector.isDeltaCRL(deltaCRL)) { logger.debug("CRL is not a delta CRL."); return false; }//from www . j a va2s. com if (X509CRLInspector.isDeltaCRL(baseCRL)) { logger.debug("CRL is not a base CRL it's a delta CRL."); return false; } if (!deltaCRL.getIssuerX500Principal().equals(baseCRL.getIssuerX500Principal())) { logger.debug("Delta CRL issuer does not match Base CRL issuer."); return false; } IssuingDistributionPoint deltaIDP = X509CRLInspector.getIssuingDistributionPoint(deltaCRL); IssuingDistributionPoint baseIDP = X509CRLInspector.getIssuingDistributionPoint(baseCRL); if (baseIDP != null) { if (!baseIDP.equals(deltaIDP)) { logger.debug("The Base CRL has a non matching IssuingDistributionPoint."); return false; } } else { if (deltaIDP != null) { logger.debug("The Delta CRL has a non matching IssuingDistributionPoint."); return false; } } AuthorityKeyIdentifier baseAKI = X509CRLInspector.getAuthorityKeyIdentifier(baseCRL); AuthorityKeyIdentifier deltaAKI = X509CRLInspector.getAuthorityKeyIdentifier(deltaCRL); if (baseAKI != null) { if (!baseAKI.equals(deltaAKI)) { logger.debug("Base AuthorityKeyIdentifier does not match Delta AuthorityKeyIdentifier."); return false; } } else { if (deltaAKI != null) { logger.debug("Delta AuthorityKeyIdentifier does not match Base AuthorityKeyIdentifier."); return false; } } return true; }
From source file:mitm.common.security.crl.PKIXRevocationChecker.java
private DeltaCRLStatus getDeltaCRLStatus(X509Certificate targetCertificate, X509CRL deltaCRL, PublicKey issuerPublicKey, Date now) throws NoSuchProviderException { DeltaCRLStatus status = DeltaCRLStatus.UNKNOWN; BigInteger baseCRLNumber;/* w ww . j a v a 2s. c o m*/ try { baseCRLNumber = X509CRLInspector.getDeltaIndicator(deltaCRL); } catch (IOException e) { logger.error("Error getting base CRL number", e); return DeltaCRLStatus.UNKNOWN; } X509CRLSelector crlSelector = new X509CRLSelector(); /* We need to find a valid base CRL with the same issuer as the delta CRL */ crlSelector.addIssuer(deltaCRL.getIssuerX500Principal()); /* * we need to find a baseCRL with at least a CRL number specified by the DeltaCRLIndicator in * the delta CRL */ crlSelector.setMinCRLNumber(baseCRLNumber); BigInteger deltaCRLNumber = null; try { deltaCRLNumber = X509CRLInspector.getCRLNumber(deltaCRL); } catch (IOException e) { logger.error("Error getting CRLNumber extension from the delta CRL.", e); } if (deltaCRLNumber != null) { /* * the base CRL we need to find should have a CRL number less than the delta CRL * otherwise it cannot be a base for this delta CRL */ crlSelector.setMaxCRLNumber(deltaCRLNumber.subtract(BigInteger.valueOf(1))); List<X509CRL> crls = findCRLs(targetCertificate, crlSelector, issuerPublicKey, now); for (X509CRL baseCRL : crls) { try { if (checkDeltaCRL_6_3_3_b(targetCertificate, deltaCRL, baseCRL)) { status = DeltaCRLStatus.OK; break; } } catch (IOException e) { logger.error("Error executing checkDeltaCRL_6_3_3_b.", e); continue; } if (hasUnsupportedCriticalExtensions(baseCRL)) { logger.warn("The base CRL has unsupported critical extensions."); status = DeltaCRLStatus.UNSUPPORTED_CRITICAL_EXTENSION; continue; } } } return status; }
From source file:be.fedict.trust.service.bean.HarvesterMDB.java
private void processHarvestMessage(HarvestMessage harvestMessage) { if (null == harvestMessage) { return;/* w w w .j a va 2s . co m*/ } String caName = harvestMessage.getCaName(); boolean update = harvestMessage.isUpdate(); String crlFilePath = harvestMessage.getCrlFile(); File crlFile = new File(crlFilePath); LOG.debug("processHarvestMessage - Don't have CA's Serial Number??"); LOG.debug("issuer: " + caName); CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO .findCertificateAuthority(caName); if (null == certificateAuthority) { LOG.error("unknown certificate authority: " + caName); deleteCrlFile(crlFile); return; } if (!update && Status.PROCESSING != certificateAuthority.getStatus()) { /* * Possible that another harvester instance already activated or is * processing the CA cache in the meanwhile. */ LOG.debug("CA status not marked for processing"); deleteCrlFile(crlFile); return; } Date validationDate = new Date(); X509Certificate issuerCertificate = certificateAuthority.getCertificate(); Date notAfter = issuerCertificate.getNotAfter(); if (validationDate.after(notAfter)) { LOG.info("will not update CRL cache for expired CA: " + issuerCertificate.getSubjectX500Principal()); deleteCrlFile(crlFile); return; } FileInputStream crlInputStream; try { crlInputStream = new FileInputStream(crlFile); } catch (FileNotFoundException e) { LOG.error("CRL file does not exist: " + crlFilePath); return; } X509CRL crl; try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC"); crl = (X509CRL) certificateFactory.generateCRL(crlInputStream); } catch (Exception e) { LOG.error("BC error: " + e.getMessage(), e); deleteCrlFile(crlFile); return; } LOG.debug("checking integrity CRL..."); boolean crlValid = CrlTrustLinker.checkCrlIntegrity(crl, issuerCertificate, validationDate); if (!crlValid) { this.auditDAO.logAudit("Invalid CRL for CA=" + caName); deleteCrlFile(crlFile); return; } BigInteger crlNumber = getCrlNumber(crl); LOG.debug("CRL number: " + crlNumber); BigInteger currentCrlNumber = this.certificateAuthorityDAO.findCrlNumber(caName); if (null != currentCrlNumber) { LOG.debug("CRL number in database: " + currentCrlNumber); } if (null != currentCrlNumber && currentCrlNumber.compareTo(crlNumber) >= 0 && certificateAuthority.getStatus() == Status.ACTIVE) { // current CRL cache is higher or equal, no update needed LOG.debug("current CA cache is new enough."); deleteCrlFile(crlFile); return; } List<RevokedCertificateEntity> revokedCertificateEntities = this.certificateAuthorityDAO .getRevokedCertificates(caName); LOG.debug("number of revoked certificates in database: " + revokedCertificateEntities.size()); Map<String, RevokedCertificateEntity> revokedCertificatesMap = new HashMap<String, RevokedCertificateEntity>(); for (RevokedCertificateEntity revokedCertificateEntity : revokedCertificateEntities) { String serialNumber = revokedCertificateEntity.getPk().getSerialNumber(); revokedCertificatesMap.put(serialNumber, revokedCertificateEntity); } LOG.debug("processing CRL... " + caName); boolean isIndirect; Enumeration revokedCertificatesEnum; try { isIndirect = isIndirectCRL(crl); revokedCertificatesEnum = getRevokedCertificatesEnum(crl); } catch (Exception e) { this.auditDAO.logAudit("Failed to parse CRL for CA=" + caName); this.failures++; throw new RuntimeException(e); } int entries = 0; if (revokedCertificatesEnum.hasMoreElements()) { /* * Split up persisting the crl entries to avoid memory issues. */ Set<X509CRLEntry> revokedCertsBatch = new HashSet<X509CRLEntry>(); X500Principal previousCertificateIssuer = crl.getIssuerX500Principal(); int added = 0; while (revokedCertificatesEnum.hasMoreElements()) { TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry) revokedCertificatesEnum.nextElement(); X500Name x500name = new X500Name(previousCertificateIssuer.getName(X500Principal.RFC1779)); X509CRLEntryObject revokedCertificate = new X509CRLEntryObject(entry, isIndirect, x500name); previousCertificateIssuer = revokedCertificate.getCertificateIssuer(); revokedCertsBatch.add(revokedCertificate); added++; if (added == BATCH_SIZE) { /* * Persist batch */ this.certificateAuthorityDAO.updateRevokedCertificates(revokedCertsBatch, crlNumber, crl.getIssuerX500Principal(), revokedCertificatesMap); entries += revokedCertsBatch.size(); revokedCertsBatch.clear(); added = 0; } } /* * Persist final batch */ this.certificateAuthorityDAO.updateRevokedCertificates(revokedCertsBatch, crlNumber, crl.getIssuerX500Principal(), revokedCertificatesMap); entries += revokedCertsBatch.size(); /* * Cleanup redundant CRL entries */ if (null != crlNumber) { this.certificateAuthorityDAO.removeOldRevokedCertificates(crlNumber, crl.getIssuerX500Principal().toString()); } } deleteCrlFile(crlFile); LOG.debug("CRL this update: " + crl.getThisUpdate()); LOG.debug("CRL next update: " + crl.getNextUpdate()); certificateAuthority.setStatus(Status.ACTIVE); certificateAuthority.setThisUpdate(crl.getThisUpdate()); certificateAuthority.setNextUpdate(crl.getNextUpdate()); LOG.debug("cache activated for CA: " + crl.getIssuerX500Principal() + " (entries=" + entries + ")"); }
From source file:org.apache.hadoop.security.ssl.TestCRLValidator.java
@Test public void testServerWithCRLInvalid() throws Exception { Path serverkeystore = Paths.get(BASE_DIR, "server.kstore.jks"); Path serverTruststore = Paths.get(BASE_DIR, "server.tstore.jks"); Path crlPath = Paths.get(BASE_DIR, "input.server.crl.pem"); Path fetchedCrlPath = Paths.get(BASE_DIR, "server.crl.pem"); String clientUsername = "Client_username"; Path clientKeystore = Paths.get(BASE_DIR, clientUsername + HopsSSLSocketFactory.KEYSTORE_SUFFIX); Path clientTruststore = Paths.get(BASE_DIR, clientUsername + HopsSSLSocketFactory.TRUSTSTORE_SUFFIX); Path clientPasswordLocation = Paths.get(BASE_DIR, clientUsername + HopsSSLSocketFactory.PASSWD_FILE_SUFFIX); Path sslServerConfPath = Paths.get(confDir, TestCRLValidator.class.getSimpleName() + ".ssl-server.xml"); Server server = null;/* w w w .j av a 2 s . c o m*/ TestRpcBase.TestRpcService proxy = null; RpcTLSUtils.TLSSetup tlsSetup = new RpcTLSUtils.TLSSetup.Builder().setKeyAlgorithm(keyAlgorithm) .setSignatureAlgorithm(signatureAlgorithm).setServerKstore(serverkeystore) .setServerTstore(serverTruststore).setServerStorePassword(password).setClientKstore(clientKeystore) .setClientTstore(clientTruststore).setClientStorePassword(password) .setClientPasswordLocation(clientPasswordLocation).setClientUserName(clientUsername) .setSslServerConf(sslServerConfPath).build(); RpcTLSUtils.TestCryptoMaterial testCryptoMaterial = RpcTLSUtils.setupTLSMaterial(conf, tlsSetup, TestCRLValidator.class); X509CRL crl = KeyStoreTestUtil.generateCRL(testCryptoMaterial.getServerCertificate(), testCryptoMaterial.getServerKeyPair().getPrivate(), signatureAlgorithm, null, testCryptoMaterial.getClientCertificate().getSerialNumber()); writeCRLToFile(crl, crlPath); configureCRL(conf, crlPath, fetchedCrlPath); // Set RPC engine RPC.setProtocolEngine(conf, TestRpcBase.TestRpcService.class, ProtobufRpcEngine.class); // Order here is important // First start the CRLFetcher service with short interval RevocationListFetcherService crlFetcherService = startCRLFetcherService(conf); // And then register CRLValidator with short reload interval CRLValidator testingValidator = new CRLValidator(conf); testingValidator.setReloadTimeunit(TimeUnit.SECONDS); testingValidator.setReloadInterval(1); testingValidator.startReloadingThread(); CRLValidatorFactory.getInstance().registerValidator(CRLValidatorFactory.TYPE.NORMAL, testingValidator); // Mock environment variables RpcTLSUtils.MockEnvironmentVariables envs = new RpcTLSUtils.MockEnvironmentVariables(); envs.setEnv(HopsSSLSocketFactory.CRYPTO_MATERIAL_ENV_VAR, BASE_DIR); EnvironmentVariablesFactory.setInstance(envs); // Create Server RPC.Builder serverBuilder = TestRpcBase.newServerBuilder(conf).setNumHandlers(1).setSecretManager(null) .setnumReaders(2); try { final String message = "Hello, is it me you're looking for?"; server = TestRpcBase.setupTestServer(serverBuilder); UserGroupInformation clientUGI = UserGroupInformation.createRemoteUser(clientUsername); boolean exceptionRaised = false; try { RpcTLSUtils.makeEchoRequest(clientUGI, server.getListenerAddress(), conf, message); } catch (Exception ex) { if (ex.getCause().getCause() instanceof RemoteException) { if (ex.getCause().getCause().getMessage() .contains("HopsCRLValidator: Certificate " + testCryptoMaterial.getClientCertificate().getSubjectDN() + " has been revoked by " + crl.getIssuerX500Principal())) { // Exception here is normal exceptionRaised = true; } else { throw ex; } } } Assert.assertTrue(exceptionRaised); LOG.info("Removing client certificate from CRL and wait for the CRL fetcher to pick it up"); // Remove client certificate from CRL crl = KeyStoreTestUtil.generateCRL(testCryptoMaterial.getServerCertificate(), testCryptoMaterial.getServerKeyPair().getPrivate(), signatureAlgorithm, null, null); writeCRLToFile(crl, crlPath); // Wait for the new CRL to be picked up TimeUnit.SECONDS .sleep(crlFetcherService.getFetcherInterval() * 2 + testingValidator.getReloadInterval() * 2); TestProtos.EchoResponseProto response = RpcTLSUtils.makeEchoRequest(clientUGI, server.getListenerAddress(), conf, message); Assert.assertEquals(response.getMessage(), message); } finally { if (server != null) { server.stop(); } if (crlFetcherService != null) { crlFetcherService.serviceStop(); } } }
From source file:org.candlepin.util.X509CRLStreamWriterTest.java
@Test public void testAddEntryToEmptyCRL() throws Exception { Date oneHourAgo = new Date(new Date().getTime() - 60L * 60L * 1000L); Date oneHourHence = new Date(new Date().getTime() + 60L * 60L * 1000L); X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, oneHourAgo); crlBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(keyPair.getPublic())); /* With a CRL number of 127, incrementing it should cause the number of bytes in the length * portion of the TLV to increase by one.*/ crlBuilder.addExtension(X509Extension.cRLNumber, false, new CRLNumber(new BigInteger("127"))); crlBuilder.setNextUpdate(oneHourHence); X509CRLHolder holder = crlBuilder.build(signer); File crlToChange = writeCRL(holder); File outfile = new File(folder.getRoot(), "new.crl"); X509CRLStreamWriter stream = new X509CRLStreamWriter(crlToChange, (RSAPrivateKey) keyPair.getPrivate(), (RSAPublicKey) keyPair.getPublic()); // Add enough items to cause the number of length bytes to change Set<BigInteger> newSerials = new HashSet<BigInteger>(Arrays.asList(new BigInteger("2358215310"), new BigInteger("7231352433"), new BigInteger("8233181205"), new BigInteger("1455615868"), new BigInteger("4323487764"), new BigInteger("6673256679"))); for (BigInteger i : newSerials) { stream.add(i, new Date(), CRLReason.privilegeWithdrawn); }/*from w w w . ja v a 2s. c o m*/ stream.preScan(crlToChange).lock(); OutputStream o = new BufferedOutputStream(new FileOutputStream(outfile)); stream.write(o); o.close(); X509CRL changedCrl = readCRL(); Set<BigInteger> discoveredSerials = new HashSet<BigInteger>(); for (X509CRLEntry entry : changedCrl.getRevokedCertificates()) { discoveredSerials.add(entry.getSerialNumber()); } X509CRL originalCrl = new JcaX509CRLConverter().setProvider(BC).getCRL(holder); assertNotNull(changedCrl.getNextUpdate()); long changedCrlUpdateDelta = changedCrl.getNextUpdate().getTime() - changedCrl.getThisUpdate().getTime(); // We're allowing a tolerance of a few milliseconds to deal with minor timing issues long deltaTolerance = 3; long deltaDiff = changedCrlUpdateDelta - (oneHourHence.getTime() - oneHourAgo.getTime()); assertTrue(Math.abs(deltaDiff) <= deltaTolerance); assertThat(changedCrl.getThisUpdate(), greaterThan(originalCrl.getThisUpdate())); assertEquals(newSerials, discoveredSerials); assertEquals(originalCrl.getIssuerX500Principal(), changedCrl.getIssuerX500Principal()); ASN1ObjectIdentifier crlNumberOID = X509Extension.cRLNumber; byte[] oldCrlNumberBytes = originalCrl.getExtensionValue(crlNumberOID.getId()); byte[] newCrlNumberBytes = changedCrl.getExtensionValue(crlNumberOID.getId()); DEROctetString oldOctet = (DEROctetString) DERTaggedObject.fromByteArray(oldCrlNumberBytes); DEROctetString newOctet = (DEROctetString) DERTaggedObject.fromByteArray(newCrlNumberBytes); DERInteger oldNumber = (DERInteger) DERTaggedObject.fromByteArray(oldOctet.getOctets()); DERInteger newNumber = (DERInteger) DERTaggedObject.fromByteArray(newOctet.getOctets()); assertEquals(oldNumber.getValue().add(BigInteger.ONE), newNumber.getValue()); ASN1ObjectIdentifier authorityKeyOID = X509Extension.authorityKeyIdentifier; byte[] oldAuthorityKeyId = originalCrl.getExtensionValue(authorityKeyOID.getId()); byte[] newAuthorityKeyId = changedCrl.getExtensionValue(authorityKeyOID.getId()); assertArrayEquals(oldAuthorityKeyId, newAuthorityKeyId); }
From source file:org.globus.gsi.CertificateRevocationLists.java
public synchronized void reload(String locations) { if (locations == null) { return;/*from w w w . jav a 2 s . c om*/ } StringTokenizer tokens = new StringTokenizer(locations, ","); Map<String, X509CRL> newCrlIssuerDNMap = new HashMap<String, X509CRL>(); while (tokens.hasMoreTokens()) { try { String location = tokens.nextToken().toString().trim(); CertStore tmp = Stores.getCRLStore("file:" + location + "/*.r*"); Collection<X509CRL> coll = (Collection<X509CRL>) tmp.getCRLs(new X509CRLSelector()); for (X509CRL crl : coll) { newCrlIssuerDNMap.put(crl.getIssuerX500Principal().getName(), crl); } } catch (Exception e) { throw new RuntimeException(e); } } this.crlIssuerDNMap = newCrlIssuerDNMap; }
From source file:org.xdi.oxauth.cert.validation.CRLCertificateVerifier.java
private boolean validateCRL(X509CRL x509crl, X509Certificate certificate, X509Certificate issuerCertificate, Date validationDate) {/*from ww w . j ava 2 s . c om*/ Principal subjectX500Principal = certificate.getSubjectX500Principal(); if (x509crl == null) { log.error("No CRL found for certificate '" + subjectX500Principal + "'"); return false; } if (log.isTraceEnabled()) { try { log.trace("CRL number: " + getCrlNumber(x509crl)); } catch (IOException ex) { log.error("Failed to get CRL number", ex); } } if (!x509crl.getIssuerX500Principal().equals(issuerCertificate.getSubjectX500Principal())) { log.error("The CRL must be signed by the issuer '" + subjectX500Principal + "' but instead is signed by '" + x509crl.getIssuerX500Principal() + "'"); return false; } try { x509crl.verify(issuerCertificate.getPublicKey()); } catch (Exception ex) { log.error("The signature verification for CRL cannot be performed", ex); return false; } log.debug("CRL validationDate: " + validationDate); log.debug("CRL nextUpdate: " + x509crl.getThisUpdate()); log.debug("CRL thisUpdate: " + x509crl.getNextUpdate()); if (x509crl.getNextUpdate() != null && validationDate.after(x509crl.getNextUpdate())) { log.error("CRL is too old"); return false; } if (issuerCertificate.getKeyUsage() == null) { log.error("There is no KeyUsage extension for certificate '" + subjectX500Principal + "'"); return false; } if (!issuerCertificate.getKeyUsage()[6]) { log.error("cRLSign bit is not set for CRL certificate'" + subjectX500Principal + "'"); return false; } return true; }
From source file:test.unit.be.fedict.eid.dss.document.ooxml.OOXMLDSSDocumentServiceTest.java
/** * When you register the root-signed Belgium Root CA2 within Windows Trust * Store, Office 2010 SP1 will use a certificate chain up to GlobalSign Root * CA instead of the self-signed Belgium Root CA2. * //from ww w .ja va 2s .com * @throws Exception */ @Test public void testVerifySignaturesTest123Office() throws Exception { // setup OOXMLDSSDocumentService testedInstance = new OOXMLDSSDocumentService(); byte[] document = IOUtils.toByteArray( OOXMLDSSDocumentServiceTest.class.getResourceAsStream("/Office2010-SP1-GlobalSign.docx")); DSSDocumentContext mockContext = EasyMock.createMock(DSSDocumentContext.class); Capture<List<X509Certificate>> certificateChainCapture = new Capture<List<X509Certificate>>(); Capture<Date> validationDateCapture = new Capture<Date>(); Capture<List<OCSPResp>> ocspResponsesCapture = new Capture<List<OCSPResp>>(); Capture<List<X509CRL>> crlsCapture = new Capture<List<X509CRL>>(); Capture<TimeStampToken> timeStampTokenCapture = new Capture<TimeStampToken>(); mockContext.validate(EasyMock.capture(certificateChainCapture), EasyMock.capture(validationDateCapture), EasyMock.capture(ocspResponsesCapture), EasyMock.capture(crlsCapture)); mockContext.validate(EasyMock.capture(timeStampTokenCapture)); mockContext.validate(EasyMock.capture(timeStampTokenCapture)); expect(mockContext.getTimestampMaxOffset()).andReturn(33 * 1000L); expect(mockContext.getMaxGracePeriod()).andReturn(1000L * 60 * 60 * 24 * 7); // prepare EasyMock.replay(mockContext); // operate testedInstance.init(mockContext, "mime-type"); List<SignatureInfo> signatureInfos = testedInstance.verifySignatures(document, null); // verify EasyMock.verify(mockContext); assertNotNull(signatureInfos); assertEquals(1, signatureInfos.size()); SignatureInfo signatureInfo = signatureInfos.get(0); assertNotNull(signatureInfo.getSigner()); assertNotNull(signatureInfo.getSigningTime()); LOG.debug("signing time: " + signatureInfo.getSigningTime()); assertEquals(signatureInfo.getSigningTime(), validationDateCapture.getValue()); assertEquals(signatureInfo.getSigner(), certificateChainCapture.getValue().get(0)); assertEquals(1, ocspResponsesCapture.getValue().size()); assertEquals(2, crlsCapture.getValue().size()); List<X509CRL> crls = crlsCapture.getValue(); for (X509CRL crl : crls) { LOG.debug("CRL: " + crl.getIssuerX500Principal()); } assertEquals(4, certificateChainCapture.getValue().size()); for (X509Certificate certificate : certificateChainCapture.getValue()) { LOG.debug("certificate: " + certificate.getSubjectX500Principal()); } }