List of usage examples for org.bouncycastle.asn1.x509 Extension getParsedValue
public ASN1Encodable getParsedValue()
From source file:org.xipki.commons.security.util.X509Util.java
License:Open Source License
public static byte[] extractSki(final org.bouncycastle.asn1.x509.Certificate cert) throws CertificateEncodingException { ParamUtil.requireNonNull("cert", cert); Extension encodedSkiValue = cert.getTBSCertificate().getExtensions() .getExtension(Extension.subjectKeyIdentifier); if (encodedSkiValue == null) { return null; }/*from w w w . j a va 2 s . co m*/ try { return ASN1OctetString.getInstance(encodedSkiValue.getParsedValue()).getOctets(); } catch (IllegalArgumentException ex) { throw new CertificateEncodingException("invalid extension SubjectKeyIdentifier: " + ex.getMessage()); } }
From source file:org.xipki.dbtool.CaCertStoreDbImporter.java
License:Open Source License
private int[] do_import_cert(final PreparedStatement ps_cert, final PreparedStatement ps_rawcert, final String certsZipFile, final int minId, final File processLogFile, final int totalProcessedSum) throws IOException, JAXBException, DataAccessException, CertificateException { ZipFile zipFile = new ZipFile(new File(baseDir, certsZipFile)); ZipEntry certsXmlEntry = zipFile.getEntry("certs.xml"); CertsType certs;//from w w w.ja va2s. c o m try { @SuppressWarnings("unchecked") JAXBElement<CertsType> rootElement = (JAXBElement<CertsType>) unmarshaller .unmarshal(zipFile.getInputStream(certsXmlEntry)); certs = rootElement.getValue(); } catch (JAXBException e) { try { zipFile.close(); } catch (Exception e2) { } throw XMLUtil.convert(e); } disableAutoCommit(); try { List<CertType> list = certs.getCert(); final int size = list.size(); final int n = 100; int numProcessed = 0; int numEntriesInBatch = 0; int lastSuccessfulCertId = 0; for (int i = 0; i < size; i++) { CertType cert = list.get(i); int id = cert.getId(); lastSuccessfulCertId = id; if (id < minId) { continue; } int certArt = cert.getArt() == null ? 1 : cert.getArt(); numEntriesInBatch++; String filename = cert.getCertFile(); // rawcert ZipEntry certZipEnty = zipFile.getEntry(filename); // rawcert byte[] encodedCert = IoUtil.read(zipFile.getInputStream(certZipEnty)); Certificate c; try { c = Certificate.getInstance(encodedCert); } catch (Exception e) { LOG.error("could not parse certificate in file {}", filename); LOG.debug("could not parse certificate in file " + filename, e); if (e instanceof CertificateException) { throw (CertificateException) e; } else { throw new CertificateException(e.getMessage(), e); } } byte[] encodedKey = c.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); String hexSha1FpCert = HashCalculator.hexHash(HashAlgoType.SHA1, encodedCert); // cert try { int idx = 1; ps_cert.setInt(idx++, id); ps_cert.setInt(idx++, certArt); ps_cert.setLong(idx++, cert.getLastUpdate()); ps_cert.setLong(idx++, c.getSerialNumber().getPositiveValue().longValue()); ps_cert.setString(idx++, X509Util.getRFC4519Name(c.getSubject())); ps_cert.setLong(idx++, c.getTBSCertificate().getStartDate().getDate().getTime() / 1000); ps_cert.setLong(idx++, c.getTBSCertificate().getEndDate().getDate().getTime() / 1000); setBoolean(ps_cert, idx++, cert.isRevoked()); setInt(ps_cert, idx++, cert.getRevReason()); setLong(ps_cert, idx++, cert.getRevTime()); setLong(ps_cert, idx++, cert.getRevInvTime()); setInt(ps_cert, idx++, cert.getProfileId()); setInt(ps_cert, idx++, cert.getCaId()); setInt(ps_cert, idx++, cert.getRequestorId()); setInt(ps_cert, idx++, cert.getUserId()); ps_cert.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA1, encodedKey)); String sha1FpSubject = X509Util.sha1sum_canonicalized_name(c.getSubject()); ps_cert.setString(idx++, sha1FpSubject); Extension extension = c.getTBSCertificate().getExtensions() .getExtension(Extension.basicConstraints); boolean ee = true; if (extension != null) { ASN1Encodable asn1 = extension.getParsedValue(); try { ee = BasicConstraints.getInstance(asn1).isCA() == false; } catch (Exception e) { } } ps_cert.setInt(idx++, ee ? 1 : 0); ps_cert.addBatch(); } catch (SQLException e) { throw translate(SQL_ADD_CERT, e); } try { int idx = 1; ps_rawcert.setInt(idx++, cert.getId()); ps_rawcert.setString(idx++, hexSha1FpCert); ps_rawcert.setString(idx++, Base64.toBase64String(encodedCert)); ps_rawcert.addBatch(); } catch (SQLException e) { throw translate(SQL_ADD_RAWCERT, e); } if (numEntriesInBatch > 0 && (numEntriesInBatch % n == 0 || i == size - 1)) { String sql = null; try { sql = SQL_ADD_CERT; ps_cert.executeBatch(); sql = SQL_ADD_RAWCERT; ps_rawcert.executeBatch(); sql = null; commit("(commit import cert to CA)"); } catch (SQLException e) { rollback(); throw translate(sql, e); } catch (DataAccessException e) { rollback(); throw e; } numProcessed += numEntriesInBatch; numEntriesInBatch = 0; echoToFile((totalProcessedSum + numProcessed) + ":" + lastSuccessfulCertId, processLogFile); } } return new int[] { numProcessed, lastSuccessfulCertId }; } finally { try { recoverAutoCommit(); } catch (DataAccessException e) { } zipFile.close(); } }
From source file:org.xipki.ocsp.client.shell.OCSPStatusCommand.java
License:Open Source License
@Override protected Object processResponse(final OCSPResp response, final X509Certificate respIssuer, final X509Certificate issuer, final List<BigInteger> serialNumbers, final Map<BigInteger, byte[]> encodedCerts) throws Exception { BasicOCSPResp basicResp = OCSPUtils.extractBasicOCSPResp(response); boolean extendedRevoke = basicResp.getExtension(OCSPRequestor.id_pkix_ocsp_extendedRevoke) != null; SingleResp[] singleResponses = basicResp.getResponses(); int n = singleResponses == null ? 0 : singleResponses.length; if (n == 0) { throw new CmdFailure("received no status from server"); }/* w ww . j a v a 2 s . c o m*/ if (n != serialNumbers.size()) { throw new CmdFailure("received status with " + n + " single responses from server, but " + serialNumbers.size() + " were requested"); } Date[] thisUpdates = new Date[n]; for (int i = 0; i < n; i++) { thisUpdates[i] = singleResponses[i].getThisUpdate(); } // check the signature if available if (null == basicResp.getSignature()) { out("response is not signed"); } else { X509CertificateHolder[] responderCerts = basicResp.getCerts(); if (responderCerts == null || responderCerts.length < 1) { throw new CmdFailure("no responder certificate is contained in the response"); } X509CertificateHolder respSigner = responderCerts[0]; boolean validOn = true; for (Date thisUpdate : thisUpdates) { validOn = respSigner.isValidOn(thisUpdate); if (validOn == false) { throw new CmdFailure("responder certificate is not valid on " + thisUpdate); } } if (validOn) { PublicKey responderPubKey = KeyUtil.generatePublicKey(respSigner.getSubjectPublicKeyInfo()); ContentVerifierProvider cvp = KeyUtil.getContentVerifierProvider(responderPubKey); boolean sigValid = basicResp.isSignatureValid(cvp); if (sigValid == false) { throw new CmdFailure("response is equipped with invalid signature"); } // verify the OCSPResponse signer if (respIssuer != null) { boolean certValid = true; X509Certificate jceRespSigner = new X509CertificateObject(respSigner.toASN1Structure()); if (X509Util.issues(respIssuer, jceRespSigner)) { try { jceRespSigner.verify(respIssuer.getPublicKey()); } catch (SignatureException e) { certValid = false; } } if (certValid == false) { throw new CmdFailure( "response is equipped with valid signature but the OCSP signer is not trusted"); } } else { out("response is equipped with valid signature"); } } if (verbose.booleanValue()) { out("responder is " + X509Util.getRFC4519Name(responderCerts[0].getSubject())); } } for (int i = 0; i < n; i++) { if (n > 1) { out("---------------------------- " + i + " ----------------------------"); } SingleResp singleResp = singleResponses[i]; BigInteger serialNumber = singleResp.getCertID().getSerialNumber(); CertificateStatus singleCertStatus = singleResp.getCertStatus(); String status; if (singleCertStatus == null) { status = "good"; } else if (singleCertStatus instanceof RevokedStatus) { RevokedStatus revStatus = (RevokedStatus) singleCertStatus; Date revTime = revStatus.getRevocationTime(); Date invTime = null; Extension ext = singleResp.getExtension(Extension.invalidityDate); if (ext != null) { invTime = ASN1GeneralizedTime.getInstance(ext.getParsedValue()).getDate(); } if (revStatus.hasRevocationReason()) { int reason = revStatus.getRevocationReason(); if (extendedRevoke && reason == CRLReason.CERTIFICATE_HOLD.getCode() && revTime.getTime() == 0) { status = "unknown (RFC6960)"; } else { StringBuilder sb = new StringBuilder("revoked, reason = "); sb.append(CRLReason.forReasonCode(reason).getDescription()); sb.append(", revocationTime = "); sb.append(revTime); if (invTime != null) { sb.append(", invalidityTime = "); sb.append(invTime); } status = sb.toString(); } } else { status = "revoked, no reason, revocationTime = " + revTime; } } else if (singleCertStatus instanceof UnknownStatus) { status = "unknown (RFC2560)"; } else { status = "ERROR"; } StringBuilder msg = new StringBuilder(); msg.append("serialNumber: ").append(serialNumber); msg.append("\nCertificate status: ").append(status); if (verbose.booleanValue()) { msg.append("\nthisUpdate: " + singleResp.getThisUpdate()); msg.append("\nnextUpdate: " + singleResp.getNextUpdate()); Extension extension = singleResp.getExtension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash); if (extension != null) { msg.append("\nCertHash is provided:\n"); ASN1Encodable extensionValue = extension.getParsedValue(); CertHash certHash = CertHash.getInstance(extensionValue); ASN1ObjectIdentifier hashAlgOid = certHash.getHashAlgorithm().getAlgorithm(); byte[] hashValue = certHash.getCertificateHash(); msg.append("\tHash algo : ").append(hashAlgOid.getId()).append("\n"); msg.append("\tHash value: ").append(Hex.toHexString(hashValue)).append("\n"); if (encodedCerts != null) { byte[] encodedCert = encodedCerts.get(serialNumber); MessageDigest md = MessageDigest.getInstance(hashAlgOid.getId()); byte[] expectedHashValue = md.digest(encodedCert); if (Arrays.equals(expectedHashValue, hashValue)) { msg.append("\tThis matches the requested certificate"); } else { msg.append("\tThis differs from the requested certificate"); } } } extension = singleResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff); if (extension != null) { ASN1Encodable extensionValue = extension.getParsedValue(); ASN1GeneralizedTime time = ASN1GeneralizedTime.getInstance(extensionValue); msg.append("\nArchive-CutOff: "); msg.append(time.getTimeString()); } AlgorithmIdentifier sigAlg = basicResp.getSignatureAlgorithmID(); if (sigAlg == null) { msg.append(("\nresponse is not signed")); } else { String sigAlgName = AlgorithmUtil.getSignatureAlgoName(sigAlg); if (sigAlgName == null) { sigAlgName = "unknown"; } msg.append("\nresponse is signed with ").append(sigAlgName); } // extensions msg.append("\nExtensions: "); List<?> extensionOIDs = basicResp.getExtensionOIDs(); if (extensionOIDs == null || extensionOIDs.size() == 0) { msg.append("-"); } else { int size = extensionOIDs.size(); for (int j = 0; j < size; j++) { ASN1ObjectIdentifier extensionOID = (ASN1ObjectIdentifier) extensionOIDs.get(j); String name = extensionOidNameMap.get(extensionOID); msg.append(name == null ? extensionOID.getId() : name); if (j != size - 1) { msg.append(", "); } } } } out(msg.toString()); } out(""); return null; }
From source file:org.xipki.ocsp.qa.impl.OcspQAImpl.java
License:Open Source License
private List<ValidationIssue> checkSingleCert(final int index, final SingleResp singleResp, final OcspCertStatus expectedStatus, final byte[] encodedCert, final boolean extendedRevoke, final Occurrence nextupdateOccurrence, final Occurrence certhashOccurrence, final ASN1ObjectIdentifier certhashAlg) { List<ValidationIssue> issues = new LinkedList<>(); {/*from ww w. j a va 2 s . c o m*/ // status ValidationIssue issue = new ValidationIssue("OCSP.RESPONSE." + index + ".STATUS", "certificate status"); issues.add(issue); CertificateStatus singleCertStatus = singleResp.getCertStatus(); OcspCertStatus status = null; if (singleCertStatus == null) { status = OcspCertStatus.good; } else if (singleCertStatus instanceof RevokedStatus) { RevokedStatus revStatus = (RevokedStatus) singleCertStatus; Date revTime = revStatus.getRevocationTime(); if (revStatus.hasRevocationReason()) { int reason = revStatus.getRevocationReason(); if (extendedRevoke && reason == CRLReason.CERTIFICATE_HOLD.getCode() && revTime.getTime() == 0) { status = OcspCertStatus.unknown; } else { CRLReason revocationReason = CRLReason.forReasonCode(reason); switch (revocationReason) { case UNSPECIFIED: status = OcspCertStatus.unspecified; break; case KEY_COMPROMISE: status = OcspCertStatus.keyCompromise; break; case CA_COMPROMISE: status = OcspCertStatus.cACompromise; break; case AFFILIATION_CHANGED: status = OcspCertStatus.affiliationChanged; break; case SUPERSEDED: status = OcspCertStatus.superseded; break; case CERTIFICATE_HOLD: status = OcspCertStatus.certificateHold; break; case REMOVE_FROM_CRL: status = OcspCertStatus.removeFromCRL; break; case PRIVILEGE_WITHDRAWN: status = OcspCertStatus.privilegeWithdrawn; break; case AA_COMPROMISE: status = OcspCertStatus.aACompromise; break; default: issue.setFailureMessage("should not reach here, unknwon CRLReason " + revocationReason); break; } } } else { status = OcspCertStatus.rev_noreason; } } else if (singleCertStatus instanceof UnknownStatus) { status = OcspCertStatus.issuerUnknown; } else { issue.setFailureMessage("unknown certstatus: " + singleCertStatus.getClass().getName()); } if (issue.isFailed() == false && expectedStatus != status) { issue.setFailureMessage("is='" + status + "', but expected='" + expectedStatus + "'"); } } { // nextUpdate Date nextUpdate = singleResp.getNextUpdate(); checkOccurrence("OCSP.RESPONSE." + index + ".NEXTUPDATE", nextUpdate, nextupdateOccurrence); } Extension extension = singleResp.getExtension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash); { checkOccurrence("OCSP.RESPONSE." + index + ".CERTHASh", extension, certhashOccurrence); } if (extension != null) { ASN1Encodable extensionValue = extension.getParsedValue(); CertHash certHash = CertHash.getInstance(extensionValue); ASN1ObjectIdentifier hashAlgOid = certHash.getHashAlgorithm().getAlgorithm(); if (certhashAlg != null) { // certHash algorithm ValidationIssue issue = new ValidationIssue("OCSP.RESPONSE." + index + ".CERTHASH.ALG", "certhash algorithm"); issues.add(issue); ASN1ObjectIdentifier is = certHash.getHashAlgorithm().getAlgorithm(); if (certhashAlg.equals(is) == false) { issue.setFailureMessage("is '" + is.getId() + "', but expected '" + certhashAlg.getId() + "'"); } } byte[] hashValue = certHash.getCertificateHash(); if (encodedCert != null) { ValidationIssue issue = new ValidationIssue("OCSP.RESPONSE." + index + ".CERTHASH.VALIDITY", "certhash validity"); issues.add(issue); try { MessageDigest md = MessageDigest.getInstance(hashAlgOid.getId()); byte[] expectedHashValue = md.digest(encodedCert); if (Arrays.equals(expectedHashValue, hashValue) == false) { issue.setFailureMessage("certHash does not match the requested certificate"); } } catch (NoSuchAlgorithmException e) { issue.setFailureMessage("NoSuchAlgorithm " + hashAlgOid.getId()); } } } return issues; }
From source file:org.xipki.ocsp.server.impl.OcspServer.java
License:Open Source License
public OcspRespWithCacheInfo answer(final Responder responder, final OCSPReq request, final AuditEvent auditEvent, final boolean viaGet) { ResponderOption responderOption = responder.getResponderOption(); RequestOption requestOption = responder.getRequestOption(); ResponseOption responseOption = responder.getResponseOption(); ResponderSigner signer = responder.getSigner(); AuditOption auditOption = responder.getAuditOption(); CertprofileOption certprofileOption = responder.getCertprofileOption(); int version = request.getVersionNumber(); if (requestOption.isVersionAllowed(version) == false) { String message = "invalid request version " + version; LOG.warn(message);/* ww w.jav a 2 s . com*/ if (auditEvent != null) { fillAuditEvent(auditEvent, AuditLevel.INFO, AuditStatus.FAILED, message); } return createUnsuccessfullOCSPResp(OcspResponseStatus.malformedRequest); } try { OcspRespWithCacheInfo resp = checkSignature(request, requestOption, auditEvent); if (resp != null) { return resp; } boolean couldCacheInfo = viaGet; List<Extension> responseExtensions = new ArrayList<>(2); Req[] requestList = request.getRequestList(); int n = requestList.length; Set<ASN1ObjectIdentifier> criticalExtensionOIDs = new HashSet<>(); Set<?> tmp = request.getCriticalExtensionOIDs(); if (tmp != null) { for (Object oid : tmp) { criticalExtensionOIDs.add((ASN1ObjectIdentifier) oid); } } RespID respID = new RespID(signer.getResponderId()); BasicOCSPRespBuilder basicOcspBuilder = new BasicOCSPRespBuilder(respID); ASN1ObjectIdentifier extensionType = OCSPObjectIdentifiers.id_pkix_ocsp_nonce; criticalExtensionOIDs.remove(extensionType); Extension nonceExtn = request.getExtension(extensionType); if (nonceExtn != null) { byte[] nonce = nonceExtn.getExtnValue().getOctets(); int len = nonce.length; int min = requestOption.getNonceMinLen(); int max = requestOption.getNonceMaxLen(); if (len < min || len > max) { LOG.warn("length of nonce {} not within [{},{}]", new Object[] { len, min, max }); if (auditEvent != null) { StringBuilder sb = new StringBuilder(); sb.append("length of nonce ").append(len); sb.append(" not within [").append(min).append(", ").append(max); fillAuditEvent(auditEvent, AuditLevel.INFO, AuditStatus.FAILED, sb.toString()); } return createUnsuccessfullOCSPResp(OcspResponseStatus.malformedRequest); } couldCacheInfo = false; responseExtensions.add(nonceExtn); } else if (requestOption.isNonceRequired()) { String message = "nonce required, but is not present in the request"; LOG.warn(message); if (auditEvent != null) { fillAuditEvent(auditEvent, AuditLevel.INFO, AuditStatus.FAILED, message); } return createUnsuccessfullOCSPResp(OcspResponseStatus.malformedRequest); } boolean includeExtendedRevokeExtension = false; long cacheThisUpdate = 0; long cacheNextUpdate = Long.MAX_VALUE; for (int i = 0; i < n; i++) { AuditChildEvent childAuditEvent = null; if (auditEvent != null) { childAuditEvent = new AuditChildEvent(); auditEvent.addChildAuditEvent(childAuditEvent); } Req req = requestList[i]; CertificateID certID = req.getCertID(); String certIdHashAlgo = certID.getHashAlgOID().getId(); HashAlgoType reqHashAlgo = HashAlgoType.getHashAlgoType(certIdHashAlgo); if (reqHashAlgo == null) { LOG.warn("unknown CertID.hashAlgorithm {}", certIdHashAlgo); if (childAuditEvent != null) { fillAuditEvent(childAuditEvent, AuditLevel.INFO, AuditStatus.FAILED, "unknown CertID.hashAlgorithm " + certIdHashAlgo); } return createUnsuccessfullOCSPResp(OcspResponseStatus.malformedRequest); } else if (requestOption.allows(reqHashAlgo) == false) { LOG.warn("CertID.hashAlgorithm {} not allowed", certIdHashAlgo); if (childAuditEvent != null) { fillAuditEvent(childAuditEvent, AuditLevel.INFO, AuditStatus.FAILED, "CertID.hashAlgorithm " + certIdHashAlgo + " not allowed"); } return createUnsuccessfullOCSPResp(OcspResponseStatus.malformedRequest); } CertStatusInfo certStatusInfo = null; CertStatusStore answeredStore = null; boolean exceptionOccurs = false; for (CertStatusStore store : responder.getStores()) { try { certStatusInfo = store.getCertStatus(reqHashAlgo, certID.getIssuerNameHash(), certID.getIssuerKeyHash(), certID.getSerialNumber(), responseOption.isIncludeCerthash(), responseOption.getCertHashAlgo(), certprofileOption); if (certStatusInfo.getCertStatus() != CertStatus.ISSUER_UNKNOWN) { answeredStore = store; break; } } catch (CertStatusStoreException e) { exceptionOccurs = true; final String message = "getCertStatus() of CertStatusStore " + store.getName(); if (LOG.isErrorEnabled()) { LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage()); } LOG.debug(message, e); } } if (certStatusInfo == null) { if (childAuditEvent != null) { fillAuditEvent(childAuditEvent, AuditLevel.ERROR, AuditStatus.FAILED, "no CertStatusStore can answer the request"); } if (exceptionOccurs) { return createUnsuccessfullOCSPResp(OcspResponseStatus.tryLater); } else { certStatusInfo = CertStatusInfo.getIssuerUnknownCertStatusInfo(new Date(), null); } } else if (answeredStore != null) { if (responderOption.isInheritCaRevocation()) { CertRevocationInfo caRevInfo = answeredStore.getCARevocationInfo(reqHashAlgo, certID.getIssuerNameHash(), certID.getIssuerKeyHash()); if (caRevInfo != null) { CertStatus certStatus = certStatusInfo.getCertStatus(); boolean replaced = false; if (certStatus == CertStatus.GOOD || certStatus == CertStatus.UNKNOWN) { replaced = true; } else if (certStatus == CertStatus.REVOKED) { if (certStatusInfo.getRevocationInfo().getRevocationTime() .after(caRevInfo.getRevocationTime())) { replaced = true; } } if (replaced) { CertRevocationInfo newRevInfo; if (caRevInfo.getReason() == CRLReason.CA_COMPROMISE) { newRevInfo = caRevInfo; } else { newRevInfo = new CertRevocationInfo(CRLReason.CA_COMPROMISE, caRevInfo.getRevocationTime(), caRevInfo.getInvalidityTime()); } certStatusInfo = CertStatusInfo.getRevokedCertStatusInfo(newRevInfo, certStatusInfo.getCertHashAlgo(), certStatusInfo.getCertHash(), certStatusInfo.getThisUpdate(), certStatusInfo.getNextUpdate(), certStatusInfo.getCertprofile()); } } } } if (childAuditEvent != null) { String certprofile = certStatusInfo.getCertprofile(); String auditCertType; if (certprofile != null) { auditCertType = auditOption.getCertprofileMapping().get(certprofile); if (auditCertType == null) { auditCertType = certprofile; } } else { auditCertType = "UNKNOWN"; } childAuditEvent.addEventData(new AuditEventData("certType", auditCertType)); } // certStatusInfo could not be null in any case, since at least one store is configured Date thisUpdate = certStatusInfo.getThisUpdate(); if (thisUpdate == null) { thisUpdate = new Date(); } Date nextUpdate = certStatusInfo.getNextUpdate(); List<Extension> extensions = new LinkedList<>(); boolean unknownAsRevoked = false; CertificateStatus bcCertStatus = null; switch (certStatusInfo.getCertStatus()) { case GOOD: bcCertStatus = null; break; case ISSUER_UNKNOWN: couldCacheInfo = false; bcCertStatus = new UnknownStatus(); break; case UNKNOWN: case IGNORE: couldCacheInfo = false; if (responderOption.getMode() == OCSPMode.RFC2560) { bcCertStatus = new UnknownStatus(); } else// (ocspMode == OCSPMode.RFC6960) { unknownAsRevoked = true; includeExtendedRevokeExtension = true; bcCertStatus = new RevokedStatus(new Date(0L), CRLReason.CERTIFICATE_HOLD.getCode()); } break; case REVOKED: CertRevocationInfo revInfo = certStatusInfo.getRevocationInfo(); ASN1GeneralizedTime revTime = new ASN1GeneralizedTime(revInfo.getRevocationTime()); org.bouncycastle.asn1.x509.CRLReason _reason = null; if (responseOption.isIncludeRevReason()) { _reason = org.bouncycastle.asn1.x509.CRLReason.lookup(revInfo.getReason().getCode()); } RevokedInfo _revInfo = new RevokedInfo(revTime, _reason); bcCertStatus = new RevokedStatus(_revInfo); Date invalidityDate = revInfo.getInvalidityTime(); if (responseOption.isIncludeInvalidityDate() && invalidityDate != null && invalidityDate.equals(revTime) == false) { Extension extension = new Extension(Extension.invalidityDate, false, new ASN1GeneralizedTime(invalidityDate).getEncoded()); extensions.add(extension); } break; } byte[] certHash = certStatusInfo.getCertHash(); if (certHash != null) { ASN1ObjectIdentifier hashAlgoOid = new ASN1ObjectIdentifier( certStatusInfo.getCertHashAlgo().getOid()); AlgorithmIdentifier aId = new AlgorithmIdentifier(hashAlgoOid, DERNull.INSTANCE); CertHash bcCertHash = new CertHash(aId, certHash); byte[] encodedCertHash; try { encodedCertHash = bcCertHash.getEncoded(); } catch (IOException e) { final String message = "answer() bcCertHash.getEncoded"; if (LOG.isErrorEnabled()) { LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage()); } LOG.debug(message, e); if (childAuditEvent != null) { fillAuditEvent(childAuditEvent, AuditLevel.ERROR, AuditStatus.FAILED, "CertHash.getEncoded() with IOException"); } return createUnsuccessfullOCSPResp(OcspResponseStatus.internalError); } Extension extension = new Extension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash, false, encodedCertHash); extensions.add(extension); } if (certStatusInfo.getArchiveCutOff() != null) { Extension extension = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff, false, new ASN1GeneralizedTime(certStatusInfo.getArchiveCutOff()).getEncoded()); extensions.add(extension); } String certStatusText; if (bcCertStatus instanceof UnknownStatus) { certStatusText = "unknown"; } else if (bcCertStatus instanceof RevokedStatus) { certStatusText = unknownAsRevoked ? "unknown_as_revoked" : "revoked"; } else if (bcCertStatus == null) { certStatusText = "good"; } else { certStatusText = "should-not-happen"; } if (childAuditEvent != null) { childAuditEvent.setLevel(AuditLevel.INFO); childAuditEvent.setStatus(AuditStatus.SUCCESSFUL); childAuditEvent.addEventData(new AuditEventData("certStatus", certStatusText)); } if (LOG.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("certHashAlgo: ").append(certID.getHashAlgOID().getId()).append(", "); String hexCertHash = null; if (certHash != null) { hexCertHash = Hex.toHexString(certHash).toUpperCase(); } sb.append("issuerKeyHash: ").append(Hex.toHexString(certID.getIssuerKeyHash()).toUpperCase()) .append(", "); sb.append("issuerNameHash: ").append(Hex.toHexString(certID.getIssuerNameHash()).toUpperCase()) .append(", "); sb.append("serialNumber: ").append(certID.getSerialNumber()).append(", "); sb.append("certStatus: ").append(certStatusText).append(", "); sb.append("thisUpdate: ").append(thisUpdate).append(", "); sb.append("nextUpdate: ").append(nextUpdate).append(", "); sb.append("certHash: ").append(hexCertHash); LOG.debug(sb.toString()); } basicOcspBuilder.addResponse(certID, bcCertStatus, thisUpdate, nextUpdate, CollectionUtil.isEmpty(extensions) ? null : new Extensions(extensions.toArray(new Extension[0]))); cacheThisUpdate = Math.max(cacheThisUpdate, thisUpdate.getTime()); if (nextUpdate != null) { cacheNextUpdate = Math.min(cacheNextUpdate, nextUpdate.getTime()); } } if (includeExtendedRevokeExtension) { responseExtensions.add(new Extension(ObjectIdentifiers.id_pkix_ocsp_extendedRevoke, true, DERNull.INSTANCE.getEncoded())); } if (CollectionUtil.isNotEmpty(responseExtensions)) { basicOcspBuilder .setResponseExtensions(new Extensions(responseExtensions.toArray(new Extension[0]))); } ConcurrentContentSigner concurrentSigner = null; if (responderOption.getMode() != OCSPMode.RFC2560) { extensionType = ObjectIdentifiers.id_pkix_ocsp_prefSigAlgs; criticalExtensionOIDs.remove(extensionType); Extension ext = request.getExtension(extensionType); if (ext != null) { ASN1Sequence preferredSigAlgs = ASN1Sequence.getInstance(ext.getParsedValue()); concurrentSigner = signer.getSignerForPreferredSigAlgs(preferredSigAlgs); } } if (CollectionUtil.isNotEmpty(criticalExtensionOIDs)) { return createUnsuccessfullOCSPResp(OcspResponseStatus.malformedRequest); } if (concurrentSigner == null) { concurrentSigner = signer.getFirstSigner(); } ContentSigner singleSigner; try { singleSigner = concurrentSigner.borrowContentSigner(); } catch (NoIdleSignerException e) { return createUnsuccessfullOCSPResp(OcspResponseStatus.tryLater); } X509CertificateHolder[] certsInResp; EmbedCertsMode certsMode = responseOption.getEmbedCertsMode(); if (certsMode == null || certsMode == EmbedCertsMode.SIGNER) { certsInResp = new X509CertificateHolder[] { signer.getBcCertificate() }; } else if (certsMode == EmbedCertsMode.SIGNER_AND_CA) { certsInResp = signer.getBcCertificateChain(); } else { // NONE certsInResp = null; } BasicOCSPResp basicOcspResp; try { basicOcspResp = basicOcspBuilder.build(singleSigner, certsInResp, new Date()); } catch (OCSPException e) { final String message = "answer() basicOcspBuilder.build"; if (LOG.isErrorEnabled()) { LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage()); } LOG.debug(message, e); if (auditEvent != null) { fillAuditEvent(auditEvent, AuditLevel.ERROR, AuditStatus.FAILED, "BasicOCSPRespBuilder.build() with OCSPException"); } return createUnsuccessfullOCSPResp(OcspResponseStatus.internalError); } finally { concurrentSigner.returnContentSigner(singleSigner); } OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder(); try { OCSPResp ocspResp = ocspRespBuilder.build(OcspResponseStatus.successfull.getStatus(), basicOcspResp); if (couldCacheInfo) { ResponseCacheInfo cacheInfo = new ResponseCacheInfo(cacheThisUpdate); if (cacheNextUpdate != Long.MAX_VALUE) { cacheInfo.setNextUpdate(cacheNextUpdate); } return new OcspRespWithCacheInfo(ocspResp, cacheInfo); } else { return new OcspRespWithCacheInfo(ocspResp, null); } } catch (OCSPException e) { final String message = "answer() ocspRespBuilder.build"; if (LOG.isErrorEnabled()) { LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage()); } LOG.debug(message, e); if (auditEvent != null) { fillAuditEvent(auditEvent, AuditLevel.ERROR, AuditStatus.FAILED, "OCSPRespBuilder.build() with OCSPException"); } return createUnsuccessfullOCSPResp(OcspResponseStatus.internalError); } } catch (Throwable t) { final String message = "Throwable"; if (LOG.isErrorEnabled()) { LOG.error(LogUtil.buildExceptionLogFormat(message), t.getClass().getName(), t.getMessage()); } LOG.debug(message, t); if (auditEvent != null) { fillAuditEvent(auditEvent, AuditLevel.ERROR, AuditStatus.FAILED, "internal error"); } return createUnsuccessfullOCSPResp(OcspResponseStatus.internalError); } }
From source file:org.xipki.pki.ca.certprofile.XmlX509Certprofile.java
License:Open Source License
@Override public ExtensionValues getExtensions(final Map<ASN1ObjectIdentifier, ExtensionControl> extensionOccurences, final X500Name requestedSubject, final X500Name grantedSubject, final Extensions requestedExtensions, final Date notBefore, final Date notAfter) throws CertprofileException, BadCertTemplateException { ExtensionValues values = new ExtensionValues(); if (CollectionUtil.isEmpty(extensionOccurences)) { return values; }/*from w ww. j av a 2 s . c o m*/ ParamUtil.requireNonNull("requestedSubject", requestedSubject); ParamUtil.requireNonNull("notBefore", notBefore); ParamUtil.requireNonNull("notAfter", notAfter); Set<ASN1ObjectIdentifier> occurences = new HashSet<>(extensionOccurences.keySet()); // AuthorityKeyIdentifier // processed by the CA // SubjectKeyIdentifier // processed by the CA // KeyUsage // processed by the CA // CertificatePolicies ASN1ObjectIdentifier type = Extension.certificatePolicies; if (certificatePolicies != null) { if (occurences.remove(type)) { values.addExtension(type, certificatePolicies); } } // Policy Mappings type = Extension.policyMappings; if (policyMappings != null) { if (occurences.remove(type)) { values.addExtension(type, policyMappings); } } // SubjectAltName type = Extension.subjectAlternativeName; if (occurences.contains(type)) { GeneralNames genNames = createRequestedSubjectAltNames(requestedSubject, grantedSubject, requestedExtensions); if (genNames != null) { ExtensionValue value = new ExtensionValue(extensionControls.get(type).isCritical(), genNames); values.addExtension(type, value); occurences.remove(type); } } // IssuerAltName // processed by the CA // Subject Directory Attributes type = Extension.subjectDirectoryAttributes; if (occurences.contains(type) && subjectDirAttrsControl != null) { Extension extension = (requestedExtensions == null) ? null : requestedExtensions.getExtension(type); if (extension == null) { throw new BadCertTemplateException( "no SubjectDirecotryAttributes extension is contained in the request"); } ASN1GeneralizedTime dateOfBirth = null; String placeOfBirth = null; String gender = null; List<String> countryOfCitizenshipList = new LinkedList<>(); List<String> countryOfResidenceList = new LinkedList<>(); Map<ASN1ObjectIdentifier, List<ASN1Encodable>> otherAttrs = new HashMap<>(); Vector<?> reqSubDirAttrs = SubjectDirectoryAttributes.getInstance(extension.getParsedValue()) .getAttributes(); final int n = reqSubDirAttrs.size(); for (int i = 0; i < n; i++) { Attribute attr = (Attribute) reqSubDirAttrs.get(i); ASN1ObjectIdentifier attrType = attr.getAttrType(); ASN1Encodable attrVal = attr.getAttributeValues()[0]; if (ObjectIdentifiers.DN_DATE_OF_BIRTH.equals(attrType)) { dateOfBirth = ASN1GeneralizedTime.getInstance(attrVal); } else if (ObjectIdentifiers.DN_PLACE_OF_BIRTH.equals(attrType)) { placeOfBirth = DirectoryString.getInstance(attrVal).getString(); } else if (ObjectIdentifiers.DN_GENDER.equals(attrType)) { gender = DERPrintableString.getInstance(attrVal).getString(); } else if (ObjectIdentifiers.DN_COUNTRY_OF_CITIZENSHIP.equals(attrType)) { String country = DERPrintableString.getInstance(attrVal).getString(); countryOfCitizenshipList.add(country); } else if (ObjectIdentifiers.DN_COUNTRY_OF_RESIDENCE.equals(attrType)) { String country = DERPrintableString.getInstance(attrVal).getString(); countryOfResidenceList.add(country); } else { List<ASN1Encodable> otherAttrVals = otherAttrs.get(attrType); if (otherAttrVals == null) { otherAttrVals = new LinkedList<>(); otherAttrs.put(attrType, otherAttrVals); } otherAttrVals.add(attrVal); } } Vector<Attribute> attrs = new Vector<>(); for (ASN1ObjectIdentifier attrType : subjectDirAttrsControl.getTypes()) { if (ObjectIdentifiers.DN_DATE_OF_BIRTH.equals(attrType)) { if (dateOfBirth != null) { String timeStirng = dateOfBirth.getTimeString(); if (!SubjectDnSpec.PATTERN_DATE_OF_BIRTH.matcher(timeStirng).matches()) { throw new BadCertTemplateException("invalid dateOfBirth " + timeStirng); } attrs.add(new Attribute(attrType, new DERSet(dateOfBirth))); continue; } } else if (ObjectIdentifiers.DN_PLACE_OF_BIRTH.equals(attrType)) { if (placeOfBirth != null) { ASN1Encodable attrVal = new DERUTF8String(placeOfBirth); attrs.add(new Attribute(attrType, new DERSet(attrVal))); continue; } } else if (ObjectIdentifiers.DN_GENDER.equals(attrType)) { if (gender != null && !gender.isEmpty()) { char ch = gender.charAt(0); if (!(gender.length() == 1 && (ch == 'f' || ch == 'F' || ch == 'm' || ch == 'M'))) { throw new BadCertTemplateException("invalid gender " + gender); } ASN1Encodable attrVal = new DERPrintableString(gender); attrs.add(new Attribute(attrType, new DERSet(attrVal))); continue; } } else if (ObjectIdentifiers.DN_COUNTRY_OF_CITIZENSHIP.equals(attrType)) { if (!countryOfCitizenshipList.isEmpty()) { for (String country : countryOfCitizenshipList) { if (!SubjectDnSpec.isValidCountryAreaCode(country)) { throw new BadCertTemplateException("invalid countryOfCitizenship code " + country); } ASN1Encodable attrVal = new DERPrintableString(country); attrs.add(new Attribute(attrType, new DERSet(attrVal))); } continue; } } else if (ObjectIdentifiers.DN_COUNTRY_OF_RESIDENCE.equals(attrType)) { if (!countryOfResidenceList.isEmpty()) { for (String country : countryOfResidenceList) { if (!SubjectDnSpec.isValidCountryAreaCode(country)) { throw new BadCertTemplateException("invalid countryOfResidence code " + country); } ASN1Encodable attrVal = new DERPrintableString(country); attrs.add(new Attribute(attrType, new DERSet(attrVal))); } continue; } } else if (otherAttrs.containsKey(attrType)) { for (ASN1Encodable attrVal : otherAttrs.get(attrType)) { attrs.add(new Attribute(attrType, new DERSet(attrVal))); } continue; } throw new BadCertTemplateException( "could not process type " + attrType.getId() + " in extension SubjectDirectoryAttributes"); } SubjectDirectoryAttributes subjDirAttrs = new SubjectDirectoryAttributes(attrs); ExtensionValue extValue = new ExtensionValue(extensionControls.get(type).isCritical(), subjDirAttrs); values.addExtension(type, extValue); occurences.remove(type); } // Basic Constraints // processed by the CA // Name Constraints type = Extension.nameConstraints; if (nameConstraints != null) { if (occurences.remove(type)) { values.addExtension(type, nameConstraints); } } // PolicyConstrains type = Extension.policyConstraints; if (policyConstraints != null) { if (occurences.remove(type)) { values.addExtension(type, policyConstraints); } } // ExtendedKeyUsage // processed by CA // CRL Distribution Points // processed by the CA // Inhibit anyPolicy type = Extension.inhibitAnyPolicy; if (inhibitAnyPolicy != null) { if (occurences.remove(type)) { values.addExtension(type, inhibitAnyPolicy); } } // Freshest CRL // processed by the CA // Authority Information Access // processed by the CA // Subject Information Access // processed by the CA // Admission type = ObjectIdentifiers.id_extension_admission; if (occurences.contains(type) && admission != null) { if (admission.isInputFromRequestRequired()) { Extension extension = (requestedExtensions == null) ? null : requestedExtensions.getExtension(type); if (extension == null) { throw new BadCertTemplateException("No Admission extension is contained in the request"); } Admissions[] reqAdmissions = org.bouncycastle.asn1.isismtt.x509.AdmissionSyntax .getInstance(extension.getParsedValue()).getContentsOfAdmissions(); final int n = reqAdmissions.length; List<List<String>> reqRegNumsList = new ArrayList<>(n); for (int i = 0; i < n; i++) { Admissions reqAdmission = reqAdmissions[i]; ProfessionInfo[] reqPis = reqAdmission.getProfessionInfos(); List<String> reqNums = new ArrayList<>(reqPis.length); reqRegNumsList.add(reqNums); for (ProfessionInfo reqPi : reqPis) { String reqNum = reqPi.getRegistrationNumber(); reqNums.add(reqNum); } } values.addExtension(type, admission.getExtensionValue(reqRegNumsList)); occurences.remove(type); } else { values.addExtension(type, admission.getExtensionValue(null)); occurences.remove(type); } } // OCSP Nocheck // processed by the CA // restriction type = ObjectIdentifiers.id_extension_restriction; if (restriction != null) { if (occurences.remove(type)) { values.addExtension(type, restriction); } } // AdditionalInformation type = ObjectIdentifiers.id_extension_additionalInformation; if (additionalInformation != null) { if (occurences.remove(type)) { values.addExtension(type, additionalInformation); } } // ValidityModel type = ObjectIdentifiers.id_extension_validityModel; if (validityModel != null) { if (occurences.remove(type)) { values.addExtension(type, validityModel); } } // PrivateKeyUsagePeriod type = Extension.privateKeyUsagePeriod; if (occurences.contains(type)) { Date tmpNotAfter; if (privateKeyUsagePeriod == null) { tmpNotAfter = notAfter; } else { tmpNotAfter = privateKeyUsagePeriod.add(notBefore); if (tmpNotAfter.after(notAfter)) { tmpNotAfter = notAfter; } } ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(notBefore))); vec.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(tmpNotAfter))); ExtensionValue extValue = new ExtensionValue(extensionControls.get(type).isCritical(), new DERSequence(vec)); values.addExtension(type, extValue); occurences.remove(type); } // QCStatements type = Extension.qCStatements; if (occurences.contains(type) && (qcStatments != null || qcStatementsOption != null)) { if (qcStatments != null) { values.addExtension(type, qcStatments); occurences.remove(type); } else if (requestedExtensions != null && qcStatementsOption != null) { // extract the euLimit data from request Extension extension = requestedExtensions.getExtension(type); if (extension == null) { throw new BadCertTemplateException("No QCStatement extension is contained in the request"); } ASN1Sequence seq = ASN1Sequence.getInstance(extension.getParsedValue()); Map<String, int[]> qcEuLimits = new HashMap<>(); final int n = seq.size(); for (int i = 0; i < n; i++) { QCStatement stmt = QCStatement.getInstance(seq.getObjectAt(i)); if (!ObjectIdentifiers.id_etsi_qcs_QcLimitValue.equals(stmt.getStatementId())) { continue; } MonetaryValue monetaryValue = MonetaryValue.getInstance(stmt.getStatementInfo()); int amount = monetaryValue.getAmount().intValue(); int exponent = monetaryValue.getExponent().intValue(); Iso4217CurrencyCode currency = monetaryValue.getCurrency(); String currencyS = currency.isAlphabetic() ? currency.getAlphabetic().toUpperCase() : Integer.toString(currency.getNumeric()); qcEuLimits.put(currencyS, new int[] { amount, exponent }); } ASN1EncodableVector vec = new ASN1EncodableVector(); for (QcStatementOption m : qcStatementsOption) { if (m.getStatement() != null) { vec.add(m.getStatement()); continue; } MonetaryValueOption monetaryOption = m.getMonetaryValueOption(); String currencyS = monetaryOption.getCurrencyString(); int[] limit = qcEuLimits.get(currencyS); if (limit == null) { throw new BadCertTemplateException( "no EuLimitValue is specified for currency '" + currencyS + "'"); } int amount = limit[0]; Range2Type range = monetaryOption.getAmountRange(); if (amount < range.getMin() || amount > range.getMax()) { throw new BadCertTemplateException("amount for currency '" + currencyS + "' is not within [" + range.getMin() + ", " + range.getMax() + "]"); } int exponent = limit[1]; range = monetaryOption.getExponentRange(); if (exponent < range.getMin() || exponent > range.getMax()) { throw new BadCertTemplateException("exponent for currency '" + currencyS + "' is not within [" + range.getMin() + ", " + range.getMax() + "]"); } MonetaryValue monetaryVale = new MonetaryValue(monetaryOption.getCurrency(), amount, exponent); QCStatement qcStatment = new QCStatement(m.getStatementId(), monetaryVale); vec.add(qcStatment); } ExtensionValue extValue = new ExtensionValue(extensionControls.get(type).isCritical(), new DERSequence(vec)); values.addExtension(type, extValue); occurences.remove(type); } else { throw new RuntimeException("should not reach here"); } } // BiometricData type = Extension.biometricInfo; if (occurences.contains(type) && biometricInfo != null) { Extension extension = (requestedExtensions == null) ? null : requestedExtensions.getExtension(type); if (extension == null) { throw new BadCertTemplateException("no biometricInfo extension is contained in the request"); } ASN1Sequence seq = ASN1Sequence.getInstance(extension.getParsedValue()); final int n = seq.size(); if (n < 1) { throw new BadCertTemplateException("biometricInfo extension in request contains empty sequence"); } ASN1EncodableVector vec = new ASN1EncodableVector(); for (int i = 0; i < n; i++) { BiometricData bd = BiometricData.getInstance(seq.getObjectAt(i)); TypeOfBiometricData bdType = bd.getTypeOfBiometricData(); if (!biometricInfo.isTypePermitted(bdType)) { throw new BadCertTemplateException( "biometricInfo[" + i + "].typeOfBiometricData is not permitted"); } ASN1ObjectIdentifier hashAlgo = bd.getHashAlgorithm().getAlgorithm(); if (!biometricInfo.isHashAlgorithmPermitted(hashAlgo)) { throw new BadCertTemplateException("biometricInfo[" + i + "].hashAlgorithm is not permitted"); } int expHashValueSize; try { expHashValueSize = AlgorithmUtil.getHashOutputSizeInOctets(hashAlgo); } catch (NoSuchAlgorithmException ex) { throw new CertprofileException("should not happen, unknown hash algorithm " + hashAlgo); } byte[] hashValue = bd.getBiometricDataHash().getOctets(); if (hashValue.length != expHashValueSize) { throw new BadCertTemplateException( "biometricInfo[" + i + "].biometricDataHash has incorrect length"); } DERIA5String sourceDataUri = bd.getSourceDataUri(); switch (biometricInfo.getSourceDataUriOccurrence()) { case FORBIDDEN: sourceDataUri = null; break; case REQUIRED: if (sourceDataUri == null) { throw new BadCertTemplateException("biometricInfo[" + i + "].sourceDataUri is not specified in request but is required"); } break; case OPTIONAL: break; default: throw new BadCertTemplateException("could not reach here, unknown tripleState"); } AlgorithmIdentifier newHashAlg = new AlgorithmIdentifier(hashAlgo, DERNull.INSTANCE); BiometricData newBiometricData = new BiometricData(bdType, newHashAlg, new DEROctetString(hashValue), sourceDataUri); vec.add(newBiometricData); } ExtensionValue extValue = new ExtensionValue(extensionControls.get(type).isCritical(), new DERSequence(vec)); values.addExtension(type, extValue); occurences.remove(type); } // TlsFeature type = ObjectIdentifiers.id_pe_tlsfeature; if (tlsFeature != null) { if (occurences.remove(type)) { values.addExtension(type, tlsFeature); } } // AuthorizationTemplate type = ObjectIdentifiers.id_xipki_ext_authorizationTemplate; if (authorizationTemplate != null) { if (occurences.remove(type)) { values.addExtension(type, authorizationTemplate); } } // SMIME type = ObjectIdentifiers.id_smimeCapabilities; if (smimeCapabilities != null) { if (occurences.remove(type)) { values.addExtension(type, smimeCapabilities); } } // constant extensions if (constantExtensions != null) { for (ASN1ObjectIdentifier m : constantExtensions.keySet()) { if (!occurences.remove(m)) { continue; } ExtensionValue extensionValue = constantExtensions.get(m); if (extensionValue != null) { values.addExtension(m, extensionValue); } } } return values; }
From source file:org.xipki.pki.ca.dbtool.port.CaCertStoreDbImporter.java
License:Open Source License
private long doImportEntries(final CaDbEntryType type, final String entriesZipFile, final long minId, final File processLogFile, final ProcessLog processLog, final int numProcessedInLastProcess, final PreparedStatement[] statements, final String[] sqls) throws Exception { final int numEntriesPerCommit = Math.max(1, Math.round(type.getSqlBatchFactor() * numCertsPerCommit)); ZipFile zipFile = new ZipFile(new File(entriesZipFile)); ZipEntry entriesXmlEntry = zipFile.getEntry("overview.xml"); DbiXmlReader entries;//from w ww .j a v a 2s .c o m try { entries = createReader(type, zipFile.getInputStream(entriesXmlEntry)); } catch (Exception ex) { try { zipFile.close(); } catch (Exception e2) { LOG.error("could not close ZIP file {}: {}", entriesZipFile, e2.getMessage()); LOG.debug("could not close ZIP file " + entriesZipFile, e2); } throw ex; } disableAutoCommit(); try { int numEntriesInBatch = 0; long lastSuccessfulEntryId = 0; while (entries.hasNext()) { if (stopMe.get()) { throw new InterruptedException("interrupted by the user"); } IdentifidDbObjectType entry = (IdentifidDbObjectType) entries.next(); long id = entry.getId(); if (id < minId) { continue; } numEntriesInBatch++; if (CaDbEntryType.CERT == type) { CaCertType cert = (CaCertType) entry; int certArt = (cert.getArt() == null) ? 1 : cert.getArt(); String filename = cert.getFile(); // rawcert ZipEntry certZipEnty = zipFile.getEntry(filename); // rawcert byte[] encodedCert = IoUtil.read(zipFile.getInputStream(certZipEnty)); TBSCertificate tbsCert; try { Certificate cc = Certificate.getInstance(encodedCert); tbsCert = cc.getTBSCertificate(); } catch (RuntimeException ex) { LOG.error("could not parse certificate in file {}", filename); LOG.debug("could not parse certificate in file " + filename, ex); throw new CertificateException(ex.getMessage(), ex); } byte[] encodedKey = tbsCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); String b64Sha1FpCert = HashAlgoType.SHA1.base64Hash(encodedCert); // cert String subjectText = X509Util.cutX500Name(tbsCert.getSubject(), maxX500nameLen); PreparedStatement psCert = statements[0]; PreparedStatement psRawcert = statements[1]; try { int idx = 1; psCert.setLong(idx++, id); psCert.setInt(idx++, certArt); psCert.setLong(idx++, cert.getUpdate()); psCert.setString(idx++, tbsCert.getSerialNumber().getPositiveValue().toString(16)); psCert.setString(idx++, subjectText); long fpSubject = X509Util.fpCanonicalizedName(tbsCert.getSubject()); psCert.setLong(idx++, fpSubject); if (cert.getFpRs() != null) { psCert.setLong(idx++, cert.getFpRs()); } else { psCert.setNull(idx++, Types.BIGINT); } psCert.setLong(idx++, tbsCert.getStartDate().getDate().getTime() / 1000); psCert.setLong(idx++, tbsCert.getEndDate().getDate().getTime() / 1000); setBoolean(psCert, idx++, cert.getRev()); setInt(psCert, idx++, cert.getRr()); setLong(psCert, idx++, cert.getRt()); setLong(psCert, idx++, cert.getRit()); setInt(psCert, idx++, cert.getPid()); setInt(psCert, idx++, cert.getCaId()); setInt(psCert, idx++, cert.getRid()); psCert.setString(idx++, cert.getUser()); psCert.setLong(idx++, FpIdCalculator.hash(encodedKey)); Extension extension = tbsCert.getExtensions().getExtension(Extension.basicConstraints); boolean ee = true; if (extension != null) { ASN1Encodable asn1 = extension.getParsedValue(); ee = !BasicConstraints.getInstance(asn1).isCA(); } psCert.setInt(idx++, ee ? 1 : 0); psCert.setInt(idx++, cert.getReqType()); String tidS = null; if (cert.getTid() != null) { tidS = cert.getTid(); } psCert.setString(idx++, tidS); psCert.addBatch(); } catch (SQLException ex) { throw translate(SQL_ADD_CERT, ex); } try { int idx = 1; psRawcert.setLong(idx++, cert.getId()); psRawcert.setString(idx++, b64Sha1FpCert); psRawcert.setString(idx++, cert.getRs()); psRawcert.setString(idx++, Base64.toBase64String(encodedCert)); psRawcert.addBatch(); } catch (SQLException ex) { throw translate(SQL_ADD_CRAW, ex); } } else if (CaDbEntryType.CRL == type) { PreparedStatement psAddCrl = statements[0]; CaCrlType crl = (CaCrlType) entry; String filename = crl.getFile(); // CRL ZipEntry zipEnty = zipFile.getEntry(filename); // rawcert byte[] encodedCrl = IoUtil.read(zipFile.getInputStream(zipEnty)); X509CRL x509crl = null; try { x509crl = X509Util.parseCrl(encodedCrl); } catch (Exception ex) { LOG.error("could not parse CRL in file {}", filename); LOG.debug("could not parse CRL in file " + filename, ex); if (ex instanceof CRLException) { throw (CRLException) ex; } else { throw new CRLException(ex.getMessage(), ex); } } try { byte[] octetString = x509crl.getExtensionValue(Extension.cRLNumber.getId()); if (octetString == null) { LOG.warn("CRL without CRL number, ignore it"); continue; } byte[] extnValue = DEROctetString.getInstance(octetString).getOctets(); // CHECKSTYLE:SKIP BigInteger crlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue(); BigInteger baseCrlNumber = null; octetString = x509crl.getExtensionValue(Extension.deltaCRLIndicator.getId()); if (octetString != null) { extnValue = DEROctetString.getInstance(octetString).getOctets(); baseCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue(); } int idx = 1; psAddCrl.setLong(idx++, crl.getId()); psAddCrl.setInt(idx++, crl.getCaId()); psAddCrl.setLong(idx++, crlNumber.longValue()); psAddCrl.setLong(idx++, x509crl.getThisUpdate().getTime() / 1000); if (x509crl.getNextUpdate() != null) { psAddCrl.setLong(idx++, x509crl.getNextUpdate().getTime() / 1000); } else { psAddCrl.setNull(idx++, Types.INTEGER); } if (baseCrlNumber == null) { setBoolean(psAddCrl, idx++, false); psAddCrl.setNull(idx++, Types.BIGINT); } else { setBoolean(psAddCrl, idx++, true); psAddCrl.setLong(idx++, baseCrlNumber.longValue()); } String str = Base64.toBase64String(encodedCrl); psAddCrl.setString(idx++, str); psAddCrl.addBatch(); } catch (SQLException ex) { System.err.println( "could not import CRL with ID=" + crl.getId() + ", message: " + ex.getMessage()); throw ex; } } else if (CaDbEntryType.USER == type) { PreparedStatement psAddUser = statements[0]; CaUserType user = (CaUserType) entry; try { int idx = 1; psAddUser.setLong(idx++, user.getId()); psAddUser.setString(idx++, user.getName()); psAddUser.setString(idx++, user.getPassword()); psAddUser.setString(idx++, user.getCnRegex()); psAddUser.addBatch(); } catch (SQLException ex) { System.err.println("could not import USERNAME with ID=" + user.getId() + ", message: " + ex.getMessage()); throw ex; } } else if (CaDbEntryType.REQUEST == type) { PreparedStatement psAddRequest = statements[0]; CaRequestType request = (CaRequestType) entry; String filename = request.getFile(); ZipEntry zipEnty = zipFile.getEntry(filename); byte[] encodedRequest = IoUtil.read(zipFile.getInputStream(zipEnty)); try { int idx = 1; psAddRequest.setLong(idx++, request.getId()); psAddRequest.setLong(idx++, request.getUpdate()); psAddRequest.setString(idx++, Base64.toBase64String(encodedRequest)); psAddRequest.addBatch(); } catch (SQLException ex) { System.err.println("could not import REQUEST with ID=" + request.getId() + ", message: " + ex.getMessage()); throw ex; } } else if (CaDbEntryType.REQCERT == type) { PreparedStatement psAddReqCert = statements[0]; CaRequestCertType reqCert = (CaRequestCertType) entry; try { int idx = 1; psAddReqCert.setLong(idx++, reqCert.getId()); psAddReqCert.setLong(idx++, reqCert.getRid()); psAddReqCert.setLong(idx++, reqCert.getCid()); psAddReqCert.addBatch(); } catch (SQLException ex) { System.err.println("could not import REQUEST with ID=" + reqCert.getId() + ", message: " + ex.getMessage()); throw ex; } } else { throw new RuntimeException("Unknown CaDbEntryType " + type); } boolean isLastBlock = !entries.hasNext(); if (numEntriesInBatch > 0 && (numEntriesInBatch % numEntriesPerCommit == 0 || isLastBlock)) { if (evaulateOnly) { for (PreparedStatement m : statements) { m.clearBatch(); } } else { String sql = null; try { for (int i = 0; i < sqls.length; i++) { sql = sqls[i]; statements[i].executeBatch(); } sql = null; commit("(commit import to CA)"); } catch (Throwable th) { rollback(); deleteFromTableWithLargerId(type.getTableName(), "ID", id, LOG); if (CaDbEntryType.CERT == type) { deleteFromTableWithLargerId("CRAW", "CID", id, LOG); } if (th instanceof SQLException) { throw translate(sql, (SQLException) th); } else if (th instanceof Exception) { throw (Exception) th; } else { throw new Exception(th); } } } lastSuccessfulEntryId = id; processLog.addNumProcessed(numEntriesInBatch); numEntriesInBatch = 0; echoToFile(type + ":" + (numProcessedInLastProcess + processLog.getNumProcessed()) + ":" + lastSuccessfulEntryId, processLogFile); processLog.printStatus(); } } // end while return lastSuccessfulEntryId; } finally { recoverAutoCommit(); zipFile.close(); } }
From source file:org.xipki.pki.ca.qa.ExtensionsChecker.java
License:Open Source License
private Set<ASN1ObjectIdentifier> getExensionTypes(final Certificate cert, final X509IssuerInfo issuerInfo, final Extensions requestedExtensions) { Set<ASN1ObjectIdentifier> types = new HashSet<>(); // profile required extension types Map<ASN1ObjectIdentifier, ExtensionControl> extensionControls = certProfile.getExtensionControls(); for (ASN1ObjectIdentifier oid : extensionControls.keySet()) { if (extensionControls.get(oid).isRequired()) { types.add(oid);// w w w. j a v a 2s. co m } } Set<ASN1ObjectIdentifier> wantedExtensionTypes = new HashSet<>(); if (requestedExtensions != null) { Extension reqExtension = requestedExtensions .getExtension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions); if (reqExtension != null) { ExtensionExistence ee = ExtensionExistence.getInstance(reqExtension.getParsedValue()); types.addAll(ee.getNeedExtensions()); wantedExtensionTypes.addAll(ee.getWantExtensions()); } } if (CollectionUtil.isEmpty(wantedExtensionTypes)) { return types; } // wanted extension types // Authority key identifier ASN1ObjectIdentifier type = Extension.authorityKeyIdentifier; if (wantedExtensionTypes.contains(type)) { types.add(type); } // Subject key identifier type = Extension.subjectKeyIdentifier; if (wantedExtensionTypes.contains(type)) { types.add(type); } // KeyUsage type = Extension.keyUsage; if (wantedExtensionTypes.contains(type)) { boolean required = false; if (requestedExtensions != null && requestedExtensions.getExtension(type) != null) { required = true; } if (!required) { Set<KeyUsageControl> requiredKeyusage = getKeyusage(true); if (CollectionUtil.isNonEmpty(requiredKeyusage)) { required = true; } } if (required) { types.add(type); } } // CertificatePolicies type = Extension.certificatePolicies; if (wantedExtensionTypes.contains(type)) { if (certificatePolicies != null) { types.add(type); } } // Policy Mappings type = Extension.policyMappings; if (wantedExtensionTypes.contains(type)) { if (policyMappings != null) { types.add(type); } } // SubjectAltNames type = Extension.subjectAlternativeName; if (wantedExtensionTypes.contains(type)) { if (requestedExtensions != null && requestedExtensions.getExtension(type) != null) { types.add(type); } } // IssuerAltName type = Extension.issuerAlternativeName; if (wantedExtensionTypes.contains(type)) { if (cert.getTBSCertificate().getExtensions().getExtension(Extension.subjectAlternativeName) != null) { types.add(type); } } // BasicConstraints type = Extension.basicConstraints; if (wantedExtensionTypes.contains(type)) { types.add(type); } // Name Constraints type = Extension.nameConstraints; if (wantedExtensionTypes.contains(type)) { if (nameConstraints != null) { types.add(type); } } // PolicyConstrains type = Extension.policyConstraints; if (wantedExtensionTypes.contains(type)) { if (policyConstraints != null) { types.add(type); } } // ExtendedKeyUsage type = Extension.extendedKeyUsage; if (wantedExtensionTypes.contains(type)) { boolean required = false; if (requestedExtensions != null && requestedExtensions.getExtension(type) != null) { required = true; } if (!required) { Set<ExtKeyUsageControl> requiredExtKeyusage = getExtKeyusage(true); if (CollectionUtil.isNonEmpty(requiredExtKeyusage)) { required = true; } } if (required) { types.add(type); } } // CRLDistributionPoints type = Extension.cRLDistributionPoints; if (wantedExtensionTypes.contains(type)) { if (issuerInfo.getCrlUrls() != null) { types.add(type); } } // Inhibit anyPolicy type = Extension.inhibitAnyPolicy; if (wantedExtensionTypes.contains(type)) { if (inhibitAnyPolicy != null) { types.add(type); } } // FreshestCRL type = Extension.freshestCRL; if (wantedExtensionTypes.contains(type)) { if (issuerInfo.getDeltaCrlUrls() != null) { types.add(type); } } // AuthorityInfoAccess type = Extension.authorityInfoAccess; if (wantedExtensionTypes.contains(type)) { if (issuerInfo.getOcspUrls() != null) { types.add(type); } } // SubjectInfoAccess type = Extension.subjectInfoAccess; if (wantedExtensionTypes.contains(type)) { if (requestedExtensions != null && requestedExtensions.getExtension(type) != null) { types.add(type); } } // Admission type = ObjectIdentifiers.id_extension_admission; if (wantedExtensionTypes.contains(type)) { if (certProfile.getAdmission() != null) { types.add(type); } } // ocsp-nocheck type = ObjectIdentifiers.id_extension_pkix_ocsp_nocheck; if (wantedExtensionTypes.contains(type)) { types.add(type); } wantedExtensionTypes.removeAll(types); for (ASN1ObjectIdentifier oid : wantedExtensionTypes) { if (requestedExtensions != null && requestedExtensions.getExtension(oid) != null) { if (constantExtensions.containsKey(oid)) { types.add(oid); } } } return types; }
From source file:org.xipki.pki.ca.qa.ExtensionsChecker.java
License:Open Source License
private void checkExtensionKeyUsage(final StringBuilder failureMsg, final byte[] extensionValue, final boolean[] usages, final Extensions requestedExtensions, final ExtensionControl extControl) { int len = usages.length; if (len > 9) { failureMsg.append("invalid syntax: size of valid bits is larger than 9: ").append(len); failureMsg.append("; "); }/*from w w w .jav a2 s . c o m*/ Set<String> isUsages = new HashSet<>(); for (int i = 0; i < len; i++) { if (usages[i]) { isUsages.add(ALL_USAGES.get(i)); } } Set<String> expectedUsages = new HashSet<>(); Set<KeyUsageControl> requiredKeyusage = getKeyusage(true); for (KeyUsageControl usage : requiredKeyusage) { expectedUsages.add(usage.getKeyUsage().getName()); } Set<KeyUsageControl> optionalKeyusage = getKeyusage(false); if (requestedExtensions != null && extControl.isRequest() && CollectionUtil.isNonEmpty(optionalKeyusage)) { Extension extension = requestedExtensions.getExtension(Extension.keyUsage); if (extension != null) { org.bouncycastle.asn1.x509.KeyUsage reqKeyUsage = org.bouncycastle.asn1.x509.KeyUsage .getInstance(extension.getParsedValue()); for (KeyUsageControl k : optionalKeyusage) { if (reqKeyUsage.hasUsages(k.getKeyUsage().getBcUsage())) { expectedUsages.add(k.getKeyUsage().getName()); } } } } if (CollectionUtil.isEmpty(expectedUsages)) { byte[] constantExtValue = getConstantExtensionValue(Extension.keyUsage); if (constantExtValue != null) { expectedUsages = getKeyUsage(constantExtValue); } } Set<String> diffs = strInBnotInA(expectedUsages, isUsages); if (CollectionUtil.isNonEmpty(diffs)) { failureMsg.append("usages ").append(diffs.toString()).append(" are present but not expected; "); } diffs = strInBnotInA(isUsages, expectedUsages); if (CollectionUtil.isNonEmpty(diffs)) { failureMsg.append("usages ").append(diffs.toString()).append(" are absent but are required; "); } }
From source file:org.xipki.pki.ca.qa.ExtensionsChecker.java
License:Open Source License
private void checkExtensionExtendedKeyUsage(final StringBuilder failureMsg, final byte[] extensionValue, final Extensions requestedExtensions, final ExtensionControl extControl) { Set<String> isUsages = new HashSet<>(); org.bouncycastle.asn1.x509.ExtendedKeyUsage keyusage = org.bouncycastle.asn1.x509.ExtendedKeyUsage .getInstance(extensionValue); KeyPurposeId[] usages = keyusage.getUsages(); if (usages != null) { for (KeyPurposeId usage : usages) { isUsages.add(usage.getId()); }/*from w ww . j a v a 2 s .c om*/ } Set<String> expectedUsages = new HashSet<>(); Set<ExtKeyUsageControl> requiredExtKeyusage = getExtKeyusage(true); if (requiredExtKeyusage != null) { for (ExtKeyUsageControl usage : requiredExtKeyusage) { expectedUsages.add(usage.getExtKeyUsage().getId()); } } Set<ExtKeyUsageControl> optionalExtKeyusage = getExtKeyusage(false); if (requestedExtensions != null && extControl.isRequest() && CollectionUtil.isNonEmpty(optionalExtKeyusage)) { Extension extension = requestedExtensions.getExtension(Extension.extendedKeyUsage); if (extension != null) { org.bouncycastle.asn1.x509.ExtendedKeyUsage reqKeyUsage = org.bouncycastle.asn1.x509.ExtendedKeyUsage .getInstance(extension.getParsedValue()); for (ExtKeyUsageControl k : optionalExtKeyusage) { if (reqKeyUsage.hasKeyPurposeId(KeyPurposeId.getInstance(k.getExtKeyUsage()))) { expectedUsages.add(k.getExtKeyUsage().getId()); } } } } if (CollectionUtil.isEmpty(expectedUsages)) { byte[] constantExtValue = getConstantExtensionValue(Extension.keyUsage); if (constantExtValue != null) { expectedUsages = getExtKeyUsage(constantExtValue); } } Set<String> diffs = strInBnotInA(expectedUsages, isUsages); if (CollectionUtil.isNonEmpty(diffs)) { failureMsg.append("usages ").append(diffs.toString()).append(" are present but not expected; "); } diffs = strInBnotInA(isUsages, expectedUsages); if (CollectionUtil.isNonEmpty(diffs)) { failureMsg.append("usages ").append(diffs.toString()).append(" are absent but are required; "); } }