Example usage for org.bouncycastle.asn1.x509 Extension reasonCode

List of usage examples for org.bouncycastle.asn1.x509 Extension reasonCode

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 Extension reasonCode.

Prototype

ASN1ObjectIdentifier reasonCode

To view the source code for org.bouncycastle.asn1.x509 Extension reasonCode.

Click Source Link

Document

Reason code

Usage

From source file:org.ejbca.core.protocol.cmp.RevocationMessageHandler.java

License:Open Source License

public ResponseMessage handleMessage(final BaseCmpMessage msg, boolean authenticated) {
    if (LOG.isTraceEnabled()) {
        LOG.trace(">handleMessage");
    }/*from   www .  j  av  a  2s .c om*/

    CA ca = null;
    try {
        final String caDN = msg.getHeader().getRecipient().getName().toString();
        final int caId = CertTools.stringToBCDNString(caDN).hashCode();
        if (LOG.isDebugEnabled()) {
            LOG.debug("CA DN is '" + caDN + "' and resulting caId is " + caId
                    + ", after CertTools.stringToBCDNString conversion.");
        }
        ca = caSession.getCA(admin, caId);
    } catch (CADoesntExistsException e) {
        final String errMsg = "CA with DN '" + msg.getHeader().getRecipient().getName().toString()
                + "' is unknown";
        LOG.info(errMsg);
        return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                errMsg);
    } catch (AuthorizationDeniedException e) {
        LOG.info(INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()), e);
        return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                FailInfo.INCORRECT_DATA, e.getMessage());
    }

    ResponseMessage resp = null;
    // if version == 1 it is cmp1999 and we should not return a message back
    // Try to find a HMAC/SHA1 protection key
    final String keyId = CmpMessageHelper.getStringFromOctets(msg.getHeader().getSenderKID());
    ResponseStatus status = ResponseStatus.FAILURE;
    FailInfo failInfo = FailInfo.BAD_MESSAGE_CHECK;
    String failText = null;

    //Verify the authenticity of the message
    final VerifyPKIMessage messageVerifyer = new VerifyPKIMessage(ca.getCAInfo(), this.confAlias, admin,
            caSession, endEntityAccessSession, certificateStoreSession, authorizationSession,
            endEntityProfileSession, authenticationProviderSession, endEntityManagementSession,
            this.cmpConfiguration);
    ICMPAuthenticationModule authenticationModule = messageVerifyer
            .getUsedAuthenticationModule(msg.getMessage(), null, authenticated);
    if (authenticationModule == null) {
        LOG.info(messageVerifyer.getErrorMessage());
        return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                FailInfo.BAD_MESSAGE_CHECK, messageVerifyer.getErrorMessage());
    }

    // If authentication was correct, we will now try to find the certificate to revoke
    final PKIMessage pkimsg = msg.getMessage();
    final PKIBody body = pkimsg.getBody();
    final RevReqContent rr = (RevReqContent) body.getContent();
    RevDetails rd;
    try {
        rd = rr.toRevDetailsArray()[0];
    } catch (Exception e) {
        LOG.debug("Could not parse the revocation request. Trying to parse it as novosec generated message.");
        rd = CmpMessageHelper.getNovosecRevDetails(rr);
        LOG.debug("Succeeded in parsing the novosec generated request.");
    }
    final CertTemplate ct = rd.getCertDetails();
    final ASN1Integer serno = ct.getSerialNumber();
    final X500Name issuer = ct.getIssuer();
    // Get the revocation reason. 
    // For CMPv1 this can be a simple DERBitString or it can be a requested CRL Entry Extension
    // If there exists CRL Entry Extensions we will use that, because it's the only thing allowed in CMPv2
    int reason = RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED;
    final ASN1OctetString reasonoctets = rd.getCrlEntryDetails().getExtension(Extension.reasonCode)
            .getExtnValue();
    DERBitString reasonbits;
    try {
        reasonbits = new DERBitString(reasonoctets.getEncoded());
    } catch (IOException e1) {
        LOG.info(INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e1.getMessage()), e1);
        return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                FailInfo.INCORRECT_DATA, e1.getMessage());
    }
    if (reasonbits != null) {
        reason = CertTools.bitStringToRevokedCertInfo(reasonbits);
        if (LOG.isDebugEnabled()) {
            LOG.debug("CMPv1 revocation reason: " + reason);
        }
    }
    final Extensions crlExt = rd.getCrlEntryDetails();
    if (crlExt != null) {
        final Extension ext = crlExt.getExtension(Extension.reasonCode);
        if (ext != null) {
            try {
                final ASN1InputStream ai = new ASN1InputStream(ext.getExtnValue().getOctets());
                final ASN1Primitive obj = ai.readObject();
                final ASN1Enumerated crlreason = ASN1Enumerated.getInstance(obj);
                // RevokedCertInfo.REVOCATION_REASON_AACOMPROMISE are the same integer values as the CRL reason extension code
                reason = crlreason.getValue().intValue();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("CRLReason extension: " + reason);
                }
                ai.close();
            } catch (IOException e) {
                LOG.info("Exception parsin CRL reason extension: ", e);
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No CRL reason code extension present.");
            }
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No CRL entry extensions present");
        }
    }

    if ((serno != null) && (issuer != null)) {
        final String iMsg = INTRES.getLocalizedMessage("cmp.receivedrevreq", issuer.toString(),
                serno.getValue().toString(16));
        LOG.info(iMsg);
        try {
            endEntityManagementSession.revokeCert(admin, serno.getValue(), issuer.toString(), reason);
            status = ResponseStatus.SUCCESS;
        } catch (AuthorizationDeniedException e) {
            failInfo = FailInfo.NOT_AUTHORIZED;
            final String errMsg = INTRES.getLocalizedMessage("cmp.errornotauthrevoke", issuer.toString(),
                    serno.getValue().toString(16));
            failText = errMsg;
            LOG.info(failText);
        } catch (FinderException e) {
            failInfo = FailInfo.BAD_CERTIFICATE_ID;
            final String errMsg = INTRES.getLocalizedMessage("cmp.errorcertnofound", issuer.toString(),
                    serno.getValue().toString(16));
            failText = errMsg;
            // This is already info logged in endEntityManagementSession.revokeCert
            // LOG.info(failText);
        } catch (WaitingForApprovalException e) {
            status = ResponseStatus.GRANTED_WITH_MODS;
        } catch (ApprovalException e) {
            failInfo = FailInfo.BAD_REQUEST;
            final String errMsg = INTRES.getLocalizedMessage("cmp.erroralreadyrequested");
            failText = errMsg;
            LOG.info(failText);
        } catch (AlreadyRevokedException e) {
            failInfo = FailInfo.BAD_REQUEST;
            final String errMsg = INTRES.getLocalizedMessage("cmp.erroralreadyrevoked");
            failText = errMsg;
            // This is already info logged in endEntityManagementSession.revokeCert
            // LOG.info(failText);
        }
    } else {
        failInfo = FailInfo.BAD_CERTIFICATE_ID;
        final String errMsg = INTRES.getLocalizedMessage("cmp.errormissingissuerrevoke", issuer.toString(),
                serno.getValue().toString(16));
        failText = errMsg;
        LOG.info(failText);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating a PKI revocation message response");
    }
    final CmpRevokeResponseMessage rresp = new CmpRevokeResponseMessage();
    rresp.setRecipientNonce(msg.getSenderNonce());
    rresp.setSenderNonce(new String(Base64.encode(CmpMessageHelper.createSenderNonce())));
    rresp.setSender(msg.getRecipient());
    rresp.setRecipient(msg.getSender());
    rresp.setTransactionId(msg.getTransactionId());
    rresp.setFailInfo(failInfo);
    rresp.setFailText(failText);
    rresp.setStatus(status);

    if (StringUtils.equals(responseProtection, "pbe")) {
        final HMACAuthenticationModule hmacmodule = (HMACAuthenticationModule) authenticationModule;
        final String owfAlg = hmacmodule.getCmpPbeVerifyer().getOwfOid();
        final String macAlg = hmacmodule.getCmpPbeVerifyer().getMacOid();
        final int iterationCount = 1024;
        final String cmpRaAuthSecret = hmacmodule.getAuthenticationString();

        if ((owfAlg != null) && (macAlg != null) && (keyId != null) && (cmpRaAuthSecret != null)) {
            // Set all protection parameters
            if (LOG.isDebugEnabled()) {
                LOG.debug(responseProtection + ", " + owfAlg + ", " + macAlg + ", " + keyId + ", "
                        + cmpRaAuthSecret);
            }
            rresp.setPbeParameters(keyId, cmpRaAuthSecret, owfAlg, macAlg, iterationCount);
        }
    } else if (StringUtils.equals(responseProtection, "signature")) {
        try {
            final CryptoToken cryptoToken = cryptoTokenSession
                    .getCryptoToken(ca.getCAToken().getCryptoTokenId());
            final String aliasCertSign = ca.getCAToken()
                    .getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
            rresp.setSignKeyInfo(ca.getCertificateChain(), cryptoToken.getPrivateKey(aliasCertSign),
                    cryptoToken.getSignProviderName());
            if (msg.getHeader().getProtectionAlg() != null) {
                rresp.setPreferredDigestAlg(AlgorithmTools
                        .getDigestFromSigAlg(msg.getHeader().getProtectionAlg().getAlgorithm().getId()));
            }
        } catch (CryptoTokenOfflineException e) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    }
    resp = rresp;
    try {
        resp.create();
    } catch (InvalidKeyException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    } catch (NoSuchAlgorithmException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    } catch (NoSuchProviderException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    } catch (CertificateEncodingException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    } catch (CRLException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    }

    return resp;
}

From source file:org.ejbca.ui.cli.ca.CaImportCRLCommand.java

License:Open Source License

/**
 * Return a CRL reason code from a CRL entry, or RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED if a reson code extension does not exist
 *///w w  w  . j a  v  a2  s. c  o  m
private int getCRLReasonValue(final X509CRLEntry entry) throws IOException {
    int reason = RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED;
    if ((entry != null) && entry.hasExtensions()) {
        final byte[] bytes = entry.getExtensionValue(Extension.reasonCode.getId());
        if (bytes != null) {
            ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bytes));
            final ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
            aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
            final ASN1Primitive obj = aIn.readObject();
            if (obj != null) {
                try {
                    final ASN1Enumerated ext = (ASN1Enumerated) obj;
                    reason = ext.getValue().intValue();
                } catch (ClassCastException e) {
                    // this was not a reason code, very strange
                    log.info("Reason code extension did not contain DEREnumerated, is this CRL corrupt?. "
                            + obj.getClass().getName());
                }
            }
        }
    }
    return reason;
}

From source file:org.ejbca.ui.cmpclient.commands.RevocationRequestCommand.java

License:Open Source License

@Override
public PKIMessage generatePKIMessage(ParameterContainer parameters) throws Exception {
    boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name("CN=foo");
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));
    BigInteger serno = new BigInteger(parameters.get(SERNO_KEY), 16);

    if (verbose) {
        log.info("Creating revocation request with: SubjectDN=" + userDN.toString());
        log.info("Creating revocation request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating revocation request with: CertSerno=" + serno.toString(16));
    }/*from  ww w .j av a 2  s .c  o  m*/

    byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce();
    byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce();

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setIssuer(issuerDN);
    myCertTemplate.setSubject(userDN);
    myCertTemplate.setSerialNumber(new ASN1Integer(serno));

    ExtensionsGenerator extgen = new ExtensionsGenerator();
    extgen.addExtension(Extension.reasonCode, false, getCRLReason(parameters.get(REVOCATION_REASON_KEY)));

    Extensions exts = extgen.generate();

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(myCertTemplate.build());
    v.add(exts);
    ASN1Sequence seq = new DERSequence(v);

    RevDetails myRevDetails = RevDetails.getInstance(seq);

    RevReqContent myRevReqContent = new RevReqContent(myRevDetails);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(issuerDN));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(null);
    myPKIHeader.setSenderKID(new byte[0]);

    PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, myRevReqContent); // revocation request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    return myPKIMessage;
}

From source file:org.xipki.ca.client.impl.X509CmpRequestor.java

License:Open Source License

private PKIMessage buildRevokeCertRequest(final RevokeCertRequestType request) throws CmpRequestorException {
    PKIHeader header = buildPKIHeader(null);

    List<RevokeCertRequestEntryType> requestEntries = request.getRequestEntries();
    List<RevDetails> revDetailsArray = new ArrayList<>(requestEntries.size());
    for (RevokeCertRequestEntryType requestEntry : requestEntries) {
        CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
        certTempBuilder.setIssuer(requestEntry.getIssuer());
        certTempBuilder.setSerialNumber(new ASN1Integer(requestEntry.getSerialNumber()));

        Date invalidityDate = requestEntry.getInvalidityDate();
        Extension[] extensions = new Extension[invalidityDate == null ? 1 : 2];

        try {//from w  ww .j a  v  a 2s .c o m
            ASN1Enumerated reason = new ASN1Enumerated(requestEntry.getReason());
            extensions[0] = new Extension(Extension.reasonCode, true, new DEROctetString(reason.getEncoded()));

            if (invalidityDate != null) {
                ASN1GeneralizedTime time = new ASN1GeneralizedTime(invalidityDate);
                extensions[1] = new Extension(Extension.invalidityDate, true,
                        new DEROctetString(time.getEncoded()));
            }
        } catch (IOException e) {
            throw new CmpRequestorException(e.getMessage(), e);
        }
        Extensions exts = new Extensions(extensions);

        RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts);
        revDetailsArray.add(revDetails);
    }

    RevReqContent content = new RevReqContent(revDetailsArray.toArray(new RevDetails[0]));
    PKIBody body = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content);
    return new PKIMessage(header, body);
}

From source file:org.xipki.ca.client.impl.X509CmpRequestor.java

License:Open Source License

private PKIMessage buildUnrevokeOrRemoveCertRequest(final UnrevokeOrRemoveCertRequestType request,
        final int reasonCode) throws CmpRequestorException {
    PKIHeader header = buildPKIHeader(null);

    List<IssuerSerialEntryType> requestEntries = request.getRequestEntries();
    List<RevDetails> revDetailsArray = new ArrayList<>(requestEntries.size());
    for (IssuerSerialEntryType requestEntry : requestEntries) {
        CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
        certTempBuilder.setIssuer(requestEntry.getIssuer());
        certTempBuilder.setSerialNumber(new ASN1Integer(requestEntry.getSerialNumber()));

        Extension[] extensions = new Extension[1];

        try {/*from   w ww .j av a 2 s  . com*/
            ASN1Enumerated reason = new ASN1Enumerated(reasonCode);
            extensions[0] = new Extension(Extension.reasonCode, true, new DEROctetString(reason.getEncoded()));
        } catch (IOException e) {
            throw new CmpRequestorException(e.getMessage(), e);
        }
        Extensions exts = new Extensions(extensions);

        RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts);
        revDetailsArray.add(revDetails);
    }

    RevReqContent content = new RevReqContent(revDetailsArray.toArray(new RevDetails[0]));
    PKIBody body = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content);
    return new PKIMessage(header, body);
}

From source file:org.xipki.ca.server.impl.X509CA.java

License:Open Source License

private static Extension createReasonExtension(final int reasonCode) {
    org.bouncycastle.asn1.x509.CRLReason crlReason = org.bouncycastle.asn1.x509.CRLReason.lookup(reasonCode);

    try {//from w  w  w .j  ava2  s  .c  o  m
        return new Extension(Extension.reasonCode, false, crlReason.getEncoded());
    } catch (IOException e) {
        throw new IllegalArgumentException("error encoding reason: " + e.getMessage(), e);
    }
}

From source file:org.xipki.ca.server.impl.X509CACmpResponder.java

License:Open Source License

private PKIBody revokeOrUnrevokeOrRemoveCertificates(final RevReqContent rr, final AuditEvent auditEvent,
        final Permission permission) {
    RevDetails[] revContent = rr.toRevDetailsArray();

    RevRepContentBuilder repContentBuilder = new RevRepContentBuilder();

    final int n = revContent.length;
    // test the reques
    for (int i = 0; i < n; i++) {
        RevDetails revDetails = revContent[i];

        CertTemplate certDetails = revDetails.getCertDetails();
        X500Name issuer = certDetails.getIssuer();
        ASN1Integer serialNumber = certDetails.getSerialNumber();

        try {/* w  w  w.jav  a2s .co m*/
            X500Name caSubject = getCA().getCAInfo().getCertificate().getSubjectAsX500Name();

            if (issuer == null) {
                return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate,
                        "issuer is not present");
            } else if (issuer.equals(caSubject) == false) {
                return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate,
                        "issuer not targets at the CA");
            } else if (serialNumber == null) {
                return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate,
                        "serialNumber is not present");
            } else if (certDetails.getSigningAlg() != null || certDetails.getValidity() != null
                    || certDetails.getSubject() != null || certDetails.getPublicKey() != null
                    || certDetails.getIssuerUID() != null || certDetails.getSubjectUID() != null
                    || certDetails.getExtensions() != null) {
                return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate,
                        "only version, issuer and serialNumber in RevDetails.certDetails are allowed, "
                                + "but more is specified");
            }
        } catch (IllegalArgumentException e) {
            return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.badRequest,
                    "the request is not invalid");
        }
    }

    for (int i = 0; i < n; i++) {
        AuditChildEvent childAuditEvent = null;
        if (auditEvent != null) {
            childAuditEvent = new AuditChildEvent();
            auditEvent.addChildAuditEvent(childAuditEvent);
        }

        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);

        if (childAuditEvent != null) {
            AuditEventData eventData = new AuditEventData("serialNumber", snBigInt.toString());
            childAuditEvent.addEventData(eventData);
        }

        PKIStatusInfo status;

        try {
            Object returnedObj = null;
            X509CA ca = getCA();
            if (Permission.UNREVOKE_CERT == permission) {
                // unrevoke
                returnedObj = ca.unrevokeCertificate(snBigInt);
            } else if (Permission.REMOVE_CERT == permission) {
                // remove
                returnedObj = ca.removeCertificate(snBigInt);
            } 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) extValue).getValue().intValue();
                        reason = CRLReason.forReasonCode(reasonCode);
                    }

                    extId = Extension.invalidityDate;
                    extValue = crlDetails.getExtensionParsedValue(extId);
                    if (extValue != null) {
                        try {
                            invalidityDate = ((ASN1GeneralizedTime) extValue).getDate();
                        } catch (ParseException e) {
                            throw new OperationException(ErrorCode.INVALID_EXTENSION,
                                    "invalid extension " + extId.getId());
                        }
                    }
                } // end if(crlDetails)

                if (reason == null) {
                    reason = CRLReason.UNSPECIFIED;
                }

                if (childAuditEvent != null) {
                    childAuditEvent.addEventData(new AuditEventData("reason", reason.getDescription()));
                    if (invalidityDate != null) {
                        String value;
                        synchronized (dateFormat) {
                            value = dateFormat.format(invalidityDate);
                        }
                        childAuditEvent.addEventData(new AuditEventData("invalidityDate", value));
                    }
                }

                returnedObj = ca.revokeCertificate(snBigInt, reason, invalidityDate);
            } // end if(permission)

            if (returnedObj == null) {
                throw new OperationException(ErrorCode.UNKNOWN_CERT, "cert not exists");
            }

            status = new PKIStatusInfo(PKIStatus.granted);
            if (childAuditEvent != null) {
                childAuditEvent.setStatus(AuditStatus.SUCCESSFUL);
            }
        } catch (OperationException e) {
            ErrorCode code = e.getErrorCode();
            LOG.warn("{} certificate, OperationException: code={}, message={}",
                    new Object[] { permission.name(), code.name(), e.getErrorMessage() });

            String auditMessage;

            int failureInfo;
            switch (code) {
            case BAD_REQUEST:
                failureInfo = PKIFailureInfo.badRequest;
                auditMessage = "BAD_REQUEST";
                break;
            case CERT_REVOKED:
                failureInfo = PKIFailureInfo.certRevoked;
                auditMessage = "CERT_REVOKED";
                break;
            case CERT_UNREVOKED:
                failureInfo = PKIFailureInfo.notAuthorized;
                auditMessage = "CERT_UNREVOKED";
                break;
            case DATABASE_FAILURE:
                failureInfo = PKIFailureInfo.systemFailure;
                auditMessage = "DATABASE_FAILURE";
                break;
            case INVALID_EXTENSION:
                failureInfo = PKIFailureInfo.unacceptedExtension;
                auditMessage = "INVALID_EXTENSION";
                break;
            case INSUFFICIENT_PERMISSION:
                failureInfo = PKIFailureInfo.notAuthorized;
                auditMessage = "INSUFFICIENT_PERMISSION";
                break;
            case NOT_PERMITTED:
                failureInfo = PKIFailureInfo.notAuthorized;
                auditMessage = "NOT_PERMITTED";
                break;
            case SYSTEM_FAILURE:
                failureInfo = PKIFailureInfo.systemFailure;
                auditMessage = "System_Failure";
                break;
            case SYSTEM_UNAVAILABLE:
                failureInfo = PKIFailureInfo.systemUnavail;
                auditMessage = "System_Unavailable";
                break;
            case UNKNOWN_CERT:
                failureInfo = PKIFailureInfo.badCertId;
                auditMessage = "UNKNOWN_CERT";
                break;
            default:
                failureInfo = PKIFailureInfo.systemFailure;
                auditMessage = "InternalErrorCode " + e.getErrorCode();
                break;
            } // end switch(code)

            if (childAuditEvent != null) {
                childAuditEvent.setStatus(AuditStatus.FAILED);
                childAuditEvent.addEventData(new AuditEventData("message", auditMessage));
            }

            String errorMessage;
            switch (code) {
            case DATABASE_FAILURE:
            case SYSTEM_FAILURE:
                errorMessage = code.name();
                break;
            default:
                errorMessage = code.name() + ": " + e.getErrorMessage();
                break;
            } // end switch(code)

            status = generateCmpRejectionStatus(failureInfo, errorMessage);
        } // end try

        repContentBuilder.add(status, certId);
    } // end for

    return new PKIBody(PKIBody.TYPE_REVOCATION_REP, repContentBuilder.build());
}

From source file:org.xipki.ca.server.impl.X509CACmpResponder.java

License:Open Source License

private PKIBody cmpRevokeOrUnrevokeOrRemoveCertificates(final PKIHeaderBuilder respHeader,
        final CmpControl cmpControl, final PKIHeader reqHeader, final PKIBody reqBody,
        final CmpRequestorInfo requestor, final String user, final ASN1OctetString tid,
        final AuditEvent auditEvent) throws InsuffientPermissionException {
    Permission requiredPermission = null;
    boolean allRevdetailsOfSameType = true;

    RevReqContent rr = (RevReqContent) reqBody.getContent();
    RevDetails[] revContent = rr.toRevDetailsArray();

    int n = revContent.length;
    for (int i = 0; i < n; i++) {
        RevDetails revDetails = revContent[i];
        Extensions crlDetails = revDetails.getCrlEntryDetails();
        int reasonCode = CRLReason.UNSPECIFIED.getCode();
        if (crlDetails != null) {
            ASN1ObjectIdentifier extId = Extension.reasonCode;
            ASN1Encodable extValue = crlDetails.getExtensionParsedValue(extId);
            if (extValue != null) {
                reasonCode = ((ASN1Enumerated) extValue).getValue().intValue();
            }//  w  ww.  j av a 2 s . co  m
        }

        if (reasonCode == XipkiCmpConstants.CRL_REASON_REMOVE) {
            if (requiredPermission == null) {
                addAutitEventType(auditEvent, "CERT_REMOVE");
                requiredPermission = Permission.REMOVE_CERT;
            } else if (requiredPermission != Permission.REMOVE_CERT) {
                allRevdetailsOfSameType = false;
                break;
            }
        } else if (reasonCode == CRLReason.REMOVE_FROM_CRL.getCode()) {
            if (requiredPermission == null) {
                addAutitEventType(auditEvent, "CERT_UNREVOKE");
                requiredPermission = Permission.UNREVOKE_CERT;
            } else if (requiredPermission != Permission.UNREVOKE_CERT) {
                allRevdetailsOfSameType = false;
                break;
            }
        } else {
            if (requiredPermission == null) {
                addAutitEventType(auditEvent, "CERT_REVOKE");
                requiredPermission = Permission.REVOKE_CERT;
            } else if (requiredPermission != Permission.REVOKE_CERT) {
                allRevdetailsOfSameType = false;
                break;
            }
        }
    }

    if (allRevdetailsOfSameType == false) {
        ErrorMsgContent emc = new ErrorMsgContent(new PKIStatusInfo(PKIStatus.rejection,
                new PKIFreeText("not all revDetails are of the same type"),
                new PKIFailureInfo(PKIFailureInfo.badRequest)));

        return new PKIBody(PKIBody.TYPE_ERROR, emc);
    } else {
        checkPermission(requestor, requiredPermission);
        return revokeOrUnrevokeOrRemoveCertificates(rr, auditEvent, requiredPermission);
    }
}

From source file:org.xipki.commons.console.karaf.completer.ExtensionNameCompleter.java

License:Open Source License

public ExtensionNameCompleter() {
    List<ASN1ObjectIdentifier> oids = new LinkedList<>();
    oids.add(ObjectIdentifiers.id_extension_pkix_ocsp_nocheck);
    oids.add(ObjectIdentifiers.id_extension_admission);
    oids.add(Extension.auditIdentity);
    oids.add(Extension.authorityInfoAccess);
    oids.add(Extension.authorityKeyIdentifier);
    oids.add(Extension.basicConstraints);
    oids.add(Extension.biometricInfo);
    oids.add(Extension.certificateIssuer);
    oids.add(Extension.certificatePolicies);
    oids.add(Extension.cRLDistributionPoints);
    oids.add(Extension.cRLNumber);
    oids.add(Extension.deltaCRLIndicator);
    oids.add(Extension.extendedKeyUsage);
    oids.add(Extension.freshestCRL);
    oids.add(Extension.inhibitAnyPolicy);
    oids.add(Extension.instructionCode);
    oids.add(Extension.invalidityDate);
    oids.add(Extension.issuerAlternativeName);
    oids.add(Extension.issuingDistributionPoint);
    oids.add(Extension.keyUsage);
    oids.add(Extension.logoType);
    oids.add(Extension.nameConstraints);
    oids.add(Extension.noRevAvail);
    oids.add(Extension.policyConstraints);
    oids.add(Extension.policyMappings);
    oids.add(Extension.privateKeyUsagePeriod);
    oids.add(Extension.qCStatements);
    oids.add(Extension.reasonCode);
    oids.add(Extension.subjectAlternativeName);
    oids.add(Extension.subjectDirectoryAttributes);
    oids.add(Extension.subjectInfoAccess);
    oids.add(Extension.subjectKeyIdentifier);
    oids.add(Extension.targetInformation);
    oids.add(ObjectIdentifiers.id_pe_tlsfeature);

    StringBuilder enums = new StringBuilder();

    for (ASN1ObjectIdentifier oid : oids) {
        String name = ObjectIdentifiers.getName(oid);
        if (StringUtil.isBlank(name)) {
            name = oid.getId();//  w w  w  .  ja  v  a2 s . co  m
        }
        enums.append(name).append(",");
    }
    enums.deleteCharAt(enums.length() - 1);
    setTokens(enums.toString());
}

From source file:org.xipki.console.karaf.impl.completer.ExtensionNameCompleterImpl.java

License:Open Source License

public ExtensionNameCompleterImpl() {
    List<ASN1ObjectIdentifier> oids = new LinkedList<>();
    oids.add(ObjectIdentifiers.id_extension_pkix_ocsp_nocheck);
    oids.add(ObjectIdentifiers.id_extension_admission);
    oids.add(Extension.auditIdentity);
    oids.add(Extension.authorityInfoAccess);
    oids.add(Extension.authorityKeyIdentifier);
    oids.add(Extension.basicConstraints);
    oids.add(Extension.biometricInfo);
    oids.add(Extension.certificateIssuer);
    oids.add(Extension.certificatePolicies);
    oids.add(Extension.cRLDistributionPoints);
    oids.add(Extension.cRLNumber);
    oids.add(Extension.deltaCRLIndicator);
    oids.add(Extension.extendedKeyUsage);
    oids.add(Extension.freshestCRL);
    oids.add(Extension.inhibitAnyPolicy);
    oids.add(Extension.instructionCode);
    oids.add(Extension.invalidityDate);
    oids.add(Extension.issuerAlternativeName);
    oids.add(Extension.issuingDistributionPoint);
    oids.add(Extension.keyUsage);
    oids.add(Extension.logoType);
    oids.add(Extension.nameConstraints);
    oids.add(Extension.noRevAvail);
    oids.add(Extension.policyConstraints);
    oids.add(Extension.policyMappings);
    oids.add(Extension.privateKeyUsagePeriod);
    oids.add(Extension.qCStatements);
    oids.add(Extension.reasonCode);
    oids.add(Extension.subjectAlternativeName);
    oids.add(Extension.subjectDirectoryAttributes);
    oids.add(Extension.subjectInfoAccess);
    oids.add(Extension.subjectKeyIdentifier);
    oids.add(Extension.targetInformation);

    StringBuilder enums = new StringBuilder();

    for (ASN1ObjectIdentifier oid : oids) {
        String name = ObjectIdentifiers.getName(oid);
        if (StringUtil.isBlank(name)) {
            name = oid.getId();//from  ww w .j av  a  2s . c  o  m
        }
        enums.append(name).append(",");
    }
    enums.deleteCharAt(enums.length() - 1);
    setTokens(enums.toString());
}