Search in sources :

Example 1 with ThreadTerminateException

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

the class MwPrivateKey method sign.

/**
 * Signs Data with a {@link Mechanism}.
 * Returns the signed Data in an byte array.
 *
 * @param mechanism
 * @param data
 * @return
 * @throws CryptokiException
 */
public byte[] sign(long mechanism, byte[] data) throws CryptokiException {
    Pointer paramsPtr;
    NativeLong paramsPtrSize;
    if (isPSSAlg((int) mechanism)) {
        // only execute with PSS algorithm
        // determine parameters for PKCS#11 PSS
        LOG.debug("Preparing PSS Parameters.");
        NativeLong hashAlg = new NativeLong(getHashAlg((int) mechanism, data), true);
        NativeLong mgfAlg = new NativeLong(getMgf1Alg(hashAlg.intValue()), true);
        NativeLong sLen = new NativeLong(getHashLen(hashAlg.intValue()), true);
        CK_RSA_PKCS_PSS_PARAMS pssParams = new CK_RSA_PKCS_PSS_PARAMS(hashAlg, mgfAlg, sLen);
        pssParams.write();
        paramsPtr = pssParams.getPointer();
        paramsPtrSize = new NativeLong(pssParams.size(), true);
    } else {
        paramsPtr = Pointer.NULL;
        paramsPtrSize = new NativeLong(0, true);
    }
    CK_MECHANISM pMechanism = new CK_MECHANISM(new NativeLong(mechanism, true), paramsPtr, paramsPtrSize);
    try (MiddleWareWrapper.LockedMiddlewareWrapper lmw = mw.lock()) {
        lmw.signInit(session.getSessionId(), pMechanism, objectHandle);
        return lmw.sign(session.getSessionId(), data);
    } catch (InterruptedException ex) {
        throw new ThreadTerminateException("Thread interrupted while waiting for Middleware lock.", ex);
    }
}
Also used : CK_RSA_PKCS_PSS_PARAMS(org.openecard.mdlw.sal.cryptoki.CK_RSA_PKCS_PSS_PARAMS) NativeLong(com.sun.jna.NativeLong) Pointer(com.sun.jna.Pointer) ThreadTerminateException(org.openecard.common.ThreadTerminateException) CK_MECHANISM(org.openecard.mdlw.sal.cryptoki.CK_MECHANISM)

Example 2 with ThreadTerminateException

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

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

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

the class ChipGateway method processTokensRequest.

private CommandType processTokensRequest(ListTokensRequestType tokensReq) throws ConnectionError, JsonProcessingException, InvalidRedirectUrlException, ChipGatewayDataError {
    // check if we have been interrupted
    checkProcessCancelled();
    ListTokensResponseType tokensResp = new ListTokensResponseType();
    tokensResp.setSessionIdentifier(sessionId);
    try {
        tokensResp = waitForTokens(tokensReq);
    } catch (UnsupportedAlgorithmException ex) {
        LOG.error("Unsupported algorithm used.", ex);
        tokensResp.setResult(ChipGatewayStatusCodes.INCORRECT_PARAMETER);
    } catch (WSHelper.WSException ex) {
        LOG.error("Unknown error.", ex);
        tokensResp.setResult(ChipGatewayStatusCodes.OTHER);
    } catch (ThreadTerminateException | InterruptedException ex) {
        LOG.info("Chipgateway process interrupted.", ex);
        tokensResp.setResult(ChipGatewayStatusCodes.STOPPED);
    } catch (TimeoutException ex) {
        LOG.info("Waiting for new tokens timed out.", ex);
        tokensResp.setResult(ChipGatewayStatusCodes.TIMEOUT);
    }
    return sendMessageInterruptableAndCheckTermination(getResource(listTokensUrl), tokensResp);
}
Also used : WSHelper(org.openecard.common.WSHelper) ListTokensResponseType(org.openecard.ws.chipgateway.ListTokensResponseType) UnsupportedAlgorithmException(org.openecard.crypto.common.UnsupportedAlgorithmException) ThreadTerminateException(org.openecard.common.ThreadTerminateException) TimeoutException(java.util.concurrent.TimeoutException)

Example 5 with ThreadTerminateException

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

the class ChipGateway method sendMessageInterruptable.

private <T> T sendMessageInterruptable(final String resource, final String msg, final Class<T> resClass) throws ConnectionError, InvalidRedirectUrlException, ChipGatewayDataError, ThreadTerminateException {
    FutureTask<T> task = new FutureTask<>(new Callable<T>() {

        @Override
        public T call() throws Exception {
            return sendMessage(resource, msg, resClass);
        }
    });
    new Thread(task, "HTTP-Client-" + HTTP_THREAD_NUM.getAndIncrement()).start();
    try {
        return task.get();
    } catch (ExecutionException ex) {
        Throwable cause = ex.getCause();
        if (cause instanceof ConnectionError) {
            throw (ConnectionError) cause;
        } else if (cause instanceof InvalidRedirectUrlException) {
            throw (InvalidRedirectUrlException) cause;
        } else if (cause instanceof ChipGatewayDataError) {
            throw (ChipGatewayDataError) cause;
        } else if (cause instanceof RuntimeException) {
            throw (RuntimeException) cause;
        } else {
            throw new RuntimeException("Unexpected exception raised by HTTP message sending thread.", cause);
        }
    } catch (InterruptedException ex) {
        LOG.debug("Sending HTTP message interrupted.");
        task.cancel(true);
        // force new connection because this one may be unfinished and thus unusable
        try {
            conn.shutdown();
        } catch (IOException ignore) {
        }
        throw new ThreadTerminateException("Interrupt received while sending HTTP message.");
    }
}
Also used : InvalidRedirectUrlException(org.openecard.addons.cg.ex.InvalidRedirectUrlException) ConnectionError(org.openecard.addons.cg.ex.ConnectionError) ChipGatewayDataError(org.openecard.addons.cg.ex.ChipGatewayDataError) IOException(java.io.IOException) 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) FutureTask(java.util.concurrent.FutureTask) ExecutionException(java.util.concurrent.ExecutionException) ThreadTerminateException(org.openecard.common.ThreadTerminateException)

Aggregations

ThreadTerminateException (org.openecard.common.ThreadTerminateException)12 UnsupportedAlgorithmException (org.openecard.crypto.common.UnsupportedAlgorithmException)7 IOException (java.io.IOException)5 ExecutionException (java.util.concurrent.ExecutionException)5 WSHelper (org.openecard.common.WSHelper)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 FutureTask (java.util.concurrent.FutureTask)4 TimeoutException (java.util.concurrent.TimeoutException)4 InvalidRedirectUrlException (org.openecard.addons.cg.ex.InvalidRedirectUrlException)4 ParameterInvalid (org.openecard.addons.cg.ex.ParameterInvalid)4 SlotHandleInvalid (org.openecard.addons.cg.ex.SlotHandleInvalid)4 SecurityConditionUnsatisfiable (org.openecard.common.SecurityConditionUnsatisfiable)4 NativeLong (com.sun.jna.NativeLong)3 MalformedURLException (java.net.MalformedURLException)3 URISyntaxException (java.net.URISyntaxException)3 KeyStoreException (java.security.KeyStoreException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 CertificateException (java.security.cert.CertificateException)3 JoseException (org.jose4j.lang.JoseException)3 AuthServerException (org.openecard.addons.cg.ex.AuthServerException)3