Example usage for org.bouncycastle.asn1.cmp PKIStatus REJECTION

List of usage examples for org.bouncycastle.asn1.cmp PKIStatus REJECTION

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cmp PKIStatus REJECTION.

Prototype

int REJECTION

To view the source code for org.bouncycastle.asn1.cmp PKIStatus REJECTION.

Click Source Link

Usage

From source file:be.apsu.extremon.probes.tsp.TSPProbe.java

License:Open Source License

public void probe_forever() {
    double start = 0, end = 0;
    BigInteger requestNonce;/*from w  ww.  j ava  2  s.c o m*/
    byte[] requestHashedMessage = new byte[20];
    List<String> comments = new ArrayList<String>();
    STATE result = STATE.OK;

    log("running");

    this.running = true;
    while (this.running) {
        comments.clear();
        this.random.nextBytes(requestHashedMessage);
        requestNonce = new BigInteger(512, this.random);
        TimeStampRequest request = requestGenerator.generate(TSPAlgorithms.SHA1, requestHashedMessage,
                requestNonce);

        end = 0;
        start = System.currentTimeMillis();

        try {
            TimeStampResponse response = probe(request);

            switch (response.getStatus()) {
            case PKIStatus.GRANTED:
                comments.add("granted");
                result = STATE.OK;
                break;
            case PKIStatus.GRANTED_WITH_MODS:
                comments.add("granted with modifications");
                result = STATE.WARNING;
                break;
            case PKIStatus.REJECTION:
                comments.add("rejected");
                result = STATE.ALERT;
                break;
            case PKIStatus.WAITING:
                comments.add("waiting");
                result = STATE.ALERT;
                break;
            case PKIStatus.REVOCATION_WARNING:
                comments.add("revocation warning");
                result = STATE.WARNING;
                break;
            case PKIStatus.REVOCATION_NOTIFICATION:
                comments.add("revocation notification");
                result = STATE.ALERT;
                break;
            default:
                comments.add("response outside RFC3161");
                result = STATE.ALERT;
                break;
            }

            if (response.getStatus() >= 2)
                comments.add(response.getFailInfo() != null ? response.getFailInfo().getString()
                        : "(missing failinfo)");

            if (response.getStatusString() != null)
                comments.add(response.getStatusString());

            end = System.currentTimeMillis();
            TimeStampToken timestampToken = response.getTimeStampToken();

            timestampToken.validate(this.signerVerifier);
            comments.add("validated");

            AttributeTable table = timestampToken.getSignedAttributes();
            TimeStampTokenInfo tokenInfo = timestampToken.getTimeStampInfo();
            BigInteger responseNonce = tokenInfo.getNonce();
            byte[] responseHashedMessage = tokenInfo.getMessageImprintDigest();
            long genTimeSeconds = (tokenInfo.getGenTime().getTime()) / 1000;
            long currentTimeSeconds = (long) (start + ((end - start) / 2)) / 1000;

            put("clockskew", (genTimeSeconds - currentTimeSeconds) * 1000);

            if (Math.abs((genTimeSeconds - currentTimeSeconds)) > 1) {
                comments.add("clock skew > 1s");
                result = STATE.ALERT;
            }

            Store responseCertificatesStore = timestampToken.toCMSSignedData().getCertificates();
            @SuppressWarnings("unchecked")
            Collection<X509CertificateHolder> certs = responseCertificatesStore.getMatches(null);
            for (X509CertificateHolder certificate : certs) {
                AlgorithmIdentifier sigalg = certificate.getSignatureAlgorithm();
                if (!(oidsAllowed.contains(sigalg.getAlgorithm().getId()))) {
                    String cleanDn = certificate.getSubject().toString().replace("=", ":");
                    comments.add("signature cert \"" + cleanDn + "\" signed using "
                            + getName(sigalg.getAlgorithm().getId()));
                    result = STATE.ALERT;
                }
            }

            if (!responseNonce.equals(requestNonce)) {
                comments.add("nonce modified");
                result = STATE.ALERT;
            }

            if (!Arrays.equals(responseHashedMessage, requestHashedMessage)) {
                comments.add("hashed message modified");
                result = STATE.ALERT;
            }

            if (table.get(PKCSObjectIdentifiers.id_aa_signingCertificate) == null) {
                comments.add("signingcertificate missing");
                result = STATE.ALERT;
            }
        } catch (TSPException tspEx) {
            comments.add("validation failed");
            comments.add("tspexception-" + tspEx.getMessage().toLowerCase());
            result = STATE.ALERT;
        } catch (IOException iox) {
            comments.add("unable to obtain response");
            comments.add("ioexception-" + iox.getMessage().toLowerCase());
            result = STATE.ALERT;
        } catch (Exception ex) {
            comments.add("unhandled exception");
            result = STATE.ALERT;
        } finally {
            if (end == 0)
                end = System.currentTimeMillis();
        }

        put(RESULT_SUFFIX, result);
        put(RESULT_COMMENT_SUFFIX, StringUtils.join(comments, "|"));
        put("responsetime", (end - start));

        try {
            Thread.sleep(this.delay);
        } catch (InterruptedException ex) {
            log("interrupted");
        }
    }
}

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

License:Open Source License

@Override
public boolean create() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    final PKIHeaderBuilder myPKIHeaderBuilder = CmpMessageHelper.createPKIHeaderBuilder(getSender(),
            getRecipient(), getSenderNonce(), getRecipientNonce(), getTransactionId());
    boolean pbeProtected = (getPbeDigestAlg() != null) && (getPbeMacAlg() != null) && (getPbeKeyId() != null)
            && (getPbeKey() != null);
    if (pbeProtected) {
        myPKIHeaderBuilder.setProtectionAlg(new AlgorithmIdentifier(CMPObjectIdentifiers.passwordBasedMac));
    }/* w  ww.jav  a2 s.c om*/
    final PKIHeader myPKIHeader = myPKIHeaderBuilder.build();

    PKIStatusInfo myPKIStatusInfo = new PKIStatusInfo(PKIStatus.rejection);
    if (failInfo != null && failText != null) {
        myPKIStatusInfo = new PKIStatusInfo(PKIStatus.rejection, new PKIFreeText(new DERUTF8String(failText)),
                CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
    } else if (failText != null) {
        myPKIStatusInfo = new PKIStatusInfo(PKIStatus.rejection, new PKIFreeText(new DERUTF8String(failText)));
    }

    PKIBody myPKIBody = null;
    log.debug("Create error message from requestType: " + requestType);
    if (requestType == 0 || requestType == 2) {
        myPKIBody = CmpMessageHelper.createCertRequestRejectBody(myPKIStatusInfo, requestId, requestType);
    } else {
        ErrorMsgContent myErrorContent = new ErrorMsgContent(myPKIStatusInfo);
        myPKIBody = new PKIBody(23, myErrorContent); // 23 = error                  
    }
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader, myPKIBody);
    if (pbeProtected) {
        responseMessage = CmpMessageHelper.protectPKIMessageWithPBE(myPKIMessage, getPbeKeyId(), getPbeKey(),
                getPbeDigestAlg(), getPbeMacAlg(), getPbeIterationCount());
    } else {
        responseMessage = CmpMessageHelper.pkiMessageToByteArray(myPKIMessage);
    }
    return true;
}

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

License:Open Source License

@Override
public boolean create() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    boolean ret = false;
    // Some general stuff, common for all types of messages
    String issuer = null;//from w w w  .  j a  v  a2  s  .  c  o  m
    String subject = null;
    if (cert != null) {
        X509Certificate x509cert = (X509Certificate) cert;
        issuer = x509cert.getIssuerDN().getName();
        subject = x509cert.getSubjectDN().getName();
    } else if ((signCertChain != null) && (signCertChain.size() > 0)) {
        issuer = ((X509Certificate) signCertChain.iterator().next()).getSubjectDN().getName();
        subject = "CN=fooSubject";
    } else {
        issuer = "CN=fooIssuer";
        subject = "CN=fooSubject";
    }

    final GeneralName issuerName = new GeneralName(new X500Name(issuer));
    final GeneralName subjectName = new GeneralName(new X500Name(subject));
    final PKIHeaderBuilder myPKIHeader = CmpMessageHelper.createPKIHeaderBuilder(issuerName, subjectName,
            senderNonce, recipientNonce, transactionId);
    PKIBody myPKIBody = null;
    final PKIMessage myPKIMessage;

    try {
        if (status.equals(ResponseStatus.SUCCESS)) {
            if (cert != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Creating a CertRepMessage 'accepted'");
                }
                PKIStatusInfo myPKIStatusInfo = new PKIStatusInfo(PKIStatus.granted); // 0 = accepted
                ASN1InputStream certASN1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(cert.getEncoded()));
                ASN1InputStream cacertASN1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(cacert.getEncoded()));
                try {
                    try {
                        CMPCertificate cmpcert = CMPCertificate.getInstance(certASN1InputStream.readObject());
                        CertOrEncCert retCert = new CertOrEncCert(cmpcert);
                        CertifiedKeyPair myCertifiedKeyPair = new CertifiedKeyPair(retCert);
                        CertResponse myCertResponse = new CertResponse(new ASN1Integer(requestId),
                                myPKIStatusInfo, myCertifiedKeyPair, null);

                        CertResponse[] certRespos = { myCertResponse };
                        CMPCertificate[] caPubs = {
                                CMPCertificate.getInstance(cacertASN1InputStream.readObject()) };

                        CertRepMessage myCertRepMessage = new CertRepMessage(caPubs, certRespos);

                        int respType = requestType + 1; // 1 = intitialization response, 3 = certification response etc
                        if (log.isDebugEnabled()) {
                            log.debug("Creating response body of type " + respType);
                        }
                        myPKIBody = new PKIBody(respType, myCertRepMessage);
                    } finally {
                        certASN1InputStream.close();
                        cacertASN1InputStream.close();
                    }
                } catch (IOException e) {
                    throw new IllegalStateException("Unexpected IOException caught.", e);
                }
            }
        } else if (status.equals(ResponseStatus.FAILURE)) {
            if (log.isDebugEnabled()) {
                log.debug("Creating a CertRepMessage 'rejected'");
            }
            // Create a failure message
            ASN1EncodableVector statusInfoV = new ASN1EncodableVector();
            statusInfoV.add(ASN1Integer.getInstance(PKIStatus.rejection.toASN1Primitive()));
            if (failText != null) {
                statusInfoV.add(new PKIFreeText(new DERUTF8String(failText)));
            }
            statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
            PKIStatusInfo myPKIStatusInfo = PKIStatusInfo
                    .getInstance(ASN1Sequence.getInstance(new DERSequence(statusInfoV)));
            myPKIBody = CmpMessageHelper.createCertRequestRejectBody(myPKIStatusInfo, requestId, requestType);

        } else {
            if (log.isDebugEnabled()) {
                log.debug("Creating a 'waiting' message?");
            }
            // Not supported, lets create a PKIError failure instead
            // Create a failure message
            ASN1EncodableVector statusInfoV = new ASN1EncodableVector();
            statusInfoV.add(PKIStatus.rejection); // 2 = rejection
            if (failText != null) {
                statusInfoV.add(new PKIFreeText(new DERUTF8String(failText)));
            }
            statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
            PKIStatusInfo myPKIStatusInfo = PKIStatusInfo.getInstance(new DERSequence(statusInfoV));

            ErrorMsgContent myErrorContent = new ErrorMsgContent(myPKIStatusInfo);
            myPKIBody = new PKIBody(23, myErrorContent); // 23 = error                
        }

        if ((pbeKeyId != null) && (pbeKey != null) && (pbeDigestAlg != null) && (pbeMacAlg != null)) {
            myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(CMPObjectIdentifiers.passwordBasedMac));
            PKIHeader header = myPKIHeader.build();
            myPKIMessage = new PKIMessage(header, myPKIBody);
            responseMessage = CmpMessageHelper.protectPKIMessageWithPBE(myPKIMessage, pbeKeyId, pbeKey,
                    pbeDigestAlg, pbeMacAlg, pbeIterationCount);
        } else {
            myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(digest));
            PKIHeader header = myPKIHeader.build();
            myPKIMessage = new PKIMessage(header, myPKIBody);
            responseMessage = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, signKey, digest,
                    provider);
        }

        ret = true;

    } catch (CertificateEncodingException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (InvalidKeyException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (NoSuchProviderException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (NoSuchAlgorithmException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (SecurityException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (SignatureException e) {
        log.error("Error creating CertRepMessage: ", e);
    }

    return ret;
}

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

License:Open Source License

@Override
public boolean create() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    final PKIHeaderBuilder myPKIHeader = CmpMessageHelper.createPKIHeaderBuilder(getSender(), getRecipient(),
            getSenderNonce(), getRecipientNonce(), getTransactionId());
    PKIStatusInfo myPKIStatusInfo = new PKIStatusInfo(PKIStatus.granted); // 0 = accepted
    if (status != ResponseStatus.SUCCESS && status != ResponseStatus.GRANTED_WITH_MODS) {
        if (log.isDebugEnabled()) {
            log.debug("Creating a rejection message");
        }/*  w  ww  .j a va 2  s  . co  m*/
        myPKIStatusInfo = new PKIStatusInfo(PKIStatus.rejection, null,
                CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
        if (failText != null && failInfo != null) {
            myPKIStatusInfo = new PKIStatusInfo(PKIStatus.rejection, new PKIFreeText(failText),
                    CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
        }
    }
    RevRepContentBuilder revBuilder = new RevRepContentBuilder();
    revBuilder.add(myPKIStatusInfo);
    RevRepContent myRevrepMessage = revBuilder.build();

    PKIBody myPKIBody = new PKIBody(CmpPKIBodyConstants.REVOCATIONRESPONSE, myRevrepMessage);
    PKIMessage myPKIMessage;

    if ((getPbeDigestAlg() != null) && (getPbeMacAlg() != null) && (getPbeKeyId() != null)
            && (getPbeKey() != null)) {
        myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(CMPObjectIdentifiers.passwordBasedMac));
        myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
        responseMessage = CmpMessageHelper.protectPKIMessageWithPBE(myPKIMessage, getPbeKeyId(), getPbeKey(),
                getPbeDigestAlg(), getPbeMacAlg(), getPbeIterationCount());
    } else {
        myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(digestAlg));
        myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
        try {
            responseMessage = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, signKey, digestAlg,
                    provider);
        } catch (CertificateEncodingException e) {
            log.error("Failed to sign CMPRevokeResponseMessage");
            log.error(e.getLocalizedMessage(), e);
            responseMessage = getUnprotectedResponseMessage(myPKIMessage);
        } catch (SecurityException e) {
            log.error("Failed to sign CMPRevokeResponseMessage");
            log.error(e.getLocalizedMessage(), e);
            responseMessage = getUnprotectedResponseMessage(myPKIMessage);
        } catch (SignatureException e) {
            log.error("Failed to sign CMPRevokeResponseMessage");
            log.error(e.getLocalizedMessage(), e);
            responseMessage = getUnprotectedResponseMessage(myPKIMessage);
        }
    }
    return true;
}

From source file:org.jnotary.dvcs.SimpleResponseTest.java

License:Open Source License

@Test
public void errorResponse() throws IOException {

    PKIStatus status = PKIStatus.getInstance(new DERInteger(PKIStatus.REJECTION));
    PKIFreeText statusString = new PKIFreeText("Free text");
    PKIFailureInfo failInfo = new PKIFailureInfo(PKIFailureInfo.badRequest);

    PKIStatusInfo transactionStatus = new PKIStatusInfo(status, statusString, failInfo);

    DVCSErrorNotice dvErrorNote = new DVCSErrorNotice(transactionStatus);
    DVCSResponse respOut = new DVCSResponse(dvErrorNote);

    DVCSResponse respIn = DVCSResponse.getInstance(respOut.getEncoded());
    assertTrue("Status igetInstances incorrect", respIn.getDvErrorNote().getTransactionStatus().getStatus()
            .equals(respOut.getDvErrorNote().getTransactionStatus().getStatus()));
    assertTrue("Status string is incorrect", respIn.getDvErrorNote().getTransactionStatus().getStatusString()
            .equals(respOut.getDvErrorNote().getTransactionStatus().getStatusString()));
    assertTrue("Status is incorrect", respIn.getDvErrorNote().getTransactionStatus().getFailInfo()
            .equals(respOut.getDvErrorNote().getTransactionStatus().getFailInfo()));

}

From source file:org.jnotary.service.dvcs.DvcsHandler.java

License:Open Source License

@Override
public byte[] handle(DVCSRequest request) throws Exception {
    DVCSResponse response = null;/*from   w ww . j ava2 s .c o m*/
    try {
        if (!globalResources.getServiceConfig().asAllowed(request.getRequestInformation().getService())) {
            throw new DVCSException(PKIStatus.REJECTION, "Service is disabled", PKIFailureInfo.systemUnavail);
        }

        switch (request.getRequestInformation().getService()) {
        case ServiceType.CPD:
            response = handleCpd(request);
            break;
        case ServiceType.CCPD:
            response = handleCcpd(request);
            break;
        case ServiceType.VPKC:
            response = handleVpkc(request);
            break;
        case ServiceType.VSD:
            response = handleVsd(request);
            break;
        }
    } catch (DVCSException e) {
        //Signature is bad
        log.severe(e.getLocalizedMessage());
        response = ErrorResponseFactory.getInstance(e);
    } catch (Exception e) {
        //Signature is bad
        log.severe(e.getLocalizedMessage());
        response = ErrorResponseFactory.getInstance(PKIStatus.REJECTION, e.getLocalizedMessage());
    }

    return cryptoService.sign(response.getEncoded());
}

From source file:org.jnotary.service.dvcs.DvcsHandler.java

License:Open Source License

private DVCSResponse handleVpkc(DVCSRequest request) throws DVCSException {
    PKIStatusInfo dvStatus = null;//  ww w  .j  a v a2s . c  om
    byte[] certData = null;
    try {
        try {
            java.security.cert.X509Certificate certificate = getCertificate(request);
            certData = request.getData().toASN1Primitive().getEncoded();
            cryptoService.verifyCerificate(certificate, true);
            dvStatus = StatusInfoFactory.getInstance(PKIStatus.GRANTED, null, null);
        } catch (DVCSException e) {
            dvStatus = StatusInfoFactory.getInstance(e.getPkiStatus(), e.getFreeText(), e.getPkiFailInfo());
        }

    } catch (Exception e) {
        throw new DVCSException(PKIStatus.REJECTION, e.getLocalizedMessage(), PKIFailureInfo.systemFailure);
    }
    DvcsResponseHelper response = new DvcsResponseHelper(globalResources.getSerialNumber(),
            globalResources.getServiceConfig());
    byte[] digestData = response.getDigest(certData);
    DigestInfo messageImprint = response.getDigestInfo(digestData);
    return response.createResponse(request, messageImprint, dvStatus);

}

From source file:org.jnotary.service.dvcs.DvcsHandler.java

License:Open Source License

private java.security.cert.X509Certificate getCertificate(DVCSRequest request) throws DVCSException {

    if (request.getData().getCerts() == null || request.getData().getCerts().length == 0) {
        throw new DVCSException(PKIStatus.REJECTION, "No certificates in request", PKIFailureInfo.badRequest);
    }//from   ww w .  j  a  va  2s.  com

    CertEtcToken targetIn = request.getData().getCerts()[0].getTarget();
    if (targetIn == null)
        throw new DVCSException(PKIStatus.REJECTION, "No certificates in request", PKIFailureInfo.badRequest);

    java.security.cert.X509Certificate certificate = null;
    try {
        CertificateFactory rd = CertificateFactory.getInstance("X.509");
        InputStream in = new ByteArrayInputStream(targetIn.getCertificate().getEncoded());
        certificate = (X509Certificate) rd.generateCertificate(in);
    } catch (Exception e) {
        throw new DVCSException(PKIStatus.REJECTION, e.getLocalizedMessage(), PKIFailureInfo.badRequest);
    }
    return certificate;
}

From source file:org.jnotary.service.dvcs.DvcsResponseHelper.java

License:Open Source License

protected byte[] getDigest(byte[] data) throws DVCSException {
    byte[] digestData = null;
    try {//from w  w w. j ava  2 s.c  om
        digestData = Hasher.makeHash(config.getHashAlgorithm(), data);
    } catch (Exception e) {
        throw new DVCSException(PKIStatus.REJECTION, e.getLocalizedMessage(), PKIFailureInfo.systemFailure);
    }
    return digestData;
}

From source file:org.jnotary.service.rest.DvcsRequestHandler.java

License:Open Source License

@POST
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response call(byte[] incomingRequest, @Context HttpServletRequest request) {
    log.info("Remote address: " + request.getRemoteAddr());
    if (incomingRequest == null || incomingRequest.length == 0) {
        log.severe("Bad HTTP-request");
        return Response.status(400).build();
    }//from w w  w . j a  va 2 s . co m

    byte[] signedResponse = null;
    try {
        log.fine("Signature verification..");
        VerifyResult dvcsReqVerifyResult = cryptoService.verifySignature(incomingRequest);
        //TODO: checkCertificateEnabled(dvcsReqVerifyResult);
        cryptoService.verifyCerificates(dvcsReqVerifyResult, globalResources.getServiceConfig().isVerifyCRL());

        log.fine("Message parsing..");
        DVCSRequest dvcsRequest = getDVCSRequest(dvcsReqVerifyResult.getContent());
        log.info("Service: " + dvcsRequest.getRequestInformation().getService());
        log.info(dvcsRequest.getRequestInformation().getNonce().getPositiveValue().toString());
        log.info(dvcsRequest.getRequestInformation().getRequestTime().getGenTime().getTimeString());

        signedResponse = dvcsHandler.handle(dvcsRequest);
    } catch (DVCSException e) {
        try {
            DVCSResponse response = ErrorResponseFactory.getInstance(e);
            signedResponse = cryptoService.sign(response.getEncoded());
        } catch (Exception ex) {
            log.severe(ex.getLocalizedMessage());
            return Response.status(500).build();
        }

    } catch (Exception e) {
        log.severe(e.getLocalizedMessage());
        DVCSResponse response = ErrorResponseFactory.getInstance(PKIStatus.REJECTION, e.getLocalizedMessage());
        try {
            signedResponse = cryptoService.sign(response.getEncoded());
        } catch (Exception ex) {
            log.severe(ex.getLocalizedMessage());
            return Response.status(500).build();
        }
    }

    return Response.status(200).entity(signedResponse).build();
}