Search in sources :

Example 11 with SignerConf

use of org.xipki.security.SignerConf in project xipki by xipki.

the class AbstractOcspRequestor method buildRequest.

// method ask
private OCSPRequest buildRequest(X509Certificate caCert, BigInteger[] serialNumbers, byte[] nonce, RequestOptions requestOptions) throws OcspRequestorException {
    HashAlgo hashAlgo = HashAlgo.getInstance(requestOptions.getHashAlgorithmId());
    if (hashAlgo == null) {
        throw new OcspRequestorException("unknown HashAlgo " + requestOptions.getHashAlgorithmId().getId());
    }
    List<AlgorithmIdentifier> prefSigAlgs = requestOptions.getPreferredSignatureAlgorithms();
    XiOCSPReqBuilder reqBuilder = new XiOCSPReqBuilder();
    List<Extension> extensions = new LinkedList<>();
    if (nonce != null) {
        extensions.add(new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce)));
    }
    if (prefSigAlgs != null && prefSigAlgs.size() > 0) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (AlgorithmIdentifier algId : prefSigAlgs) {
            vec.add(new DERSequence(algId));
        }
        ASN1Sequence extnValue = new DERSequence(vec);
        Extension extn;
        try {
            extn = new Extension(ObjectIdentifiers.id_pkix_ocsp_prefSigAlgs, false, new DEROctetString(extnValue));
        } catch (IOException ex) {
            throw new OcspRequestorException(ex.getMessage(), ex);
        }
        extensions.add(extn);
    }
    if (CollectionUtil.isNonEmpty(extensions)) {
        reqBuilder.setRequestExtensions(new Extensions(extensions.toArray(new Extension[0])));
    }
    try {
        DEROctetString issuerNameHash = new DEROctetString(hashAlgo.hash(caCert.getSubjectX500Principal().getEncoded()));
        TBSCertificate tbsCert;
        try {
            tbsCert = TBSCertificate.getInstance(caCert.getTBSCertificate());
        } catch (CertificateEncodingException ex) {
            throw new OcspRequestorException(ex);
        }
        DEROctetString issuerKeyHash = new DEROctetString(hashAlgo.hash(tbsCert.getSubjectPublicKeyInfo().getPublicKeyData().getOctets()));
        for (BigInteger serialNumber : serialNumbers) {
            CertID certId = new CertID(hashAlgo.getAlgorithmIdentifier(), issuerNameHash, issuerKeyHash, new ASN1Integer(serialNumber));
            reqBuilder.addRequest(certId);
        }
        if (requestOptions.isSignRequest()) {
            synchronized (signerLock) {
                if (signer == null) {
                    if (StringUtil.isBlank(signerType)) {
                        throw new OcspRequestorException("signerType is not configured");
                    }
                    if (StringUtil.isBlank(signerConf)) {
                        throw new OcspRequestorException("signerConf is not configured");
                    }
                    X509Certificate cert = null;
                    if (StringUtil.isNotBlank(signerCertFile)) {
                        try {
                            cert = X509Util.parseCert(signerCertFile);
                        } catch (CertificateException ex) {
                            throw new OcspRequestorException("could not parse certificate " + signerCertFile + ": " + ex.getMessage());
                        }
                    }
                    try {
                        signer = getSecurityFactory().createSigner(signerType, new SignerConf(signerConf), cert);
                    } catch (Exception ex) {
                        throw new OcspRequestorException("could not create signer: " + ex.getMessage());
                    }
                }
            // end if
            }
            // end synchronized
            reqBuilder.setRequestorName(signer.getBcCertificate().getSubject());
            X509CertificateHolder[] certChain0 = signer.getBcCertificateChain();
            Certificate[] certChain = new Certificate[certChain0.length];
            for (int i = 0; i < certChain.length; i++) {
                certChain[i] = certChain0[i].toASN1Structure();
            }
            ConcurrentBagEntrySigner signer0;
            try {
                signer0 = signer.borrowSigner();
            } catch (NoIdleSignerException ex) {
                throw new OcspRequestorException("NoIdleSignerException: " + ex.getMessage());
            }
            try {
                return reqBuilder.build(signer0.value(), certChain);
            } finally {
                signer.requiteSigner(signer0);
            }
        } else {
            return reqBuilder.build();
        }
    // end if
    } catch (OCSPException | IOException ex) {
        throw new OcspRequestorException(ex.getMessage(), ex);
    }
}
Also used : HashAlgo(org.xipki.security.HashAlgo) CertID(org.bouncycastle.asn1.ocsp.CertID) CertificateException(java.security.cert.CertificateException) Extensions(org.bouncycastle.asn1.x509.Extensions) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERSequence(org.bouncycastle.asn1.DERSequence) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) NoIdleSignerException(org.xipki.security.exception.NoIdleSignerException) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) OcspRequestorException(org.xipki.ocsp.client.api.OcspRequestorException) SignerConf(org.xipki.security.SignerConf) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) ConcurrentBagEntrySigner(org.xipki.security.ConcurrentBagEntrySigner) LinkedList(java.util.LinkedList) X509Certificate(java.security.cert.X509Certificate) OcspNonceUnmatchedException(org.xipki.ocsp.client.api.OcspNonceUnmatchedException) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) OcspResponseException(org.xipki.ocsp.client.api.OcspResponseException) OcspRequestorException(org.xipki.ocsp.client.api.OcspRequestorException) CertificateEncodingException(java.security.cert.CertificateEncodingException) NoIdleSignerException(org.xipki.security.exception.NoIdleSignerException) ResponderUnreachableException(org.xipki.ocsp.client.api.ResponderUnreachableException) OcspTargetUnmatchedException(org.xipki.ocsp.client.api.OcspTargetUnmatchedException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) InvalidOcspResponseException(org.xipki.ocsp.client.api.InvalidOcspResponseException) Extension(org.bouncycastle.asn1.x509.Extension) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate)

Example 12 with SignerConf

use of org.xipki.security.SignerConf 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 13 with SignerConf

use of org.xipki.security.SignerConf in project xipki by xipki.

the class X509CrlSignerEntryWrapper method initSigner.

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

Example 14 with SignerConf

use of org.xipki.security.SignerConf in project xipki by xipki.

the class P12CsrGenCmd method getSigner.

@Override
protected ConcurrentContentSigner getSigner(SignatureAlgoControl signatureAlgoControl) throws ObjectCreationException {
    ParamUtil.requireNonNull("signatureAlgoControl", signatureAlgoControl);
    char[] pwd;
    try {
        pwd = getPassword();
    } catch (IOException ex) {
        throw new ObjectCreationException("could not read password: " + ex.getMessage(), ex);
    }
    SignerConf conf = SignerConf.getKeystoreSignerConf(p12File, new String(pwd), 1, HashAlgo.getNonNullInstance(hashAlgo), signatureAlgoControl);
    return securityFactory.createSigner("PKCS12", conf, (X509Certificate[]) null);
}
Also used : ObjectCreationException(org.xipki.common.ObjectCreationException) SignerConf(org.xipki.security.SignerConf) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate)

Example 15 with SignerConf

use of org.xipki.security.SignerConf in project xipki by xipki.

the class P11EnrollCertCmd method getSigner.

@Override
protected ConcurrentContentSigner getSigner(SignatureAlgoControl signatureAlgoControl) throws ObjectCreationException {
    byte[] keyIdBytes = null;
    if (keyId != null) {
        keyIdBytes = Hex.decode(keyId);
    }
    SignerConf signerConf = SignerConf.getPkcs11SignerConf(moduleName, slotIndex, null, keyLabel, keyIdBytes, 1, HashAlgo.getNonNullInstance(hashAlgo), signatureAlgoControl);
    return securityFactory.createSigner("PKCS11", signerConf, (X509Certificate[]) null);
}
Also used : SignerConf(org.xipki.security.SignerConf) X509Certificate(java.security.cert.X509Certificate)

Aggregations

SignerConf (org.xipki.security.SignerConf)16 X509Certificate (java.security.cert.X509Certificate)13 ObjectCreationException (org.xipki.common.ObjectCreationException)11 IOException (java.io.IOException)8 ConcurrentContentSigner (org.xipki.security.ConcurrentContentSigner)7 CertificateException (java.security.cert.CertificateException)6 XiSecurityException (org.xipki.security.exception.XiSecurityException)6 CertificateEncodingException (java.security.cert.CertificateEncodingException)4 ConfPairs (org.xipki.common.ConfPairs)4 BigInteger (java.math.BigInteger)3 CaMgmtException (org.xipki.ca.server.mgmt.api.CaMgmtException)3 X509CaEntry (org.xipki.ca.server.mgmt.api.x509.X509CaEntry)3 InvalidKeyException (java.security.InvalidKeyException)2 HashMap (java.util.HashMap)2 NameId (org.xipki.ca.api.NameId)2 AddUserEntry (org.xipki.ca.server.mgmt.api.AddUserEntry)2 CaHasRequestorEntry (org.xipki.ca.server.mgmt.api.CaHasRequestorEntry)2 CaHasUserEntry (org.xipki.ca.server.mgmt.api.CaHasUserEntry)2 CertprofileEntry (org.xipki.ca.server.mgmt.api.CertprofileEntry)2 CmpControlEntry (org.xipki.ca.server.mgmt.api.CmpControlEntry)2