Search in sources :

Example 6 with CaClientException

use of org.xipki.ca.client.api.CaClientException in project xipki by xipki.

the class CaClientImpl method revokeCerts.

@Override
public Map<String, CertIdOrError> revokeCerts(RevokeCertRequest request, RequestResponseDebug debug) throws CaClientException, PkiErrorException {
    ParamUtil.requireNonNull("request", request);
    List<RevokeCertRequestEntry> requestEntries = request.getRequestEntries();
    if (CollectionUtil.isEmpty(requestEntries)) {
        return Collections.emptyMap();
    }
    X500Name issuer = requestEntries.get(0).getIssuer();
    for (int i = 1; i < requestEntries.size(); i++) {
        if (!issuer.equals(requestEntries.get(i).getIssuer())) {
            throw new PkiErrorException(PKIStatus.REJECTION, PKIFailureInfo.badRequest, "revoking certificates issued by more than one CA is not allowed");
        }
    }
    final String caName = getCaNameByIssuer(issuer);
    CaConf caConf = casMap.get(caName);
    if (caConf.getCmpControl().isRrAkiRequired()) {
        byte[] aki = caConf.getSubjectKeyIdentifier();
        List<RevokeCertRequestEntry> entries = request.getRequestEntries();
        for (RevokeCertRequestEntry entry : entries) {
            if (entry.getAuthorityKeyIdentifier() == null) {
                entry.setAuthorityKeyIdentifier(aki);
            }
        }
    }
    X509CmpRequestor cmpRequestor = caConf.getRequestor();
    RevokeCertResultType result;
    try {
        result = cmpRequestor.revokeCertificate(request, debug);
    } catch (CmpRequestorException ex) {
        throw new CaClientException(ex.getMessage(), ex);
    }
    return parseRevokeCertResult(result);
}
Also used : RevokeCertRequestEntry(org.xipki.ca.client.api.dto.RevokeCertRequestEntry) PkiErrorException(org.xipki.ca.client.api.PkiErrorException) RevokeCertResultType(org.xipki.ca.client.api.dto.RevokeCertResultType) X500Name(org.bouncycastle.asn1.x500.X500Name) CaClientException(org.xipki.ca.client.api.CaClientException)

Example 7 with CaClientException

use of org.xipki.ca.client.api.CaClientException in project xipki by xipki.

the class CaClientImpl method init0.

private synchronized void init0(boolean force) throws CaClientException {
    if (confFile == null) {
        throw new IllegalStateException("confFile is not set");
    }
    if (securityFactory == null) {
        throw new IllegalStateException("securityFactory is not set");
    }
    if (!force && initialized.get()) {
        return;
    }
    // reset
    this.casMap.clear();
    this.autoConfCaNames.clear();
    if (this.scheduledThreadPoolExecutor != null) {
        this.scheduledThreadPoolExecutor.shutdownNow();
    }
    this.initialized.set(false);
    LOG.info("initializing ...");
    File configFile = new File(IoUtil.expandFilepath(confFile));
    if (!configFile.exists()) {
        throw new CaClientException("could not find configuration file " + confFile);
    }
    CAClientType config;
    try {
        config = parse(new FileInputStream(configFile));
    } catch (FileNotFoundException ex) {
        throw new CaClientException("could not read file " + confFile);
    }
    int numActiveCAs = 0;
    for (CAType caType : config.getCAs().getCA()) {
        if (!caType.isEnabled()) {
            LOG.info("CA " + caType.getName() + " is disabled");
            continue;
        }
        numActiveCAs++;
    }
    if (numActiveCAs == 0) {
        LOG.warn("no active CA is configured");
    }
    // responders
    Map<String, CmpResponder> responders = new HashMap<>();
    for (ResponderType m : config.getResponders().getResponder()) {
        X509Certificate cert;
        try {
            cert = X509Util.parseCert(readData(m.getCert()));
        } catch (CertificateException | IOException ex) {
            LogUtil.error(LOG, ex, "could not configure responder " + m.getName());
            throw new CaClientException(ex.getMessage(), ex);
        }
        Set<String> algoNames = new HashSet<>();
        for (String algo : m.getSignatureAlgos().getSignatureAlgo()) {
            algoNames.add(algo);
        }
        AlgorithmValidator sigAlgoValidator;
        try {
            sigAlgoValidator = new CollectionAlgorithmValidator(algoNames);
        } catch (NoSuchAlgorithmException ex) {
            throw new CaClientException(ex.getMessage());
        }
        responders.put(m.getName(), new CmpResponder(cert, sigAlgoValidator));
    }
    // CA
    Set<CaConf> cas = new HashSet<>();
    for (CAType caType : config.getCAs().getCA()) {
        if (!caType.isEnabled()) {
            continue;
        }
        String caName = caType.getName();
        try {
            // responder
            CmpResponder responder = responders.get(caType.getResponder());
            if (responder == null) {
                throw new CaClientException("no responder named " + caType.getResponder() + " is configured");
            }
            CaConf ca = new CaConf(caName, caType.getUrl(), caType.getHealthUrl(), caType.getRequestor(), responder);
            // CA cert
            if (caType.getCaCert().getAutoconf() != null) {
                ca.setCertAutoconf(true);
            } else {
                ca.setCertAutoconf(false);
                ca.setCert(X509Util.parseCert(readData(caType.getCaCert().getCert())));
            }
            // CMPControl
            CmpControlType cmpCtrlType = caType.getCmpControl();
            if (cmpCtrlType.getAutoconf() != null) {
                ca.setCmpControlAutoconf(true);
            } else {
                ca.setCmpControlAutoconf(false);
                Boolean tmpBo = cmpCtrlType.isRrAkiRequired();
                ClientCmpControl control = new ClientCmpControl((tmpBo == null) ? false : tmpBo.booleanValue());
                ca.setCmpControl(control);
            }
            // Certprofiles
            CertprofilesType certprofilesType = caType.getCertprofiles();
            if (certprofilesType.getAutoconf() != null) {
                ca.setCertprofilesAutoconf(true);
            } else {
                ca.setCertprofilesAutoconf(false);
                List<CertprofileType> types = certprofilesType.getCertprofile();
                Set<CertprofileInfo> profiles = new HashSet<>(types.size());
                for (CertprofileType m : types) {
                    String conf = null;
                    if (m.getConf() != null) {
                        conf = m.getConf().getValue();
                        if (conf == null) {
                            conf = new String(IoUtil.read(m.getConf().getFile()));
                        }
                    }
                    CertprofileInfo profile = new CertprofileInfo(m.getName(), m.getType(), conf);
                    profiles.add(profile);
                }
                ca.setCertprofiles(profiles);
            }
            cas.add(ca);
            if (ca.isCertAutoconf() || ca.isCertprofilesAutoconf() || ca.isCmpControlAutoconf()) {
                autoConfCaNames.add(caName);
            }
        } catch (IOException | CertificateException ex) {
            LogUtil.error(LOG, ex, "could not configure CA " + caName);
            throw new CaClientException(ex.getMessage(), ex);
        }
    }
    // requestors
    Map<String, X509Certificate> requestorCerts = new HashMap<>();
    Map<String, ConcurrentContentSigner> requestorSigners = new HashMap<>();
    Map<String, Boolean> requestorSignRequests = new HashMap<>();
    for (RequestorType requestorConf : config.getRequestors().getRequestor()) {
        String name = requestorConf.getName();
        requestorSignRequests.put(name, requestorConf.isSignRequest());
        X509Certificate requestorCert = null;
        if (requestorConf.getCert() != null) {
            try {
                requestorCert = X509Util.parseCert(readData(requestorConf.getCert()));
                requestorCerts.put(name, requestorCert);
            } catch (Exception ex) {
                throw new CaClientException(ex.getMessage(), ex);
            }
        }
        if (requestorConf.getSignerType() != null) {
            try {
                SignerConf signerConf = new SignerConf(requestorConf.getSignerConf());
                ConcurrentContentSigner requestorSigner = securityFactory.createSigner(requestorConf.getSignerType(), signerConf, requestorCert);
                requestorSigners.put(name, requestorSigner);
            } catch (ObjectCreationException ex) {
                throw new CaClientException(ex.getMessage(), ex);
            }
        } else {
            if (requestorConf.isSignRequest()) {
                throw new CaClientException("signer of requestor must be configured");
            } else if (requestorCert == null) {
                throw new CaClientException("at least one of certificate and signer of requestor must be configured");
            }
        }
    }
    for (CaConf ca : cas) {
        if (this.casMap.containsKey(ca.getName())) {
            throw new CaClientException("duplicate CAs with the same name " + ca.getName());
        }
        String requestorName = ca.getRequestorName();
        X509CmpRequestor cmpRequestor;
        if (requestorSigners.containsKey(requestorName)) {
            cmpRequestor = new DfltHttpX509CmpRequestor(requestorSigners.get(requestorName), ca.getResponder(), ca.getUrl(), securityFactory);
            cmpRequestor.setSignRequest(requestorSignRequests.get(requestorName));
        } else if (requestorCerts.containsKey(requestorName)) {
            cmpRequestor = new DfltHttpX509CmpRequestor(requestorCerts.get(requestorName), ca.getResponder(), ca.getUrl(), securityFactory);
        } else {
            throw new CaClientException("could not find requestor named " + requestorName + " for CA " + ca.getName());
        }
        ca.setRequestor(cmpRequestor);
        this.casMap.put(ca.getName(), ca);
    }
    if (!autoConfCaNames.isEmpty()) {
        Integer caInfoUpdateInterval = config.getCAs().getCAInfoUpdateInterval();
        if (caInfoUpdateInterval == null) {
            caInfoUpdateInterval = 10;
        } else if (caInfoUpdateInterval <= 0) {
            caInfoUpdateInterval = 0;
        } else if (caInfoUpdateInterval < 5) {
            caInfoUpdateInterval = 5;
        }
        LOG.info("configuring CAs {}", autoConfCaNames);
        Set<String> failedCaNames = autoConfCas(autoConfCaNames);
        // try to re-configure the failed CAs
        if (CollectionUtil.isNonEmpty(failedCaNames)) {
            for (int i = 0; i < 3; i++) {
                LOG.info("configuring ({}-th retry) CAs {}", i + 1, failedCaNames);
                failedCaNames = autoConfCas(failedCaNames);
                if (CollectionUtil.isEmpty(failedCaNames)) {
                    break;
                }
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException ex) {
                    LOG.warn("interrupted", ex);
                }
            }
        }
        if (CollectionUtil.isNonEmpty(failedCaNames)) {
            throw new CaClientException("could not configure following CAs " + failedCaNames);
        }
        if (caInfoUpdateInterval > 0) {
            scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
            scheduledThreadPoolExecutor.scheduleAtFixedRate(new ClientConfigUpdater(), caInfoUpdateInterval, caInfoUpdateInterval, TimeUnit.MINUTES);
        }
    }
    initialized.set(true);
    LOG.info("initialized");
}
Also used : CollectionAlgorithmValidator(org.xipki.security.CollectionAlgorithmValidator) AlgorithmValidator(org.xipki.security.AlgorithmValidator) HashMap(java.util.HashMap) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) FileNotFoundException(java.io.FileNotFoundException) RequestorType(org.xipki.ca.client.impl.jaxb.RequestorType) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CmpControlType(org.xipki.ca.client.impl.jaxb.CmpControlType) CertprofilesType(org.xipki.ca.client.impl.jaxb.CertprofilesType) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashSet(java.util.HashSet) CertprofileType(org.xipki.ca.client.impl.jaxb.CertprofileType) CertprofileInfo(org.xipki.ca.client.api.CertprofileInfo) CAType(org.xipki.ca.client.impl.jaxb.CAType) SignerConf(org.xipki.security.SignerConf) IOException(java.io.IOException) ResponderType(org.xipki.ca.client.impl.jaxb.ResponderType) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) CollectionAlgorithmValidator(org.xipki.security.CollectionAlgorithmValidator) ObjectCreationException(org.xipki.common.ObjectCreationException) SignatureException(java.security.SignatureException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SAXException(org.xml.sax.SAXException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) PkiErrorException(org.xipki.ca.client.api.PkiErrorException) CaClientException(org.xipki.ca.client.api.CaClientException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) BigInteger(java.math.BigInteger) ConcurrentContentSigner(org.xipki.security.ConcurrentContentSigner) CAClientType(org.xipki.ca.client.impl.jaxb.CAClientType) ObjectCreationException(org.xipki.common.ObjectCreationException) File(java.io.File) CaClientException(org.xipki.ca.client.api.CaClientException)

Example 8 with CaClientException

use of org.xipki.ca.client.api.CaClientException in project xipki by xipki.

the class CaClientImpl method requestCert.

@Override
public EnrollCertResult requestCert(String caName, CertificationRequest csr, String profile, Date notBefore, Date notAfter, RequestResponseDebug debug) throws CaClientException, PkiErrorException {
    ParamUtil.requireNonNull("csr", csr);
    if (caName == null) {
        caName = getCaNameForProfile(profile);
    } else {
        caName = caName.toLowerCase();
    }
    if (caName == null) {
        throw new CaClientException("certprofile " + profile + " is not supported by any CA");
    }
    CaConf ca = casMap.get(caName);
    if (ca == null) {
        throw new CaClientException("could not find CA named " + caName);
    }
    final String id = "cert-1";
    CsrEnrollCertRequest request = new CsrEnrollCertRequest(id, profile, csr);
    EnrollCertResultResp result;
    try {
        result = ca.getRequestor().requestCertificate(request, notBefore, notAfter, debug);
    } catch (CmpRequestorException ex) {
        throw new CaClientException(ex.getMessage(), ex);
    }
    return parseEnrollCertResult(result);
}
Also used : CsrEnrollCertRequest(org.xipki.ca.client.api.dto.CsrEnrollCertRequest) EnrollCertResultResp(org.xipki.ca.client.api.dto.EnrollCertResultResp) CaClientException(org.xipki.ca.client.api.CaClientException)

Example 9 with CaClientException

use of org.xipki.ca.client.api.CaClientException in project xipki by xipki.

the class CaClientImpl method envelopeRevocation.

// method verify
@Override
public byte[] envelopeRevocation(X500Name issuer, BigInteger serial, int reason) throws CaClientException {
    ParamUtil.requireNonNull("issuer", issuer);
    init0(false);
    final String id = "cert-1";
    RevokeCertRequestEntry entry = new RevokeCertRequestEntry(id, issuer, serial, reason, null);
    RevokeCertRequest request = new RevokeCertRequest();
    request.addRequestEntry(entry);
    String caName = getCaNameByIssuer(issuer);
    X509CmpRequestor cmpRequestor = casMap.get(caName).getRequestor();
    try {
        PKIMessage pkiMessage = cmpRequestor.envelopeRevocation(request);
        return pkiMessage.getEncoded();
    } catch (CmpRequestorException | IOException ex) {
        throw new CaClientException(ex.getMessage(), ex);
    }
}
Also used : PKIMessage(org.bouncycastle.asn1.cmp.PKIMessage) RevokeCertRequestEntry(org.xipki.ca.client.api.dto.RevokeCertRequestEntry) IOException(java.io.IOException) RevokeCertRequest(org.xipki.ca.client.api.dto.RevokeCertRequest) CaClientException(org.xipki.ca.client.api.CaClientException)

Example 10 with CaClientException

use of org.xipki.ca.client.api.CaClientException in project xipki by xipki.

the class CaClientImpl method getHealthCheckResult.

@Override
public HealthCheckResult getHealthCheckResult(String caName) throws CaClientException {
    caName = ParamUtil.requireNonNull("caName", caName).toLowerCase();
    String name = "X509CA";
    HealthCheckResult healthCheckResult = new HealthCheckResult(name);
    try {
        init0(false);
    } catch (CaClientException ex) {
        LogUtil.error(LOG, ex, "could not initialize CaCleint");
        healthCheckResult.setHealthy(false);
        return healthCheckResult;
    }
    CaConf ca = casMap.get(caName);
    if (ca == null) {
        throw new IllegalArgumentException("unknown CA " + caName);
    }
    String healthUrlStr = ca.getHealthUrl();
    URL serverUrl;
    try {
        serverUrl = new URL(healthUrlStr);
    } catch (MalformedURLException ex) {
        throw new CaClientException("invalid URL '" + healthUrlStr + "'");
    }
    try {
        HttpURLConnection httpUrlConnection = IoUtil.openHttpConn(serverUrl);
        InputStream inputStream = httpUrlConnection.getInputStream();
        int responseCode = httpUrlConnection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_INTERNAL_ERROR) {
            inputStream.close();
            throw new IOException(String.format("bad response: code='%s', message='%s'", httpUrlConnection.getResponseCode(), httpUrlConnection.getResponseMessage()));
        }
        String responseContentType = httpUrlConnection.getContentType();
        boolean isValidContentType = false;
        if (responseContentType != null) {
            if ("application/json".equalsIgnoreCase(responseContentType)) {
                isValidContentType = true;
            }
        }
        if (!isValidContentType) {
            inputStream.close();
            throw new IOException("bad response: mime type " + responseContentType + " not supported!");
        }
        byte[] responseBytes = IoUtil.read(inputStream);
        if (responseBytes.length == 0) {
            healthCheckResult.setHealthy(responseCode == HttpURLConnection.HTTP_OK);
        } else {
            String response = new String(responseBytes);
            try {
                healthCheckResult = HealthCheckResult.getInstanceFromJsonMessage(name, response);
            } catch (IllegalArgumentException ex) {
                LogUtil.error(LOG, ex, "IOException while parsing the health json message");
                if (LOG.isDebugEnabled()) {
                    LOG.debug("json message: {}", response);
                }
                healthCheckResult.setHealthy(false);
            }
        }
    } catch (IOException ex) {
        LogUtil.error(LOG, ex, "IOException while fetching the URL " + healthUrlStr);
        healthCheckResult.setHealthy(false);
    }
    return healthCheckResult;
}
Also used : MalformedURLException(java.net.MalformedURLException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) HealthCheckResult(org.xipki.common.HealthCheckResult) IOException(java.io.IOException) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) CaClientException(org.xipki.ca.client.api.CaClientException)

Aggregations

CaClientException (org.xipki.ca.client.api.CaClientException)14 IOException (java.io.IOException)5 PkiErrorException (org.xipki.ca.client.api.PkiErrorException)4 HashMap (java.util.HashMap)3 X500Name (org.bouncycastle.asn1.x500.X500Name)3 RevokeCertResultType (org.xipki.ca.client.api.dto.RevokeCertResultType)3 FileInputStream (java.io.FileInputStream)2 MalformedURLException (java.net.MalformedURLException)2 URL (java.net.URL)2 CertificateException (java.security.cert.CertificateException)2 X509Certificate (java.security.cert.X509Certificate)2 JAXBException (javax.xml.bind.JAXBException)2 PKIMessage (org.bouncycastle.asn1.cmp.PKIMessage)2 EnrollCertResultEntry (org.xipki.ca.client.api.dto.EnrollCertResultEntry)2 EnrollCertResultResp (org.xipki.ca.client.api.dto.EnrollCertResultResp)2 RevokeCertRequestEntry (org.xipki.ca.client.api.dto.RevokeCertRequestEntry)2 CAClientType (org.xipki.ca.client.impl.jaxb.CAClientType)2 CAType (org.xipki.ca.client.impl.jaxb.CAType)2 RequestorType (org.xipki.ca.client.impl.jaxb.RequestorType)2 ResponderType (org.xipki.ca.client.impl.jaxb.ResponderType)2