Example usage for org.bouncycastle.cert.cmp GeneralPKIMessage hasProtection

List of usage examples for org.bouncycastle.cert.cmp GeneralPKIMessage hasProtection

Introduction

In this page you can find the example usage for org.bouncycastle.cert.cmp GeneralPKIMessage hasProtection.

Prototype

public boolean hasProtection() 

Source Link

Document

Return true if this message has protection bits on it.

Usage

From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java

License:Open Source License

/**
 * Test the basic certification request message
 *
 * @throws OperatorCreationException//from  w w w.  j  av  a 2s  . c  o m
 * @throws CertificateEncodingException
 * @throws IOException
 * @throws CRMFException
 * @throws CMPException
 * @throws CMSException
 */
@Test
public void testCertification() throws OperatorCreationException, CertificateEncodingException, IOException,
        CRMFException, CMPException, CMSException, ParseException, PKICMPMessageException,
        NoSuchProviderException, NoSuchAlgorithmException, NoSuchFieldException, IllegalAccessException {
    String distinguishedName = pki.getTestUser1Cert().getSubjectX500Principal().getName();

    KeyPair keyPair = new KeyPair(pki.getTestUser1Cert().getPublicKey(), pki.getTestUser1CertPrivateKey());

    PKICMPMessages pkiMessages = new PKICMPMessages();
    pkiMessages.setPkiKeyStore(pkiKeyStoreRA);
    byte[] result = pkiMessages.createCertificateMessageWithLocalKey(distinguishedName, keyPair);

    ASN1InputStream asn1InputStream = new ASN1InputStream(result);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive);

    // Header verification
    Assert.assertEquals(pkiMessage.getHeader().getPvno().getValue(), BigInteger.valueOf(2));
    Assert.assertEquals(pkiKeyStoreRA.getRecipientCertificate().getSubjectDN().getName(),
            pkiMessage.getHeader().getRecipient().getName().toString());
    Assert.assertEquals(pkiKeyStoreRA.getSenderCertificate().getSubjectDN().getName(),
            pkiMessage.getHeader().getSender().getName().toString());
    Assert.assertNotNull(pkiMessage.getHeader().getSenderNonce());
    Assert.assertNotNull(pkiMessage.getHeader().getTransactionID());
    Assert.assertNotNull(pkiMessage.getHeader().getMessageTime().getDate());
    // check the body
    // Check the tests in Bouncycastle for decoding cert request
    Assert.assertEquals(PKIBody.TYPE_CERT_REQ, pkiMessage.getBody().getType());
    CertReqMsg[] certReqMsgs = CertReqMessages.getInstance(pkiMessage.getBody().getContent())
            .toCertReqMsgArray();
    Assert.assertEquals(BigInteger.ZERO.toString(), certReqMsgs[0].getCertReq().getCertReqId().toString());
    Assert.assertEquals(distinguishedName,
            certReqMsgs[0].getCertReq().getCertTemplate().getSubject().toString());
    Assert.assertArrayEquals(keyPair.getPublic().getEncoded(),
            certReqMsgs[0].getCertReq().getCertTemplate().getPublicKey().getEncoded());
    AttributeTypeAndValue[] attributeTypeAndValue = certReqMsgs[0].getCertReq().getControls()
            .toAttributeTypeAndValueArray();
    Assert.assertEquals(CRMFObjectIdentifiers.id_regCtrl_pkiArchiveOptions, attributeTypeAndValue[0].getType());
    // Check the signature
    GeneralPKIMessage generalPKIMessage = new GeneralPKIMessage(result);
    Assert.assertTrue(generalPKIMessage.hasProtection());
    ProtectedPKIMessage pkiMsg = new ProtectedPKIMessage(generalPKIMessage);
    ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder()
            .setProvider(pkiKeyStoreRA.getProvider())
            .build(pkiKeyStoreRA.getSenderCertificate().getPublicKey());

    Assert.assertTrue(pkiMsg.verify(verifierProvider));
}

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

License:Open Source License

protected PKIResponse signAndSend(final PKIMessage request, final RequestResponseDebug debug)
        throws CmpRequestorException {
    PKIMessage _request;/*from w w  w  .j a v a2s .  c o  m*/
    if (signRequest) {
        _request = sign(request);
    } else {
        _request = request;
    }

    if (responderCert == null) {
        throw new CmpRequestorException("CMP responder is not configured");
    }

    byte[] encodedRequest;
    try {
        encodedRequest = _request.getEncoded();
    } catch (IOException e) {
        LOG.error("error while encode the PKI request {}", _request);
        throw new CmpRequestorException(e.getMessage(), e);
    }

    RequestResponsePair reqResp = null;
    if (debug != null) {
        reqResp = new RequestResponsePair();
        debug.add(reqResp);
        reqResp.setRequest(encodedRequest);
    }

    byte[] encodedResponse;
    try {
        encodedResponse = send(encodedRequest);
    } catch (IOException e) {
        LOG.error("error while send the PKI request {} to server", _request);
        throw new CmpRequestorException("TRANSPORT_ERROR", e);
    }

    if (reqResp != null) {
        reqResp.setResponse(encodedResponse);
    }

    GeneralPKIMessage response;
    try {
        response = new GeneralPKIMessage(encodedResponse);
    } catch (IOException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("error while decode the received PKI message: {}", Hex.toHexString(encodedResponse));
        }
        throw new CmpRequestorException(e.getMessage(), e);
    }

    PKIHeader respHeader = response.getHeader();
    ASN1OctetString tid = respHeader.getTransactionID();
    GeneralName recipient = respHeader.getRecipient();
    if (sender.equals(recipient) == false) {
        LOG.warn("tid={}: unknown CMP requestor '{}'", tid, recipient);
    }

    PKIResponse ret = new PKIResponse(response);
    if (response.hasProtection()) {
        try {
            ProtectionVerificationResult verifyProtection = verifyProtection(Hex.toHexString(tid.getOctets()),
                    response, responderCert);
            ret.setProtectionVerificationResult(verifyProtection);
        } catch (InvalidKeyException | OperatorCreationException | CMPException e) {
            throw new CmpRequestorException(e.getMessage(), e);
        }
    } else if (signRequest) {
        PKIBody respBody = response.getBody();
        int bodyType = respBody.getType();
        if (bodyType != PKIBody.TYPE_ERROR) {
            throw new CmpRequestorException("response is not signed");
        }
    }

    return ret;
}

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);
    }//www . j a  va  2  s  .co  m
    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 PkiResponse signAndSend(final PKIMessage request, final RequestResponseDebug debug)
        throws CmpRequestorException {
    ParamUtil.requireNonNull("request", request);

    PKIMessage tmpRequest = (signRequest) ? sign(request) : request;

    byte[] encodedRequest;
    try {/*from  ww w. j  a va  2s  .c o  m*/
        encodedRequest = tmpRequest.getEncoded();
    } catch (IOException ex) {
        LOG.error("could not encode the PKI request {}", tmpRequest);
        throw new CmpRequestorException(ex.getMessage(), ex);
    }

    RequestResponsePair reqResp = null;
    if (debug != null) {
        reqResp = new RequestResponsePair();
        debug.add(reqResp);
        reqResp.setRequest(encodedRequest);
    }

    byte[] encodedResponse;
    try {
        encodedResponse = send(encodedRequest);
    } catch (IOException ex) {
        LOG.error("could not send the PKI request {} to server", tmpRequest);
        throw new CmpRequestorException("TRANSPORT_ERROR", ex);
    }

    if (reqResp != null) {
        reqResp.setResponse(encodedResponse);
    }

    GeneralPKIMessage response;
    try {
        response = new GeneralPKIMessage(encodedResponse);
    } catch (IOException ex) {
        LOG.error("could not decode the received PKI message: {}", Hex.toHexString(encodedResponse));
        throw new CmpRequestorException(ex.getMessage(), ex);
    }

    PKIHeader respHeader = response.getHeader();
    ASN1OctetString tid = respHeader.getTransactionID();
    GeneralName rec = respHeader.getRecipient();
    if (!sender.equals(rec)) {
        LOG.warn("tid={}: unknown CMP requestor '{}'", tid, rec);
    }

    PkiResponse ret = new PkiResponse(response);
    if (response.hasProtection()) {
        try {
            ProtectionVerificationResult verifyProtection = verifyProtection(Hex.toHexString(tid.getOctets()),
                    response);
            ret.setProtectionVerificationResult(verifyProtection);
        } catch (InvalidKeyException | OperatorCreationException | CMPException ex) {
            throw new CmpRequestorException(ex.getMessage(), ex);
        }
    } else if (signRequest) {
        PKIBody respBody = response.getBody();
        int bodyType = respBody.getType();
        if (bodyType != PKIBody.TYPE_ERROR) {
            throw new CmpRequestorException("response is not signed");
        }
    }

    return ret;
}

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;/*w ww .  j a  v  a  2 s  .c  om*/
    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;
}