Search in sources :

Example 1 with SecurityConditionUnsatisfiable

use of org.openecard.common.SecurityConditionUnsatisfiable in project open-ecard by ecsec.

the class ListCertificates method getCertificates.

public List<CertificateInfoType> getCertificates() throws WSHelper.WSException, NoSuchDid, CertificateException, CertificateEncodingException, SecurityConditionUnsatisfiable, ParameterInvalid, SlotHandleInvalid {
    try {
        ArrayList<CertificateInfoType> result = new ArrayList<>();
        // get crypto dids
        DidInfos didInfos = tokenCache.getInfo(pin, handle);
        List<DidInfo> cryptoDids = didInfos.getCryptoDidInfos();
        // get certificates for each crypto did
        for (DidInfo nextDid : cryptoDids) {
            LOG.debug("Reading certificates from DID={}.", nextDid.getDidName());
            List<X509Certificate> certChain = getCertChain(nextDid);
            if (!certChain.isEmpty() && matchesFilter(certChain)) {
                AlgorithmInfoType algInfo = nextDid.getGenericCryptoMarker().getAlgorithmInfo();
                try {
                    String jcaAlg = convertAlgInfo(algInfo);
                    X509Certificate cert = certChain.get(0);
                    CertificateInfoType certInfo = new CertificateInfoType();
                    for (X509Certificate nextCert : certChain) {
                        certInfo.getCertificate().add(nextCert.getEncoded());
                    }
                    certInfo.setUniqueSSN(getUniqueIdentifier(cert));
                    certInfo.setAlgorithm(jcaAlg);
                    certInfo.setDIDName(nextDid.getDidName());
                    result.add(certInfo);
                } catch (UnsupportedAlgorithmException ex) {
                    // ignore this DID
                    String algId = algInfo.getAlgorithmIdentifier().getAlgorithm();
                    LOG.warn("Ignoring DID with unsupported algorithm ({}).", algId);
                }
            }
        }
        return result;
    } catch (WSHelper.WSException ex) {
        String minor = StringUtils.nullToEmpty(ex.getResultMinor());
        switch(minor) {
            case ECardConstants.Minor.App.INCORRECT_PARM:
                throw new ParameterInvalid(ex.getMessage(), ex);
            case ECardConstants.Minor.IFD.INVALID_SLOT_HANDLE:
                throw new SlotHandleInvalid(ex.getMessage(), ex);
            case ECardConstants.Minor.SAL.SECURITY_CONDITION_NOT_SATISFIED:
                throw new SecurityConditionUnsatisfiable(ex.getMessage(), ex);
            case ECardConstants.Minor.IFD.CANCELLATION_BY_USER:
            case ECardConstants.Minor.SAL.CANCELLATION_BY_USER:
                throw new ThreadTerminateException("Certificate retrieval interrupted.", ex);
            default:
                throw ex;
        }
    } catch (InvocationTargetExceptionUnchecked ex) {
        if (ex.getCause() instanceof InterruptedException || ex.getCause() instanceof ThreadTerminateException) {
            String msg = "Certificate retrieval interrupted.";
            LOG.debug(msg, ex);
            throw new ThreadTerminateException(msg);
        } else {
            String msg = ex.getCause().getMessage();
            throw WSHelper.createException(WSHelper.makeResultError(ECardConstants.Minor.App.INT_ERROR, msg));
        }
    } finally {
        tokenCache.clearPins();
    }
}
Also used : WSHelper(org.openecard.common.WSHelper) InvocationTargetExceptionUnchecked(org.openecard.common.interfaces.InvocationTargetExceptionUnchecked) ArrayList(java.util.ArrayList) SecurityConditionUnsatisfiable(org.openecard.common.SecurityConditionUnsatisfiable) CertificateInfoType(org.openecard.ws.chipgateway.CertificateInfoType) SlotHandleInvalid(org.openecard.addons.cg.ex.SlotHandleInvalid) ASN1String(org.openecard.bouncycastle.asn1.ASN1String) ASN1OctetString(org.openecard.bouncycastle.asn1.ASN1OctetString) X509Certificate(java.security.cert.X509Certificate) DidInfo(org.openecard.crypto.common.sal.did.DidInfo) AlgorithmInfoType(iso.std.iso_iec._24727.tech.schema.AlgorithmInfoType) UnsupportedAlgorithmException(org.openecard.crypto.common.UnsupportedAlgorithmException) ParameterInvalid(org.openecard.addons.cg.ex.ParameterInvalid) ThreadTerminateException(org.openecard.common.ThreadTerminateException) DidInfos(org.openecard.crypto.common.sal.did.DidInfos)

Example 2 with SecurityConditionUnsatisfiable

use of org.openecard.common.SecurityConditionUnsatisfiable 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 3 with SecurityConditionUnsatisfiable

use of org.openecard.common.SecurityConditionUnsatisfiable in project open-ecard by ecsec.

the class Signer method sign.

public byte[] sign(byte[] data) throws NoSuchDid, WSHelper.WSException, SecurityConditionUnsatisfiable, ParameterInvalid, SlotHandleInvalid, PinBlocked {
    Semaphore s = getLock(handle.getIFDName());
    boolean acquired = false;
    try {
        s.acquire();
        acquired = true;
        // get crypto dids
        DidInfos didInfos = tokenCache.getInfo(pin, handle);
        DidInfo didInfo = didInfos.getDidInfo(didName);
        didInfo.connectApplication();
        didInfo.authenticateMissing();
        CryptoMarkerType cryptoMarker = didInfo.getGenericCryptoMarker();
        String algUri = cryptoMarker.getAlgorithmInfo().getAlgorithmIdentifier().getAlgorithm();
        try {
            SignatureAlgorithms alg = SignatureAlgorithms.fromAlgId(algUri);
            // calculate hash if needed
            byte[] digest = data;
            if (alg.getHashAlg() != null && (cryptoMarker.getHashGenerationInfo() == null || cryptoMarker.getHashGenerationInfo() == HashGenerationInfoType.NOT_ON_CARD)) {
                digest = didInfo.hash(digest);
            }
            // wrap hash in DigestInfo if needed
            if (alg == SignatureAlgorithms.CKM_RSA_PKCS) {
                try {
                    ASN1ObjectIdentifier digestOid = getHashAlgOid(data);
                    DigestInfo di = new DigestInfo(new AlgorithmIdentifier(digestOid, DERNull.INSTANCE), digest);
                    byte[] sigMsg = di.getEncoded(ASN1Encoding.DER);
                    digest = sigMsg;
                } catch (IOException ex) {
                    String msg = "Error encoding DigestInfo object.";
                    Result r = WSHelper.makeResultError(ECardConstants.Minor.App.INT_ERROR, msg);
                    throw WSHelper.createException(r);
                } catch (InvalidParameterException ex) {
                    String msg = "Hash algorithm could not be determined for the given hash.";
                    Result r = WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, msg);
                    throw WSHelper.createException(r);
                }
            }
            byte[] signature = didInfo.sign(digest);
            return signature;
        } catch (UnsupportedAlgorithmException ex) {
            String msg = String.format("DID uses unsupported algorithm %s.", algUri);
            throw WSHelper.createException(WSHelper.makeResultError(ECardConstants.Minor.App.INT_ERROR, msg));
        }
    } catch (WSHelper.WSException ex) {
        String minor = StringUtils.nullToEmpty(ex.getResultMinor());
        switch(minor) {
            case ECardConstants.Minor.App.INCORRECT_PARM:
                throw new ParameterInvalid(ex.getMessage(), ex);
            case ECardConstants.Minor.IFD.INVALID_SLOT_HANDLE:
                throw new SlotHandleInvalid(ex.getMessage(), ex);
            case ECardConstants.Minor.IFD.PASSWORD_BLOCKED:
            case ECardConstants.Minor.IFD.PASSWORD_SUSPENDED:
            case ECardConstants.Minor.IFD.PASSWORD_DEACTIVATED:
                throw new PinBlocked(ex.getMessage(), ex);
            case ECardConstants.Minor.SAL.SECURITY_CONDITION_NOT_SATISFIED:
                throw new SecurityConditionUnsatisfiable(ex.getMessage(), ex);
            case ECardConstants.Minor.IFD.CANCELLATION_BY_USER:
            case ECardConstants.Minor.SAL.CANCELLATION_BY_USER:
                throw new ThreadTerminateException("Signature generation cancelled.", ex);
            default:
                throw ex;
        }
    } catch (InvocationTargetExceptionUnchecked ex) {
        if (ex.getCause() instanceof InterruptedException || ex.getCause() instanceof ThreadTerminateException) {
            throw new ThreadTerminateException("Signature creation interrupted.");
        } else {
            String msg = ex.getCause().getMessage();
            throw WSHelper.createException(WSHelper.makeResultError(ECardConstants.Minor.App.INT_ERROR, msg));
        }
    } catch (InterruptedException ex) {
        throw new ThreadTerminateException("Signature creation interrupted.");
    } finally {
        tokenCache.clearPins();
        if (acquired) {
            s.release();
        }
    }
}
Also used : WSHelper(org.openecard.common.WSHelper) PinBlocked(org.openecard.addons.cg.ex.PinBlocked) InvocationTargetExceptionUnchecked(org.openecard.common.interfaces.InvocationTargetExceptionUnchecked) SecurityConditionUnsatisfiable(org.openecard.common.SecurityConditionUnsatisfiable) CryptoMarkerType(org.openecard.crypto.common.sal.did.CryptoMarkerType) SlotHandleInvalid(org.openecard.addons.cg.ex.SlotHandleInvalid) Semaphore(java.util.concurrent.Semaphore) IOException(java.io.IOException) AlgorithmIdentifier(org.openecard.bouncycastle.asn1.x509.AlgorithmIdentifier) Result(oasis.names.tc.dss._1_0.core.schema.Result) InvalidParameterException(java.security.InvalidParameterException) DidInfo(org.openecard.crypto.common.sal.did.DidInfo) DigestInfo(org.openecard.bouncycastle.asn1.x509.DigestInfo) SignatureAlgorithms(org.openecard.crypto.common.SignatureAlgorithms) UnsupportedAlgorithmException(org.openecard.crypto.common.UnsupportedAlgorithmException) ParameterInvalid(org.openecard.addons.cg.ex.ParameterInvalid) ThreadTerminateException(org.openecard.common.ThreadTerminateException) DidInfos(org.openecard.crypto.common.sal.did.DidInfos) ASN1ObjectIdentifier(org.openecard.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 4 with SecurityConditionUnsatisfiable

use of org.openecard.common.SecurityConditionUnsatisfiable 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 5 with SecurityConditionUnsatisfiable

use of org.openecard.common.SecurityConditionUnsatisfiable 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)

Aggregations

SecurityConditionUnsatisfiable (org.openecard.common.SecurityConditionUnsatisfiable)8 WSHelper (org.openecard.common.WSHelper)7 IOException (java.io.IOException)6 UnsupportedAlgorithmException (org.openecard.crypto.common.UnsupportedAlgorithmException)6 NoSuchDid (org.openecard.crypto.common.sal.did.NoSuchDid)6 DidInfo (org.openecard.crypto.common.sal.did.DidInfo)5 CertificateException (java.security.cert.CertificateException)4 ParameterInvalid (org.openecard.addons.cg.ex.ParameterInvalid)4 SlotHandleInvalid (org.openecard.addons.cg.ex.SlotHandleInvalid)4 ThreadTerminateException (org.openecard.common.ThreadTerminateException)4 DidInfos (org.openecard.crypto.common.sal.did.DidInfos)4 AlgorithmInfoType (iso.std.iso_iec._24727.tech.schema.AlgorithmInfoType)3 X509Certificate (java.security.cert.X509Certificate)3 SignatureAlgorithms (org.openecard.crypto.common.SignatureAlgorithms)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)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