Search in sources :

Example 56 with OperationException

use of org.xipki.ca.api.OperationException in project xipki by xipki.

the class X509Ca method generateCrlOnDemand.

// method cleanupCrls
public X509CRL generateCrlOnDemand(String msgId) throws OperationException {
    X509CrlSignerEntryWrapper crlSigner = getCrlSigner();
    if (crlSigner == null) {
        throw new OperationException(ErrorCode.NOT_PERMITTED, "CA could not generate CRL");
    }
    if (crlGenInProcess.get()) {
        throw new OperationException(ErrorCode.SYSTEM_UNAVAILABLE, "TRY_LATER");
    }
    crlGenInProcess.set(true);
    try {
        Date thisUpdate = new Date();
        Date nextUpdate = getCrlNextUpdate(thisUpdate);
        if (nextUpdate != null && !nextUpdate.after(thisUpdate)) {
            nextUpdate = null;
        }
        long maxIdOfDeltaCrlCache = certstore.getMaxIdOfDeltaCrlCache(caIdent);
        X509CRL crl = generateCrl(false, thisUpdate, nextUpdate, msgId);
        if (crl == null) {
            return null;
        }
        try {
            certstore.clearDeltaCrlCache(caIdent, maxIdOfDeltaCrlCache);
        } catch (Throwable th) {
            LogUtil.error(LOG, th, "could not clear DeltaCRLCache of CA " + caIdent);
        }
        return crl;
    } finally {
        crlGenInProcess.set(false);
    }
}
Also used : X509CRL(java.security.cert.X509CRL) OperationException(org.xipki.ca.api.OperationException) Date(java.util.Date)

Example 57 with OperationException

use of org.xipki.ca.api.OperationException in project xipki by xipki.

the class X509Ca method removeExpirtedCerts0.

private int removeExpirtedCerts0(Date expiredAtTime, AuditEvent event, String msgId) throws OperationException {
    ParamUtil.requireNonNull("expiredtime", expiredAtTime);
    if (!masterMode) {
        throw new OperationException(ErrorCode.NOT_PERMITTED, "CA could not remove expired certificates in slave mode");
    }
    event.addEventData(CaAuditConstants.NAME_expiredAt, expiredAtTime);
    final int numEntries = 100;
    final long expiredAt = expiredAtTime.getTime() / 1000;
    int sum = 0;
    while (true) {
        List<BigInteger> serials = certstore.getExpiredCertSerials(caIdent, expiredAt, numEntries);
        if (CollectionUtil.isEmpty(serials)) {
            return sum;
        }
        for (BigInteger serial : serials) {
            // do not delete CA's own certificate
            if ((caInfo.isSelfSigned() && caInfo.getSerialNumber().equals(serial))) {
                continue;
            }
            try {
                if (removeCertificate(serial, msgId) != null) {
                    sum++;
                }
            } catch (OperationException ex) {
                LOG.info("removed {} expired certificates of CA {}", sum, caIdent);
                LogUtil.error(LOG, ex, "could not remove expired certificate with serial" + serial);
                throw ex;
            }
        }
    // end for
    }
// end while (true)
}
Also used : BigInteger(java.math.BigInteger) OperationException(org.xipki.ca.api.OperationException) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint)

Example 58 with OperationException

use of org.xipki.ca.api.OperationException in project xipki by xipki.

the class X509Ca method adaptGrantedSubejct.

// method generateCertificate0
private void adaptGrantedSubejct(GrantedCertTemplate gct) throws OperationException {
    boolean duplicateSubjectPermitted = caInfo.isDuplicateSubjectPermitted();
    if (duplicateSubjectPermitted && !gct.certprofile.isDuplicateSubjectPermitted()) {
        duplicateSubjectPermitted = false;
    }
    if (duplicateSubjectPermitted) {
        return;
    }
    long fpSubject = X509Util.fpCanonicalizedName(gct.grantedSubject);
    String grantedSubjectText = X509Util.getRfc4519Name(gct.grantedSubject);
    final boolean incSerial = gct.certprofile.incSerialNumberIfSubjectExists();
    final boolean certIssued = certstore.isCertForSubjectIssued(caIdent, fpSubject);
    if (certIssued && !incSerial) {
        throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate for the given subject " + grantedSubjectText + " already issued");
    }
    if (!certIssued) {
        return;
    }
    X500Name subject = gct.grantedSubject;
    String latestSn;
    try {
        Object[] objs = incSerialNumber(gct.certprofile, subject, null);
        latestSn = certstore.getLatestSerialNumber((X500Name) objs[0]);
    } catch (BadFormatException ex) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
    }
    boolean foundUniqueSubject = false;
    // maximal 100 tries
    for (int i = 0; i < 100; i++) {
        try {
            Object[] objs = incSerialNumber(gct.certprofile, subject, latestSn);
            subject = (X500Name) objs[0];
            if (CompareUtil.equalsObject(latestSn, objs[1])) {
                break;
            }
            latestSn = (String) objs[1];
        } catch (BadFormatException ex) {
            throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
        }
        foundUniqueSubject = !certstore.isCertForSubjectIssued(caIdent, X509Util.fpCanonicalizedName(subject));
        if (foundUniqueSubject) {
            break;
        }
    }
    if (!foundUniqueSubject) {
        throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate for the given subject " + grantedSubjectText + " and profile " + gct.certprofile.getIdent() + " already issued, and could not create new unique serial number");
    }
    gct.setGrantedSubject(subject);
}
Also used : BadFormatException(org.xipki.ca.api.BadFormatException) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) X500Name(org.bouncycastle.asn1.x500.X500Name) OperationException(org.xipki.ca.api.OperationException) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint)

Example 59 with OperationException

use of org.xipki.ca.api.OperationException in project xipki by xipki.

the class X509CrlSignerEntryWrapper method initSigner.

public void initSigner(SecurityFactory securityFactory) throws XiSecurityException, OperationException, InvalidConfException {
    ParamUtil.requireNonNull("securityFactory", securityFactory);
    if (signer != null) {
        return;
    }
    if (dbEntry == null) {
        throw new XiSecurityException("dbEntry is null");
    }
    if ("CA".equals(dbEntry.getType())) {
        return;
    }
    dbEntry.setConfFaulty(true);
    X509Certificate responderCert = dbEntry.getCert();
    try {
        signer = securityFactory.createSigner(dbEntry.getType(), new SignerConf(dbEntry.getConf()), responderCert);
    } catch (ObjectCreationException ex1) {
        throw new XiSecurityException("signer without certificate is not allowed");
    }
    X509Certificate signerCert = signer.getCertificate();
    if (signerCert == null) {
        throw new XiSecurityException("signer without certificate is not allowed");
    }
    if (dbEntry.getBase64Cert() == null) {
        dbEntry.setCert(signerCert);
    }
    byte[] encodedSkiValue = signerCert.getExtensionValue(Extension.subjectKeyIdentifier.getId());
    if (encodedSkiValue == null) {
        throw new OperationException(ErrorCode.INVALID_EXTENSION, "CA certificate does not have required extension SubjectKeyIdentifier");
    }
    ASN1OctetString ski;
    try {
        ski = (ASN1OctetString) X509ExtensionUtil.fromExtensionValue(encodedSkiValue);
    } catch (IOException ex) {
        throw new OperationException(ErrorCode.INVALID_EXTENSION, ex);
    }
    this.subjectKeyIdentifier = ski.getOctets();
    if (!X509Util.hasKeyusage(signerCert, KeyUsage.cRLSign)) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CRL signer does not have keyusage cRLSign");
    }
    dbEntry.setConfFaulty(false);
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) XiSecurityException(org.xipki.security.exception.XiSecurityException) ObjectCreationException(org.xipki.common.ObjectCreationException) SignerConf(org.xipki.security.SignerConf) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) OperationException(org.xipki.ca.api.OperationException)

Example 60 with OperationException

use of org.xipki.ca.api.OperationException 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)

Aggregations

OperationException (org.xipki.ca.api.OperationException)70 DERPrintableString (org.bouncycastle.asn1.DERPrintableString)20 CaMgmtException (org.xipki.ca.server.mgmt.api.CaMgmtException)19 Date (java.util.Date)16 BigInteger (java.math.BigInteger)15 X509Certificate (java.security.cert.X509Certificate)15 CertificateException (java.security.cert.CertificateException)13 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)13 X509Ca (org.xipki.ca.server.impl.X509Ca)13 PreparedStatement (java.sql.PreparedStatement)12 SQLException (java.sql.SQLException)12 IOException (java.io.IOException)11 X509CertificateInfo (org.xipki.ca.api.publisher.x509.X509CertificateInfo)11 DEROctetString (org.bouncycastle.asn1.DEROctetString)10 X500Name (org.bouncycastle.asn1.x500.X500Name)10 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)10 IssuingDistributionPoint (org.bouncycastle.asn1.x509.IssuingDistributionPoint)10 CrlReason (org.xipki.security.CrlReason)10 AuditEvent (org.xipki.audit.AuditEvent)9 NameId (org.xipki.ca.api.NameId)9