Search in sources :

Example 1 with AuditStatus

use of org.xipki.audit.AuditStatus in project xipki by xipki.

the class X509CaCmpResponderImpl method processPkiMessage0.

@Override
protected PKIMessage processPkiMessage0(PKIMessage request, RequestorInfo requestor, ASN1OctetString tid, GeneralPKIMessage message, String msgId, AuditEvent event) {
    if (!(requestor instanceof CmpRequestorInfo)) {
        throw new IllegalArgumentException("unknown requestor type " + requestor.getClass().getName());
    }
    CmpRequestorInfo tmpRequestor = (CmpRequestorInfo) requestor;
    event.addEventData(CaAuditConstants.NAME_requestor, tmpRequestor.getIdent().getName());
    PKIHeader reqHeader = message.getHeader();
    PKIHeaderBuilder respHeader = new PKIHeaderBuilder(reqHeader.getPvno().getValue().intValue(), getSender(), reqHeader.getSender());
    respHeader.setTransactionID(tid);
    ASN1OctetString senderNonce = reqHeader.getSenderNonce();
    if (senderNonce != null) {
        respHeader.setRecipNonce(senderNonce);
    }
    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:
                String eventType = null;
                if (PKIBody.TYPE_CERT_REQ == type) {
                    eventType = CaAuditConstants.TYPE_CMP_cr;
                } else if (PKIBody.TYPE_KEY_UPDATE_REQ == type) {
                    eventType = CaAuditConstants.TYPE_CMP_kur;
                } else if (PKIBody.TYPE_P10_CERT_REQ == type) {
                    eventType = CaAuditConstants.TYPE_CMP_p10Cr;
                } else if (PKIBody.TYPE_CROSS_CERT_REQ == type) {
                    eventType = CaAuditConstants.TYPE_CMP_ccr;
                }
                if (eventType != null) {
                    event.addEventType(eventType);
                }
                respBody = cmpEnrollCert(request, respHeader, cmpControl, reqHeader, reqBody, tmpRequestor, tid, msgId, event);
                break;
            case PKIBody.TYPE_CERT_CONFIRM:
                event.addEventType(CaAuditConstants.TYPE_CMP_certConf);
                CertConfirmContent certConf = (CertConfirmContent) reqBody.getContent();
                respBody = confirmCertificates(tid, certConf, msgId);
                break;
            case PKIBody.TYPE_REVOCATION_REQ:
                respBody = cmpUnRevokeRemoveCertificates(request, respHeader, cmpControl, reqHeader, reqBody, tmpRequestor, msgId, event);
                break;
            case PKIBody.TYPE_CONFIRM:
                event.addEventType(CaAuditConstants.TYPE_CMP_pkiConf);
                respBody = new PKIBody(PKIBody.TYPE_CONFIRM, DERNull.INSTANCE);
                break;
            case PKIBody.TYPE_GEN_MSG:
                respBody = cmpGeneralMsg(respHeader, cmpControl, reqHeader, reqBody, tmpRequestor, tid, msgId, event);
                break;
            case PKIBody.TYPE_ERROR:
                event.addEventType(CaAuditConstants.TYPE_CMP_error);
                revokePendingCertificates(tid, msgId);
                respBody = new PKIBody(PKIBody.TYPE_CONFIRM, DERNull.INSTANCE);
                break;
            default:
                event.addEventType("PKIBody." + type);
                respBody = buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badRequest, "unsupported type " + type);
                break;
        }
    // end switch (type)
    } catch (InsuffientPermissionException ex) {
        ErrorMsgContent emc = new ErrorMsgContent(new PKIStatusInfo(PKIStatus.rejection, new PKIFreeText(ex.getMessage()), new PKIFailureInfo(PKIFailureInfo.notAuthorized)));
        respBody = new PKIBody(PKIBody.TYPE_ERROR, emc);
    }
    if (respBody.getType() == PKIBody.TYPE_ERROR) {
        ErrorMsgContent errorMsgContent = (ErrorMsgContent) respBody.getContent();
        AuditStatus auditStatus = AuditStatus.FAILED;
        org.xipki.cmp.PkiStatusInfo pkiStatus = new org.xipki.cmp.PkiStatusInfo(errorMsgContent.getPKIStatusInfo());
        if (pkiStatus.pkiFailureInfo() == PKIFailureInfo.systemFailure) {
            auditStatus = AuditStatus.FAILED;
        }
        event.setStatus(auditStatus);
        String statusString = pkiStatus.statusMessage();
        if (statusString != null) {
            event.addEventData(CaAuditConstants.NAME_message, statusString);
        }
    } else if (event.getStatus() == null) {
        event.setStatus(AuditStatus.SUCCESSFUL);
    }
    return new PKIMessage(respHeader.build(), respBody);
}
Also used : PKIHeader(org.bouncycastle.asn1.cmp.PKIHeader) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) PKIMessage(org.bouncycastle.asn1.cmp.PKIMessage) GeneralPKIMessage(org.bouncycastle.cert.cmp.GeneralPKIMessage) PKIBody(org.bouncycastle.asn1.cmp.PKIBody) PKIHeaderBuilder(org.bouncycastle.asn1.cmp.PKIHeaderBuilder) PKIStatusInfo(org.bouncycastle.asn1.cmp.PKIStatusInfo) InsuffientPermissionException(org.xipki.ca.api.InsuffientPermissionException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) PKIFreeText(org.bouncycastle.asn1.cmp.PKIFreeText) PKIFailureInfo(org.bouncycastle.asn1.cmp.PKIFailureInfo) CertConfirmContent(org.bouncycastle.asn1.cmp.CertConfirmContent) AuditStatus(org.xipki.audit.AuditStatus) CmpControl(org.xipki.ca.server.mgmt.api.CmpControl) ErrorMsgContent(org.bouncycastle.asn1.cmp.ErrorMsgContent)

Example 2 with AuditStatus

use of org.xipki.audit.AuditStatus in project xipki by xipki.

the class HttpScepServlet method service0.

private void service0(HttpServletRequest req, HttpServletResponse resp, boolean viaPost) throws ServletException, IOException {
    AuditServiceRegister auditServiceRegister = ServletHelper.getAuditServiceRegister();
    if (auditServiceRegister == null) {
        LOG.error("ServletHelper.auditServiceRegister not configured");
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    ResponderManager responderManager = ServletHelper.getResponderManager();
    if (responderManager == null) {
        LOG.error("ServletHelper.responderManager not configured");
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    String path = StringUtil.getRelativeRequestUri(req.getServletPath(), req.getRequestURI());
    String scepName = null;
    String certProfileName = null;
    if (path.length() > 1) {
        String scepPath = path;
        if (scepPath.endsWith(CGI_PROGRAM)) {
            // skip also the first char (which is always '/')
            String tpath = scepPath.substring(1, scepPath.length() - CGI_PROGRAM_LEN);
            String[] tokens = tpath.split("/");
            if (tokens.length == 2) {
                scepName = tokens[0];
                certProfileName = tokens[1].toLowerCase();
            }
        }
    // end if
    }
    if (scepName == null || certProfileName == null) {
        sendError(resp, HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    AuditService auditService = auditServiceRegister.getAuditService();
    AuditEvent event = new AuditEvent(new Date());
    event.setApplicationName("SCEP");
    event.setName(CaAuditConstants.NAME_PERF);
    event.addEventData(CaAuditConstants.NAME_SCEP_name, scepName + "/" + certProfileName);
    event.addEventData(CaAuditConstants.NAME_reqType, RequestType.SCEP.name());
    String msgId = RandomUtil.nextHexLong();
    event.addEventData(CaAuditConstants.NAME_mid, msgId);
    AuditLevel auditLevel = AuditLevel.INFO;
    AuditStatus auditStatus = AuditStatus.SUCCESSFUL;
    String auditMessage = null;
    try {
        Scep responder = responderManager.getScep(scepName);
        if (responder == null || !responder.isOnService() || !responder.supportsCertProfile(certProfileName)) {
            auditMessage = "unknown SCEP '" + scepName + "/" + certProfileName + "'";
            LOG.warn(auditMessage);
            auditStatus = AuditStatus.FAILED;
            sendError(resp, HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        String operation = req.getParameter("operation");
        event.addEventData(CaAuditConstants.NAME_SCEP_operation, operation);
        if ("PKIOperation".equalsIgnoreCase(operation)) {
            CMSSignedData reqMessage;
            // parse the request
            try {
                byte[] content;
                if (viaPost) {
                    content = IoUtil.read(req.getInputStream());
                } else {
                    String b64 = req.getParameter("message");
                    content = Base64.decode(b64);
                }
                reqMessage = new CMSSignedData(content);
            } catch (Exception ex) {
                final String msg = "invalid request";
                LogUtil.error(LOG, ex, msg);
                auditMessage = msg;
                auditStatus = AuditStatus.FAILED;
                sendError(resp, HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            ContentInfo ci;
            try {
                ci = responder.servicePkiOperation(reqMessage, certProfileName, msgId, event);
            } catch (MessageDecodingException ex) {
                final String msg = "could not decrypt and/or verify the request";
                LogUtil.error(LOG, ex, msg);
                auditMessage = msg;
                auditStatus = AuditStatus.FAILED;
                sendError(resp, HttpServletResponse.SC_BAD_REQUEST);
                return;
            } catch (OperationException ex) {
                ErrorCode code = ex.getErrorCode();
                int httpCode;
                switch(code) {
                    case ALREADY_ISSUED:
                    case CERT_REVOKED:
                    case CERT_UNREVOKED:
                        httpCode = HttpServletResponse.SC_FORBIDDEN;
                        break;
                    case BAD_CERT_TEMPLATE:
                    case BAD_REQUEST:
                    case BAD_POP:
                    case INVALID_EXTENSION:
                    case UNKNOWN_CERT:
                    case UNKNOWN_CERT_PROFILE:
                        httpCode = HttpServletResponse.SC_BAD_REQUEST;
                        break;
                    case NOT_PERMITTED:
                        httpCode = HttpServletResponse.SC_UNAUTHORIZED;
                        break;
                    case SYSTEM_UNAVAILABLE:
                        httpCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
                        break;
                    case CRL_FAILURE:
                    case DATABASE_FAILURE:
                    case SYSTEM_FAILURE:
                        httpCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                        break;
                    default:
                        httpCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                        break;
                }
                auditMessage = ex.getMessage();
                LogUtil.error(LOG, ex, auditMessage);
                auditStatus = AuditStatus.FAILED;
                sendError(resp, httpCode);
                return;
            }
            byte[] bodyBytes = ci.getEncoded();
            sendOKResponse(resp, CT_RESPONSE, bodyBytes);
        } else if (Operation.GetCACaps.getCode().equalsIgnoreCase(operation)) {
            // CA-Ident is ignored
            byte[] caCapsBytes = responder.getCaCaps().getBytes();
            sendOKResponse(resp, ScepConstants.CT_TEXT_PLAIN, caCapsBytes);
        } else if (Operation.GetCACert.getCode().equalsIgnoreCase(operation)) {
            // CA-Ident is ignored
            byte[] respBytes = responder.getCaCertResp().getBytes();
            sendOKResponse(resp, ScepConstants.CT_X509_CA_RA_CERT, respBytes);
        } else if (Operation.GetNextCACert.getCode().equalsIgnoreCase(operation)) {
            auditMessage = "SCEP operation '" + operation + "' is not permitted";
            auditStatus = AuditStatus.FAILED;
            sendError(resp, HttpServletResponse.SC_FORBIDDEN);
            return;
        } else {
            auditMessage = "unknown SCEP operation '" + operation + "'";
            auditStatus = AuditStatus.FAILED;
            sendError(resp, HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
    } catch (Throwable th) {
        if (th instanceof EOFException) {
            final String msg = "connection reset by peer";
            if (LOG.isWarnEnabled()) {
                LogUtil.warn(LOG, th, msg);
            }
            LOG.debug(msg, th);
        } else {
            LOG.error("Throwable thrown, this should not happen!", th);
        }
        auditLevel = AuditLevel.ERROR;
        auditStatus = AuditStatus.FAILED;
        auditMessage = "internal error";
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        audit(auditService, event, auditLevel, auditStatus, auditMessage);
    }
}
Also used : AuditLevel(org.xipki.audit.AuditLevel) ResponderManager(org.xipki.ca.server.api.ResponderManager) CMSSignedData(org.bouncycastle.cms.CMSSignedData) Date(java.util.Date) ServletException(javax.servlet.ServletException) MessageDecodingException(org.xipki.scep.exception.MessageDecodingException) IOException(java.io.IOException) EOFException(java.io.EOFException) OperationException(org.xipki.ca.api.OperationException) AuditStatus(org.xipki.audit.AuditStatus) MessageDecodingException(org.xipki.scep.exception.MessageDecodingException) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) EOFException(java.io.EOFException) AuditEvent(org.xipki.audit.AuditEvent) ErrorCode(org.xipki.ca.api.OperationException.ErrorCode) Scep(org.xipki.ca.server.api.Scep) AuditServiceRegister(org.xipki.audit.AuditServiceRegister) AuditService(org.xipki.audit.AuditService) OperationException(org.xipki.ca.api.OperationException)

Example 3 with AuditStatus

use of org.xipki.audit.AuditStatus in project xipki by xipki.

the class RestImpl method service.

public RestResponse service(String path, AuditEvent event, byte[] request, HttpRequestMetadataRetriever httpRetriever) {
    event.setApplicationName(CaAuditConstants.APPNAME);
    event.setName(CaAuditConstants.NAME_PERF);
    event.addEventData(CaAuditConstants.NAME_reqType, RequestType.REST.name());
    String msgId = RandomUtil.nextHexLong();
    event.addEventData(CaAuditConstants.NAME_mid, msgId);
    AuditLevel auditLevel = AuditLevel.INFO;
    AuditStatus auditStatus = AuditStatus.SUCCESSFUL;
    String auditMessage = null;
    try {
        if (responderManager == null) {
            String message = "responderManager in servlet not configured";
            LOG.error(message);
            throw new HttpRespAuditException(HttpResponseStatus.INTERNAL_SERVER_ERROR, null, message, AuditLevel.ERROR, AuditStatus.FAILED);
        }
        String caName = null;
        String command = null;
        X509Ca ca = null;
        if (path.length() > 1) {
            // the first char is always '/'
            String coreUri = path;
            int sepIndex = coreUri.indexOf('/', 1);
            if (sepIndex == -1 || sepIndex == coreUri.length() - 1) {
                String message = "invalid path " + path;
                LOG.error(message);
                throw new HttpRespAuditException(HttpResponseStatus.NOT_FOUND, null, message, AuditLevel.ERROR, AuditStatus.FAILED);
            }
            // skip also the first char ('/')
            String caAlias = coreUri.substring(1, sepIndex);
            command = coreUri.substring(sepIndex + 1);
            caName = responderManager.getCaNameForAlias(caAlias);
            if (caName == null) {
                caName = caAlias.toLowerCase();
            }
            ca = ((X509CaCmpResponderImpl) responderManager.getX509CaResponder(caName)).getCa();
        }
        if (caName == null || ca == null || ca.getCaInfo().getStatus() != CaStatus.ACTIVE) {
            String message;
            if (caName == null) {
                message = "no CA is specified";
            } else if (ca == null) {
                message = "unknown CA '" + caName + "'";
            } else {
                message = "CA '" + caName + "' is out of service";
            }
            LOG.warn(message);
            throw new HttpRespAuditException(HttpResponseStatus.NOT_FOUND, null, message, AuditLevel.INFO, AuditStatus.FAILED);
        }
        event.addEventData(CaAuditConstants.NAME_ca, ca.getCaIdent().getName());
        event.addEventType(command);
        RequestorInfo requestor;
        // Retrieve the user:password
        String hdrValue = httpRetriever.getHeader("Authorization");
        if (hdrValue != null && hdrValue.startsWith("Basic ")) {
            String user = null;
            byte[] password = null;
            if (hdrValue.length() > 6) {
                String b64 = hdrValue.substring(6);
                byte[] userPwd = Base64.decodeFast(b64);
                int idx = -1;
                for (int i = 0; i < userPwd.length; i++) {
                    if (userPwd[i] == ':') {
                        idx = i;
                        break;
                    }
                }
                if (idx != -1 && idx < userPwd.length - 1) {
                    user = new String(Arrays.copyOfRange(userPwd, 0, idx));
                    password = Arrays.copyOfRange(userPwd, idx + 1, userPwd.length);
                }
            }
            if (user == null) {
                throw new HttpRespAuditException(HttpResponseStatus.UNAUTHORIZED, "invalid Authorization information", AuditLevel.INFO, AuditStatus.FAILED);
            }
            NameId userIdent = ca.authenticateUser(user, password);
            if (userIdent == null) {
                throw new HttpRespAuditException(HttpResponseStatus.UNAUTHORIZED, "could not authenticate user", AuditLevel.INFO, AuditStatus.FAILED);
            }
            requestor = ca.getByUserRequestor(userIdent);
        } else {
            X509Certificate clientCert = httpRetriever.getTlsClientCert();
            if (clientCert == null) {
                throw new HttpRespAuditException(HttpResponseStatus.UNAUTHORIZED, null, "no client certificate", AuditLevel.INFO, AuditStatus.FAILED);
            }
            requestor = ca.getRequestor(clientCert);
        }
        if (requestor == null) {
            throw new OperationException(ErrorCode.NOT_PERMITTED, "no requestor specified");
        }
        event.addEventData(CaAuditConstants.NAME_requestor, requestor.getIdent().getName());
        String respCt = null;
        byte[] respBytes = null;
        if (RestAPIConstants.CMD_cacert.equalsIgnoreCase(command)) {
            respCt = RestAPIConstants.CT_pkix_cert;
            respBytes = ca.getCaInfo().getCert().getEncodedCert();
        } else if (RestAPIConstants.CMD_enroll_cert.equalsIgnoreCase(command)) {
            String profile = httpRetriever.getParameter(RestAPIConstants.PARAM_profile);
            if (StringUtil.isBlank(profile)) {
                throw new HttpRespAuditException(HttpResponseStatus.BAD_REQUEST, null, "required parameter " + RestAPIConstants.PARAM_profile + " not specified", AuditLevel.INFO, AuditStatus.FAILED);
            }
            profile = profile.toLowerCase();
            try {
                requestor.assertPermitted(PermissionConstants.ENROLL_CERT);
            } catch (InsuffientPermissionException ex) {
                throw new OperationException(ErrorCode.NOT_PERMITTED, ex.getMessage());
            }
            if (!requestor.isCertProfilePermitted(profile)) {
                throw new OperationException(ErrorCode.NOT_PERMITTED, "certProfile " + profile + " is not allowed");
            }
            String ct = httpRetriever.getHeader("Content-Type");
            if (!RestAPIConstants.CT_pkcs10.equalsIgnoreCase(ct)) {
                String message = "unsupported media type " + ct;
                throw new HttpRespAuditException(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE, message, AuditLevel.INFO, AuditStatus.FAILED);
            }
            String strNotBefore = httpRetriever.getParameter(RestAPIConstants.PARAM_not_before);
            Date notBefore = (strNotBefore == null) ? null : DateUtil.parseUtcTimeyyyyMMddhhmmss(strNotBefore);
            String strNotAfter = httpRetriever.getParameter(RestAPIConstants.PARAM_not_after);
            Date notAfter = (strNotAfter == null) ? null : DateUtil.parseUtcTimeyyyyMMddhhmmss(strNotAfter);
            byte[] encodedCsr = request;
            CertificationRequest csr = CertificationRequest.getInstance(encodedCsr);
            ca.checkCsr(csr);
            CertificationRequestInfo certTemp = csr.getCertificationRequestInfo();
            X500Name subject = certTemp.getSubject();
            SubjectPublicKeyInfo publicKeyInfo = certTemp.getSubjectPublicKeyInfo();
            Extensions extensions = CaUtil.getExtensions(certTemp);
            CertTemplateData certTemplate = new CertTemplateData(subject, publicKeyInfo, notBefore, notAfter, extensions, profile);
            X509CertificateInfo certInfo = ca.generateCertificate(certTemplate, requestor, RequestType.REST, null, msgId);
            if (ca.getCaInfo().isSaveRequest()) {
                long dbId = ca.addRequest(encodedCsr);
                ca.addRequestCert(dbId, certInfo.getCert().getCertId());
            }
            X509Cert cert = certInfo.getCert();
            if (cert == null) {
                String message = "could not generate certificate";
                LOG.warn(message);
                throw new HttpRespAuditException(HttpResponseStatus.INTERNAL_SERVER_ERROR, null, message, AuditLevel.INFO, AuditStatus.FAILED);
            }
            respCt = RestAPIConstants.CT_pkix_cert;
            respBytes = cert.getEncodedCert();
        } else if (RestAPIConstants.CMD_revoke_cert.equalsIgnoreCase(command) || RestAPIConstants.CMD_delete_cert.equalsIgnoreCase(command)) {
            int permission;
            if (RestAPIConstants.CMD_revoke_cert.equalsIgnoreCase(command)) {
                permission = PermissionConstants.REVOKE_CERT;
            } else {
                permission = PermissionConstants.REMOVE_CERT;
            }
            try {
                requestor.assertPermitted(permission);
            } catch (InsuffientPermissionException ex) {
                throw new OperationException(ErrorCode.NOT_PERMITTED, ex.getMessage());
            }
            String strCaSha1 = httpRetriever.getParameter(RestAPIConstants.PARAM_ca_sha1);
            if (StringUtil.isBlank(strCaSha1)) {
                throw new HttpRespAuditException(HttpResponseStatus.BAD_REQUEST, null, "required parameter " + RestAPIConstants.PARAM_ca_sha1 + " not specified", AuditLevel.INFO, AuditStatus.FAILED);
            }
            String strSerialNumber = httpRetriever.getParameter(RestAPIConstants.PARAM_serial_number);
            if (StringUtil.isBlank(strSerialNumber)) {
                throw new HttpRespAuditException(HttpResponseStatus.BAD_REQUEST, null, "required parameter " + RestAPIConstants.PARAM_serial_number + " not specified", AuditLevel.INFO, AuditStatus.FAILED);
            }
            if (!strCaSha1.equalsIgnoreCase(ca.getHexSha1OfCert())) {
                throw new HttpRespAuditException(HttpResponseStatus.BAD_REQUEST, null, "unknown " + RestAPIConstants.PARAM_ca_sha1, AuditLevel.INFO, AuditStatus.FAILED);
            }
            BigInteger serialNumber = toBigInt(strSerialNumber);
            if (RestAPIConstants.CMD_revoke_cert.equalsIgnoreCase(command)) {
                String strReason = httpRetriever.getParameter(RestAPIConstants.PARAM_reason);
                CrlReason reason = (strReason == null) ? CrlReason.UNSPECIFIED : CrlReason.forNameOrText(strReason);
                if (reason == CrlReason.REMOVE_FROM_CRL) {
                    ca.unrevokeCertificate(serialNumber, msgId);
                } else {
                    Date invalidityTime = null;
                    String strInvalidityTime = httpRetriever.getParameter(RestAPIConstants.PARAM_invalidity_time);
                    if (StringUtil.isNotBlank(strInvalidityTime)) {
                        invalidityTime = DateUtil.parseUtcTimeyyyyMMddhhmmss(strInvalidityTime);
                    }
                    ca.revokeCertificate(serialNumber, reason, invalidityTime, msgId);
                }
            } else if (RestAPIConstants.CMD_delete_cert.equalsIgnoreCase(command)) {
                ca.removeCertificate(serialNumber, msgId);
            }
        } else if (RestAPIConstants.CMD_crl.equalsIgnoreCase(command)) {
            try {
                requestor.assertPermitted(PermissionConstants.GET_CRL);
            } catch (InsuffientPermissionException ex) {
                throw new OperationException(ErrorCode.NOT_PERMITTED, ex.getMessage());
            }
            String strCrlNumber = httpRetriever.getParameter(RestAPIConstants.PARAM_crl_number);
            BigInteger crlNumber = null;
            if (StringUtil.isNotBlank(strCrlNumber)) {
                try {
                    crlNumber = toBigInt(strCrlNumber);
                } catch (NumberFormatException ex) {
                    String message = "invalid crlNumber '" + strCrlNumber + "'";
                    LOG.warn(message);
                    throw new HttpRespAuditException(HttpResponseStatus.BAD_REQUEST, null, message, AuditLevel.INFO, AuditStatus.FAILED);
                }
            }
            X509CRL crl = ca.getCrl(crlNumber);
            if (crl == null) {
                String message = "could not get CRL";
                LOG.warn(message);
                throw new HttpRespAuditException(HttpResponseStatus.INTERNAL_SERVER_ERROR, null, message, AuditLevel.INFO, AuditStatus.FAILED);
            }
            respCt = RestAPIConstants.CT_pkix_crl;
            respBytes = crl.getEncoded();
        } else if (RestAPIConstants.CMD_new_crl.equalsIgnoreCase(command)) {
            try {
                requestor.assertPermitted(PermissionConstants.GEN_CRL);
            } catch (InsuffientPermissionException ex) {
                throw new OperationException(ErrorCode.NOT_PERMITTED, ex.getMessage());
            }
            X509CRL crl = ca.generateCrlOnDemand(msgId);
            if (crl == null) {
                String message = "could not generate CRL";
                LOG.warn(message);
                throw new HttpRespAuditException(HttpResponseStatus.INTERNAL_SERVER_ERROR, null, message, AuditLevel.INFO, AuditStatus.FAILED);
            }
            respCt = RestAPIConstants.CT_pkix_crl;
            respBytes = crl.getEncoded();
        } else {
            String message = "invalid command '" + command + "'";
            LOG.error(message);
            throw new HttpRespAuditException(HttpResponseStatus.NOT_FOUND, message, AuditLevel.INFO, AuditStatus.FAILED);
        }
        Map<String, String> headers = new HashMap<>();
        headers.put(RestAPIConstants.HEADER_PKISTATUS, RestAPIConstants.PKISTATUS_accepted);
        return new RestResponse(HttpResponseStatus.OK, respCt, headers, respBytes);
    } catch (OperationException ex) {
        ErrorCode code = ex.getErrorCode();
        if (LOG.isWarnEnabled()) {
            String msg = StringUtil.concat("generate certificate, OperationException: code=", code.name(), ", message=", ex.getErrorMessage());
            LOG.warn(msg);
            LOG.debug(msg, ex);
        }
        int sc;
        String failureInfo;
        switch(code) {
            case ALREADY_ISSUED:
                sc = HttpResponseStatus.BAD_REQUEST;
                failureInfo = RestAPIConstants.FAILINFO_badRequest;
                break;
            case BAD_CERT_TEMPLATE:
                sc = HttpResponseStatus.BAD_REQUEST;
                failureInfo = RestAPIConstants.FAILINFO_badCertTemplate;
                break;
            case BAD_REQUEST:
                sc = HttpResponseStatus.BAD_REQUEST;
                failureInfo = RestAPIConstants.FAILINFO_badRequest;
                break;
            case CERT_REVOKED:
                sc = HttpResponseStatus.CONFLICT;
                failureInfo = RestAPIConstants.FAILINFO_certRevoked;
                break;
            case CRL_FAILURE:
                sc = HttpResponseStatus.INTERNAL_SERVER_ERROR;
                failureInfo = RestAPIConstants.FAILINFO_systemFailure;
                break;
            case DATABASE_FAILURE:
                sc = HttpResponseStatus.INTERNAL_SERVER_ERROR;
                failureInfo = RestAPIConstants.FAILINFO_systemFailure;
                break;
            case NOT_PERMITTED:
                sc = HttpResponseStatus.UNAUTHORIZED;
                failureInfo = RestAPIConstants.FAILINFO_notAuthorized;
                break;
            case INVALID_EXTENSION:
                sc = HttpResponseStatus.BAD_REQUEST;
                failureInfo = RestAPIConstants.FAILINFO_badRequest;
                break;
            case SYSTEM_FAILURE:
                sc = HttpResponseStatus.INTERNAL_SERVER_ERROR;
                failureInfo = RestAPIConstants.FAILINFO_systemFailure;
                break;
            case SYSTEM_UNAVAILABLE:
                sc = HttpResponseStatus.SERVICE_UNAVAILABLE;
                failureInfo = RestAPIConstants.FAILINFO_systemUnavail;
                break;
            case UNKNOWN_CERT:
                sc = HttpResponseStatus.BAD_REQUEST;
                failureInfo = RestAPIConstants.FAILINFO_badCertId;
                break;
            case UNKNOWN_CERT_PROFILE:
                sc = HttpResponseStatus.BAD_REQUEST;
                failureInfo = RestAPIConstants.FAILINFO_badCertTemplate;
                break;
            default:
                sc = HttpResponseStatus.INTERNAL_SERVER_ERROR;
                failureInfo = RestAPIConstants.FAILINFO_systemFailure;
                break;
        }
        // end switch (code)
        event.setStatus(AuditStatus.FAILED);
        event.addEventData(CaAuditConstants.NAME_message, code.name());
        switch(code) {
            case DATABASE_FAILURE:
            case SYSTEM_FAILURE:
                auditMessage = code.name();
                break;
            default:
                auditMessage = code.name() + ": " + ex.getErrorMessage();
                break;
        }
        // end switch code
        Map<String, String> headers = new HashMap<>();
        headers.put(RestAPIConstants.HEADER_PKISTATUS, RestAPIConstants.PKISTATUS_rejection);
        if (StringUtil.isNotBlank(failureInfo)) {
            headers.put(RestAPIConstants.HEADER_failInfo, failureInfo);
        }
        return new RestResponse(sc, null, headers, null);
    } catch (HttpRespAuditException ex) {
        auditStatus = ex.getAuditStatus();
        auditLevel = ex.getAuditLevel();
        auditMessage = ex.getAuditMessage();
        return new RestResponse(ex.getHttpStatus(), null, null, null);
    } catch (Throwable th) {
        if (th instanceof EOFException) {
            LogUtil.warn(LOG, th, "connection reset by peer");
        } else {
            LOG.error("Throwable thrown, this should not happen!", th);
        }
        auditLevel = AuditLevel.ERROR;
        auditStatus = AuditStatus.FAILED;
        auditMessage = "internal error";
        return new RestResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR, null, null, null);
    } finally {
        event.setStatus(auditStatus);
        event.setLevel(auditLevel);
        if (auditMessage != null) {
            event.addEventData(CaAuditConstants.NAME_message, auditMessage);
        }
    }
}
Also used : CertificationRequestInfo(org.bouncycastle.asn1.pkcs.CertificationRequestInfo) X509CRL(java.security.cert.X509CRL) NameId(org.xipki.ca.api.NameId) HashMap(java.util.HashMap) X509Ca(org.xipki.ca.server.impl.X509Ca) InsuffientPermissionException(org.xipki.ca.api.InsuffientPermissionException) X500Name(org.bouncycastle.asn1.x500.X500Name) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) CertTemplateData(org.xipki.ca.server.impl.CertTemplateData) X509Cert(org.xipki.security.X509Cert) EOFException(java.io.EOFException) CrlReason(org.xipki.security.CrlReason) OperationException(org.xipki.ca.api.OperationException) RestResponse(org.xipki.ca.server.api.RestResponse) AuditLevel(org.xipki.audit.AuditLevel) X509CertificateInfo(org.xipki.ca.api.publisher.x509.X509CertificateInfo) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) AuditStatus(org.xipki.audit.AuditStatus) BigInteger(java.math.BigInteger) ErrorCode(org.xipki.ca.api.OperationException.ErrorCode) HashMap(java.util.HashMap) Map(java.util.Map) RequestorInfo(org.xipki.ca.server.mgmt.api.RequestorInfo) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest)

Example 4 with AuditStatus

use of org.xipki.audit.AuditStatus in project xipki by xipki.

the class HttpCmpServlet method service.

@Override
public FullHttpResponse service(FullHttpRequest request, ServletURI servletUri, SSLSession sslSession, SslReverseProxyMode sslReverseProxyMode) throws Exception {
    HttpVersion httpVersion = request.protocolVersion();
    HttpMethod method = request.method();
    if (method != HttpMethod.POST) {
        return createErrorResponse(httpVersion, HttpResponseStatus.METHOD_NOT_ALLOWED);
    }
    X509Certificate clientCert = getClientCert(request, sslSession, sslReverseProxyMode);
    AuditService auditService = auditServiceRegister.getAuditService();
    AuditEvent event = new AuditEvent(new Date());
    event.setApplicationName(CaAuditConstants.APPNAME);
    event.setName(CaAuditConstants.NAME_PERF);
    event.addEventData(CaAuditConstants.NAME_reqType, RequestType.CMP.name());
    AuditLevel auditLevel = AuditLevel.INFO;
    AuditStatus auditStatus = AuditStatus.SUCCESSFUL;
    String auditMessage = null;
    try {
        if (responderManager == null) {
            String message = "responderManager in servlet not configured";
            LOG.error(message);
            throw new HttpRespAuditException(HttpResponseStatus.INTERNAL_SERVER_ERROR, message, AuditLevel.ERROR, AuditStatus.FAILED);
        }
        String reqContentType = request.headers().get("Content-Type");
        if (!CT_REQUEST.equalsIgnoreCase(reqContentType)) {
            String message = "unsupported media type " + reqContentType;
            throw new HttpRespAuditException(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE, message, AuditLevel.INFO, AuditStatus.FAILED);
        }
        String caName = null;
        X509CaCmpResponder responder = null;
        if (servletUri.getPath().length() > 1) {
            // skip the first char which is always '/'
            String caAlias = servletUri.getPath().substring(1);
            caName = responderManager.getCaNameForAlias(caAlias);
            if (caName == null) {
                caName = caAlias.toLowerCase();
            }
            responder = responderManager.getX509CaResponder(caName);
        }
        if (caName == null || responder == null || !responder.isOnService()) {
            String message;
            if (caName == null) {
                message = "no CA is specified";
            } else if (responder == null) {
                message = "unknown CA '" + caName + "'";
            } else {
                message = "CA '" + caName + "' is out of service";
            }
            LOG.warn(message);
            throw new HttpRespAuditException(HttpResponseStatus.NOT_FOUND, message, AuditLevel.INFO, AuditStatus.FAILED);
        }
        event.addEventData(CaAuditConstants.NAME_ca, responder.getCaName());
        byte[] reqContent = readContent(request);
        PKIMessage pkiReq;
        try {
            pkiReq = PKIMessage.getInstance(reqContent);
        } catch (Exception ex) {
            LogUtil.error(LOG, ex, "could not parse the request (PKIMessage)");
            throw new HttpRespAuditException(HttpResponseStatus.BAD_REQUEST, "bad request", AuditLevel.INFO, AuditStatus.FAILED);
        }
        PKIMessage pkiResp = responder.processPkiMessage(pkiReq, clientCert, event);
        byte[] encodedPkiResp = pkiResp.getEncoded();
        return createOKResponse(httpVersion, CT_RESPONSE, encodedPkiResp);
    } catch (HttpRespAuditException ex) {
        auditStatus = ex.getAuditStatus();
        auditLevel = ex.getAuditLevel();
        auditMessage = ex.getAuditMessage();
        return createErrorResponse(httpVersion, ex.getHttpStatus());
    } catch (Throwable th) {
        if (th instanceof EOFException) {
            LogUtil.warn(LOG, th, "connection reset by peer");
        } else {
            LOG.error("Throwable thrown, this should not happen!", th);
        }
        auditLevel = AuditLevel.ERROR;
        auditStatus = AuditStatus.FAILED;
        auditMessage = "internal error";
        return createErrorResponse(httpVersion, HttpResponseStatus.INTERNAL_SERVER_ERROR);
    } finally {
        audit(auditService, event, auditLevel, auditStatus, auditMessage);
    }
}
Also used : PKIMessage(org.bouncycastle.asn1.cmp.PKIMessage) AuditLevel(org.xipki.audit.AuditLevel) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) EOFException(java.io.EOFException) AuditStatus(org.xipki.audit.AuditStatus) X509CaCmpResponder(org.xipki.ca.server.api.X509CaCmpResponder) EOFException(java.io.EOFException) AuditEvent(org.xipki.audit.AuditEvent) HttpVersion(io.netty.handler.codec.http.HttpVersion) AuditService(org.xipki.audit.AuditService) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 5 with AuditStatus

use of org.xipki.audit.AuditStatus in project xipki by xipki.

the class HttpScepServlet method service.

@Override
public FullHttpResponse service(FullHttpRequest request, ServletURI servletUri, SSLSession sslSession, SslReverseProxyMode sslReverseProxyMode) throws Exception {
    HttpVersion version = request.protocolVersion();
    HttpMethod method = request.method();
    boolean viaPost;
    if (method == HttpMethod.POST) {
        viaPost = true;
    } else if (method == HttpMethod.GET) {
        viaPost = false;
    } else {
        return createErrorResponse(version, HttpResponseStatus.METHOD_NOT_ALLOWED);
    }
    String scepName = null;
    String certProfileName = null;
    if (servletUri.getPath().length() > 1) {
        String scepPath = servletUri.getPath();
        if (scepPath.endsWith(CGI_PROGRAM)) {
            // skip also the first char (which is always '/')
            String path = scepPath.substring(1, scepPath.length() - CGI_PROGRAM_LEN);
            String[] tokens = path.split("/");
            if (tokens.length == 2) {
                scepName = tokens[0];
                certProfileName = tokens[1].toLowerCase();
            }
        }
    // end if
    }
    if (scepName == null || certProfileName == null) {
        return createErrorResponse(version, HttpResponseStatus.NOT_FOUND);
    }
    AuditService auditService = auditServiceRegister.getAuditService();
    AuditEvent event = new AuditEvent(new Date());
    event.setApplicationName("SCEP");
    event.setName(CaAuditConstants.NAME_PERF);
    event.addEventData(CaAuditConstants.NAME_SCEP_name, scepName + "/" + certProfileName);
    event.addEventData(CaAuditConstants.NAME_reqType, RequestType.SCEP.name());
    String msgId = RandomUtil.nextHexLong();
    event.addEventData(CaAuditConstants.NAME_mid, msgId);
    AuditLevel auditLevel = AuditLevel.INFO;
    AuditStatus auditStatus = AuditStatus.SUCCESSFUL;
    String auditMessage = null;
    try {
        if (responderManager == null) {
            auditMessage = "responderManager in servlet not configured";
            LOG.error(auditMessage);
            auditLevel = AuditLevel.ERROR;
            auditStatus = AuditStatus.FAILED;
            return createErrorResponse(version, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }
        Scep responder = responderManager.getScep(scepName);
        if (responder == null || !responder.isOnService() || !responder.supportsCertProfile(certProfileName)) {
            auditMessage = "unknown SCEP '" + scepName + "/" + certProfileName + "'";
            LOG.warn(auditMessage);
            auditStatus = AuditStatus.FAILED;
            return createErrorResponse(version, HttpResponseStatus.NOT_FOUND);
        }
        String operation = servletUri.getParameter("operation");
        event.addEventData(CaAuditConstants.NAME_SCEP_operation, operation);
        if ("PKIOperation".equalsIgnoreCase(operation)) {
            CMSSignedData reqMessage;
            // parse the request
            try {
                byte[] content;
                if (viaPost) {
                    content = readContent(request);
                } else {
                    String b64 = servletUri.getParameter("message");
                    content = Base64.decode(b64);
                }
                reqMessage = new CMSSignedData(content);
            } catch (Exception ex) {
                final String msg = "invalid request";
                LogUtil.error(LOG, ex, msg);
                auditMessage = msg;
                auditStatus = AuditStatus.FAILED;
                return createErrorResponse(version, HttpResponseStatus.BAD_REQUEST);
            }
            ContentInfo ci;
            try {
                ci = responder.servicePkiOperation(reqMessage, certProfileName, msgId, event);
            } catch (MessageDecodingException ex) {
                final String msg = "could not decrypt and/or verify the request";
                LogUtil.error(LOG, ex, msg);
                auditMessage = msg;
                auditStatus = AuditStatus.FAILED;
                return createErrorResponse(version, HttpResponseStatus.BAD_REQUEST);
            } catch (OperationException ex) {
                ErrorCode code = ex.getErrorCode();
                HttpResponseStatus httpCode;
                switch(code) {
                    case ALREADY_ISSUED:
                    case CERT_REVOKED:
                    case CERT_UNREVOKED:
                        httpCode = HttpResponseStatus.FORBIDDEN;
                        break;
                    case BAD_CERT_TEMPLATE:
                    case BAD_REQUEST:
                    case BAD_POP:
                    case INVALID_EXTENSION:
                    case UNKNOWN_CERT:
                    case UNKNOWN_CERT_PROFILE:
                        httpCode = HttpResponseStatus.BAD_REQUEST;
                        break;
                    case NOT_PERMITTED:
                        httpCode = HttpResponseStatus.UNAUTHORIZED;
                        break;
                    case SYSTEM_UNAVAILABLE:
                        httpCode = HttpResponseStatus.SERVICE_UNAVAILABLE;
                        break;
                    case CRL_FAILURE:
                    case DATABASE_FAILURE:
                    case SYSTEM_FAILURE:
                        httpCode = HttpResponseStatus.INTERNAL_SERVER_ERROR;
                        break;
                    default:
                        httpCode = HttpResponseStatus.INTERNAL_SERVER_ERROR;
                        break;
                }
                auditMessage = ex.getMessage();
                LogUtil.error(LOG, ex, auditMessage);
                auditStatus = AuditStatus.FAILED;
                return createErrorResponse(version, httpCode);
            }
            byte[] bodyBytes = ci.getEncoded();
            return createOKResponse(version, CT_RESPONSE, bodyBytes);
        } else if (Operation.GetCACaps.getCode().equalsIgnoreCase(operation)) {
            // CA-Ident is ignored
            byte[] caCapsBytes = responder.getCaCaps().getBytes();
            return createOKResponse(version, ScepConstants.CT_TEXT_PLAIN, caCapsBytes);
        } else if (Operation.GetCACert.getCode().equalsIgnoreCase(operation)) {
            // CA-Ident is ignored
            byte[] respBytes = responder.getCaCertResp().getBytes();
            return createOKResponse(version, ScepConstants.CT_X509_CA_RA_CERT, respBytes);
        } else if (Operation.GetNextCACert.getCode().equalsIgnoreCase(operation)) {
            auditMessage = "SCEP operation '" + operation + "' is not permitted";
            auditStatus = AuditStatus.FAILED;
            return createErrorResponse(version, HttpResponseStatus.FORBIDDEN);
        } else {
            auditMessage = "unknown SCEP operation '" + operation + "'";
            auditStatus = AuditStatus.FAILED;
            return createErrorResponse(version, HttpResponseStatus.BAD_REQUEST);
        }
    } catch (Throwable th) {
        if (th instanceof EOFException) {
            final String msg = "connection reset by peer";
            if (LOG.isWarnEnabled()) {
                LogUtil.warn(LOG, th, msg);
            }
            LOG.debug(msg, th);
        } else {
            LOG.error("Throwable thrown, this should not happen!", th);
        }
        auditLevel = AuditLevel.ERROR;
        auditStatus = AuditStatus.FAILED;
        auditMessage = "internal error";
        return createErrorResponse(version, HttpResponseStatus.INTERNAL_SERVER_ERROR);
    } finally {
        audit(auditService, event, auditLevel, auditStatus, auditMessage);
    }
}
Also used : HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) AuditLevel(org.xipki.audit.AuditLevel) CMSSignedData(org.bouncycastle.cms.CMSSignedData) Date(java.util.Date) MessageDecodingException(org.xipki.scep.exception.MessageDecodingException) IOException(java.io.IOException) EOFException(java.io.EOFException) OperationException(org.xipki.ca.api.OperationException) AuditStatus(org.xipki.audit.AuditStatus) MessageDecodingException(org.xipki.scep.exception.MessageDecodingException) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) EOFException(java.io.EOFException) AuditEvent(org.xipki.audit.AuditEvent) ErrorCode(org.xipki.ca.api.OperationException.ErrorCode) Scep(org.xipki.ca.server.api.Scep) HttpVersion(io.netty.handler.codec.http.HttpVersion) AuditService(org.xipki.audit.AuditService) HttpMethod(io.netty.handler.codec.http.HttpMethod) OperationException(org.xipki.ca.api.OperationException)

Aggregations

AuditStatus (org.xipki.audit.AuditStatus)7 Date (java.util.Date)6 EOFException (java.io.EOFException)5 AuditLevel (org.xipki.audit.AuditLevel)5 IOException (java.io.IOException)4 AuditEvent (org.xipki.audit.AuditEvent)4 AuditService (org.xipki.audit.AuditService)4 X509Certificate (java.security.cert.X509Certificate)3 PKIMessage (org.bouncycastle.asn1.cmp.PKIMessage)3 OperationException (org.xipki.ca.api.OperationException)3 ErrorCode (org.xipki.ca.api.OperationException.ErrorCode)3 HttpMethod (io.netty.handler.codec.http.HttpMethod)2 HttpVersion (io.netty.handler.codec.http.HttpVersion)2 ServletException (javax.servlet.ServletException)2 ContentInfo (org.bouncycastle.asn1.cms.ContentInfo)2 CMSSignedData (org.bouncycastle.cms.CMSSignedData)2 AuditServiceRegister (org.xipki.audit.AuditServiceRegister)2 InsuffientPermissionException (org.xipki.ca.api.InsuffientPermissionException)2 ResponderManager (org.xipki.ca.server.api.ResponderManager)2 Scep (org.xipki.ca.server.api.Scep)2