Search in sources :

Example 1 with PinBlocked

use of org.openecard.addons.cg.ex.PinBlocked 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 2 with PinBlocked

use of org.openecard.addons.cg.ex.PinBlocked in project open-ecard by ecsec.

the class ChipGateway method processSignRequest.

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

        @Override
        public SignResponseType call() throws Exception {
            SignResponseType signResp = new SignResponseType();
            signResp.setSessionIdentifier(sessionId);
            byte[] slotHandle = signReq.getSlotHandle();
            String didName = signReq.getDIDName();
            char[] pin = null;
            try {
                pin = getPin(signReq.getPIN());
                Signer signer = new Signer(tokenCache, slotHandle, didName, pin);
                byte[] signature = signer.sign(signReq.getMessage());
                signResp.setSignature(signature);
                signResp.setResult(ChipGatewayStatusCodes.OK);
                return signResp;
            } finally {
                if (pin != null) {
                    Arrays.fill(pin, ' ');
                }
            }
        }
    });
    Thread t = new Thread(action, "SignRequest-Task-" + TASK_THREAD_NUM.getAndIncrement());
    t.setDaemon(true);
    t.start();
    SignResponseType signResp = new SignResponseType();
    signResp.setSessionIdentifier(sessionId);
    try {
        // wait for thread to finish
        signResp = 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();
            signResp.setResult(ChipGatewayStatusCodes.TIMEOUT);
        } catch (InterruptedException ignore) {
            // send stop message
            signResp.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.", cause);
            signResp.setResult(ChipGatewayStatusCodes.INCORRECT_PARAMETER);
        } else if (cause instanceof ParameterInvalid) {
            LOG.error("Error while processing the certificate filter parameters.", cause);
            signResp.setResult(ChipGatewayStatusCodes.INCORRECT_PARAMETER);
        } else if (cause instanceof SlotHandleInvalid) {
            LOG.error("No token for the given slot handle found.", cause);
            signResp.setResult(ChipGatewayStatusCodes.UNKNOWN_SLOT);
        } else if (cause instanceof NoSuchDid) {
            LOG.error("DID does not exist.", cause);
            signResp.setResult(ChipGatewayStatusCodes.UNKNOWN_DID);
        } else if (cause instanceof PinBlocked) {
            LOG.error("PIN is blocked.", ex);
            signResp.setResult(ChipGatewayStatusCodes.PIN_BLOCKED);
        } else if (cause instanceof SecurityConditionUnsatisfiable) {
            LOG.error("DID can not be authenticated.", cause);
            signResp.setResult(ChipGatewayStatusCodes.SECURITY_NOT_SATISFIED);
        } else if (cause instanceof WSHelper.WSException) {
            LOG.error("Unknown error.", cause);
            signResp.setResult(ChipGatewayStatusCodes.OTHER);
        } else if (cause instanceof ThreadTerminateException) {
            LOG.error("Chipgateway process interrupted.", cause);
            signResp.setResult(ChipGatewayStatusCodes.STOPPED);
        } else {
            LOG.error("Unknown error during sign operation.", cause);
            signResp.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
        signResp.setResult(ChipGatewayStatusCodes.STOPPED);
    }
    return sendMessageInterruptableAndCheckTermination(getResource(signUrl), signResp);
}
Also used : PinBlocked(org.openecard.addons.cg.ex.PinBlocked) WSHelper(org.openecard.common.WSHelper) SecurityConditionUnsatisfiable(org.openecard.common.SecurityConditionUnsatisfiable) 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) RemotePinException(org.openecard.addons.cg.ex.RemotePinException) FutureTask(java.util.concurrent.FutureTask) BigInteger(java.math.BigInteger) ParameterInvalid(org.openecard.addons.cg.ex.ParameterInvalid) ExecutionException(java.util.concurrent.ExecutionException) NoSuchDid(org.openecard.crypto.common.sal.did.NoSuchDid) ThreadTerminateException(org.openecard.common.ThreadTerminateException) SignResponseType(org.openecard.ws.chipgateway.SignResponseType) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

IOException (java.io.IOException)2 ParameterInvalid (org.openecard.addons.cg.ex.ParameterInvalid)2 PinBlocked (org.openecard.addons.cg.ex.PinBlocked)2 SlotHandleInvalid (org.openecard.addons.cg.ex.SlotHandleInvalid)2 SecurityConditionUnsatisfiable (org.openecard.common.SecurityConditionUnsatisfiable)2 ThreadTerminateException (org.openecard.common.ThreadTerminateException)2 WSHelper (org.openecard.common.WSHelper)2 UnsupportedAlgorithmException (org.openecard.crypto.common.UnsupportedAlgorithmException)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 BigInteger (java.math.BigInteger)1 MalformedURLException (java.net.MalformedURLException)1 URISyntaxException (java.net.URISyntaxException)1 InvalidParameterException (java.security.InvalidParameterException)1 KeyStoreException (java.security.KeyStoreException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 CertificateException (java.security.cert.CertificateException)1 ExecutionException (java.util.concurrent.ExecutionException)1 FutureTask (java.util.concurrent.FutureTask)1 Semaphore (java.util.concurrent.Semaphore)1 TimeoutException (java.util.concurrent.TimeoutException)1