Search in sources :

Example 1 with RequestOptions

use of org.xipki.ocsp.client.api.RequestOptions in project xipki by xipki.

the class BenchmarkOcspStatusCmd method execute0.

@Override
protected Object execute0() throws Exception {
    int ii = 0;
    if (serialNumberList != null) {
        ii++;
    }
    if (serialNumberFile != null) {
        ii++;
    }
    if (CollectionUtil.isNonEmpty(certFiles)) {
        ii++;
    }
    if (ii != 1) {
        throw new IllegalCmdParamException("exactly one of serial, serial-file and cert must be specified");
    }
    if (numThreads < 1) {
        throw new IllegalCmdParamException("invalid number of threads " + numThreads);
    }
    Iterator<BigInteger> serialNumberIterator;
    if (serialNumberFile != null) {
        serialNumberIterator = new FileBigIntegerIterator(IoUtil.expandFilepath(serialNumberFile), hex, true);
    } else {
        List<BigIntegerRange> serialNumbers = new LinkedList<>();
        if (serialNumberList != null) {
            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) : from;
                serialNumbers.add(new BigIntegerRange(from, to));
            }
        } else if (certFiles != null) {
            for (String certFile : certFiles) {
                X509Certificate cert;
                try {
                    cert = X509Util.parseCert(certFile);
                } catch (Exception ex) {
                    throw new IllegalCmdParamException("invalid certificate file  '" + certFile + "'", ex);
                }
                BigInteger serial = cert.getSerialNumber();
                serialNumbers.add(new BigIntegerRange(serial, serial));
            }
        }
        serialNumberIterator = new RangeBigIntegerIterator(serialNumbers, true);
    }
    try {
        String description = StringUtil.concatObjects("issuer cert: ", issuerCertFile, "\nserver URL: ", serverUrl, "\nmaxRequest: ", maxRequests, "\nhash: ", hashAlgo);
        Certificate issuerCert = Certificate.getInstance(IoUtil.read(issuerCertFile));
        RequestOptions options = getRequestOptions();
        OcspBenchmark loadTest = new OcspBenchmark(issuerCert, serverUrl, options, serialNumberIterator, maxRequests, analyzeResponse, queueSize, description.toString());
        loadTest.setDuration(duration);
        loadTest.setThreads(numThreads);
        loadTest.test();
    } finally {
        if (serialNumberIterator instanceof FileBigIntegerIterator) {
            ((FileBigIntegerIterator) serialNumberIterator).close();
        }
    }
    return null;
}
Also used : BigIntegerRange(org.xipki.common.util.BigIntegerRange) RequestOptions(org.xipki.ocsp.client.api.RequestOptions) OcspBenchmark(org.xipki.ocsp.qa.benchmark.OcspBenchmark) FileBigIntegerIterator(org.xipki.common.util.FileBigIntegerIterator) LinkedList(java.util.LinkedList) X509Certificate(java.security.cert.X509Certificate) IllegalCmdParamException(org.xipki.console.karaf.IllegalCmdParamException) StringTokenizer(java.util.StringTokenizer) IllegalCmdParamException(org.xipki.console.karaf.IllegalCmdParamException) BigInteger(java.math.BigInteger) RangeBigIntegerIterator(org.xipki.common.util.RangeBigIntegerIterator) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 2 with RequestOptions

use of org.xipki.ocsp.client.api.RequestOptions 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)

Example 3 with RequestOptions

use of org.xipki.ocsp.client.api.RequestOptions in project xipki by xipki.

the class OcspStatusAction method getRequestOptions.

protected RequestOptions getRequestOptions() throws Exception {
    ASN1ObjectIdentifier hashAlgOid = AlgorithmUtil.getHashAlg(hashAlgo);
    RequestOptions options = new RequestOptions();
    options.setUseNonce(usenonce.booleanValue());
    if (nonceLen != null) {
        options.setNonceLen(nonceLen);
    }
    options.setHashAlgorithmId(hashAlgOid);
    options.setSignRequest(signRequest.booleanValue());
    options.setUseHttpGetForRequest(useHttpGetForSmallRequest.booleanValue());
    if (isNotEmpty(prefSigAlgs)) {
        options.setPreferredSignatureAlgorithms(prefSigAlgs.toArray(new String[0]));
    }
    return options;
}
Also used : RequestOptions(org.xipki.ocsp.client.api.RequestOptions) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 4 with RequestOptions

use of org.xipki.ocsp.client.api.RequestOptions in project xipki by xipki.

the class BatchOcspQaStatusCmd method execute0.

@Override
protected final Object execute0() throws Exception {
    expectedCerthashOccurrence = Occurrence.forName(certhashOccurrenceText);
    expectedNextUpdateOccurrence = Occurrence.forName(nextUpdateOccurrenceText);
    expectedNonceOccurrence = Occurrence.forName(nonceOccurrenceText);
    File outDir = new File(outDirStr);
    File messageDir = new File(outDir, "messages");
    messageDir.mkdirs();
    File detailsDir = new File(outDir, "details");
    detailsDir.mkdirs();
    println("The result is saved in the folder " + outDir.getPath());
    String linuxIssuer = (respIssuerFile != null) ? "-CAfile ../../responder_issuer.pem" : "-no_cert_verify";
    String winIssuer = (respIssuerFile != null) ? "-CAfile ..\\..\\responder_issuer.pem" : "-no_cert_verify";
    String linuxMsg = "openssl ocsp -text ";
    String winMsg = "openssl ocsp -text ";
    String shellFilePath = null;
    if (saveReq && saveResp) {
        linuxMsg += linuxIssuer + " -reqin request.der -respin response.der";
        winMsg += winIssuer + " -reqin request.der -respin response.der";
        shellFilePath = new File(outDir, "verify-req-resp").getPath();
    } else if (saveReq) {
        linuxMsg += "-reqin request.der\n";
        winMsg += "-reqin request.der\n";
        shellFilePath = new File(outDir, "verify-req").getPath();
    } else if (saveResp) {
        linuxMsg += linuxIssuer + " -respin response.der\n";
        winMsg += winIssuer + " -respin response.der\n";
        shellFilePath = new File(outDir, "verify-resp").getPath();
    }
    if (shellFilePath != null) {
        File linuxShellFile = new File(shellFilePath + ".sh");
        IoUtil.save(linuxShellFile, ("#!/bin/sh\n" + linuxMsg).getBytes());
        IoUtil.save(shellFilePath + ".bat", ("@echo off\r\n" + winMsg).getBytes());
        linuxShellFile.setExecutable(true);
    }
    X509Certificate issuerCert = X509Util.parseCert(issuerCertFile);
    X509Certificate respIssuer = null;
    if (respIssuerFile != null) {
        respIssuer = X509Util.parseCert(IoUtil.expandFilepath(respIssuerFile));
        IoUtil.save(new File(outDir, "responder-issuer.pem"), X509Util.toPemCert(respIssuer).getBytes());
    }
    RequestOptions requestOptions = getRequestOptions();
    IssuerHash issuerHash = new IssuerHash(HashAlgo.getNonNullInstance(requestOptions.getHashAlgorithmId()), Certificate.getInstance(issuerCert.getEncoded()));
    OutputStream resultOut = new FileOutputStream(new File(outDir, "overview.txt"));
    BufferedReader snReader = new BufferedReader(new FileReader(snFile));
    int numSucc = 0;
    int numFail = 0;
    try {
        URL serverUrl = new URL(serverUrlStr);
        OcspQa ocspQa = new OcspQa(securityFactory);
        // Content of a line:
        // <hex-encoded serial number>[,<reason code>,<revocation time in epoch seconds>]
        int lineNo = 0;
        String line;
        while ((line = snReader.readLine()) != null) {
            lineNo++;
            line = line.trim();
            if (line.startsWith("#") || line.isEmpty()) {
                resultOut.write(line.getBytes());
                resultOut.write('\n');
                continue;
            }
            String resultText = lineNo + ": " + line + ": ";
            try {
                ValidationResult result = processOcspQuery(ocspQa, line, messageDir, detailsDir, serverUrl, respIssuer, issuerCert, issuerHash, requestOptions);
                if (result.isAllSuccessful()) {
                    numSucc++;
                    resultText += "valid";
                } else {
                    numFail++;
                    resultText += "invalid";
                }
            } catch (Throwable th) {
                LogUtil.error(LOG, th);
                numFail++;
                resultText += "error - " + th.getMessage();
            }
            if (!noout) {
                println(resultText);
            }
            println(resultText, resultOut);
        }
        // unknown serial number
        lineNo++;
        SecureRandom random = new SecureRandom();
        byte[] bytes = new byte[16];
        random.nextBytes(bytes);
        bytes[0] = (byte) (0x7F & bytes[0]);
        BigInteger serialNumber = new BigInteger(bytes);
        String resultText = lineNo + ": " + serialNumber.toString(16) + ",unknown: ";
        try {
            ValidationResult result = processOcspQuery(ocspQa, serialNumber, OcspCertStatus.unknown, null, messageDir, detailsDir, serverUrl, respIssuer, issuerCert, issuerHash, requestOptions);
            if (result.isAllSuccessful()) {
                numSucc++;
                resultText += "valid";
            } else {
                numFail++;
                resultText += "invalid";
            }
        } catch (Throwable th) {
            LogUtil.error(LOG, th);
            numFail++;
            resultText += "error - " + th.getMessage();
        }
        if (!noout) {
            println(resultText);
        }
        println(resultText, resultOut);
        String message = StringUtil.concatObjectsCap(200, "=====BEGIN SUMMARY=====", "\n       url: ", serverUrlStr, "\n       sum: ", numFail + numSucc, "\nsuccessful: ", numSucc, "\n    failed: ", numFail, "\n=====END SUMMARY=====");
        println(message);
        println(message, resultOut);
    } finally {
        snReader.close();
        resultOut.close();
    }
    return null;
}
Also used : RequestOptions(org.xipki.ocsp.client.api.RequestOptions) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) SecureRandom(java.security.SecureRandom) ValidationResult(org.xipki.common.qa.ValidationResult) X509Certificate(java.security.cert.X509Certificate) URL(java.net.URL) IssuerHash(org.xipki.security.IssuerHash) OcspQa(org.xipki.ocsp.qa.OcspQa) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) BigInteger(java.math.BigInteger) FileReader(java.io.FileReader) File(java.io.File)

Aggregations

RequestOptions (org.xipki.ocsp.client.api.RequestOptions)4 BigInteger (java.math.BigInteger)3 X509Certificate (java.security.cert.X509Certificate)3 URL (java.net.URL)2 LinkedList (java.util.LinkedList)2 StringTokenizer (java.util.StringTokenizer)2 BigIntegerRange (org.xipki.common.util.BigIntegerRange)2 IllegalCmdParamException (org.xipki.console.karaf.IllegalCmdParamException)2 IssuerHash (org.xipki.security.IssuerHash)2 BufferedReader (java.io.BufferedReader)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 FileReader (java.io.FileReader)1 OutputStream (java.io.OutputStream)1 SecureRandom (java.security.SecureRandom)1 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)1 ASN1String (org.bouncycastle.asn1.ASN1String)1 X500Name (org.bouncycastle.asn1.x500.X500Name)1 Certificate (org.bouncycastle.asn1.x509.Certificate)1 AttributeCertificateIssuer (org.bouncycastle.cert.AttributeCertificateIssuer)1