Example usage for org.bouncycastle.asn1.cmp PKIFailureInfo badMessageCheck

List of usage examples for org.bouncycastle.asn1.cmp PKIFailureInfo badMessageCheck

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cmp PKIFailureInfo badMessageCheck.

Prototype

int badMessageCheck

To view the source code for org.bouncycastle.asn1.cmp PKIFailureInfo badMessageCheck.

Click Source Link

Usage

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

License:Open Source License

@Test
public void test03CrmfHttpTooManyIterations() throws Exception {

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIMessage one = genCertReq(issuerDN, userDN, this.keys, this.cacert, nonce, transid, true, null, null,
            null, null, null, null);//from www.java  2s  . c  o m
    PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, 10001);
    assertNotNull(req);

    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, ALIAS);
    assertNotNull(resp);
    assertTrue(resp.length > 0);
    checkCmpFailMessage(resp, "Iteration count can not exceed 10000", 23, reqId, PKIFailureInfo.badMessageCheck,
            PKIFailureInfo.incorrectData); // We expect a FailInfo.BAD_MESSAGE_CHECK
}

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

License:Open Source License

@Test
public void test04CrmfUnauthenticated() throws Exception {

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIMessage req = genCertReq(issuerDN, userDN, this.keys, this.cacert, nonce, transid, true, null, null,
            null, null, null, null);//from w w  w .j ava2  s. c  o m

    assertNotNull(req);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, issuerDN, userDN, this.cacert, nonce, transid, false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIErrorMessage(resp, issuerDN, userDN, PKIFailureInfo.badMessageCheck,
            "PKI Message is not athenticated properly. No HMAC protection was found.");
}

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

License:Open Source License

@Test
public void test05CrmfUnknownProtection() throws Exception {

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIMessage one = genCertReq(issuerDN, userDN, this.keys, this.cacert, nonce, transid, true, null, null,
            null, null, null, null);//w  w  w .  j a  va 2s  . c o  m
    PKIMessage req = protectPKIMessage(one, true, PBEPASSWORD, 567);

    assertNotNull(req);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, issuerDN, userDN, this.cacert, nonce, transid, false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIErrorMessage(resp, issuerDN, userDN, PKIFailureInfo.badMessageCheck,
            "Could not create CmpPbeVerifyer. Protection algorithm id expected '1.2.840.113533.7.66.13' (passwordBasedMac) but was '1.2.840.113533.7.66.13.7'.");
}

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

License:Open Source License

@Test
public void test03CrmfHttpOkUser() throws Exception {
    log.trace(">test03CrmfHttpOkUser");
    // Create a new good USER
    final X500Name userDN = createCmpUser("cmptest", "C=SE,O=PrimeKey,CN=cmptest", true);

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIMessage req = genCertReq(ISSUER_DN, userDN, this.keys, this.cacert, nonce, transid, false, null, null,
            null, null, null, null);//from  w ww .  ja  v  a  2  s.  c o  m
    assertNotNull(req);
    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
    checkCmpResponseGeneral(resp, ISSUER_DN, userDN, this.cacert, nonce, transid, true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId);
    String altNames = CertTools.getSubjectAlternativeName(cert);
    assertNull("AltNames was not null (" + altNames + ").", altNames);

    // Send a confirm message to the CA
    String hash = "foo123";
    PKIMessage confirm = genCertConfirm(userDN, this.cacert, nonce, transid, hash, reqId);
    assertNotNull(confirm);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(confirm);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, cmpAlias);
    checkCmpResponseGeneral(resp, ISSUER_DN, userDN, this.cacert, nonce, transid, false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIConfirmMessage(userDN, this.cacert, resp);

    // Now revoke the bastard!
    PKIMessage rev = genRevReq(ISSUER_DN, userDN, cert.getSerialNumber(), this.cacert, nonce, transid, true,
            null, null);
    assertNotNull(rev);
    ByteArrayOutputStream baorev = new ByteArrayOutputStream();
    DEROutputStream outrev = new DEROutputStream(baorev);
    outrev.writeObject(rev);
    byte[] barev = baorev.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(barev, 200, cmpAlias);
    checkCmpResponseGeneral(resp, ISSUER_DN, userDN, this.cacert, nonce, transid, false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpFailMessage(resp, "PKI Message is not athenticated properly. No HMAC protection was found.", 23,
            reqId, PKIFailureInfo.badMessageCheck, PKIFailureInfo.incorrectData);
    log.trace("<test03CrmfHttpOkUser");
}

From source file:org.jnotary.service.test.RestTest.java

License:Open Source License

@Test
public void testDvcsCallWithWrongData() throws Exception {
    configureService();//www  . j  av  a  2  s.  c  o m

    Client client = ClientBuilder.newBuilder().build();
    WebTarget target = client.target(url + "rest/dvcs");
    target.request().accept(MediaType.APPLICATION_OCTET_STREAM);
    Response response;
    try {
        response = target.request().post(Entity.entity(sampleData, MediaType.APPLICATION_OCTET_STREAM));
        byte[] value = response.readEntity(byte[].class);
        response.close(); // You should close connections!         
        Assert.assertEquals(200, response.getStatus());

        DVCSResponse respIn = removeSignature(value);
        assertEquals(PKIStatus.REJECTION,
                respIn.getDvErrorNote().getTransactionStatus().getStatus().intValue());
        System.out.printf("Status string: %s\n",
                respIn.getDvErrorNote().getTransactionStatus().getStatusString().getStringAt(0));
        assertEquals(PKIFailureInfo.badMessageCheck,
                respIn.getDvErrorNote().getTransactionStatus().getFailInfo().intValue());

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.jnotary.service.util.CryptoService.java

License:Open Source License

public VerifyResult verifySignature(byte[] signedData) throws DVCSException {

    TrustedStore trustedUsers = null; //globalResources.getTrustedUsers();
    try {/* w w  w. j a v  a 2 s . co  m*/
        return verifier.verifySignature(signedData, trustedUsers);
    } catch (Exception e) {
        throw new DVCSException(PKIStatus.REJECTION, e.getLocalizedMessage(), PKIFailureInfo.badMessageCheck);
    }
}

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

License:Open Source License

protected void checkProtection(final PKIResponse response) throws PKIErrorException {
    ProtectionVerificationResult protectionVerificationResult = response.getProtectionVerificationResult();
    if (response.hasProtection()) {
        if (protectionVerificationResult == null
                || protectionVerificationResult.getProtectionResult() != ProtectionResult.VALID) {
            throw new PKIErrorException(ClientErrorCode.PKIStatus_RESPONSE_ERROR,
                    PKIFailureInfo.badMessageCheck, "message check of the response failed");
        }//from w  ww  .j av a 2s .  co m
    }
}

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

License:Open Source License

public PKIMessage processPKIMessage(final PKIMessage pkiMessage, final X509Certificate tlsClientCert,
        final AuditEvent auditEvent) throws ConfigurationException {
    GeneralPKIMessage message = new GeneralPKIMessage(pkiMessage);

    PKIHeader reqHeader = message.getHeader();
    ASN1OctetString tid = reqHeader.getTransactionID();

    if (tid == null) {
        byte[] randomBytes = randomTransactionId();
        tid = new DEROctetString(randomBytes);
    }/*from w w  w  . j  av  a 2  s  .c om*/
    String tidStr = Hex.toHexString(tid.getOctets());
    if (auditEvent != null) {
        auditEvent.addEventData(new AuditEventData("tid", tidStr));
    }

    CmpControl cmpControl = getCmpControl();

    Integer failureCode = null;
    String statusText = null;

    Date messageTime = null;
    if (reqHeader.getMessageTime() != null) {
        try {
            messageTime = reqHeader.getMessageTime().getDate();
        } catch (ParseException e) {
            final String msg = "tid=" + tidStr + ": could not parse messageDate";
            if (LOG.isErrorEnabled()) {
                LOG.error(LogUtil.buildExceptionLogFormat(msg), e.getClass().getName(), e.getMessage());
            }
            LOG.debug(msg, e);
            messageTime = null;
        }
    }

    GeneralName recipient = reqHeader.getRecipient();
    boolean intentMe = (recipient == null) ? null : intendsMe(recipient);
    if (intentMe == false) {
        LOG.warn("tid={}: I am not the intented recipient, but '{}'", tid, reqHeader.getRecipient());
        failureCode = PKIFailureInfo.badRequest;
        statusText = "I am not the intended recipient";
    } else if (messageTime == null) {
        if (cmpControl.isMessageTimeRequired()) {
            failureCode = PKIFailureInfo.missingTimeStamp;
            statusText = "missing timestamp";
        }
    } else {
        long messageTimeBias = cmpControl.getMessageTimeBias();
        if (messageTimeBias < 0) {
            messageTimeBias *= -1;
        }

        long msgTimeMs = messageTime.getTime();
        long currentTimeMs = System.currentTimeMillis();
        long bias = (msgTimeMs - currentTimeMs) / 1000L;
        if (bias > messageTimeBias) {
            failureCode = PKIFailureInfo.badTime;
            statusText = "message time is in the future";
        } else if (bias * -1 > messageTimeBias) {
            failureCode = PKIFailureInfo.badTime;
            statusText = "message too old";
        }
    }

    if (failureCode != null) {
        if (auditEvent != null) {
            auditEvent.setLevel(AuditLevel.INFO);
            auditEvent.setStatus(AuditStatus.FAILED);
            auditEvent.addEventData(new AuditEventData("message", statusText));
        }
        return buildErrorPkiMessage(tid, reqHeader, failureCode, statusText);
    }

    boolean isProtected = message.hasProtection();
    CmpRequestorInfo requestor = null;

    String errorStatus;

    if (isProtected) {
        try {
            ProtectionVerificationResult verificationResult = verifyProtection(tidStr, message, cmpControl);
            ProtectionResult pr = verificationResult.getProtectionResult();
            switch (pr) {
            case VALID:
                errorStatus = null;
                break;
            case INVALID:
                errorStatus = "request is protected by signature but invalid";
                break;
            case NOT_SIGNATURE_BASED:
                errorStatus = "request is not protected by signature";
                break;
            case SENDER_NOT_AUTHORIZED:
                errorStatus = "request is protected by signature but the requestor is not authorized";
                break;
            case SIGALGO_FORBIDDEN:
                errorStatus = "request is protected by signature but the protection algorithm is forbidden";
                break;
            default:
                throw new RuntimeException("should not reach here, unknown ProtectionResult " + pr);
            } // end switch
            requestor = (CmpRequestorInfo) verificationResult.getRequestor();
        } catch (Exception e) {
            final String msg = "tid=" + tidStr + ": error while verifying the signature";
            if (LOG.isErrorEnabled()) {
                LOG.error(LogUtil.buildExceptionLogFormat(msg), e.getClass().getName(), e.getMessage());
            }
            LOG.debug(msg, e);
            errorStatus = "request has invalid signature based protection";
        }
    } else if (tlsClientCert != null) {
        boolean authorized = false;

        requestor = getRequestor(reqHeader);
        if (requestor != null) {
            if (tlsClientCert.equals(requestor.getCert().getCert())) {
                authorized = true;
            }
        }

        if (authorized) {
            errorStatus = null;
        } else {
            LOG.warn("tid={}: not authorized requestor (TLS client '{}')", tid,
                    X509Util.getRFC4519Name(tlsClientCert.getSubjectX500Principal()));
            errorStatus = "requestor (TLS client certificate) is not authorized";
        }
    } else {
        errorStatus = "request has no protection";
        requestor = null;
    }

    CmpUtf8Pairs keyvalues = CmpUtil.extract(reqHeader.getGeneralInfo());
    String username = keyvalues == null ? null : keyvalues.getValue(CmpUtf8Pairs.KEY_USER);
    if (username != null) {
        if (username.indexOf('*') != -1 || username.indexOf('%') != -1) {
            errorStatus = "user could not contains characters '*' and '%'";
        }
    }

    if (errorStatus != null) {
        if (auditEvent != null) {
            auditEvent.setLevel(AuditLevel.INFO);
            auditEvent.setStatus(AuditStatus.FAILED);
            auditEvent.addEventData(new AuditEventData("message", errorStatus));
        }
        return buildErrorPkiMessage(tid, reqHeader, PKIFailureInfo.badMessageCheck, errorStatus);
    }

    PKIMessage resp = intern_processPKIMessage(requestor, username, tid, message, auditEvent);

    if (isProtected) {
        resp = addProtection(resp, auditEvent);
    } else {
        // protected by TLS connection
    }

    return resp;
}

From source file:org.xipki.pki.ca.client.impl.CmpRequestor.java

License:Open Source License

protected void checkProtection(final PkiResponse response) throws PkiErrorException {
    ParamUtil.requireNonNull("response", response);

    if (!response.hasProtection()) {
        return;/*from   ww  w  .  j  a  v a  2s.  c  om*/
    }

    ProtectionVerificationResult protectionVerificationResult = response.getProtectionVerificationResult();

    if (protectionVerificationResult == null
            || protectionVerificationResult.getProtectionResult() != ProtectionResult.VALID) {
        throw new PkiErrorException(ClientErrorCode.PKISTATUS_RESPONSE_ERROR, PKIFailureInfo.badMessageCheck,
                "message check of the response failed");
    }
}

From source file:org.xipki.pki.ca.server.impl.cmp.CmpResponder.java

License:Open Source License

public PKIMessage processPkiMessage(final PKIMessage pkiMessage, final X509Certificate tlsClientCert,
        final String tidStr, final AuditEvent event) {
    ParamUtil.requireNonNull("pkiMessage", pkiMessage);
    ParamUtil.requireNonNull("event", event);
    GeneralPKIMessage message = new GeneralPKIMessage(pkiMessage);

    PKIHeader reqHeader = message.getHeader();
    ASN1OctetString tid = reqHeader.getTransactionID();

    String msgId = null;//  www.j ava  2s .  c o  m
    if (event != null) {
        msgId = RandomUtil.nextHexLong();
        event.addEventData(CaAuditConstants.NAME_mid, msgId);
    }

    if (tid == null) {
        byte[] randomBytes = randomTransactionId();
        tid = new DEROctetString(randomBytes);
    }

    CmpControl cmpControl = getCmpControl();

    Integer failureCode = null;
    String statusText = null;

    Date messageTime = null;
    if (reqHeader.getMessageTime() != null) {
        try {
            messageTime = reqHeader.getMessageTime().getDate();
        } catch (ParseException ex) {
            LogUtil.error(LOG, ex, "tid=" + tidStr + ": could not parse messageDate");
        }
    }

    GeneralName recipient = reqHeader.getRecipient();
    boolean intentMe = (recipient == null) ? true : intendsMe(recipient);
    if (!intentMe) {
        LOG.warn("tid={}: I am not the intended recipient, but '{}'", tid, reqHeader.getRecipient());
        failureCode = PKIFailureInfo.badRequest;
        statusText = "I am not the intended recipient";
    } else if (messageTime == null) {
        if (cmpControl.isMessageTimeRequired()) {
            failureCode = PKIFailureInfo.missingTimeStamp;
            statusText = "missing time-stamp";
        }
    } else {
        long messageTimeBias = cmpControl.getMessageTimeBias();
        if (messageTimeBias < 0) {
            messageTimeBias *= -1;
        }

        long msgTimeMs = messageTime.getTime();
        long currentTimeMs = System.currentTimeMillis();
        long bias = (msgTimeMs - currentTimeMs) / 1000L;
        if (bias > messageTimeBias) {
            failureCode = PKIFailureInfo.badTime;
            statusText = "message time is in the future";
        } else if (bias * -1 > messageTimeBias) {
            failureCode = PKIFailureInfo.badTime;
            statusText = "message too old";
        }
    }

    if (failureCode != null) {
        if (event != null) {
            event.setLevel(AuditLevel.INFO);
            event.setStatus(AuditStatus.FAILED);
            event.addEventData(CaAuditConstants.NAME_message, statusText);
        }
        return buildErrorPkiMessage(tid, reqHeader, failureCode, statusText);
    }

    boolean isProtected = message.hasProtection();
    CmpRequestorInfo requestor;

    String errorStatus;

    if (isProtected) {
        try {
            ProtectionVerificationResult verificationResult = verifyProtection(tidStr, message, cmpControl);
            ProtectionResult pr = verificationResult.getProtectionResult();
            switch (pr) {
            case VALID:
                errorStatus = null;
                break;
            case INVALID:
                errorStatus = "request is protected by signature but invalid";
                break;
            case NOT_SIGNATURE_BASED:
                errorStatus = "request is not protected by signature";
                break;
            case SENDER_NOT_AUTHORIZED:
                errorStatus = "request is protected by signature but the requestor is not authorized";
                break;
            case SIGALGO_FORBIDDEN:
                errorStatus = "request is protected by signature but the protection algorithm"
                        + " is forbidden";
                break;
            default:
                throw new RuntimeException("should not reach here, unknown ProtectionResult " + pr);
            } // end switch
            requestor = (CmpRequestorInfo) verificationResult.getRequestor();
        } catch (Exception ex) {
            LogUtil.error(LOG, ex, "tid=" + tidStr + ": could not verify the signature");
            errorStatus = "request has invalid signature based protection";
            requestor = null;
        }
    } else if (tlsClientCert != null) {
        boolean authorized = false;

        requestor = getRequestor(reqHeader);
        if (requestor != null) {
            if (tlsClientCert.equals(requestor.getCert().getCert())) {
                authorized = true;
            }
        }

        if (authorized) {
            errorStatus = null;
        } else {
            LOG.warn("tid={}: not authorized requestor (TLS client '{}')", tid,
                    X509Util.getRfc4519Name(tlsClientCert.getSubjectX500Principal()));
            errorStatus = "requestor (TLS client certificate) is not authorized";
        }
    } else {
        errorStatus = "request has no protection";
        requestor = null;
    }

    CmpUtf8Pairs keyvalues = CmpUtil.extract(reqHeader.getGeneralInfo());
    String username = (keyvalues == null) ? null : keyvalues.getValue(CmpUtf8Pairs.KEY_USER);
    if (username != null) {
        if (username.indexOf('*') != -1 || username.indexOf('%') != -1) {
            errorStatus = "user could not contains characters '*' and '%'";
        }
    }

    if (errorStatus != null) {
        if (event != null) {
            event.setLevel(AuditLevel.INFO);
            event.setStatus(AuditStatus.FAILED);
            event.addEventData(CaAuditConstants.NAME_message, errorStatus);
        }
        return buildErrorPkiMessage(tid, reqHeader, PKIFailureInfo.badMessageCheck, errorStatus);
    }

    PKIMessage resp = doProcessPkiMessage(pkiMessage, requestor, username, tid, message, msgId, event);

    if (isProtected) {
        resp = addProtection(resp, event);
    } else {
        // protected by TLS connection
    }

    return resp;
}