Search in sources :

Example 1 with RequestResponseDebug

use of org.xipki.common.RequestResponseDebug in project xipki by xipki.

the class CsrEnrollCertCmd method execute0.

@Override
protected Object execute0() throws Exception {
    if (caName != null) {
        caName = caName.toLowerCase();
    }
    CertificationRequest csr = CertificationRequest.getInstance(IoUtil.read(csrFile));
    Date notBefore = StringUtil.isNotBlank(notBeforeS) ? DateUtil.parseUtcTimeyyyyMMddhhmmss(notBeforeS) : null;
    Date notAfter = StringUtil.isNotBlank(notAfterS) ? DateUtil.parseUtcTimeyyyyMMddhhmmss(notAfterS) : null;
    EnrollCertResult result;
    RequestResponseDebug debug = getRequestResponseDebug();
    try {
        result = caClient.requestCert(caName, csr, profile, notBefore, notAfter, debug);
    } finally {
        saveRequestResponse(debug);
    }
    X509Certificate cert = null;
    if (result != null) {
        String id = result.getAllIds().iterator().next();
        CertOrError certOrError = result.getCertOrError(id);
        cert = (X509Certificate) certOrError.getCertificate();
    }
    if (cert == null) {
        throw new CmdFailure("no certificate received from the server");
    }
    File certFile = new File(outputFile);
    saveVerbose("certificate saved to file", certFile, cert.getEncoded());
    return null;
}
Also used : RequestResponseDebug(org.xipki.common.RequestResponseDebug) CmdFailure(org.xipki.console.karaf.CmdFailure) EnrollCertResult(org.xipki.ca.client.api.EnrollCertResult) CertOrError(org.xipki.ca.client.api.CertOrError) File(java.io.File) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate)

Example 2 with RequestResponseDebug

use of org.xipki.common.RequestResponseDebug in project xipki by xipki.

the class GetCrlCmd method execute0.

@Override
protected Object execute0() throws Exception {
    if (caName != null) {
        caName = caName.toLowerCase();
    }
    Set<String> caNames = caClient.getCaNames();
    if (isEmpty(caNames)) {
        throw new IllegalCmdParamException("no CA is configured");
    }
    if (caName != null && !caNames.contains(caName)) {
        throw new IllegalCmdParamException("CA " + caName + " is not within the configured CAs " + caNames);
    }
    if (caName == null) {
        if (caNames.size() == 1) {
            caName = caNames.iterator().next();
        } else {
            throw new IllegalCmdParamException("no CA is specified, one of " + caNames + " is required");
        }
    }
    X509CRL crl = null;
    try {
        crl = retrieveCrl();
    } catch (PkiErrorException ex) {
        throw new CmdFailure("received no CRL from server: " + ex.getMessage());
    }
    if (crl == null) {
        throw new CmdFailure("received no CRL from server");
    }
    saveVerbose("saved CRL to file", new File(outFile), crl.getEncoded());
    if (!withBaseCrl.booleanValue()) {
        return null;
    }
    byte[] octetString = crl.getExtensionValue(Extension.deltaCRLIndicator.getId());
    if (octetString == null) {
        return null;
    }
    if (baseCrlOut == null) {
        baseCrlOut = outFile + "-baseCRL";
    }
    byte[] extnValue = DEROctetString.getInstance(octetString).getOctets();
    BigInteger baseCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();
    RequestResponseDebug debug = getRequestResponseDebug();
    try {
        crl = caClient.downloadCrl(caName, baseCrlNumber, debug);
    } catch (PkiErrorException ex) {
        throw new CmdFailure("received no baseCRL from server: " + ex.getMessage());
    } finally {
        saveRequestResponse(debug);
    }
    if (crl == null) {
        throw new CmdFailure("received no baseCRL from server");
    }
    saveVerbose("saved baseCRL to file", new File(baseCrlOut), crl.getEncoded());
    return null;
}
Also used : PkiErrorException(org.xipki.ca.client.api.PkiErrorException) X509CRL(java.security.cert.X509CRL) RequestResponseDebug(org.xipki.common.RequestResponseDebug) CmdFailure(org.xipki.console.karaf.CmdFailure) IllegalCmdParamException(org.xipki.console.karaf.IllegalCmdParamException) BigInteger(java.math.BigInteger) DEROctetString(org.bouncycastle.asn1.DEROctetString) File(java.io.File)

Example 3 with RequestResponseDebug

use of org.xipki.common.RequestResponseDebug in project xipki by xipki.

the class BatchOcspQaStatusCmd method processOcspQuery.

private ValidationResult processOcspQuery(OcspQa ocspQa, BigInteger serialNumber, OcspCertStatus status, Date revTime, File messageDir, File detailsDir, URL serverUrl, X509Certificate respIssuer, X509Certificate issuerCert, IssuerHash issuerHash, RequestOptions requestOptions) throws Exception {
    if (unknownAsGood && status == OcspCertStatus.unknown) {
        status = OcspCertStatus.good;
    }
    RequestResponseDebug debug = null;
    if (saveReq || saveResp) {
        debug = new RequestResponseDebug(saveReq, saveResp);
    }
    OCSPResp response;
    try {
        response = requestor.ask(issuerCert, serialNumber, serverUrl, requestOptions, debug);
    } finally {
        if (debug != null && debug.size() > 0) {
            RequestResponsePair reqResp = debug.get(0);
            String filename = serialNumber.toString(16);
            if (saveReq) {
                byte[] bytes = reqResp.getRequest();
                if (bytes != null) {
                    IoUtil.save(new File(messageDir, filename + FILE_SEP + "request.der"), bytes);
                }
            }
            if (saveResp) {
                byte[] bytes = reqResp.getResponse();
                if (bytes != null) {
                    IoUtil.save(new File(messageDir, filename + FILE_SEP + "response.der"), bytes);
                }
            }
        }
    // end if
    }
    // end finally
    // analyze the result
    OcspResponseOption responseOption = new OcspResponseOption();
    responseOption.setNextUpdateOccurrence(expectedNextUpdateOccurrence);
    responseOption.setCerthashOccurrence(expectedCerthashOccurrence);
    responseOption.setNonceOccurrence(expectedNonceOccurrence);
    responseOption.setRespIssuer(respIssuer);
    responseOption.setSignatureAlgName(sigAlg);
    if (isNotBlank(certhashAlg)) {
        responseOption.setCerthashAlgId(AlgorithmUtil.getHashAlg(certhashAlg));
    }
    ValidationResult ret = ocspQa.checkOcsp(response, issuerHash, serialNumber, null, null, status, responseOption, revTime, noSigVerify.booleanValue());
    String validity = ret.isAllSuccessful() ? "valid" : "invalid";
    String hexSerial = serialNumber.toString(16);
    StringBuilder sb = new StringBuilder(50);
    sb.append("OCSP response for ").append(serialNumber).append(" (0x").append(hexSerial).append(") is ").append(validity);
    for (ValidationIssue issue : ret.getValidationIssues()) {
        sb.append("\n");
        OcspQaStatusCmd.format(issue, "    ", sb);
    }
    IoUtil.save(new File(detailsDir, hexSerial + "." + validity), sb.toString().getBytes());
    return ret;
}
Also used : RequestResponsePair(org.xipki.common.RequestResponsePair) RequestResponseDebug(org.xipki.common.RequestResponseDebug) OcspResponseOption(org.xipki.ocsp.qa.OcspResponseOption) ValidationResult(org.xipki.common.qa.ValidationResult) File(java.io.File) ValidationIssue(org.xipki.common.qa.ValidationIssue) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp)

Example 4 with RequestResponseDebug

use of org.xipki.common.RequestResponseDebug in project xipki by xipki.

the class RevokeCertCmd method execute0.

@Override
protected Object execute0() throws Exception {
    if (!(certFile == null ^ getSerialNumber() == null)) {
        throw new IllegalCmdParamException("exactly one of cert and serial must be specified");
    }
    CrlReason crlReason = CrlReason.forNameOrText(reason);
    if (!CrlReason.PERMITTED_CLIENT_CRLREASONS.contains(crlReason)) {
        throw new IllegalCmdParamException("reason " + reason + " is not permitted");
    }
    CertIdOrError certIdOrError;
    Date invalidityDate = null;
    if (isNotBlank(invalidityDateS)) {
        invalidityDate = DateUtil.parseUtcTimeyyyyMMddhhmmss(invalidityDateS);
    }
    if (certFile != null) {
        X509Certificate cert = X509Util.parseCert(certFile);
        RequestResponseDebug debug = getRequestResponseDebug();
        try {
            certIdOrError = caClient.revokeCert(caName, cert, crlReason.getCode(), invalidityDate, debug);
        } finally {
            saveRequestResponse(debug);
        }
    } else {
        RequestResponseDebug debug = getRequestResponseDebug();
        try {
            certIdOrError = caClient.revokeCert(caName, getSerialNumber(), crlReason.getCode(), invalidityDate, debug);
        } finally {
            saveRequestResponse(debug);
        }
    }
    if (certIdOrError.getError() != null) {
        PkiStatusInfo error = certIdOrError.getError();
        throw new CmdFailure("revocation failed: " + error);
    } else {
        println("revoked certificate");
    }
    return null;
}
Also used : RequestResponseDebug(org.xipki.common.RequestResponseDebug) CmdFailure(org.xipki.console.karaf.CmdFailure) IllegalCmdParamException(org.xipki.console.karaf.IllegalCmdParamException) CertIdOrError(org.xipki.ca.client.api.CertIdOrError) PkiStatusInfo(org.xipki.cmp.PkiStatusInfo) CrlReason(org.xipki.security.CrlReason) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate)

Example 5 with RequestResponseDebug

use of org.xipki.common.RequestResponseDebug in project xipki by xipki.

the class BaseOcspStatusAction method execute0.

@Override
protected final Object execute0() throws Exception {
    if (StringUtil.isBlank(serialNumberList) && isEmpty(certFiles)) {
        throw new IllegalCmdParamException("Neither serialNumbers nor certFiles is set");
    }
    X509Certificate issuerCert = X509Util.parseCert(issuerCertFile);
    Map<BigInteger, byte[]> encodedCerts = null;
    List<BigInteger> sns = new LinkedList<>();
    if (isNotEmpty(certFiles)) {
        encodedCerts = new HashMap<>(certFiles.size());
        String ocspUrl = null;
        X500Name issuerX500Name = null;
        for (String certFile : certFiles) {
            BigInteger sn;
            List<String> ocspUrls;
            if (isAttrCert) {
                if (issuerX500Name == null) {
                    issuerX500Name = X500Name.getInstance(issuerCert.getSubjectX500Principal().getEncoded());
                }
                X509AttributeCertificateHolder cert = new X509AttributeCertificateHolder(IoUtil.read(certFile));
                // no signature validation
                AttributeCertificateIssuer reqIssuer = cert.getIssuer();
                if (reqIssuer != null && issuerX500Name != null) {
                    X500Name reqIssuerName = reqIssuer.getNames()[0];
                    if (!issuerX500Name.equals(reqIssuerName)) {
                        throw new IllegalCmdParamException("certificate " + certFile + " is not issued by the given issuer");
                    }
                }
                ocspUrls = extractOcspUrls(cert);
                sn = cert.getSerialNumber();
            } else {
                X509Certificate cert = X509Util.parseCert(certFile);
                if (!X509Util.issues(issuerCert, cert)) {
                    throw new IllegalCmdParamException("certificate " + certFile + " is not issued by the given issuer");
                }
                ocspUrls = extractOcspUrls(cert);
                sn = cert.getSerialNumber();
            }
            if (isBlank(serverUrl)) {
                if (CollectionUtil.isEmpty(ocspUrls)) {
                    throw new IllegalCmdParamException("could not extract OCSP responder URL");
                } else {
                    String url = ocspUrls.get(0);
                    if (ocspUrl != null && !ocspUrl.equals(url)) {
                        throw new IllegalCmdParamException("given certificates have different" + " OCSP responder URL in certificate");
                    } else {
                        ocspUrl = url;
                    }
                }
            }
            // end if
            sns.add(sn);
            byte[] encodedCert = IoUtil.read(certFile);
            encodedCerts.put(sn, encodedCert);
        }
        if (isBlank(serverUrl)) {
            serverUrl = ocspUrl;
        }
    } else {
        StringTokenizer st = new StringTokenizer(serialNumberList, ", ");
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            StringTokenizer st2 = new StringTokenizer(token, "-");
            BigInteger from = toBigInt(st2.nextToken(), hex);
            BigInteger to = st2.hasMoreTokens() ? toBigInt(st2.nextToken(), hex) : null;
            if (to == null) {
                sns.add(from);
            } else {
                BigIntegerRange range = new BigIntegerRange(from, to);
                if (range.getDiff().compareTo(BigInteger.valueOf(10)) > 0) {
                    throw new IllegalCmdParamException("to many serial numbers");
                }
                BigInteger sn = range.getFrom();
                while (range.isInRange(sn)) {
                    sns.add(sn);
                    sn = sn.add(BigInteger.ONE);
                }
            }
        }
    }
    if (isBlank(serverUrl)) {
        throw new IllegalCmdParamException("could not get URL for the OCSP responder");
    }
    X509Certificate respIssuer = null;
    if (respIssuerFile != null) {
        respIssuer = X509Util.parseCert(IoUtil.expandFilepath(respIssuerFile));
    }
    URL serverUrlObj = new URL(serverUrl);
    RequestOptions options = getRequestOptions();
    checkParameters(respIssuer, sns, encodedCerts);
    boolean saveReq = isNotBlank(reqout);
    boolean saveResp = isNotBlank(respout);
    RequestResponseDebug debug = null;
    if (saveReq || saveResp) {
        debug = new RequestResponseDebug(saveReq, saveResp);
    }
    IssuerHash issuerHash = new IssuerHash(HashAlgo.getNonNullInstance(options.getHashAlgorithmId()), Certificate.getInstance(issuerCert.getEncoded()));
    OCSPResp response;
    try {
        response = requestor.ask(issuerCert, sns.toArray(new BigInteger[0]), serverUrlObj, options, debug);
    } finally {
        if (debug != null && debug.size() > 0) {
            RequestResponsePair reqResp = debug.get(0);
            if (saveReq) {
                byte[] bytes = reqResp.getRequest();
                if (bytes != null) {
                    IoUtil.save(reqout, bytes);
                }
            }
            if (saveResp) {
                byte[] bytes = reqResp.getResponse();
                if (bytes != null) {
                    IoUtil.save(respout, bytes);
                }
            }
        }
    // end if
    }
    return processResponse(response, respIssuer, issuerHash, sns, encodedCerts);
}
Also used : RequestResponsePair(org.xipki.common.RequestResponsePair) AttributeCertificateIssuer(org.bouncycastle.cert.AttributeCertificateIssuer) BigIntegerRange(org.xipki.common.util.BigIntegerRange) RequestResponseDebug(org.xipki.common.RequestResponseDebug) RequestOptions(org.xipki.ocsp.client.api.RequestOptions) X509AttributeCertificateHolder(org.bouncycastle.cert.X509AttributeCertificateHolder) ASN1String(org.bouncycastle.asn1.ASN1String) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) LinkedList(java.util.LinkedList) URL(java.net.URL) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) StringTokenizer(java.util.StringTokenizer) IssuerHash(org.xipki.security.IssuerHash) IllegalCmdParamException(org.xipki.console.karaf.IllegalCmdParamException) BigInteger(java.math.BigInteger)

Aggregations

RequestResponseDebug (org.xipki.common.RequestResponseDebug)8 X509Certificate (java.security.cert.X509Certificate)6 CmdFailure (org.xipki.console.karaf.CmdFailure)6 IllegalCmdParamException (org.xipki.console.karaf.IllegalCmdParamException)5 File (java.io.File)4 CertIdOrError (org.xipki.ca.client.api.CertIdOrError)3 PkiStatusInfo (org.xipki.cmp.PkiStatusInfo)3 BigInteger (java.math.BigInteger)2 Date (java.util.Date)2 LinkedList (java.util.LinkedList)2 StringTokenizer (java.util.StringTokenizer)2 DEROctetString (org.bouncycastle.asn1.DEROctetString)2 X500Name (org.bouncycastle.asn1.x500.X500Name)2 URL (java.net.URL)1 MessageDigest (java.security.MessageDigest)1 X509CRL (java.security.cert.X509CRL)1 HashSet (java.util.HashSet)1 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)1 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)1 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)1