Search in sources :

Example 1 with NoSuchDid

use of org.openecard.crypto.common.sal.did.NoSuchDid in project open-ecard by ecsec.

the class ListTokens method determineTokenFeatures.

private boolean determineTokenFeatures(TokenInfoType next) {
    try {
        // request the missing information
        ConnectionHandleType h = new ConnectionHandleType();
        h.setSlotHandle(next.getConnectionHandle().getSlotHandle());
        DidInfos dids = new DidInfos(dispatcher, null, h);
        List<DidInfo> didInfos = dids.getDidInfos();
        boolean needsDidPin = false;
        boolean needsCertPin = false;
        TreeSet<String> algorithms = new TreeSet<>();
        // find out everything about the token
        for (DidInfo didInfo : didInfos) {
            if (didInfo.isCryptoDid()) {
                // only evaluate if we have no positive match yet
                if (!needsDidPin) {
                    needsDidPin |= didInfo.needsPin();
                }
                // only evaluate if we have no positive match yet
                if (!needsCertPin) {
                    for (DataSetInfo dataSetinfo : didInfo.getRelatedDataSets()) {
                        needsCertPin |= dataSetinfo.needsPin();
                    }
                }
                // get the algorithm of the did
                AlgorithmInfoType algInfo = didInfo.getGenericCryptoMarker().getAlgorithmInfo();
                AlgorithmIdentifierType algId = algInfo.getAlgorithmIdentifier();
                String alg = algInfo.getAlgorithm();
                try {
                    if (algId != null && algId.getAlgorithm() != null) {
                        String jcaName = AllowedSignatureAlgorithms.algIdtoJcaName(algId.getAlgorithm());
                        algorithms.add(jcaName);
                    }
                } catch (UnsupportedAlgorithmException ex) {
                    // ignore and fall back to Algorithm field
                    if (alg != null && !alg.isEmpty() && AllowedSignatureAlgorithms.isKnownJcaAlgorithm(alg)) {
                        algorithms.add(alg);
                    }
                }
            }
        }
        next.setNeedsPinForCertAccess(needsCertPin);
        next.setNeedsPinForPrivateKeyAccess(needsDidPin);
        next.getAlgorithm().addAll(algorithms);
        // finished evaluation everything successfully
        return true;
    } catch (NoSuchDid | WSHelper.WSException | SecurityConditionUnsatisfiable ex) {
        LOG.error("Failed to evaluate DID.", ex);
    }
    // there has been an error
    return false;
}
Also used : ConnectionHandleType(iso.std.iso_iec._24727.tech.schema.ConnectionHandleType) SecurityConditionUnsatisfiable(org.openecard.common.SecurityConditionUnsatisfiable) DataSetInfo(org.openecard.crypto.common.sal.did.DataSetInfo) DidInfo(org.openecard.crypto.common.sal.did.DidInfo) AlgorithmInfoType(iso.std.iso_iec._24727.tech.schema.AlgorithmInfoType) TreeSet(java.util.TreeSet) AlgorithmIdentifierType(iso.std.iso_iec._24727.tech.schema.AlgorithmIdentifierType) UnsupportedAlgorithmException(org.openecard.crypto.common.UnsupportedAlgorithmException) NoSuchDid(org.openecard.crypto.common.sal.did.NoSuchDid) DidInfos(org.openecard.crypto.common.sal.did.DidInfos)

Example 2 with NoSuchDid

use of org.openecard.crypto.common.sal.did.NoSuchDid in project open-ecard by ecsec.

the class ChipGateway method processCertificatesRequest.

private CommandType processCertificatesRequest(final ListCertificatesRequestType certReq) throws ConnectionError, JsonProcessingException, InvalidRedirectUrlException, ChipGatewayDataError {
    // check if we have been interrupted
    checkProcessCancelled();
    BigInteger waitSecondsBig = certReq.getMaxWaitSeconds();
    long waitMillis = getWaitMillis(waitSecondsBig);
    // run the actual stuff in the background, so we can wait and terminate if needed
    FutureTask<ListCertificatesResponseType> action = new FutureTask<>(new Callable<ListCertificatesResponseType>() {

        @Override
        public ListCertificatesResponseType call() throws Exception {
            ListCertificatesResponseType certResp = new ListCertificatesResponseType();
            certResp.setSessionIdentifier(sessionId);
            char[] pin = null;
            try {
                pin = getPin(certReq.getPIN());
                byte[] slotHandle = certReq.getSlotHandle();
                ListCertificates helper = new ListCertificates(tokenCache, slotHandle, certReq.getCertificateFilter(), pin);
                List<CertificateInfoType> certInfos = helper.getCertificates();
                certResp.getCertificateInfo().addAll(certInfos);
                certResp.setResult(ChipGatewayStatusCodes.OK);
                return certResp;
            } finally {
                if (pin != null) {
                    Arrays.fill(pin, ' ');
                }
            }
        }
    });
    Thread t = new Thread(action, "CertificatesRequest-Task-" + TASK_THREAD_NUM.getAndIncrement());
    t.setDaemon(true);
    t.start();
    ListCertificatesResponseType certResp = new ListCertificatesResponseType();
    certResp.setSessionIdentifier(sessionId);
    try {
        // wait for thread to finish
        certResp = action.get(waitMillis, TimeUnit.MILLISECONDS);
    } catch (TimeoutException ex) {
        LOG.info("Background task took longer than the timeout value permitted.", ex);
        // cancel task
        action.cancel(true);
        // wait for task to finish, so the SC stack can not get confused
        try {
            t.join();
            certResp.setResult(ChipGatewayStatusCodes.TIMEOUT);
        } catch (InterruptedException ignore) {
            // send stop message
            certResp.setResult(ChipGatewayStatusCodes.STOPPED);
        }
    } catch (ExecutionException ex) {
        LOG.error("Background task produced an exception.", ex);
        Throwable cause = ex.getCause();
        if (cause instanceof RemotePinException) {
            LOG.error("Error getting encrypted PIN.", ex);
            certResp.setResult(ChipGatewayStatusCodes.INCORRECT_PARAMETER);
        } else if (cause instanceof ParameterInvalid) {
            LOG.error("Error while processing the certificate filter parameters.", ex);
            certResp.setResult(ChipGatewayStatusCodes.INCORRECT_PARAMETER);
        } else if (cause instanceof SlotHandleInvalid) {
            LOG.error("No token for the given slot handle found.", cause);
            certResp.setResult(ChipGatewayStatusCodes.UNKNOWN_SLOT);
        } else if (cause instanceof NoSuchDid) {
            LOG.error("DID does not exist.", cause);
            certResp.setResult(ChipGatewayStatusCodes.UNKNOWN_DID);
        } else if (cause instanceof SecurityConditionUnsatisfiable) {
            LOG.error("DID can not be authenticated.", cause);
            certResp.setResult(ChipGatewayStatusCodes.SECURITY_NOT_SATISFIED);
        } else if (cause instanceof CertificateException) {
            LOG.error("Certificate could not be processed.", cause);
            certResp.setResult(ChipGatewayStatusCodes.OTHER);
        } else if (cause instanceof WSHelper.WSException) {
            LOG.error("Unknown error.", cause);
            certResp.setResult(ChipGatewayStatusCodes.OTHER);
        } else if (cause instanceof ThreadTerminateException) {
            LOG.error("Chipgateway process interrupted.", cause);
            certResp.setResult(ChipGatewayStatusCodes.STOPPED);
        } else {
            LOG.error("Unknown error during list certificate operation.", cause);
            certResp.setResult(ChipGatewayStatusCodes.OTHER);
        }
    } catch (InterruptedException ex) {
        String msg = "Interrupted while waiting for background task.";
        if (LOG.isDebugEnabled()) {
            LOG.debug(msg, ex);
        } else {
            LOG.info(msg);
        }
        // cancel task
        action.cancel(true);
        // send stop message
        certResp.setResult(ChipGatewayStatusCodes.STOPPED);
    }
    return sendMessageInterruptableAndCheckTermination(getResource(listCertsUrl), certResp);
}
Also used : ListCertificatesResponseType(org.openecard.ws.chipgateway.ListCertificatesResponseType) SecurityConditionUnsatisfiable(org.openecard.common.SecurityConditionUnsatisfiable) CertificateException(java.security.cert.CertificateException) RemotePinException(org.openecard.addons.cg.ex.RemotePinException) FutureTask(java.util.concurrent.FutureTask) List(java.util.List) ExecutionException(java.util.concurrent.ExecutionException) ThreadTerminateException(org.openecard.common.ThreadTerminateException) TimeoutException(java.util.concurrent.TimeoutException) WSHelper(org.openecard.common.WSHelper) SlotHandleInvalid(org.openecard.addons.cg.ex.SlotHandleInvalid) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) RemotePinException(org.openecard.addons.cg.ex.RemotePinException) ThreadTerminateException(org.openecard.common.ThreadTerminateException) HttpException(org.openecard.apache.http.HttpException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) InvalidRedirectUrlException(org.openecard.addons.cg.ex.InvalidRedirectUrlException) URISyntaxException(java.net.URISyntaxException) TimeoutException(java.util.concurrent.TimeoutException) JoseException(org.jose4j.lang.JoseException) AuthServerException(org.openecard.addons.cg.ex.AuthServerException) UnsupportedAlgorithmException(org.openecard.crypto.common.UnsupportedAlgorithmException) MalformedURLException(java.net.MalformedURLException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) CertificateException(java.security.cert.CertificateException) BigInteger(java.math.BigInteger) ParameterInvalid(org.openecard.addons.cg.ex.ParameterInvalid) NoSuchDid(org.openecard.crypto.common.sal.did.NoSuchDid)

Example 3 with NoSuchDid

use of org.openecard.crypto.common.sal.did.NoSuchDid in project open-ecard by ecsec.

the class SmartCardCredentialFactory method printCerts.

private void printCerts(List<DidInfo> infos) {
    for (DidInfo next : infos) {
        try {
            List<X509Certificate> chain = next.getRelatedCertificateChain();
            if (LOG.isDebugEnabled()) {
                for (X509Certificate cert : chain) {
                    StringWriter out = new StringWriter();
                    PemWriter pw = new PemWriter(out);
                    pw.writeObject(new PemObject("CERTIFICATE", cert.getEncoded()));
                    pw.close();
                    LOG.debug("Certificate for DID {}\n{}", next.getDidName(), out);
                    LOG.debug("Certificate details\n{}", cert);
                }
            }
        } catch (SecurityConditionUnsatisfiable | NoSuchDid | CertificateException | IOException ex) {
            LOG.error("Failed to read certificates from card. Skipping DID " + next.getDidName() + ".", ex);
        } catch (WSHelper.WSException ex) {
            LOG.error("Unknown error accessing DID " + next.getDidName() + ".", ex);
        }
    }
}
Also used : WSHelper(org.openecard.common.WSHelper) PemWriter(org.openecard.bouncycastle.util.io.pem.PemWriter) SecurityConditionUnsatisfiable(org.openecard.common.SecurityConditionUnsatisfiable) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) PemObject(org.openecard.bouncycastle.util.io.pem.PemObject) StringWriter(java.io.StringWriter) DidInfo(org.openecard.crypto.common.sal.did.DidInfo) NoSuchDid(org.openecard.crypto.common.sal.did.NoSuchDid)

Example 4 with NoSuchDid

use of org.openecard.crypto.common.sal.did.NoSuchDid in project open-ecard by ecsec.

the class SmartCardSignerCredential method genSig.

private byte[] genSig(SignatureAndHashAlgorithm algorithm, byte[] sigData, boolean isRaw) throws IOException {
    SignatureAlgorithms didAlg = getDidAlgorithm();
    LOG.debug("Using DID with algorithm={}.", didAlg.getJcaAlg());
    if (algorithm != null) {
        String reqAlgStr = String.format("%s-%s", SignatureAlgorithm.getText(algorithm.getSignature()), HashAlgorithm.getText(algorithm.getHash()));
        LOG.debug("Performing TLS 1.2 signature for algorithm={}.", reqAlgStr);
        if (isRaw && isRawRSA(didAlg)) {
            // TLS >= 1.2 needs a PKCS#1 v1.5 signature and no raw RSA signature
            ASN1ObjectIdentifier hashAlgId = TlsUtils.getOIDForHashAlgorithm(algorithm.getHash());
            DigestInfo digestInfo = new DigestInfo(new AlgorithmIdentifier(hashAlgId, DERNull.INSTANCE), sigData);
            sigData = digestInfo.getEncoded(ASN1Encoding.DER);
            LOG.debug("Signing DigestInfo with algorithm={}.", hashAlgId);
        }
    } else {
        LOG.debug("Performing pre-TLS 1.2 signature.");
    }
    try {
        if (isRaw) {
            LOG.debug("Raw Signature of data={}.", ByteUtils.toHexString(sigData));
        } else {
            LOG.debug("Hashed Signature of data blob.");
            CryptoMarkerType cryptoMarker = did.getGenericCryptoMarker();
            if (didAlg.getHashAlg() != null && (cryptoMarker.getHashGenerationInfo() == null || cryptoMarker.getHashGenerationInfo() == HashGenerationInfoType.NOT_ON_CARD)) {
                sigData = did.hash(sigData);
            }
        }
        did.authenticateMissing();
        byte[] signature = did.sign(sigData);
        return signature;
    } catch (WSHelper.WSException ex) {
        String msg = "Failed to create signature because of an unknown error.";
        LOG.warn(msg, ex);
        throw new IOException(msg, ex);
    } catch (SecurityConditionUnsatisfiable ex) {
        String msg = "Access to the signature DID could not be obtained.";
        LOG.warn(msg, ex);
        throw new IOException(msg, ex);
    } catch (NoSuchDid ex) {
        String msg = "Signing DID not available anymore.";
        LOG.warn(msg, ex);
        throw new IOException(msg, ex);
    }
}
Also used : WSHelper(org.openecard.common.WSHelper) DigestInfo(org.openecard.bouncycastle.asn1.x509.DigestInfo) SignatureAlgorithms(org.openecard.crypto.common.SignatureAlgorithms) SecurityConditionUnsatisfiable(org.openecard.common.SecurityConditionUnsatisfiable) CryptoMarkerType(org.openecard.crypto.common.sal.did.CryptoMarkerType) IOException(java.io.IOException) NoSuchDid(org.openecard.crypto.common.sal.did.NoSuchDid) ASN1ObjectIdentifier(org.openecard.bouncycastle.asn1.ASN1ObjectIdentifier) AlgorithmIdentifier(org.openecard.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 5 with NoSuchDid

use of org.openecard.crypto.common.sal.did.NoSuchDid in project open-ecard by ecsec.

the class SmartCardCredentialFactory method getClientCredentials.

@Override
public List<TlsCredentialedSigner> getClientCredentials(CertificateRequest cr) {
    ArrayList<TlsCredentialedSigner> credentials = new ArrayList<>();
    TlsCryptoParameters tlsCrypto = new TlsCryptoParameters(context);
    LOG.debug("Selecting a suitable DID for the following requested algorithms:");
    ArrayList<SignatureAndHashAlgorithm> crSigAlgs = getCrSigAlgs(cr);
    removeUnsupportedAlgs(crSigAlgs);
    for (SignatureAndHashAlgorithm reqAlg : crSigAlgs) {
        String reqAlgStr = String.format("%s-%s", SignatureAlgorithm.getText(reqAlg.getSignature()), HashAlgorithm.getText(reqAlg.getHash()));
        LOG.debug("  {}", reqAlgStr);
    }
    try {
        DidInfos didInfos = tokenCache.getInfo(null, handle);
        List<DidInfo> infos = didInfos.getCryptoDidInfos();
        printCerts(infos);
        // remove unsuitable DIDs
        LOG.info("Sorting out DIDs not able to handle the TLS request.");
        infos = removeSecretCertDids(infos);
        infos = removeNonAuthDids(infos);
        infos = removeUnsupportedAlgs(infos);
        infos = removeUnsupportedCerts(cr, infos);
        // infos = nonRawFirst(infos);
        LOG.info("Creating signer instances for the TLS Client Certificate signature.");
        // TLS < 1.2
        if (crSigAlgs.isEmpty()) {
            LOG.info("Looking for a raw RSA DID.");
            for (DidInfo info : infos) {
                try {
                    LOG.debug("Checking DID= {}.", info.getDidName());
                    TlsCredentialedSigner cred;
                    List<X509Certificate> chain = info.getRelatedCertificateChain();
                    Certificate clientCert = convertCert(context.getCrypto(), chain);
                    if (isRawRSA(info)) {
                        LOG.debug("Adding raw RSA signer.");
                        TlsSigner signer = new SmartCardSignerCredential(info);
                        cred = new DefaultTlsCredentialedSigner(tlsCrypto, signer, clientCert, null);
                        credentials.add(cred);
                    }
                } catch (SecurityConditionUnsatisfiable | NoSuchDid | CertificateException | IOException ex) {
                    LOG.error("Failed to read certificates from card. Skipping DID " + info.getDidName() + ".", ex);
                } catch (UnsupportedAlgorithmException ex) {
                    LOG.error("Unsupported algorithm used in CIF. Skipping DID " + info.getDidName() + ".", ex);
                } catch (WSHelper.WSException ex) {
                    LOG.error("Unknown error accessing DID " + info.getDidName() + ".", ex);
                }
            }
        } else {
            // TLS >= 1.2
            LOG.info("Looking for most specific DIDs.");
            // looping over the servers alg list preserves its ordering
            for (SignatureAndHashAlgorithm reqAlg : crSigAlgs) {
                for (DidInfo info : infos) {
                    LOG.debug("Checking DID={}.", info.getDidName());
                    try {
                        AlgorithmInfoType algInfo = info.getGenericCryptoMarker().getAlgorithmInfo();
                        SignatureAlgorithms alg = SignatureAlgorithms.fromAlgId(algInfo.getAlgorithmIdentifier().getAlgorithm());
                        TlsCredentialedSigner cred;
                        List<X509Certificate> chain = info.getRelatedCertificateChain();
                        Certificate clientCert = convertCert(context.getCrypto(), chain);
                        // find one DID for this problem, then continue with the next algorithm
                        if (matchesAlg(reqAlg, alg) && (alg.getHashAlg() != null || isSafeForNoneDid(reqAlg))) {
                            LOG.debug("Adding {} signer.", alg.getJcaAlg());
                            TlsSigner signer = new SmartCardSignerCredential(info);
                            cred = new DefaultTlsCredentialedSigner(tlsCrypto, signer, clientCert, reqAlg);
                            credentials.add(cred);
                            // break;
                            return credentials;
                        }
                    } catch (SecurityConditionUnsatisfiable | NoSuchDid | CertificateException | IOException ex) {
                        LOG.error("Failed to read certificates from card. Skipping DID " + info.getDidName() + ".", ex);
                    } catch (UnsupportedAlgorithmException ex) {
                        LOG.error("Unsupported algorithm used in CIF. Skipping DID " + info.getDidName() + ".", ex);
                    } catch (WSHelper.WSException ex) {
                        LOG.error("Unknown error accessing DID " + info.getDidName() + ".", ex);
                    }
                }
            }
        }
    } catch (NoSuchDid | WSHelper.WSException ex) {
        LOG.error("Failed to access DIDs of smartcard. Proceeding without client authentication.", ex);
    }
    return credentials;
}
Also used : ArrayList(java.util.ArrayList) SecurityConditionUnsatisfiable(org.openecard.common.SecurityConditionUnsatisfiable) CertificateException(java.security.cert.CertificateException) SignatureAndHashAlgorithm(org.openecard.bouncycastle.tls.SignatureAndHashAlgorithm) DidInfo(org.openecard.crypto.common.sal.did.DidInfo) AlgorithmInfoType(iso.std.iso_iec._24727.tech.schema.AlgorithmInfoType) DefaultTlsCredentialedSigner(org.openecard.bouncycastle.tls.DefaultTlsCredentialedSigner) TlsCryptoParameters(org.openecard.bouncycastle.tls.crypto.TlsCryptoParameters) TlsSigner(org.openecard.bouncycastle.tls.crypto.TlsSigner) WSHelper(org.openecard.common.WSHelper) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) UnsupportedAlgorithmException(org.openecard.crypto.common.UnsupportedAlgorithmException) SignatureAlgorithms(org.openecard.crypto.common.SignatureAlgorithms) DefaultTlsCredentialedSigner(org.openecard.bouncycastle.tls.DefaultTlsCredentialedSigner) TlsCredentialedSigner(org.openecard.bouncycastle.tls.TlsCredentialedSigner) NoSuchDid(org.openecard.crypto.common.sal.did.NoSuchDid) DidInfos(org.openecard.crypto.common.sal.did.DidInfos) X509Certificate(java.security.cert.X509Certificate) TlsCertificate(org.openecard.bouncycastle.tls.crypto.TlsCertificate) Certificate(org.openecard.bouncycastle.tls.Certificate)

Aggregations

SecurityConditionUnsatisfiable (org.openecard.common.SecurityConditionUnsatisfiable)6 NoSuchDid (org.openecard.crypto.common.sal.did.NoSuchDid)6 IOException (java.io.IOException)5 WSHelper (org.openecard.common.WSHelper)5 CertificateException (java.security.cert.CertificateException)4 UnsupportedAlgorithmException (org.openecard.crypto.common.UnsupportedAlgorithmException)4 DidInfo (org.openecard.crypto.common.sal.did.DidInfo)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 AlgorithmInfoType (iso.std.iso_iec._24727.tech.schema.AlgorithmInfoType)2 BigInteger (java.math.BigInteger)2 MalformedURLException (java.net.MalformedURLException)2 URISyntaxException (java.net.URISyntaxException)2 KeyStoreException (java.security.KeyStoreException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 X509Certificate (java.security.cert.X509Certificate)2 ExecutionException (java.util.concurrent.ExecutionException)2 FutureTask (java.util.concurrent.FutureTask)2 TimeoutException (java.util.concurrent.TimeoutException)2 JoseException (org.jose4j.lang.JoseException)2 AuthServerException (org.openecard.addons.cg.ex.AuthServerException)2