Search in sources :

Example 6 with CertificationRequest

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class ScepResponder method servicePkiOperation0.

private PkiMessage servicePkiOperation0(DecodedPkiMessage req, AuditEvent event) throws CaException {
    TransactionId tid = req.getTransactionId();
    PkiMessage rep = new PkiMessage(tid, MessageType.CertRep, Nonce.randomNonce());
    rep.setPkiStatus(PkiStatus.SUCCESS);
    rep.setRecipientNonce(req.getSenderNonce());
    if (req.getFailureMessage() != null) {
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
    }
    Boolean bo = req.isSignatureValid();
    if (bo != null && !bo) {
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badMessageCheck);
    }
    bo = req.isDecryptionSuccessful();
    if (bo != null && !bo) {
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
    }
    Date signingTime = req.getSigningTime();
    if (maxSigningTimeBiasInMs > 0) {
        boolean isTimeBad;
        if (signingTime == null) {
            isTimeBad = true;
        } else {
            long now = System.currentTimeMillis();
            long diff = now - signingTime.getTime();
            if (diff < 0) {
                diff = -1 * diff;
            }
            isTimeBad = diff > maxSigningTimeBiasInMs;
        }
        if (isTimeBad) {
            return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badTime);
        }
    }
    // check the digest algorithm
    HashAlgo hashAlgo = req.getDigestAlgorithm();
    boolean supported = false;
    if (hashAlgo == HashAlgo.SHA1) {
        if (caCaps.containsCapability(CaCapability.SHA1)) {
            supported = true;
        }
    } else if (hashAlgo == HashAlgo.SHA256) {
        if (caCaps.containsCapability(CaCapability.SHA256)) {
            supported = true;
        }
    } else if (hashAlgo == HashAlgo.SHA512) {
        if (caCaps.containsCapability(CaCapability.SHA512)) {
            supported = true;
        }
    }
    if (!supported) {
        LOG.warn("tid={}: unsupported digest algorithm {}", tid, hashAlgo);
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
    }
    // end if
    // check the content encryption algorithm
    ASN1ObjectIdentifier encOid = req.getContentEncryptionAlgorithm();
    if (CMSAlgorithm.DES_EDE3_CBC.equals(encOid)) {
        if (!caCaps.containsCapability(CaCapability.DES3)) {
            LOG.warn("tid={}: encryption with DES3 algorithm {} is not permitted", tid, encOid);
            return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
        }
    } else if (AES_ENC_ALGS.contains(encOid)) {
        if (!caCaps.containsCapability(CaCapability.AES)) {
            LOG.warn("tid={}: encryption with AES algorithm {} is not permitted", tid, encOid);
            return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
        }
    } else if (CMSAlgorithm.DES_CBC.equals(encOid)) {
        if (!control.isUseInsecureAlg()) {
            LOG.warn("tid={}: encryption with DES algorithm {} is not permitted", tid, encOid);
            return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
        }
    } else {
        LOG.warn("tid={}: encryption with algorithm {} is not permitted", tid, encOid);
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
    }
    if (rep.getPkiStatus() == PkiStatus.FAILURE) {
        return rep;
    }
    MessageType messageType = req.getMessageType();
    switch(messageType) {
        case PKCSReq:
            boolean selfSigned = req.getSignatureCert().isSelfSigned();
            CertificationRequest csr = CertificationRequest.getInstance(req.getMessageData());
            if (selfSigned) {
                X500Name name = req.getSignatureCert().getSubject();
                if (!name.equals(csr.getCertificationRequestInfo().getSubject())) {
                    LOG.warn("tid={}: self-signed cert.subject != CSR.subject", tid);
                    return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
                }
            }
            String challengePwd = getChallengePassword(csr.getCertificationRequestInfo());
            if (!control.getSecret().equals(challengePwd)) {
                LOG.warn("challengePassword is not trusted");
                return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
            }
            X509Cert cert;
            try {
                cert = caEmulator.generateCert(csr);
            } catch (Exception ex) {
                throw new CaException("system failure: " + ex.getMessage(), ex);
            }
            if (cert != null && control.isPendingCert()) {
                rep.setPkiStatus(PkiStatus.PENDING);
            } else if (cert != null) {
                ContentInfo messageData = createSignedData(cert);
                rep.setMessageData(messageData);
            } else {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
            }
            break;
        case CertPoll:
            IssuerAndSubject is = IssuerAndSubject.getInstance(req.getMessageData());
            cert = caEmulator.pollCert(is.getIssuer(), is.getSubject());
            if (cert != null) {
                rep.setMessageData(createSignedData(cert));
            } else {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
            }
            break;
        case GetCert:
            IssuerAndSerialNumber isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
            cert = caEmulator.getCert(isn.getName(), isn.getSerialNumber().getValue());
            if (cert != null) {
                rep.setMessageData(createSignedData(cert));
            } else {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
            }
            break;
        case RenewalReq:
            if (!caCaps.containsCapability(CaCapability.Renewal)) {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
            } else {
                csr = CertificationRequest.getInstance(req.getMessageData());
                try {
                    cert = caEmulator.generateCert(csr);
                } catch (Exception ex) {
                    throw new CaException("system failure: " + ex.getMessage(), ex);
                }
                if (cert != null) {
                    rep.setMessageData(createSignedData(cert));
                } else {
                    rep.setPkiStatus(PkiStatus.FAILURE);
                    rep.setFailInfo(FailInfo.badCertId);
                }
            }
            break;
        case UpdateReq:
            if (!caCaps.containsCapability(CaCapability.Update)) {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
            } else {
                csr = CertificationRequest.getInstance(req.getMessageData());
                try {
                    cert = caEmulator.generateCert(csr);
                } catch (Exception ex) {
                    throw new CaException("system failure: " + ex.getMessage(), ex);
                }
                if (cert != null) {
                    rep.setMessageData(createSignedData(cert));
                } else {
                    buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
                }
            }
            break;
        case GetCRL:
            isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
            CertificateList crl;
            try {
                crl = caEmulator.getCrl(isn.getName(), isn.getSerialNumber().getValue());
            } catch (Exception ex) {
                throw new CaException("system failure: " + ex.getMessage(), ex);
            }
            if (crl != null) {
                rep.setMessageData(createSignedData(crl));
            } else {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
            }
            break;
        default:
            buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
    }
    return rep;
}
Also used : IssuerAndSerialNumber(org.bouncycastle.asn1.cms.IssuerAndSerialNumber) HashAlgo(org.xipki.security.HashAlgo) CertificateList(org.bouncycastle.asn1.x509.CertificateList) X500Name(org.bouncycastle.asn1.x500.X500Name) ASN1String(org.bouncycastle.asn1.ASN1String) Date(java.util.Date) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) X509Cert(org.xipki.security.X509Cert) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest)

Example 7 with CertificationRequest

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project jruby-openssl by jruby.

the class PKCS10Request method resetSignedRequest.

private void resetSignedRequest() {
    if (signedRequest == null)
        return;
    CertificationRequest req = signedRequest.toASN1Structure();
    CertificationRequestInfo reqInfo = new CertificationRequestInfo(subject, publicKeyInfo, req.getCertificationRequestInfo().getAttributes());
    ASN1Sequence seq = (ASN1Sequence) req.toASN1Primitive();
    req = new CertificationRequest(reqInfo, (AlgorithmIdentifier) seq.getObjectAt(1), (DERBitString) seq.getObjectAt(2));
    // valid = true;
    signedRequest = new PKCS10CertificationRequest(req);
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) CertificationRequestInfo(org.bouncycastle.asn1.pkcs.CertificationRequestInfo) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DERBitString(org.bouncycastle.asn1.DERBitString) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 8 with CertificationRequest

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class RestResponder method service.

public RestResponse service(String path, AuditEvent event, byte[] request, HttpRequestMetadataRetriever httpRetriever) {
    event.setApplicationName(APPNAME);
    event.setName(NAME_perf);
    event.addEventData(NAME_req_type, RequestType.REST.name());
    String msgId = RandomUtil.nextHexLong();
    event.addEventData(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(INTERNAL_SERVER_ERROR, message, ERROR, 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(NOT_FOUND, message, ERROR, FAILED);
            }
            // skip also the first char ('/')
            String caAlias = coreUri.substring(1, sepIndex).toLowerCase();
            command = coreUri.substring(sepIndex + 1).toLowerCase();
            caName = responderManager.getCaNameForAlias(caAlias);
            if (caName == null) {
                caName = caAlias;
            }
            CmpResponder caResponder = responderManager.getX509CaResponder(caName);
            if (caResponder != null) {
                ca = caResponder.getCa();
            }
        }
        if (StringUtil.isBlank(command)) {
            String message = "command is not specified";
            LOG.warn(message);
            throw new HttpRespAuditException(NOT_FOUND, message, INFO, FAILED);
        }
        if (ca == null || !ca.getCaInfo().supportsRest() || ca.getCaInfo().getStatus() != CaStatus.ACTIVE) {
            String message;
            if (ca == null) {
                message = "unknown CA '" + caName + "'";
            } else if (!ca.getCaInfo().supportsRest()) {
                message = "REST is not supported by the CA '" + caName + "'";
            } else {
                message = "CA '" + caName + "' is out of service";
            }
            LOG.warn(message);
            throw new HttpRespAuditException(NOT_FOUND, message, INFO, FAILED);
        }
        event.addEventData(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 = StringUtil.toUtf8String(Arrays.copyOfRange(userPwd, 0, idx));
                    password = Arrays.copyOfRange(userPwd, idx + 1, userPwd.length);
                }
            }
            if (user == null) {
                throw new HttpRespAuditException(UNAUTHORIZED, "invalid Authorization information", INFO, FAILED);
            }
            NameId userIdent = ca.authenticateUser(user, password);
            if (userIdent == null) {
                throw new HttpRespAuditException(UNAUTHORIZED, "could not authenticate user", INFO, FAILED);
            }
            requestor = ca.getByUserRequestor(userIdent);
        } else {
            X509Cert clientCert = httpRetriever.getTlsClientCert();
            if (clientCert == null) {
                throw new HttpRespAuditException(UNAUTHORIZED, "no client certificate", INFO, FAILED);
            }
            requestor = ca.getRequestor(clientCert);
        }
        if (requestor == null) {
            throw new OperationException(NOT_PERMITTED, "no requestor specified");
        }
        event.addEventData(NAME_requestor, requestor.getIdent().getName());
        String respCt = null;
        byte[] respBytes = null;
        switch(command) {
            case CMD_cacert:
                {
                    respCt = CT_pkix_cert;
                    respBytes = ca.getCaInfo().getCert().getEncoded();
                    break;
                }
            case CMD_pop_dh_certs:
                {
                    PopControl control = responderManager.getX509Ca(caName).getCaInfo().getPopControl();
                    respBytes = new byte[0];
                    if (control != null) {
                        X509Cert[] dhCerts = control.getDhCertificates();
                        if (dhCerts != null) {
                            respCt = CT_pem_file;
                            respBytes = StringUtil.toUtf8Bytes(X509Util.encodeCertificates(dhCerts));
                        }
                    }
                    break;
                }
            case CMD_cacertchain:
                {
                    respCt = CT_pem_file;
                    List<X509Cert> certchain = ca.getCaInfo().getCertchain();
                    int size = 1 + (certchain == null ? 0 : certchain.size());
                    X509Cert[] certchainWithCaCert = new X509Cert[size];
                    certchainWithCaCert[0] = ca.getCaInfo().getCert();
                    if (size > 1) {
                        for (int i = 1; i < size; i++) {
                            certchainWithCaCert[i] = certchain.get(i - 1);
                        }
                    }
                    respBytes = StringUtil.toUtf8Bytes(X509Util.encodeCertificates(certchainWithCaCert));
                    break;
                }
            case CMD_enroll_cert:
            case CMD_enroll_cert_cagenkeypair:
                {
                    String profile = httpRetriever.getParameter(PARAM_profile);
                    if (StringUtil.isBlank(profile)) {
                        throw new HttpRespAuditException(BAD_REQUEST, "required parameter " + PARAM_profile + " not specified", INFO, FAILED);
                    }
                    profile = profile.toLowerCase();
                    try {
                        requestor.assertPermitted(PermissionConstants.ENROLL_CERT);
                    } catch (InsufficientPermissionException ex) {
                        throw new OperationException(NOT_PERMITTED, ex.getMessage());
                    }
                    if (!requestor.isCertprofilePermitted(profile)) {
                        throw new OperationException(NOT_PERMITTED, "certprofile " + profile + " is not allowed");
                    }
                    String strNotBefore = httpRetriever.getParameter(PARAM_not_before);
                    Date notBefore = (strNotBefore == null) ? null : DateUtil.parseUtcTimeyyyyMMddhhmmss(strNotBefore);
                    String strNotAfter = httpRetriever.getParameter(PARAM_not_after);
                    Date notAfter = (strNotAfter == null) ? null : DateUtil.parseUtcTimeyyyyMMddhhmmss(strNotAfter);
                    if (CMD_enroll_cert_cagenkeypair.equals(command)) {
                        String ct = httpRetriever.getHeader("Content-Type");
                        X500Name subject;
                        Extensions extensions;
                        if (ct.startsWith("text/plain")) {
                            Properties props = new Properties();
                            props.load(new ByteArrayInputStream(request));
                            String strSubject = props.getProperty("subject");
                            if (strSubject == null) {
                                throw new OperationException(BAD_CERT_TEMPLATE, "subject is not specified");
                            }
                            try {
                                subject = new X500Name(strSubject);
                            } catch (Exception ex) {
                                throw new OperationException(BAD_CERT_TEMPLATE, "invalid subject");
                            }
                            extensions = null;
                        } else if (CT_pkcs10.equalsIgnoreCase(ct)) {
                            // some clients may send the PEM encoded CSR.
                            request = X509Util.toDerEncoded(request);
                            // The PKCS#10 will only be used for transport of subject and extensions.
                            // The associated key will not be used, so the verification of POP is skipped.
                            CertificationRequestInfo certTemp = CertificationRequest.getInstance(request).getCertificationRequestInfo();
                            subject = certTemp.getSubject();
                            extensions = CaUtil.getExtensions(certTemp);
                        } else {
                            String message = "unsupported media type " + ct;
                            throw new HttpRespAuditException(UNSUPPORTED_MEDIA_TYPE, message, INFO, FAILED);
                        }
                        CertTemplateData certTemplate = new CertTemplateData(subject, null, notBefore, notAfter, extensions, profile, null, true);
                        CertificateInfo certInfo = ca.generateCert(certTemplate, requestor, RequestType.REST, null, msgId);
                        if (ca.getCaInfo().isSaveRequest()) {
                            long dbId = ca.addRequest(request);
                            ca.addRequestCert(dbId, certInfo.getCert().getCertId());
                        }
                        respCt = CT_pem_file;
                        byte[] keyBytes = PemEncoder.encode(certInfo.getPrivateKey().getEncoded(), PemLabel.PRIVATE_KEY);
                        byte[] certBytes = PemEncoder.encode(certInfo.getCert().getCert().getEncoded(), PemLabel.CERTIFICATE);
                        respBytes = new byte[keyBytes.length + 2 + certBytes.length];
                        System.arraycopy(keyBytes, 0, respBytes, 0, keyBytes.length);
                        respBytes[keyBytes.length] = '\r';
                        respBytes[keyBytes.length + 1] = '\n';
                        System.arraycopy(certBytes, 0, respBytes, keyBytes.length + 2, certBytes.length);
                    } else {
                        String ct = httpRetriever.getHeader("Content-Type");
                        if (!CT_pkcs10.equalsIgnoreCase(ct)) {
                            String message = "unsupported media type " + ct;
                            throw new HttpRespAuditException(UNSUPPORTED_MEDIA_TYPE, message, INFO, FAILED);
                        }
                        CertificationRequest csr = CertificationRequest.getInstance(request);
                        if (!ca.verifyCsr(csr)) {
                            throw new OperationException(BAD_POP);
                        }
                        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);
                        CertificateInfo certInfo = ca.generateCert(certTemplate, requestor, RequestType.REST, null, msgId);
                        if (ca.getCaInfo().isSaveRequest()) {
                            long dbId = ca.addRequest(request);
                            ca.addRequestCert(dbId, certInfo.getCert().getCertId());
                        }
                        CertWithDbId cert = certInfo.getCert();
                        if (cert == null) {
                            String message = "could not generate certificate";
                            LOG.warn(message);
                            throw new HttpRespAuditException(INTERNAL_SERVER_ERROR, message, INFO, FAILED);
                        }
                        respCt = CT_pkix_cert;
                        respBytes = cert.getCert().getEncoded();
                    }
                    break;
                }
            case CMD_revoke_cert:
            case CMD_delete_cert:
                {
                    int permission;
                    if (CMD_revoke_cert.equals(command)) {
                        permission = PermissionConstants.REVOKE_CERT;
                    } else {
                        permission = PermissionConstants.REMOVE_CERT;
                    }
                    try {
                        requestor.assertPermitted(permission);
                    } catch (InsufficientPermissionException ex) {
                        throw new OperationException(NOT_PERMITTED, ex.getMessage());
                    }
                    String strCaSha1 = httpRetriever.getParameter(PARAM_ca_sha1);
                    if (StringUtil.isBlank(strCaSha1)) {
                        throw new HttpRespAuditException(BAD_REQUEST, "required parameter " + PARAM_ca_sha1 + " not specified", INFO, FAILED);
                    }
                    String strSerialNumber = httpRetriever.getParameter(PARAM_serial_number);
                    if (StringUtil.isBlank(strSerialNumber)) {
                        throw new HttpRespAuditException(BAD_REQUEST, "required parameter " + PARAM_serial_number + " not specified", INFO, FAILED);
                    }
                    if (!strCaSha1.equalsIgnoreCase(ca.getHexSha1OfCert())) {
                        throw new HttpRespAuditException(BAD_REQUEST, "unknown " + PARAM_ca_sha1, INFO, FAILED);
                    }
                    BigInteger serialNumber;
                    try {
                        serialNumber = toBigInt(strSerialNumber);
                    } catch (NumberFormatException ex) {
                        throw new OperationException(ErrorCode.BAD_REQUEST, ex.getMessage());
                    }
                    if (CMD_revoke_cert.equals(command)) {
                        String strReason = httpRetriever.getParameter(PARAM_reason);
                        CrlReason reason = (strReason == null) ? CrlReason.UNSPECIFIED : CrlReason.forNameOrText(strReason);
                        if (reason == CrlReason.REMOVE_FROM_CRL) {
                            ca.unrevokeCert(serialNumber, msgId);
                        } else {
                            Date invalidityTime = null;
                            String strInvalidityTime = httpRetriever.getParameter(PARAM_invalidity_time);
                            if (StringUtil.isNotBlank(strInvalidityTime)) {
                                invalidityTime = DateUtil.parseUtcTimeyyyyMMddhhmmss(strInvalidityTime);
                            }
                            ca.revokeCert(serialNumber, reason, invalidityTime, msgId);
                        }
                    } else {
                        // if (CMD_delete_cert.equals(command)) {
                        ca.removeCert(serialNumber, msgId);
                    }
                    break;
                }
            case CMD_crl:
                {
                    try {
                        requestor.assertPermitted(PermissionConstants.GET_CRL);
                    } catch (InsufficientPermissionException ex) {
                        throw new OperationException(NOT_PERMITTED, ex.getMessage());
                    }
                    String strCrlNumber = httpRetriever.getParameter(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(BAD_REQUEST, message, INFO, FAILED);
                        }
                    }
                    X509CRLHolder crl = ca.getCrl(crlNumber, msgId);
                    if (crl == null) {
                        String message = "could not get CRL";
                        LOG.warn(message);
                        throw new HttpRespAuditException(INTERNAL_SERVER_ERROR, message, INFO, FAILED);
                    }
                    respCt = CT_pkix_crl;
                    respBytes = crl.getEncoded();
                    break;
                }
            case CMD_new_crl:
                {
                    try {
                        requestor.assertPermitted(PermissionConstants.GEN_CRL);
                    } catch (InsufficientPermissionException ex) {
                        throw new OperationException(NOT_PERMITTED, ex.getMessage());
                    }
                    X509CRLHolder crl = ca.generateCrlOnDemand(msgId);
                    respCt = CT_pkix_crl;
                    respBytes = crl.getEncoded();
                    break;
                }
            default:
                {
                    String message = "invalid command '" + command + "'";
                    LOG.error(message);
                    throw new HttpRespAuditException(NOT_FOUND, message, INFO, FAILED);
                }
        }
        Map<String, String> headers = new HashMap<>();
        headers.put(HEADER_PKISTATUS, PKISTATUS_accepted);
        return new RestResponse(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());
            LogUtil.warn(LOG, ex, msg);
        }
        int sc;
        String failureInfo;
        switch(code) {
            case ALREADY_ISSUED:
                sc = BAD_REQUEST;
                failureInfo = FAILINFO_badRequest;
                break;
            case BAD_CERT_TEMPLATE:
                sc = BAD_REQUEST;
                failureInfo = FAILINFO_badCertTemplate;
                break;
            case BAD_REQUEST:
                sc = BAD_REQUEST;
                failureInfo = FAILINFO_badRequest;
                break;
            case CERT_REVOKED:
                sc = CONFLICT;
                failureInfo = FAILINFO_certRevoked;
                break;
            case CRL_FAILURE:
                sc = INTERNAL_SERVER_ERROR;
                failureInfo = FAILINFO_systemFailure;
                break;
            case DATABASE_FAILURE:
                sc = INTERNAL_SERVER_ERROR;
                failureInfo = FAILINFO_systemFailure;
                break;
            case NOT_PERMITTED:
                sc = UNAUTHORIZED;
                failureInfo = FAILINFO_notAuthorized;
                break;
            case INVALID_EXTENSION:
                sc = BAD_REQUEST;
                failureInfo = FAILINFO_badRequest;
                break;
            case SYSTEM_FAILURE:
                sc = INTERNAL_SERVER_ERROR;
                failureInfo = FAILINFO_systemFailure;
                break;
            case SYSTEM_UNAVAILABLE:
                sc = SERVICE_UNAVAILABLE;
                failureInfo = FAILINFO_systemUnavail;
                break;
            case UNKNOWN_CERT:
                sc = BAD_REQUEST;
                failureInfo = FAILINFO_badCertId;
                break;
            case UNKNOWN_CERT_PROFILE:
                sc = BAD_REQUEST;
                failureInfo = FAILINFO_badCertTemplate;
                break;
            default:
                sc = INTERNAL_SERVER_ERROR;
                failureInfo = FAILINFO_systemFailure;
                break;
        }
        // end switch (code)
        event.setStatus(AuditStatus.FAILED);
        event.addEventData(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(HEADER_PKISTATUS, PKISTATUS_rejection);
        if (StringUtil.isNotBlank(failureInfo)) {
            headers.put(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(INTERNAL_SERVER_ERROR, null, null, null);
    } finally {
        event.setStatus(auditStatus);
        event.setLevel(auditLevel);
        if (auditMessage != null) {
            event.addEventData(NAME_message, auditMessage);
        }
    }
}
Also used : CertificationRequestInfo(org.bouncycastle.asn1.pkcs.CertificationRequestInfo) X500Name(org.bouncycastle.asn1.x500.X500Name) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) X509Cert(org.xipki.security.X509Cert) EOFException(java.io.EOFException) CrlReason(org.xipki.security.CrlReason) CmpResponder(org.xipki.ca.server.cmp.CmpResponder) AuditLevel(org.xipki.audit.AuditLevel) EOFException(java.io.EOFException) AuditStatus(org.xipki.audit.AuditStatus) ByteArrayInputStream(java.io.ByteArrayInputStream) X509CRLHolder(org.bouncycastle.cert.X509CRLHolder) BigInteger(java.math.BigInteger) ErrorCode(org.xipki.ca.api.OperationException.ErrorCode) RequestorInfo(org.xipki.ca.api.mgmt.RequestorInfo) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) PopControl(org.xipki.ca.api.mgmt.PopControl)

Example 9 with CertificationRequest

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class ScepResponder method servicePkiOperation0.

private PkiMessage servicePkiOperation0(DecodedPkiMessage req) throws CaException {
    TransactionId tid = req.getTransactionId();
    PkiMessage rep = new PkiMessage(tid, MessageType.CertRep, Nonce.randomNonce());
    rep.setPkiStatus(PkiStatus.SUCCESS);
    rep.setRecipientNonce(req.getSenderNonce());
    if (req.getFailureMessage() != null) {
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
    }
    Boolean bo = req.isSignatureValid();
    if (bo != null && !bo) {
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badMessageCheck);
    }
    bo = req.isDecryptionSuccessful();
    if (bo != null && !bo) {
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
    }
    Date signingTime = req.getSigningTime();
    if (maxSigningTimeBiasInMs > 0) {
        boolean isTimeBad;
        if (signingTime == null) {
            isTimeBad = true;
        } else {
            long now = System.currentTimeMillis();
            long diff = now - signingTime.getTime();
            if (diff < 0) {
                diff = -1 * diff;
            }
            isTimeBad = diff > maxSigningTimeBiasInMs;
        }
        if (isTimeBad) {
            return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badTime);
        }
    }
    // check the digest algorithm
    HashAlgo hashAlgo = req.getDigestAlgorithm();
    boolean supported = false;
    if (hashAlgo == HashAlgo.SHA1) {
        if (caCaps.supportsSHA1()) {
            supported = true;
        }
    } else if (hashAlgo == HashAlgo.SHA256) {
        if (caCaps.supportsSHA256()) {
            supported = true;
        }
    } else if (hashAlgo == HashAlgo.SHA512) {
        if (caCaps.supportsSHA512()) {
            supported = true;
        }
    }
    if (!supported) {
        LOG.warn("tid={}: unsupported digest algorithm {}", tid, hashAlgo);
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
    }
    // end if
    // check the content encryption algorithm
    ASN1ObjectIdentifier encOid = req.getContentEncryptionAlgorithm();
    if (CMSAlgorithm.DES_EDE3_CBC.equals(encOid)) {
        if (!caCaps.supportsDES3()) {
            LOG.warn("tid={}: encryption with DES3 algorithm {} is not permitted", tid, encOid);
            return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
        }
    } else if (CMSAlgorithm.AES128_CBC.equals(encOid)) {
        if (!caCaps.supportsAES()) {
            LOG.warn("tid={}: encryption with AES algorithm {} is not permitted", tid, encOid);
            return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
        }
    } else {
        LOG.warn("tid={}: encryption with algorithm {} is not permitted", tid, encOid);
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
    }
    if (rep.getPkiStatus() == PkiStatus.FAILURE) {
        return rep;
    }
    MessageType messageType = req.getMessageType();
    switch(messageType) {
        case PKCSReq:
            boolean selfSigned = req.getSignatureCert().isSelfSigned();
            CertificationRequest csr = CertificationRequest.getInstance(req.getMessageData());
            if (selfSigned) {
                X500Name name = req.getSignatureCert().getSubject();
                if (!name.equals(csr.getCertificationRequestInfo().getSubject())) {
                    LOG.warn("tid={}: self-signed cert.subject != CSR.subject", tid);
                    return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
                }
            }
            String challengePwd = getChallengePassword(csr.getCertificationRequestInfo());
            if (!control.getSecret().equals(challengePwd)) {
                LOG.warn("challengePassword is not trusted");
                return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
            }
            X509Cert cert;
            try {
                cert = caEmulator.generateCert(csr);
            } catch (Exception ex) {
                throw new CaException("system failure: " + ex.getMessage(), ex);
            }
            if (cert != null && control.isPendingCert()) {
                rep.setPkiStatus(PkiStatus.PENDING);
            } else if (cert != null) {
                ContentInfo messageData = createSignedData(cert);
                rep.setMessageData(messageData);
            } else {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
            }
            break;
        case CertPoll:
            IssuerAndSubject is = IssuerAndSubject.getInstance(req.getMessageData());
            cert = caEmulator.pollCert(is.getIssuer(), is.getSubject());
            if (cert != null) {
                rep.setMessageData(createSignedData(cert));
            } else {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
            }
            break;
        case GetCert:
            IssuerAndSerialNumber isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
            cert = caEmulator.getCert(isn.getName(), isn.getSerialNumber().getValue());
            if (cert != null) {
                rep.setMessageData(createSignedData(cert));
            } else {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
            }
            break;
        case RenewalReq:
            if (!caCaps.supportsRenewal()) {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
            } else {
                csr = CertificationRequest.getInstance(req.getMessageData());
                try {
                    cert = caEmulator.generateCert(csr);
                } catch (Exception ex) {
                    throw new CaException("system failure: " + ex.getMessage(), ex);
                }
                if (cert != null) {
                    rep.setMessageData(createSignedData(cert));
                } else {
                    rep.setPkiStatus(PkiStatus.FAILURE);
                    rep.setFailInfo(FailInfo.badCertId);
                }
            }
            break;
        case GetCRL:
            isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
            CertificateList crl;
            try {
                crl = caEmulator.getCrl(isn.getName(), isn.getSerialNumber().getValue());
            } catch (Exception ex) {
                throw new CaException("system failure: " + ex.getMessage(), ex);
            }
            if (crl != null) {
                rep.setMessageData(createSignedData(crl));
            } else {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
            }
            break;
        default:
            buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
    }
    return rep;
}
Also used : IssuerAndSerialNumber(org.bouncycastle.asn1.cms.IssuerAndSerialNumber) HashAlgo(org.xipki.security.HashAlgo) CertificateList(org.bouncycastle.asn1.x509.CertificateList) X500Name(org.bouncycastle.asn1.x500.X500Name) ASN1String(org.bouncycastle.asn1.ASN1String) Date(java.util.Date) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) X509Cert(org.xipki.security.X509Cert) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest)

Example 10 with CertificationRequest

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class RestCaClientExample method main.

public static void main(String[] args) {
    // System.setProperty("javax.net.debug", "all");
    try {
        RestCaClient client = new RestCaClient(CA_URL, USER, PASSWORD);
        client.init();
        // retrieve CA certificate
        printCert("===== CA Certificate (REST) =====", client.getCaCert());
        // Enroll certificate - RSA
        MyKeypair kp = generateRsaKeypair();
        CertificationRequest csr = genCsr(kp, getSubject());
        X509Certificate cert = client.requestCert(CERT_PROFILE, csr);
        printCert("===== RSA (REST) =====", cert);
        // Enroll certificate - EC
        kp = generateEcKeypair();
        csr = genCsr(kp, getSubject());
        cert = client.requestCert(CERT_PROFILE, csr);
        printCert("===== EC (REST) =====", cert);
        // Enroll certificate - DSA
        kp = generateDsaKeypair();
        csr = genCsr(kp, getSubject());
        cert = client.requestCert(CERT_PROFILE, csr);
        printCert("===== DSA =====", cert);
        BigInteger serialNumber = cert.getSerialNumber();
        // Suspend certificate
        boolean flag = client.revokeCert(serialNumber, CRLReason.lookup(CRLReason.certificateHold));
        if (flag) {
            System.out.println("(REST) suspended certificate");
        } else {
            System.err.println("(REST) suspending certificate failed");
        }
        // Unsuspend certificate
        flag = client.revokeCert(serialNumber, CRLReason.lookup(CRLReason.removeFromCRL));
        if (flag) {
            System.out.println("(REST) unsuspended certificate");
        } else {
            System.err.println("(REST) unsuspending certificate failed");
        }
        // Revoke certificate
        flag = client.revokeCert(serialNumber, CRLReason.lookup(CRLReason.keyCompromise));
        if (flag) {
            System.out.println("(REST) revoked certificate");
        } else {
            System.err.println("(REST) revoking certificate failed");
        }
        client.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(-1);
    }
}
Also used : RestCaClient(org.xipki.litecaclient.RestCaClient) BigInteger(java.math.BigInteger) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) X509Certificate(java.security.cert.X509Certificate)

Aggregations

CertificationRequest (org.bouncycastle.asn1.pkcs.CertificationRequest)24 X500Name (org.bouncycastle.asn1.x500.X500Name)12 X509Certificate (java.security.cert.X509Certificate)9 Date (java.util.Date)9 BigInteger (java.math.BigInteger)8 CertificationRequestInfo (org.bouncycastle.asn1.pkcs.CertificationRequestInfo)8 X509Cert (org.xipki.security.X509Cert)8 Extensions (org.bouncycastle.asn1.x509.Extensions)7 File (java.io.File)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 PrivateKey (java.security.PrivateKey)5 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)5 OperationException (org.xipki.ca.api.OperationException)5 IOException (java.io.IOException)4 CertificateException (java.security.cert.CertificateException)4 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)4 ContentInfo (org.bouncycastle.asn1.cms.ContentInfo)4 IssuerAndSerialNumber (org.bouncycastle.asn1.cms.IssuerAndSerialNumber)4 EnrolmentResponse (org.xipki.scep.client.EnrolmentResponse)4 ScepClient (org.xipki.scep.client.ScepClient)4