List of usage examples for org.bouncycastle.asn1.x509 Extension authorityKeyIdentifier
ASN1ObjectIdentifier authorityKeyIdentifier
To view the source code for org.bouncycastle.asn1.x509 Extension authorityKeyIdentifier.
Click Source Link
From source file:org.xipki.pki.ca.certprofile.XmlX509Certprofile.java
License:Open Source License
private void initAuthorityKeyIdentifier(ExtensionsType extensionsType) throws CertprofileException { ASN1ObjectIdentifier type = Extension.authorityKeyIdentifier; if (!extensionControls.containsKey(type)) { return;/*from w w w .j a va 2s. c o m*/ } AuthorityKeyIdentifier extConf = (AuthorityKeyIdentifier) getExtensionValue(type, extensionsType, AuthorityKeyIdentifier.class); if (extConf == null) { return; } this.includeIssuerAndSerialInAki = extConf.isIncludeIssuerAndSerial(); }
From source file:org.xipki.pki.ca.client.impl.X509CmpRequestor.java
License:Open Source License
private static Extensions getCertTempExtensions(byte[] authorityKeyIdentifier) throws CmpRequestorException { AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(authorityKeyIdentifier); byte[] encodedAki; try {// w w w . j a v a 2 s.com encodedAki = aki.getEncoded(); } catch (IOException ex) { throw new CmpRequestorException("could not encoded AuthorityKeyIdentifier", ex); } Extension extAki = new Extension(Extension.authorityKeyIdentifier, false, encodedAki); Extensions certTempExts = new Extensions(extAki); return certTempExts; }
From source file:org.xipki.pki.ca.qa.ExtensionsChecker.java
License:Open Source License
public List<ValidationIssue> checkExtensions(final Certificate cert, final X509IssuerInfo issuerInfo, final Extensions requestedExtensions, final X500Name requestedSubject) { ParamUtil.requireNonNull("cert", cert); ParamUtil.requireNonNull("issuerInfo", issuerInfo); X509Certificate jceCert;/*from w w w.j a v a 2 s.c o m*/ try { jceCert = X509Util.toX509Cert(cert); } catch (CertificateException ex) { throw new IllegalArgumentException("invalid cert: " + ex.getMessage()); } List<ValidationIssue> result = new LinkedList<>(); // detect the list of extension types in certificate Set<ASN1ObjectIdentifier> presentExtenionTypes = getExensionTypes(cert, issuerInfo, requestedExtensions); Extensions extensions = cert.getTBSCertificate().getExtensions(); ASN1ObjectIdentifier[] oids = extensions.getExtensionOIDs(); if (oids == null) { ValidationIssue issue = new ValidationIssue("X509.EXT.GEN", "extension general"); result.add(issue); issue.setFailureMessage("no extension is present"); return result; } List<ASN1ObjectIdentifier> certExtTypes = Arrays.asList(oids); for (ASN1ObjectIdentifier extType : presentExtenionTypes) { if (!certExtTypes.contains(extType)) { ValidationIssue issue = createExtensionIssue(extType); result.add(issue); issue.setFailureMessage("extension is absent but is required"); } } Map<ASN1ObjectIdentifier, ExtensionControl> extensionControls = certProfile.getExtensionControls(); for (ASN1ObjectIdentifier oid : certExtTypes) { ValidationIssue issue = createExtensionIssue(oid); result.add(issue); if (!presentExtenionTypes.contains(oid)) { issue.setFailureMessage("extension is present but is not permitted"); continue; } Extension ext = extensions.getExtension(oid); StringBuilder failureMsg = new StringBuilder(); ExtensionControl extControl = extensionControls.get(oid); if (extControl.isCritical() != ext.isCritical()) { addViolation(failureMsg, "critical", ext.isCritical(), extControl.isCritical()); } byte[] extensionValue = ext.getExtnValue().getOctets(); try { if (Extension.authorityKeyIdentifier.equals(oid)) { // AuthorityKeyIdentifier checkExtensionIssuerKeyIdentifier(failureMsg, extensionValue, issuerInfo); } else if (Extension.subjectKeyIdentifier.equals(oid)) { // SubjectKeyIdentifier checkExtensionSubjectKeyIdentifier(failureMsg, extensionValue, cert.getSubjectPublicKeyInfo()); } else if (Extension.keyUsage.equals(oid)) { // KeyUsage checkExtensionKeyUsage(failureMsg, extensionValue, jceCert.getKeyUsage(), requestedExtensions, extControl); } else if (Extension.certificatePolicies.equals(oid)) { // CertificatePolicies checkExtensionCertificatePolicies(failureMsg, extensionValue, requestedExtensions, extControl); } else if (Extension.policyMappings.equals(oid)) { // Policy Mappings checkExtensionPolicyMappings(failureMsg, extensionValue, requestedExtensions, extControl); } else if (Extension.subjectAlternativeName.equals(oid)) { // SubjectAltName checkExtensionSubjectAltName(failureMsg, extensionValue, requestedExtensions, extControl, requestedSubject); } else if (Extension.subjectDirectoryAttributes.equals(oid)) { // SubjectDirectoryAttributes checkExtensionSubjectDirAttrs(failureMsg, extensionValue, requestedExtensions, extControl); } else if (Extension.issuerAlternativeName.equals(oid)) { // IssuerAltName checkExtensionIssuerAltNames(failureMsg, extensionValue, issuerInfo); } else if (Extension.basicConstraints.equals(oid)) { // Basic Constraints checkExtensionBasicConstraints(failureMsg, extensionValue); } else if (Extension.nameConstraints.equals(oid)) { // Name Constraints checkExtensionNameConstraints(failureMsg, extensionValue, extensions, extControl); } else if (Extension.policyConstraints.equals(oid)) { // PolicyConstrains checkExtensionPolicyConstraints(failureMsg, extensionValue, requestedExtensions, extControl); } else if (Extension.extendedKeyUsage.equals(oid)) { // ExtendedKeyUsage checkExtensionExtendedKeyUsage(failureMsg, extensionValue, requestedExtensions, extControl); } else if (Extension.cRLDistributionPoints.equals(oid)) { // CRL Distribution Points checkExtensionCrlDistributionPoints(failureMsg, extensionValue, issuerInfo); } else if (Extension.inhibitAnyPolicy.equals(oid)) { // Inhibit anyPolicy checkExtensionInhibitAnyPolicy(failureMsg, extensionValue, extensions, extControl); } else if (Extension.freshestCRL.equals(oid)) { // Freshest CRL checkExtensionDeltaCrlDistributionPoints(failureMsg, extensionValue, issuerInfo); } else if (Extension.authorityInfoAccess.equals(oid)) { // Authority Information Access checkExtensionAuthorityInfoAccess(failureMsg, extensionValue, issuerInfo); } else if (Extension.subjectInfoAccess.equals(oid)) { // SubjectInfoAccess checkExtensionSubjectInfoAccess(failureMsg, extensionValue, requestedExtensions, extControl); } else if (ObjectIdentifiers.id_extension_admission.equals(oid)) { // Admission checkExtensionAdmission(failureMsg, extensionValue, requestedExtensions, extControl); } else if (ObjectIdentifiers.id_extension_pkix_ocsp_nocheck.equals(oid)) { // ocsp-nocheck checkExtensionOcspNocheck(failureMsg, extensionValue); } else if (ObjectIdentifiers.id_extension_restriction.equals(oid)) { // restriction checkExtensionRestriction(failureMsg, extensionValue, requestedExtensions, extControl); } else if (ObjectIdentifiers.id_extension_additionalInformation.equals(oid)) { // additionalInformation checkExtensionAdditionalInformation(failureMsg, extensionValue, requestedExtensions, extControl); } else if (ObjectIdentifiers.id_extension_validityModel.equals(oid)) { // validityModel checkExtensionValidityModel(failureMsg, extensionValue, requestedExtensions, extControl); } else if (Extension.privateKeyUsagePeriod.equals(oid)) { // privateKeyUsagePeriod checkExtensionPrivateKeyUsagePeriod(failureMsg, extensionValue, jceCert.getNotBefore(), jceCert.getNotAfter()); } else if (Extension.qCStatements.equals(oid)) { // qCStatements checkExtensionQcStatements(failureMsg, extensionValue, requestedExtensions, extControl); } else if (Extension.biometricInfo.equals(oid)) { // biometricInfo checkExtensionBiometricInfo(failureMsg, extensionValue, requestedExtensions, extControl); } else if (ObjectIdentifiers.id_pe_tlsfeature.equals(oid)) { // tlsFeature checkExtensionTlsFeature(failureMsg, extensionValue, requestedExtensions, extControl); } else if (ObjectIdentifiers.id_xipki_ext_authorizationTemplate.equals(oid)) { // authorizationTemplate checkExtensionAuthorizationTemplate(failureMsg, extensionValue, requestedExtensions, extControl); } else { byte[] expected; if (ObjectIdentifiers.id_smimeCapabilities.equals(oid)) { // SMIMECapabilities expected = smimeCapabilities.getValue(); } else { expected = getExpectedExtValue(oid, requestedExtensions, extControl); } if (!Arrays.equals(expected, extensionValue)) { addViolation(failureMsg, "extension valus", hex(extensionValue), (expected == null) ? "not present" : hex(expected)); } } if (failureMsg.length() > 0) { issue.setFailureMessage(failureMsg.toString()); } } catch (IllegalArgumentException | ClassCastException | ArrayIndexOutOfBoundsException ex) { LOG.debug("extension value does not have correct syntax", ex); issue.setFailureMessage("extension value does not have correct syntax"); } } return result; }
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);/*from w w w . ja v a 2 s . com*/ } } 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.server.impl.cmp.X509CaCmpResponder.java
License:Open Source License
private PKIBody unRevokeRemoveCertificates(final PKIMessage request, final RevReqContent rr, final Permission permission, final CmpControl cmpControl, final String msgId) { RevDetails[] revContent = rr.toRevDetailsArray(); RevRepContentBuilder repContentBuilder = new RevRepContentBuilder(); final int n = revContent.length; // test the request for (int i = 0; i < n; i++) { RevDetails revDetails = revContent[i]; CertTemplate certDetails = revDetails.getCertDetails(); X500Name issuer = certDetails.getIssuer(); ASN1Integer serialNumber = certDetails.getSerialNumber(); try {/*from w w w . ja va2s . c o m*/ X500Name caSubject = getCa().getCaInfo().getCertificate().getSubjectAsX500Name(); if (issuer == null) { return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate, "issuer is not present"); } if (!issuer.equals(caSubject)) { return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate, "issuer does not target at the CA"); } if (serialNumber == null) { return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate, "serialNumber is not present"); } if (certDetails.getSigningAlg() != null || certDetails.getValidity() != null || certDetails.getSubject() != null || certDetails.getPublicKey() != null || certDetails.getIssuerUID() != null || certDetails.getSubjectUID() != null) { return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate, "only version, issuer and serialNumber in RevDetails.certDetails are " + "allowed, but more is specified"); } if (certDetails.getExtensions() == null) { if (cmpControl.isRrAkiRequired()) { return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate, "issuer's AKI not present"); } } else { Extensions exts = certDetails.getExtensions(); ASN1ObjectIdentifier[] oids = exts.getCriticalExtensionOIDs(); if (oids != null) { for (ASN1ObjectIdentifier oid : oids) { if (!Extension.authorityKeyIdentifier.equals(oid)) { return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate, "unknown critical extension " + oid.getId()); } } } Extension ext = exts.getExtension(Extension.authorityKeyIdentifier); if (ext == null) { return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate, "issuer's AKI not present"); } else { AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.getInstance(ext.getParsedValue()); if (aki.getKeyIdentifier() == null) { return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate, "issuer's AKI not present"); } boolean issuerMatched = true; byte[] caSki = getCa().getCaInfo().getCertificate().getSubjectKeyIdentifier(); if (Arrays.equals(caSki, aki.getKeyIdentifier())) { issuerMatched = false; } if (issuerMatched && aki.getAuthorityCertSerialNumber() != null) { BigInteger caSerial = getCa().getCaInfo().getSerialNumber(); if (!caSerial.equals(aki.getAuthorityCertSerialNumber())) { issuerMatched = false; } } if (issuerMatched && aki.getAuthorityCertIssuer() != null) { GeneralName[] names = aki.getAuthorityCertIssuer().getNames(); for (GeneralName name : names) { if (name.getTagNo() != GeneralName.directoryName) { issuerMatched = false; break; } if (!caSubject.equals(name.getName())) { issuerMatched = false; break; } } } if (!issuerMatched) { return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate, "issuer does not target at the CA"); } } } } catch (IllegalArgumentException ex) { return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badRequest, "the request is not invalid"); } } // end for byte[] encodedRequest = null; if (getCa().getCaInfo().isSaveRequest()) { try { encodedRequest = request.getEncoded(); } catch (IOException ex) { LOG.warn("could not encode request"); } } Long reqDbId = null; for (int i = 0; i < n; i++) { RevDetails revDetails = revContent[i]; CertTemplate certDetails = revDetails.getCertDetails(); ASN1Integer serialNumber = certDetails.getSerialNumber(); // serialNumber is not null due to the check in the previous for-block. X500Name caSubject = getCa().getCaInfo().getCertificate().getSubjectAsX500Name(); BigInteger snBigInt = serialNumber.getPositiveValue(); CertId certId = new CertId(new GeneralName(caSubject), serialNumber); PKIStatusInfo status; try { Object returnedObj = null; Long certDbId = null; X509Ca ca = getCa(); if (Permission.UNREVOKE_CERT == permission) { // unrevoke returnedObj = ca.unrevokeCertificate(snBigInt, msgId); if (returnedObj != null) { certDbId = ((X509CertWithDbId) returnedObj).getCertId(); } } else if (Permission.REMOVE_CERT == permission) { // remove returnedObj = ca.removeCertificate(snBigInt, msgId); } else { // revoke Date invalidityDate = null; CrlReason reason = null; Extensions crlDetails = revDetails.getCrlEntryDetails(); if (crlDetails != null) { ASN1ObjectIdentifier extId = Extension.reasonCode; ASN1Encodable extValue = crlDetails.getExtensionParsedValue(extId); if (extValue != null) { int reasonCode = ASN1Enumerated.getInstance(extValue).getValue().intValue(); reason = CrlReason.forReasonCode(reasonCode); } extId = Extension.invalidityDate; extValue = crlDetails.getExtensionParsedValue(extId); if (extValue != null) { try { invalidityDate = ASN1GeneralizedTime.getInstance(extValue).getDate(); } catch (ParseException ex) { throw new OperationException(ErrorCode.INVALID_EXTENSION, "invalid extension " + extId.getId()); } } } // end if (crlDetails) if (reason == null) { reason = CrlReason.UNSPECIFIED; } returnedObj = ca.revokeCertificate(snBigInt, reason, invalidityDate, msgId); if (returnedObj != null) { certDbId = ((X509CertWithRevocationInfo) returnedObj).getCert().getCertId(); } } // end if (permission) if (returnedObj == null) { throw new OperationException(ErrorCode.UNKNOWN_CERT, "cert not exists"); } if (certDbId != null && ca.getCaInfo().isSaveRequest()) { if (reqDbId == null) { reqDbId = ca.addRequest(encodedRequest); } ca.addRequestCert(reqDbId, certDbId); } status = new PKIStatusInfo(PKIStatus.granted); } catch (OperationException ex) { ErrorCode code = ex.getErrorCode(); LOG.warn("{} certificate, OperationException: code={}, message={}", permission.name(), code.name(), ex.getErrorMessage()); String errorMessage; switch (code) { case DATABASE_FAILURE: case SYSTEM_FAILURE: errorMessage = code.name(); break; default: errorMessage = code.name() + ": " + ex.getErrorMessage(); break; } // end switch code int failureInfo = getPKiFailureInfo(ex); status = generateRejectionStatus(failureInfo, errorMessage); } // end try repContentBuilder.add(status, certId); } // end for return new PKIBody(PKIBody.TYPE_REVOCATION_REP, repContentBuilder.build()); }
From source file:org.xipki.pki.ca.server.impl.IdentifiedX509Certprofile.java
License:Open Source License
public ExtensionValues getExtensions(@NonNull final X500Name requestedSubject, @NonNull final X500Name grantedSubject, @Nullable final Extensions requestedExtensions, @NonNull final SubjectPublicKeyInfo publicKeyInfo, @NonNull final PublicCaInfo publicCaInfo, @Nullable final X509Certificate crlSignerCert, @NonNull final Date notBefore, @NonNull final Date notAfter) throws CertprofileException, BadCertTemplateException { ParamUtil.requireNonNull("publicKeyInfo", publicKeyInfo); ExtensionValues values = new ExtensionValues(); Map<ASN1ObjectIdentifier, ExtensionControl> controls = new HashMap<>(certprofile.getExtensionControls()); Set<ASN1ObjectIdentifier> neededExtTypes = new HashSet<>(); Set<ASN1ObjectIdentifier> wantedExtTypes = new HashSet<>(); if (requestedExtensions != null) { Extension reqExtension = requestedExtensions .getExtension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions); if (reqExtension != null) { ExtensionExistence ee = ExtensionExistence.getInstance(reqExtension.getParsedValue()); neededExtTypes.addAll(ee.getNeedExtensions()); wantedExtTypes.addAll(ee.getWantExtensions()); }/*from w w w . j a v a 2 s . co m*/ for (ASN1ObjectIdentifier oid : neededExtTypes) { if (wantedExtTypes.contains(oid)) { wantedExtTypes.remove(oid); } if (!controls.containsKey(oid)) { throw new BadCertTemplateException("could not add needed extension " + oid.getId()); } } } // SubjectKeyIdentifier ASN1ObjectIdentifier extType = Extension.subjectKeyIdentifier; ExtensionControl extControl = controls.remove(extType); if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) { byte[] encodedSpki = publicKeyInfo.getPublicKeyData().getBytes(); byte[] skiValue = HashAlgoType.SHA1.hash(encodedSpki); SubjectKeyIdentifier value = new SubjectKeyIdentifier(skiValue); addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes); } // Authority key identifier extType = Extension.authorityKeyIdentifier; extControl = controls.remove(extType); if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) { byte[] ikiValue = publicCaInfo.getSubjectKeyIdentifer(); AuthorityKeyIdentifier value = null; if (ikiValue != null) { if (certprofile.includeIssuerAndSerialInAki()) { GeneralNames x509CaSubject = new GeneralNames(new GeneralName(publicCaInfo.getX500Subject())); value = new AuthorityKeyIdentifier(ikiValue, x509CaSubject, publicCaInfo.getSerialNumber()); } else { value = new AuthorityKeyIdentifier(ikiValue); } } addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes); } // IssuerAltName extType = Extension.issuerAlternativeName; extControl = controls.remove(extType); if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) { GeneralNames value = publicCaInfo.getSubjectAltName(); addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes); } // AuthorityInfoAccess extType = Extension.authorityInfoAccess; extControl = controls.remove(extType); if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) { AuthorityInfoAccessControl aiaControl = certprofile.getAiaControl(); List<String> caIssuers = null; if (aiaControl == null || aiaControl.includesCaIssuers()) { caIssuers = publicCaInfo.getCaCertUris(); } List<String> ocspUris = null; if (aiaControl == null || aiaControl.includesOcsp()) { ocspUris = publicCaInfo.getOcspUris(); } if (CollectionUtil.isNonEmpty(caIssuers) || CollectionUtil.isNonEmpty(ocspUris)) { AuthorityInformationAccess value = CaUtil.createAuthorityInformationAccess(caIssuers, ocspUris); addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes); } } if (controls.containsKey(Extension.cRLDistributionPoints) || controls.containsKey(Extension.freshestCRL)) { X500Name crlSignerSubject = (crlSignerCert == null) ? null : X500Name.getInstance(crlSignerCert.getSubjectX500Principal().getEncoded()); X500Name x500CaPrincipal = publicCaInfo.getX500Subject(); // CRLDistributionPoints extType = Extension.cRLDistributionPoints; extControl = controls.remove(extType); if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) { if (CollectionUtil.isNonEmpty(publicCaInfo.getCrlUris())) { CRLDistPoint value = CaUtil.createCrlDistributionPoints(publicCaInfo.getCrlUris(), x500CaPrincipal, crlSignerSubject); addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes); } } // FreshestCRL extType = Extension.freshestCRL; extControl = controls.remove(extType); if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) { if (CollectionUtil.isNonEmpty(publicCaInfo.getDeltaCrlUris())) { CRLDistPoint value = CaUtil.createCrlDistributionPoints(publicCaInfo.getDeltaCrlUris(), x500CaPrincipal, crlSignerSubject); addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes); } } } // BasicConstraints extType = Extension.basicConstraints; extControl = controls.remove(extType); if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) { BasicConstraints value = CaUtil.createBasicConstraints(certprofile.getCertLevel(), certprofile.getPathLenBasicConstraint()); addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes); } // KeyUsage extType = Extension.keyUsage; extControl = controls.remove(extType); if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) { Set<KeyUsage> usages = new HashSet<>(); Set<KeyUsageControl> usageOccs = certprofile.getKeyUsage(); for (KeyUsageControl k : usageOccs) { if (k.isRequired()) { usages.add(k.getKeyUsage()); } } // the optional KeyUsage will only be set if requested explicitly if (requestedExtensions != null && extControl.isRequest()) { addRequestedKeyusage(usages, requestedExtensions, usageOccs); } org.bouncycastle.asn1.x509.KeyUsage value = X509Util.createKeyUsage(usages); addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes); } // ExtendedKeyUsage extType = Extension.extendedKeyUsage; extControl = controls.remove(extType); if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) { List<ASN1ObjectIdentifier> usages = new LinkedList<>(); Set<ExtKeyUsageControl> usageOccs = certprofile.getExtendedKeyUsages(); for (ExtKeyUsageControl k : usageOccs) { if (k.isRequired()) { usages.add(k.getExtKeyUsage()); } } // the optional ExtKeyUsage will only be set if requested explicitly if (requestedExtensions != null && extControl.isRequest()) { addRequestedExtKeyusage(usages, requestedExtensions, usageOccs); } if (extControl.isCritical() && usages.contains(ObjectIdentifiers.id_anyExtendedKeyUsage)) { extControl = new ExtensionControl(false, extControl.isRequired(), extControl.isRequest()); } ExtendedKeyUsage value = X509Util.createExtendedUsage(usages); addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes); } // ocsp-nocheck extType = ObjectIdentifiers.id_extension_pkix_ocsp_nocheck; extControl = controls.remove(extType); if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) { // the extension ocsp-nocheck will only be set if requested explicitly DERNull value = DERNull.INSTANCE; addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes); } // SubjectInfoAccess extType = Extension.subjectInfoAccess; extControl = controls.remove(extType); if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) { ASN1Sequence value = null; if (requestedExtensions != null && extControl.isRequest()) { value = createSubjectInfoAccess(requestedExtensions, certprofile.getSubjectInfoAccessModes()); } addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes); } ExtensionValues subvalues = certprofile.getExtensions(Collections.unmodifiableMap(controls), requestedSubject, grantedSubject, requestedExtensions, notBefore, notAfter); Set<ASN1ObjectIdentifier> extTypes = new HashSet<>(controls.keySet()); for (ASN1ObjectIdentifier type : extTypes) { extControl = controls.remove(type); boolean addMe = addMe(type, extControl, neededExtTypes, wantedExtTypes); if (addMe) { ExtensionValue value = null; if (requestedExtensions != null && extControl.isRequest()) { Extension reqExt = requestedExtensions.getExtension(type); if (reqExt != null) { value = new ExtensionValue(reqExt.isCritical(), reqExt.getParsedValue()); } } if (value == null) { value = subvalues.getExtensionValue(type); } addExtension(values, type, value, extControl, neededExtTypes, wantedExtTypes); } } Set<ASN1ObjectIdentifier> unprocessedExtTypes = new HashSet<>(); for (ASN1ObjectIdentifier type : controls.keySet()) { if (controls.get(type).isRequired()) { unprocessedExtTypes.add(type); } } if (CollectionUtil.isNonEmpty(unprocessedExtTypes)) { throw new CertprofileException("could not add required extensions " + toString(unprocessedExtTypes)); } if (CollectionUtil.isNonEmpty(neededExtTypes)) { throw new BadCertTemplateException("could not add requested extensions " + toString(neededExtTypes)); } return values; }
From source file:org.xipki.pki.ca.server.impl.IdentifiedX509Certprofile.java
License:Open Source License
public void validate() throws CertprofileException { StringBuilder msg = new StringBuilder(); Map<ASN1ObjectIdentifier, ExtensionControl> controls = getExtensionControls(); // make sure that non-request extensions are not permitted in requests Set<ASN1ObjectIdentifier> set = new HashSet<>(); for (ASN1ObjectIdentifier type : NONE_REQUEST_EXTENSION_TYPES) { ExtensionControl control = controls.get(type); if (control != null && control.isRequest()) { set.add(type);//from ww w . j av a2 s . c om } } if (CollectionUtil.isNonEmpty(set)) { msg.append("extensions ").append(toString(set)); msg.append(" must not be contained in request, "); } X509CertLevel level = getCertLevel(); boolean ca = (level == X509CertLevel.RootCA) || (level == X509CertLevel.SubCA); // make sure that CA-only extensions are not permitted in EE certificate set.clear(); if (!ca) { set.clear(); for (ASN1ObjectIdentifier type : CA_ONLY_EXTENSION_TYPES) { if (controls.containsKey(type)) { set.add(type); } } if (CollectionUtil.isNonEmpty(set)) { msg.append("EE profile contains CA-only extensions ").append(toString(set)).append(", "); } } // make sure that critical only extensions are not marked as non-critical. set.clear(); for (ASN1ObjectIdentifier type : controls.keySet()) { ExtensionControl control = controls.get(type); if (CRITICAL_ONLY_EXTENSION_TYPES.contains(type)) { if (!control.isCritical()) { set.add(type); } } if (ca && CA_CRITICAL_ONLY_EXTENSION_TYPES.contains(type)) { if (!control.isCritical()) { set.add(type); } } } if (CollectionUtil.isNonEmpty(set)) { msg.append("critical only extensions are marked as non-critical "); msg.append(toString(set)).append(", "); } // make sure that non-critical only extensions are not marked as critical. set.clear(); for (ASN1ObjectIdentifier type : controls.keySet()) { ExtensionControl control = controls.get(type); if (NONCRITICAL_ONLY_EXTENSION_TYPES.contains(type)) { if (control.isCritical()) { set.add(type); } } } if (CollectionUtil.isNonEmpty(set)) { msg.append("non-critical extensions are marked as critical ").append(toString(set)); msg.append(", "); } // make sure that required extensions are present set.clear(); Set<ASN1ObjectIdentifier> requiredTypes = ca ? REQUIRED_CA_EXTENSION_TYPES : REQUIRED_EE_EXTENSION_TYPES; for (ASN1ObjectIdentifier type : requiredTypes) { ExtensionControl extCtrl = controls.get(type); if (extCtrl == null || !extCtrl.isRequired()) { set.add(type); } } if (level == X509CertLevel.SubCA) { ASN1ObjectIdentifier type = Extension.authorityKeyIdentifier; ExtensionControl extCtrl = controls.get(type); if (extCtrl == null || !extCtrl.isRequired()) { set.add(type); } } if (!set.isEmpty()) { msg.append("required extensions are not marked as required "); msg.append(toString(set)).append(", "); } // KeyUsage Set<KeyUsageControl> usages = getKeyUsage(); if (ca) { // make sure the CA certificate contains usage keyCertSign if (!containsKeyusage(usages, KeyUsage.keyCertSign)) { msg.append("CA profile does not contain keyUsage "); msg.append(KeyUsage.keyCertSign).append(", "); } } else { // make sure the EE certificate does not contain CA-only usages KeyUsage[] caOnlyUsages = new KeyUsage[] { KeyUsage.keyCertSign, KeyUsage.cRLSign }; Set<KeyUsage> setUsages = new HashSet<>(); for (KeyUsage caOnlyUsage : caOnlyUsages) { if (containsKeyusage(usages, caOnlyUsage)) { setUsages.add(caOnlyUsage); } } if (CollectionUtil.isNonEmpty(set)) { msg.append("EE profile contains CA-only keyUsage ").append(setUsages).append(", "); } } final int len = msg.length(); if (len > 2) { msg.delete(len - 2, len); throw new CertprofileException(msg.toString()); } }
From source file:org.xipki.pki.ca.server.impl.X509Ca.java
License:Open Source License
private X509CRL doGenerateCrl(final boolean deltaCrl, final Date thisUpdate, final Date nextUpdate, final AuditEvent event, final String msgId) throws OperationException { X509CrlSignerEntryWrapper crlSigner = getCrlSigner(); if (crlSigner == null) { throw new OperationException(ErrorCode.NOT_PERMITTED, "CRL generation is not allowed"); }//w w w . j a v a 2 s . c o m String caName = caInfo.getName(); LOG.info(" START generateCrl: ca={}, deltaCRL={}, nextUpdate={}", caName, deltaCrl, nextUpdate); event.addEventData(CaAuditConstants.NAME_crlType, deltaCrl ? "DELTA_CRL" : "FULL_CRL"); if (nextUpdate == null) { event.addEventData(CaAuditConstants.NAME_nextUpdate, "null"); } else { event.addEventData(CaAuditConstants.NAME_nextUpdate, DateUtil.toUtcTimeyyyyMMddhhmmss(nextUpdate)); if (nextUpdate.getTime() - thisUpdate.getTime() < 10 * 60 * MS_PER_SECOND) { // less than 10 minutes throw new OperationException(ErrorCode.CRL_FAILURE, "nextUpdate and thisUpdate are too close"); } } CrlControl crlControl = crlSigner.getCrlControl(); boolean successful = false; try { ConcurrentContentSigner tmpCrlSigner = crlSigner.getSigner(); CrlControl control = crlSigner.getCrlControl(); boolean directCrl; X500Name crlIssuer; if (tmpCrlSigner == null) { directCrl = true; crlIssuer = caInfo.getPublicCaInfo().getX500Subject(); } else { directCrl = false; crlIssuer = X500Name .getInstance(tmpCrlSigner.getCertificate().getSubjectX500Principal().getEncoded()); } X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(crlIssuer, thisUpdate); if (nextUpdate != null) { crlBuilder.setNextUpdate(nextUpdate); } final int numEntries = 100; X509Cert caCert = caInfo.getCertificate(); List<CertRevInfoWithSerial> revInfos; boolean isFirstCrlEntry = true; Date notExpireAt; if (control.isIncludeExpiredCerts()) { notExpireAt = new Date(0); } else { // 10 minutes buffer notExpireAt = new Date(thisUpdate.getTime() - 600L * MS_PER_SECOND); } long startId = 1; do { if (deltaCrl) { revInfos = certstore.getCertsForDeltaCrl(caCert, startId, numEntries, control.isOnlyContainsCaCerts(), control.isOnlyContainsUserCerts()); } else { revInfos = certstore.getRevokedCerts(caCert, notExpireAt, startId, numEntries, control.isOnlyContainsCaCerts(), control.isOnlyContainsUserCerts()); } long maxId = 1; for (CertRevInfoWithSerial revInfo : revInfos) { if (revInfo.getId() > maxId) { maxId = revInfo.getId(); } CrlReason reason = revInfo.getReason(); if (crlControl.isExcludeReason() && reason != CrlReason.REMOVE_FROM_CRL) { reason = CrlReason.UNSPECIFIED; } Date revocationTime = revInfo.getRevocationTime(); Date invalidityTime = revInfo.getInvalidityTime(); switch (crlControl.getInvalidityDateMode()) { case FORBIDDEN: invalidityTime = null; break; case OPTIONAL: break; case REQUIRED: if (invalidityTime == null) { invalidityTime = revocationTime; } break; default: throw new RuntimeException("unknown TripleState: " + crlControl.getInvalidityDateMode()); } BigInteger serial = revInfo.getSerial(); LOG.debug("added cert ca={} serial={} to CRL", caName, serial); if (directCrl || !isFirstCrlEntry) { if (invalidityTime != null) { crlBuilder.addCRLEntry(serial, revocationTime, reason.getCode(), invalidityTime); } else { crlBuilder.addCRLEntry(serial, revocationTime, reason.getCode()); } continue; } List<Extension> extensions = new ArrayList<>(3); if (reason != CrlReason.UNSPECIFIED) { Extension ext = createReasonExtension(reason.getCode()); extensions.add(ext); } if (invalidityTime != null) { Extension ext = createInvalidityDateExtension(invalidityTime); extensions.add(ext); } Extension ext = createCertificateIssuerExtension(caInfo.getPublicCaInfo().getX500Subject()); extensions.add(ext); crlBuilder.addCRLEntry(serial, revocationTime, new Extensions(extensions.toArray(new Extension[0]))); isFirstCrlEntry = false; } // end for startId = maxId + 1; } while (revInfos.size() >= numEntries); // end do BigInteger crlNumber = caInfo.nextCrlNumber(); event.addEventData(CaAuditConstants.NAME_crlNumber, crlNumber); boolean onlyUserCerts = crlControl.isOnlyContainsUserCerts(); boolean onlyCaCerts = crlControl.isOnlyContainsCaCerts(); if (onlyUserCerts && onlyCaCerts) { throw new RuntimeException("should not reach here, onlyUserCerts and onlyCACerts are both true"); } try { // AuthorityKeyIdentifier byte[] akiValues = directCrl ? caInfo.getPublicCaInfo().getSubjectKeyIdentifer() : crlSigner.getSubjectKeyIdentifier(); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(akiValues); crlBuilder.addExtension(Extension.authorityKeyIdentifier, false, aki); // add extension CRL Number crlBuilder.addExtension(Extension.cRLNumber, false, new ASN1Integer(crlNumber)); // IssuingDistributionPoint if (onlyUserCerts || onlyCaCerts || !directCrl) { IssuingDistributionPoint idp = new IssuingDistributionPoint((DistributionPointName) null, // distributionPoint, onlyUserCerts, // onlyContainsUserCerts, onlyCaCerts, // onlyContainsCACerts, (ReasonFlags) null, // onlySomeReasons, !directCrl, // indirectCRL, false); // onlyContainsAttributeCerts crlBuilder.addExtension(Extension.issuingDistributionPoint, true, idp); } // freshestCRL List<String> deltaCrlUris = getCaInfo().getPublicCaInfo().getDeltaCrlUris(); if (control.getDeltaCrlIntervals() > 0 && CollectionUtil.isNonEmpty(deltaCrlUris)) { CRLDistPoint cdp = CaUtil.createCrlDistributionPoints(deltaCrlUris, caInfo.getPublicCaInfo().getX500Subject(), crlIssuer); crlBuilder.addExtension(Extension.freshestCRL, false, cdp); } } catch (CertIOException ex) { LogUtil.error(LOG, ex, "crlBuilder.addExtension"); throw new OperationException(ErrorCode.INVALID_EXTENSION, ex); } addXipkiCertset(crlBuilder, deltaCrl, control, caCert, notExpireAt, onlyCaCerts, onlyUserCerts); ConcurrentContentSigner concurrentSigner = (tmpCrlSigner == null) ? caInfo.getSigner(null) : tmpCrlSigner; X509CRLHolder crlHolder; try { crlHolder = concurrentSigner.build(crlBuilder); } catch (NoIdleSignerException ex) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "NoIdleSignerException: " + ex.getMessage()); } try { X509CRL crl = X509Util.toX509Crl(crlHolder.toASN1Structure()); caInfo.getCaEntry().setNextCrlNumber(crlNumber.longValue() + 1); caInfo.commitNextCrlNo(); publishCrl(crl); successful = true; LOG.info("SUCCESSFUL generateCrl: ca={}, crlNumber={}, thisUpdate={}", caName, crlNumber, crl.getThisUpdate()); if (!deltaCrl) { // clean up the CRL cleanupCrlsWithoutException(msgId); } return crl; } catch (CRLException | CertificateException ex) { throw new OperationException(ErrorCode.CRL_FAILURE, ex); } } finally { if (!successful) { LOG.info(" FAILED generateCrl: ca={}", caName); } } }
From source file:org.xipki.pki.scep.util.ScepUtil.java
License:Open Source License
private static byte[] extractAki(final X509Certificate cert) throws CertificateEncodingException { byte[] extValue = getCoreExtValue(cert, Extension.authorityKeyIdentifier); if (extValue == null) { return null; }/*from w ww . j a v a2s .com*/ try { AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.getInstance(extValue); return aki.getKeyIdentifier(); } catch (IllegalArgumentException ex) { throw new CertificateEncodingException("invalid extension AuthorityKeyIdentifier: " + ex.getMessage()); } }
From source file:org.xwiki.crypto.pkix.internal.extension.DefaultX509ExtensionBuilder.java
License:Open Source License
@Override public X509ExtensionBuilder addAuthorityKeyIdentifier(CertifiedPublicKey issuer) { if (issuer == null) { return this; }/*from ww w . j a v a 2 s . c o m*/ return addExtension(Extension.authorityKeyIdentifier, false, new BcX509ExtensionUtils().createAuthorityKeyIdentifier(BcUtils.getX509CertificateHolder(issuer))); }