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

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

Introduction

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

Prototype

public PKIHeader getHeader() 

Source Link

Usage

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  av  a2 s . c om*/
    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.client.impl.CmpRequestor.java

License:Open Source License

private ProtectionVerificationResult verifyProtection(final String tid, final GeneralPKIMessage pkiMessage,
        final X509Certificate cert) throws CMPException, InvalidKeyException, OperatorCreationException {
    ProtectedPKIMessage pMsg = new ProtectedPKIMessage(pkiMessage);

    if (pMsg.hasPasswordBasedMacProtection()) {
        LOG.warn("NOT_SIGNAUTRE_BASED: " + pkiMessage.getHeader().getProtectionAlg().getAlgorithm().getId());
        return new ProtectionVerificationResult(null, ProtectionResult.NOT_SIGNATURE_BASED);
    }/*from  w  w w. j  a  v a  2  s.c o m*/

    PKIHeader h = pMsg.getHeader();

    if (c14nRecipientName != null) {
        boolean authorizedResponder = true;
        if (h.getSender().getTagNo() != GeneralName.directoryName) {
            authorizedResponder = false;
        } else {
            String c14nMsgSender = getSortedRFC4519Name((X500Name) h.getSender().getName());
            authorizedResponder = c14nRecipientName.equalsIgnoreCase(c14nMsgSender);
        }

        if (authorizedResponder == false) {
            LOG.warn("tid={}: not authorized responder '{}'", tid, h.getSender());
            return new ProtectionVerificationResult(null, ProtectionResult.SENDER_NOT_AUTHORIZED);
        }
    }

    ContentVerifierProvider verifierProvider = securityFactory.getContentVerifierProvider(cert);
    if (verifierProvider == null) {
        LOG.warn("tid={}: not authorized responder '{}'", tid, h.getSender());
        return new ProtectionVerificationResult(cert, ProtectionResult.SENDER_NOT_AUTHORIZED);
    }

    boolean signatureValid = pMsg.verify(verifierProvider);
    return new ProtectionVerificationResult(cert,
            signatureValid ? ProtectionResult.VALID : ProtectionResult.INVALID);
}

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  .com*/
    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.ca.server.impl.CmpResponder.java

License:Open Source License

private ProtectionVerificationResult verifyProtection(final String tid, final GeneralPKIMessage pkiMessage,
        final CmpControl cmpControl) throws CMPException, InvalidKeyException, OperatorCreationException {
    ProtectedPKIMessage pMsg = new ProtectedPKIMessage(pkiMessage);

    if (pMsg.hasPasswordBasedMacProtection()) {
        LOG.warn("NOT_SIGNAUTRE_BASED: " + pkiMessage.getHeader().getProtectionAlg().getAlgorithm().getId());
        return new ProtectionVerificationResult(null, ProtectionResult.NOT_SIGNATURE_BASED);
    }//www .  j av a 2s  .co m

    PKIHeader h = pMsg.getHeader();
    AlgorithmIdentifier protectionAlg = h.getProtectionAlg();
    if (cmpControl.isSigAlgoPermitted(protectionAlg) == false) {
        LOG.warn("SIG_ALGO_FORBIDDEN: " + pkiMessage.getHeader().getProtectionAlg().getAlgorithm().getId());
        return new ProtectionVerificationResult(null, ProtectionResult.SIGALGO_FORBIDDEN);
    }

    CmpRequestorInfo requestor = getRequestor(h);
    if (requestor == null) {
        LOG.warn("tid={}: not authorized requestor '{}'", tid, h.getSender());
        return new ProtectionVerificationResult(null, ProtectionResult.SENDER_NOT_AUTHORIZED);
    }

    ContentVerifierProvider verifierProvider = securityFactory
            .getContentVerifierProvider(requestor.getCert().getCert());
    if (verifierProvider == null) {
        LOG.warn("tid={}: not authorized requestor '{}'", tid, h.getSender());
        return new ProtectionVerificationResult(requestor, ProtectionResult.SENDER_NOT_AUTHORIZED);
    }

    boolean signatureValid = pMsg.verify(verifierProvider);
    return new ProtectionVerificationResult(requestor,
            signatureValid ? ProtectionResult.VALID : ProtectionResult.INVALID);
}

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

License:Open Source License

@Override
protected PKIMessage intern_processPKIMessage(final RequestorInfo requestor, final String user,
        final ASN1OctetString tid, final GeneralPKIMessage message, final AuditEvent auditEvent)
        throws ConfigurationException {
    if (requestor instanceof CmpRequestorInfo == false) {
        throw new IllegalArgumentException("unknown requestor type " + requestor.getClass().getName());
    }//from ww  w .  ja va2s  .c o  m

    CmpRequestorInfo _requestor = (CmpRequestorInfo) requestor;
    if (_requestor != null && auditEvent != null) {
        auditEvent.addEventData(new AuditEventData("requestor", _requestor.getCert().getSubject()));
    }

    PKIHeader reqHeader = message.getHeader();
    PKIHeaderBuilder respHeader = new PKIHeaderBuilder(reqHeader.getPvno().getValue().intValue(), getSender(),
            reqHeader.getSender());
    respHeader.setTransactionID(tid);

    PKIBody respBody;
    PKIBody reqBody = message.getBody();
    final int type = reqBody.getType();

    CmpControl cmpControl = getCmpControl();

    try {
        switch (type) {
        case PKIBody.TYPE_CERT_REQ:
        case PKIBody.TYPE_KEY_UPDATE_REQ:
        case PKIBody.TYPE_P10_CERT_REQ:
        case PKIBody.TYPE_CROSS_CERT_REQ: {
            respBody = cmpEnrollCert(respHeader, cmpControl, reqHeader, reqBody, _requestor, user, tid,
                    auditEvent);
            break;
        }
        case PKIBody.TYPE_CERT_CONFIRM: {
            addAutitEventType(auditEvent, "CERT_CONFIRM");
            CertConfirmContent certConf = (CertConfirmContent) reqBody.getContent();
            respBody = confirmCertificates(tid, certConf);
            break;
        }
        case PKIBody.TYPE_REVOCATION_REQ: {
            respBody = cmpRevokeOrUnrevokeOrRemoveCertificates(respHeader, cmpControl, reqHeader, reqBody,
                    _requestor, user, tid, auditEvent);
            break;
        }
        case PKIBody.TYPE_CONFIRM: {
            addAutitEventType(auditEvent, "CONFIRM");
            respBody = new PKIBody(PKIBody.TYPE_CONFIRM, DERNull.INSTANCE);
        }
        case PKIBody.TYPE_ERROR: {
            addAutitEventType(auditEvent, "ERROR");
            revokePendingCertificates(tid);
            respBody = new PKIBody(PKIBody.TYPE_CONFIRM, DERNull.INSTANCE);
            break;
        }
        case PKIBody.TYPE_GEN_MSG: {
            respBody = cmpGeneralMsg(respHeader, cmpControl, reqHeader, reqBody, _requestor, user, tid,
                    auditEvent);
            break;
        }
        default: {
            addAutitEventType(auditEvent, "PKIBody." + type);
            respBody = createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.badRequest,
                    "unsupported type " + type);
            break;
        }
        } // end switch(type)
    } catch (InsuffientPermissionException e) {
        ErrorMsgContent emc = new ErrorMsgContent(new PKIStatusInfo(PKIStatus.rejection,
                new PKIFreeText(e.getMessage()), new PKIFailureInfo(PKIFailureInfo.notAuthorized)));

        respBody = new PKIBody(PKIBody.TYPE_ERROR, emc);
    }

    if (auditEvent != null) {
        if (respBody.getType() == PKIBody.TYPE_ERROR) {
            ErrorMsgContent errorMsgContent = (ErrorMsgContent) respBody.getContent();

            AuditStatus auditStatus = AuditStatus.FAILED;
            org.xipki.ca.common.cmp.PKIStatusInfo pkiStatus = new org.xipki.ca.common.cmp.PKIStatusInfo(
                    errorMsgContent.getPKIStatusInfo());

            if (pkiStatus.getPkiFailureInfo() == PKIFailureInfo.systemFailure) {
                auditStatus = AuditStatus.FAILED;
            }
            auditEvent.setStatus(auditStatus);

            String statusString = pkiStatus.getStatusMessage();
            if (statusString != null) {
                auditEvent.addEventData(new AuditEventData("message", statusString));
            }
        } else if (auditEvent.getStatus() == null) {
            auditEvent.setStatus(AuditStatus.SUCCESSFUL);
        }
    }

    return new PKIMessage(respHeader.build(), respBody);
}

From source file:org.xipki.commons.remotep11.server.CmpResponder.java

License:Open Source License

PKIMessage processPkiMessage(final LocalP11CryptServicePool p11CryptServicePool, final String moduleName,
        final PKIMessage pkiMessage) {
    ParamUtil.requireNonNull("p11CryptServicePool", p11CryptServicePool);
    ParamUtil.requireNonNull("pkiMessage", pkiMessage);
    GeneralPKIMessage message = new GeneralPKIMessage(pkiMessage);

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

    if (tid == null) {
        byte[] randomBytes = randomTransactionId();
        tid = new DEROctetString(randomBytes);
    }/* ww  w  .  j a  v  a 2s  .co m*/
    String tidStr = Hex.toHexString(tid.getOctets());

    PKIHeaderBuilder respHeaderBuilder = new PKIHeaderBuilder(reqHeader.getPvno().getValue().intValue(), sender,
            reqHeader.getSender());
    respHeaderBuilder.setTransactionID(tid);

    PKIBody reqBody = message.getBody();
    final int type = reqBody.getType();

    PKIHeader respHeader = respHeaderBuilder.build();

    if (type != PKIBody.TYPE_GEN_MSG) {
        ErrorMsgContent emc = new ErrorMsgContent(new PKIStatusInfo(PKIStatus.rejection,
                new PKIFreeText("unsupported type " + type), new PKIFailureInfo(PKIFailureInfo.badRequest)));

        PKIBody respBody = new PKIBody(PKIBody.TYPE_ERROR, emc);
        return new PKIMessage(respHeader, respBody);
    }

    GenMsgContent genMsgBody = GenMsgContent.getInstance(reqBody.getContent());
    InfoTypeAndValue[] itvs = genMsgBody.toInfoTypeAndValueArray();

    InfoTypeAndValue itv = null;
    if (itvs != null && itvs.length > 0) {
        for (InfoTypeAndValue m : itvs) {
            ASN1ObjectIdentifier itvType = m.getInfoType();
            if (ObjectIdentifiers.id_xipki_cmp_cmpGenmsg.equals(itvType)) {
                itv = m;
                break;
            }
        }
    }

    if (itv == null) {
        final String statusMessage = String.format("PKIBody type %s is only supported with the sub-knownTypes",
                ObjectIdentifiers.id_xipki_cmp_cmpGenmsg.getId());
        return createRejectionPkiMessage(respHeader, PKIFailureInfo.badRequest, statusMessage);
    }

    try {
        return doProcessPkiMessage(p11CryptServicePool, moduleName, itv, respHeader);
    } catch (BadAsn1ObjectException ex) {
        LogUtil.error(LOG, ex, "could not process CMP message " + tidStr);
        return createRejectionPkiMessage(respHeader, PKIFailureInfo.badRequest, ex.getMessage());
    } catch (P11TokenException ex) {
        LogUtil.error(LOG, ex, "could not process CMP message " + tidStr);

        String p11ErrorType;
        if (ex instanceof P11UnknownEntityException) {
            p11ErrorType = P11ProxyConstants.ERROR_UNKNOWN_ENTITY;
        } else if (ex instanceof P11DuplicateEntityException) {
            p11ErrorType = P11ProxyConstants.ERROR_DUPLICATE_ENTITY;
        } else if (ex instanceof P11UnsupportedMechanismException) {
            p11ErrorType = P11ProxyConstants.ERROR_UNSUPPORTED_MECHANISM;
        } else {
            p11ErrorType = P11ProxyConstants.ERROR_P11_TOKENERROR;
        }

        String errorMessage = ex.getMessage();

        if (errorMessage == null) {
            errorMessage = "NULL";
        } else if (StringUtil.isBlank(errorMessage.trim())) {
            errorMessage = "NULL";
        }

        ConfPairs confPairs = new ConfPairs(p11ErrorType, errorMessage);
        return createRejectionPkiMessage(respHeader, PKIFailureInfo.badRequest, confPairs.getEncoded());
    } catch (Throwable th) {
        LogUtil.error(LOG, th, "could not process CMP message " + tidStr);
        return createRejectionPkiMessage(respHeader, PKIFailureInfo.systemFailure, "SYSTEM_FAILURE");
    }
}

From source file:org.xipki.commons.security.pkcs11.proxy.ProxyP11Module.java

License:Open Source License

ASN1Encodable send(final int action, final ASN1Encodable content) throws P11TokenException {
    ASN1EncodableVector vec = new ASN1EncodableVector();
    vec.add(new ASN1Integer(version));
    vec.add(new ASN1Integer(action));
    vec.add((content != null) ? content : DERNull.INSTANCE);
    InfoTypeAndValue itvReq = new InfoTypeAndValue(ObjectIdentifiers.id_xipki_cmp_cmpGenmsg,
            new DERSequence(vec));

    GenMsgContent genMsgContent = new GenMsgContent(itvReq);
    PKIHeader header = buildPkiHeader(null);
    PKIBody body = new PKIBody(PKIBody.TYPE_GEN_MSG, genMsgContent);
    PKIMessage request = new PKIMessage(header, body);

    byte[] encodedRequest;
    try {/*from w  w  w .  java2 s.c  o  m*/
        encodedRequest = request.getEncoded();
    } catch (IOException ex) {
        final String msg = "could not encode the PKI request";
        LOG.error(msg + " {}", request);
        throw new P11TokenException(msg + ": " + ex.getMessage(), ex);
    }

    byte[] encodedResponse;
    try {
        encodedResponse = send(encodedRequest);
    } catch (IOException ex) {
        final String msg = "could not send the PKI request";
        LOG.error(msg + " {}", request);
        throw new P11TokenException(msg + ": " + ex.getMessage(), ex);
    }

    GeneralPKIMessage response;
    try {
        response = new GeneralPKIMessage(encodedResponse);
    } catch (IOException ex) {
        final String msg = "could not decode the received PKI message";
        LOG.error(msg + ": {}", Hex.toHexString(encodedResponse));
        throw new P11TokenException(msg + ": " + 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);
    }

    return extractItvInfoValue(action, response);
}

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 v a 2 s  .c om
        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.client.impl.CmpRequestor.java

License:Open Source License

private ProtectionVerificationResult verifyProtection(final String tid, final GeneralPKIMessage pkiMessage)
        throws CMPException, InvalidKeyException, OperatorCreationException {
    ProtectedPKIMessage protectedMsg = new ProtectedPKIMessage(pkiMessage);

    if (protectedMsg.hasPasswordBasedMacProtection()) {
        LOG.warn("NOT_SIGNAUTRE_BASED: " + pkiMessage.getHeader().getProtectionAlg().getAlgorithm().getId());
        return new ProtectionVerificationResult(null, ProtectionResult.NOT_SIGNATURE_BASED);
    }/*from  w  w  w. j  a  va  2s.  c  om*/

    PKIHeader header = protectedMsg.getHeader();

    if (recipientName != null) {
        boolean authorizedResponder = true;
        if (header.getSender().getTagNo() != GeneralName.directoryName) {
            authorizedResponder = false;
        } else {
            X500Name msgSender = X500Name.getInstance(header.getSender().getName());
            authorizedResponder = recipientName.equals(msgSender);
        }

        if (!authorizedResponder) {
            LOG.warn("tid={}: not authorized responder '{}'", tid, header.getSender());
            return new ProtectionVerificationResult(null, ProtectionResult.SENDER_NOT_AUTHORIZED);
        }
    }

    AlgorithmIdentifier protectionAlgo = protectedMsg.getHeader().getProtectionAlg();
    if (!responder.getSigAlgoValidator().isAlgorithmPermitted(protectionAlgo)) {
        String algoName;
        try {
            algoName = AlgorithmUtil.getSignatureAlgoName(protectionAlgo);
        } catch (NoSuchAlgorithmException ex) {
            algoName = protectionAlgo.getAlgorithm().getId();
        }
        LOG.warn("tid={}: response protected by untrusted protection algorithm '{}'", tid, algoName);
        return new ProtectionVerificationResult(null, ProtectionResult.INVALID);
    }

    X509Certificate cert = responder.getCert();
    ContentVerifierProvider verifierProvider = securityFactory.getContentVerifierProvider(cert);
    if (verifierProvider == null) {
        LOG.warn("tid={}: not authorized responder '{}'", tid, header.getSender());
        return new ProtectionVerificationResult(cert, ProtectionResult.SENDER_NOT_AUTHORIZED);
    }

    boolean signatureValid = protectedMsg.verify(verifierProvider);
    ProtectionResult protRes = signatureValid ? ProtectionResult.VALID : ProtectionResult.INVALID;
    return new ProtectionVerificationResult(cert, protRes);
}

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;//from   w w w  .j a v a2s .  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;
}