Search in sources :

Example 1 with InvocationTargetExceptionUnchecked

use of org.openecard.common.interfaces.InvocationTargetExceptionUnchecked 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 InvocationTargetExceptionUnchecked

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

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

the class ExecutionEngine method process.

/**
 * Processes the user consent associated with this instance. <br>
 * The following algorithm is used to process the dialog.
 * <ol>
 * <li>Display the first step.</li>
 * <li>Evaluate step result. Break execution on CANCEL.</li>
 * <li>Execute step action. Break execution on CANCEL.</li>
 * <li>Display either next previous or current step, or a replacement according to result.</li>
 * <li>Proceed with point 2.</li>
 * </ol>
 *
 * @return Overall result of the execution.
 * @throws ThreadTerminateException Thrown in case the GUI has been closed externally (interrupted).
 */
public ResultStatus process() throws ThreadTerminateException {
    // get first step
    StepResult next = navigator.next();
    // loop over steps. break inside loop
    while (true) {
        ResultStatus result = next.getStatus();
        // close dialog on cancel and interrupt
        if (result == ResultStatus.INTERRUPTED || Thread.currentThread().isInterrupted()) {
            navigator.close();
            throw new ThreadTerminateException("GUI has been interrupted.");
        } else if (result == ResultStatus.CANCEL) {
            navigator.close();
            return result;
        }
        // get result and put it in resultmap
        List<OutputInfoUnit> stepResults = next.getResults();
        Map<String, ExecutionResults> oldResults = Collections.unmodifiableMap(results);
        results.put(next.getStepID(), new ExecutionResults(next.getStepID(), stepResults));
        // replace InfoInputUnit values in live list
        if (!next.getStep().isResetOnLoad()) {
            Step s = next.getStep();
            List<InputInfoUnit> inputInfo = s.getInputInfoUnits();
            Map<String, InputInfoUnit> infoMap = new HashMap<>();
            // create index over infos
            for (InputInfoUnit nextInfo : inputInfo) {
                infoMap.put(nextInfo.getID(), nextInfo);
            }
            for (OutputInfoUnit nextOut : stepResults) {
                InputInfoUnit matchingInfo = infoMap.get(nextOut.getID());
                // an entry must exist, otherwise this is an error in the GUI implementation
                // this type of error should be found in tests
                matchingInfo.copyContentFrom(nextOut);
            }
        }
        // replace step if told by result value
        if (next.getReplacement() != null) {
            switch(next.getStatus()) {
                case BACK:
                    next = navigator.replacePrevious(next.getReplacement());
                    break;
                case OK:
                    if (navigator.hasNext()) {
                        next = navigator.replaceNext(next.getReplacement());
                    } else {
                        navigator.close();
                        return convertStatus(StepActionResultStatus.NEXT);
                    }
                    break;
                case RELOAD:
                    next = navigator.replaceCurrent(next.getReplacement());
                    break;
                default:
                    // fallthrough because CANCEL and INTERRUPTED are already handled
                    break;
            }
        } else {
            // step replacement did not happen, so we can execute the action
            StepAction action = next.getStep().getAction();
            StepActionCallable actionCallable = new StepActionCallable(action, oldResults, next);
            // use separate thread or tasks running outside the JVM context, like PCSC calls, won't stop on cancellation
            ExecutorService execService = Executors.newSingleThreadExecutor();
            Future<StepActionResult> actionFuture = execService.submit(actionCallable);
            navigator.setRunningAction(actionFuture);
            StepActionResult actionResult;
            try {
                actionResult = actionFuture.get();
            } catch (CancellationException ex) {
                LOG.info("StepAction was canceled.", ex);
                navigator.close();
                return ResultStatus.CANCEL;
            } catch (InterruptedException ex) {
                LOG.info("StepAction was interrupted.", ex);
                navigator.close();
                throw new ThreadTerminateException("GUI has been interrupted.");
            } catch (ExecutionException ex) {
                // there are some special kinds we need to handle here
                if (ex.getCause() instanceof InvocationTargetExceptionUnchecked) {
                    InvocationTargetExceptionUnchecked iex = (InvocationTargetExceptionUnchecked) ex.getCause();
                    if (iex.getCause() instanceof ThreadTerminateException) {
                        LOG.info("StepAction was interrupted.", ex);
                        navigator.close();
                        throw new ThreadTerminateException("GUI has been interrupted.");
                    }
                }
                // all other types
                LOG.error("StepAction failed with error.", ex.getCause());
                navigator.close();
                return ResultStatus.CANCEL;
            }
            // break out if cancel was returned
            if (actionResult.getStatus() == StepActionResultStatus.CANCEL) {
                LOG.info("StepAction was canceled.");
                navigator.close();
                return ResultStatus.CANCEL;
            }
            // replace step if told by result value
            if (actionResult.getReplacement() != null) {
                switch(actionResult.getStatus()) {
                    case BACK:
                        next = navigator.replacePrevious(actionResult.getReplacement());
                        break;
                    case NEXT:
                        if (navigator.hasNext()) {
                            next = navigator.replaceNext(actionResult.getReplacement());
                        } else {
                            navigator.close();
                            return convertStatus(StepActionResultStatus.NEXT);
                        }
                        break;
                    case REPEAT:
                        next = navigator.replaceCurrent(actionResult.getReplacement());
                        break;
                    default:
                        // fallthrough because CANCEL is already handled
                        break;
                }
            } else {
                // no replacement just proceed
                switch(actionResult.getStatus()) {
                    case BACK:
                        next = navigator.previous();
                        break;
                    case NEXT:
                        if (navigator.hasNext()) {
                            next = navigator.next();
                        } else {
                            navigator.close();
                            return convertStatus(StepActionResultStatus.NEXT);
                        }
                        break;
                    case REPEAT:
                        next = navigator.current();
                        break;
                    default:
                        // fallthrough because CANCEL is already handled
                        break;
                }
            }
        }
    }
}
Also used : InvocationTargetExceptionUnchecked(org.openecard.common.interfaces.InvocationTargetExceptionUnchecked) ResultStatus(org.openecard.gui.ResultStatus) HashMap(java.util.HashMap) Step(org.openecard.gui.definition.Step) InputInfoUnit(org.openecard.gui.definition.InputInfoUnit) CancellationException(java.util.concurrent.CancellationException) ExecutorService(java.util.concurrent.ExecutorService) OutputInfoUnit(org.openecard.gui.definition.OutputInfoUnit) StepResult(org.openecard.gui.StepResult) ThreadTerminateException(org.openecard.common.ThreadTerminateException) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

ThreadTerminateException (org.openecard.common.ThreadTerminateException)3 InvocationTargetExceptionUnchecked (org.openecard.common.interfaces.InvocationTargetExceptionUnchecked)3 ParameterInvalid (org.openecard.addons.cg.ex.ParameterInvalid)2 SlotHandleInvalid (org.openecard.addons.cg.ex.SlotHandleInvalid)2 SecurityConditionUnsatisfiable (org.openecard.common.SecurityConditionUnsatisfiable)2 WSHelper (org.openecard.common.WSHelper)2 UnsupportedAlgorithmException (org.openecard.crypto.common.UnsupportedAlgorithmException)2 DidInfo (org.openecard.crypto.common.sal.did.DidInfo)2 DidInfos (org.openecard.crypto.common.sal.did.DidInfos)2 AlgorithmInfoType (iso.std.iso_iec._24727.tech.schema.AlgorithmInfoType)1 IOException (java.io.IOException)1 InvalidParameterException (java.security.InvalidParameterException)1 X509Certificate (java.security.cert.X509Certificate)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 CancellationException (java.util.concurrent.CancellationException)1 ExecutionException (java.util.concurrent.ExecutionException)1 ExecutorService (java.util.concurrent.ExecutorService)1 Semaphore (java.util.concurrent.Semaphore)1 Result (oasis.names.tc.dss._1_0.core.schema.Result)1