Search in sources :

Example 1 with TLVException

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

the class AuthenticationToken method verifyToken.

/**
 * Verify the authentication token by the PICC and extract Certificate Authority Reference (CAR).
 *
 * @param T_PICC Token from the PICC
 * @param specifiedCHAT true if PACE is used with a CHAT
 * @return true if T_PICC is equal to my T_PICC
 * @throws GeneralSecurityException
 */
public boolean verifyToken(byte[] T_PICC, boolean specifiedCHAT) throws GeneralSecurityException {
    try {
        TLV dataSet = TLV.fromBER(T_PICC);
        // set of dynamic authentication data
        if (dataSet.getTagNumWithClass() != 0x7C) {
            throw new GeneralSecurityException("The returned object is not a set of dynamic authentication data.");
        }
        // Authentication Token
        List<TLV> authTokens = dataSet.findChildTags(0x86);
        if (authTokens.isEmpty()) {
            String msg = "Authentication Token is missing in set of dynamic authentication data.";
            throw new GeneralSecurityException(msg);
        } else if (authTokens.size() > 1) {
            String msg = "Authentication Token is present multiple times in set of dynamic authentication data.";
            throw new GeneralSecurityException(msg);
        } else {
            byte[] newToken = authTokens.get(0).getValue();
            if (!ByteUtils.compare(newToken, token)) {
                throw new GeneralSecurityException("Can not verify authentication token.");
            }
        }
        // CAR
        if (specifiedCHAT) {
            // current CAR
            List<TLV> car1 = dataSet.findChildTags(0x87);
            if (car1.isEmpty()) {
                String msg = "Current CAR is missing in set of dynamic authentication data.";
                throw new GeneralSecurityException(msg);
            } else if (car1.size() > 1) {
                String msg = "Current CAR is present multiple times in set of dynamic authentication data.";
                throw new GeneralSecurityException(msg);
            } else {
                currentCAR = car1.get(0).getValue();
                verifyCAR("Current CAR", currentCAR);
            }
            // last CAR
            List<TLV> car2 = dataSet.findChildTags(0x88);
            if (car2.size() > 1) {
                String msg = "Previous CAR is present multiple times in set of dynamic authentication data.";
                throw new GeneralSecurityException(msg);
            } else if (car2.size() == 1) {
                previousCAR = car2.get(0).getValue();
                verifyCAR("Previous CAR", previousCAR);
            }
        }
    } catch (TLVException ex) {
        throw new GeneralSecurityException("Given data is not a valid ASN.1 object.", ex);
    }
    return true;
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) TLVException(org.openecard.common.tlv.TLVException) TLV(org.openecard.common.tlv.TLV)

Example 2 with TLVException

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

the class TinySAL method dataSetSelect.

/**
 * The DataSetSelect function selects a data set in a card application.
 * See BSI-TR-03112-4, version 1.1.2, section 3.4.3.
 *
 * @param request DataSetSelect
 * @return DataSetSelectResponse
 */
@Publish
@Override
public DataSetSelectResponse dataSetSelect(DataSetSelect request) {
    DataSetSelectResponse response = WSHelper.makeResponse(DataSetSelectResponse.class, WSHelper.makeResultOK());
    try {
        ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
        CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle);
        byte[] applicationID = connectionHandle.getCardApplication();
        String dataSetName = request.getDataSetName();
        Assert.assertIncorrectParameter(dataSetName, "The parameter DataSetName is empty.");
        CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo();
        DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSet(dataSetName, applicationID);
        Assert.assertNamedEntityNotFound(dataSetInfo, "The given DataSet cannot be found.");
        Assert.securityConditionDataSet(cardStateEntry, applicationID, dataSetName, NamedDataServiceActionName.DATA_SET_SELECT);
        byte[] fileID = dataSetInfo.getDataSetPath().getEfIdOrPath();
        byte[] slotHandle = connectionHandle.getSlotHandle();
        CardResponseAPDU result = CardUtils.selectFileWithOptions(env.getDispatcher(), slotHandle, fileID, null, CardUtils.FCP_RESPONSE_DATA);
        FCP fcp = null;
        if (result != null && result.getData().length > 0) {
            try {
                fcp = new FCP(result.getData());
            } catch (TLVException ex) {
                LOG.warn("Invalid FCP received.");
            }
        }
        if (fcp == null) {
            LOG.info("Using fake FCP.");
            fcp = new FCP(createFakeFCP(Arrays.copyOfRange(fileID, fileID.length - 2, fileID.length)));
        }
        cardStateEntry.setFCPOfSelectedEF(fcp);
    } catch (ECardException e) {
        response.setResult(e.getResult());
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        throwThreadKillException(e);
        response.setResult(WSHelper.makeResult(e));
    }
    return response;
}
Also used : ConnectionHandleType(iso.std.iso_iec._24727.tech.schema.ConnectionHandleType) ECardException(org.openecard.common.ECardException) CardStateEntry(org.openecard.common.sal.state.CardStateEntry) FCP(org.openecard.common.tlv.iso7816.FCP) CardInfoWrapper(org.openecard.common.sal.state.cif.CardInfoWrapper) DataSetInfoType(iso.std.iso_iec._24727.tech.schema.DataSetInfoType) CardResponseAPDU(org.openecard.common.apdu.common.CardResponseAPDU) TLVException(org.openecard.common.tlv.TLVException) PrerequisitesNotSatisfiedException(org.openecard.common.sal.exception.PrerequisitesNotSatisfiedException) NameExistsException(org.openecard.common.sal.exception.NameExistsException) AddonNotFoundException(org.openecard.addon.AddonNotFoundException) ThreadTerminateException(org.openecard.common.ThreadTerminateException) ECardException(org.openecard.common.ECardException) NamedEntityNotFoundException(org.openecard.common.sal.exception.NamedEntityNotFoundException) UnknownProtocolException(org.openecard.common.sal.exception.UnknownProtocolException) IncorrectParameterException(org.openecard.common.sal.exception.IncorrectParameterException) InappropriateProtocolForActionException(org.openecard.common.sal.exception.InappropriateProtocolForActionException) TLVException(org.openecard.common.tlv.TLVException) SecurityConditionNotSatisfiedException(org.openecard.common.sal.exception.SecurityConditionNotSatisfiedException) UnknownConnectionHandleException(org.openecard.common.sal.exception.UnknownConnectionHandleException) DataSetSelectResponse(iso.std.iso_iec._24727.tech.schema.DataSetSelectResponse) Publish(org.openecard.common.interfaces.Publish)

Example 3 with TLVException

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

the class ChipAuthentication method readEFCardSecurity.

/**
 * Reads the EFCardSecurity from the card.
 *
 * @return EFCardSecurtiy
 * @throws ProtocolException Thrown in case there is a problem reading the file.
 */
public byte[] readEFCardSecurity() throws ProtocolException {
    try {
        byte[] file = ShortUtils.toByteArray(EACConstants.EF_CARDSECURITY_FID);
        CardResponseAPDU resp = CardUtils.selectFileWithOptions(dispatcher, slotHandle, file, null, CardUtils.FCP_RESPONSE_DATA);
        FCP efCardSecurityFCP = new FCP(TLV.fromBER(resp.getData()));
        byte[] efCardSecurity = CardUtils.readFile(efCardSecurityFCP, dispatcher, slotHandle);
        return efCardSecurity;
    } catch (APDUException ex) {
        throw new ProtocolException(ex.getResult());
    } catch (TLVException ex) {
        throw new ProtocolException("Failed to parse FCP.", ex);
    }
}
Also used : ProtocolException(org.openecard.common.sal.protocol.exception.ProtocolException) FCP(org.openecard.common.tlv.iso7816.FCP) APDUException(org.openecard.common.apdu.exception.APDUException) CardResponseAPDU(org.openecard.common.apdu.common.CardResponseAPDU) TLVException(org.openecard.common.tlv.TLVException)

Example 4 with TLVException

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

the class ChipAuthenticationStep method perform.

@Override
public DIDAuthenticateResponse perform(DIDAuthenticate didAuthenticate, Map<String, Object> internalData) {
    DIDAuthenticateResponse response = new DIDAuthenticateResponse();
    byte[] slotHandle = didAuthenticate.getConnectionHandle().getSlotHandle();
    DynamicContext dynCtx = DynamicContext.getInstance(TR03112Keys.INSTANCE_KEY);
    try {
        ObjectSchemaValidator valid = (ObjectSchemaValidator) dynCtx.getPromise(EACProtocol.SCHEMA_VALIDATOR).deref();
        boolean messageValid = valid.validateObject(didAuthenticate);
        if (!messageValid) {
            String msg = "Validation of the EACAdditionalInputType message failed.";
            logger.error(msg);
            dynCtx.put(EACProtocol.AUTHENTICATION_FAILED, true);
            response.setResult(WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, msg));
            return response;
        }
    } catch (ObjectValidatorException ex) {
        String msg = "Validation of the EACAdditionalInputType message failed due to invalid input data.";
        logger.error(msg, ex);
        dynCtx.put(EACProtocol.AUTHENTICATION_FAILED, true);
        response.setResult(WSHelper.makeResultError(ECardConstants.Minor.App.INT_ERROR, msg));
        return response;
    } catch (InterruptedException ex) {
        String msg = "Thread interrupted while waiting for schema validator instance.";
        logger.error(msg, ex);
        dynCtx.put(EACProtocol.AUTHENTICATION_FAILED, true);
        response.setResult(WSHelper.makeResultError(ECardConstants.Minor.App.INT_ERROR, msg));
        return response;
    }
    try {
        EACAdditionalInputType eacAdditionalInput = new EACAdditionalInputType(didAuthenticate.getAuthenticationProtocolData());
        EAC2OutputType eac2Output = eacAdditionalInput.getOutputType();
        TerminalAuthentication ta = new TerminalAuthentication(dispatcher, slotHandle);
        ChipAuthentication ca = new ChipAuthentication(dispatcher, slotHandle);
        // save signature, it is needed in the authentication step
        byte[] signature = eacAdditionalInput.getSignature();
        internalData.put(EACConstants.IDATA_SIGNATURE, signature);
        // perform TA and CA authentication
        AuthenticationHelper auth = new AuthenticationHelper(ta, ca);
        eac2Output = auth.performAuth(eac2Output, internalData);
        response.setResult(WSHelper.makeResultOK());
        response.setAuthenticationProtocolData(eac2Output.getAuthDataType());
    } catch (ParserConfigurationException | ProtocolException | TLVException e) {
        logger.error(e.getMessage(), e);
        response.setResult(WSHelper.makeResultUnknownError(e.getMessage()));
        dynCtx.put(EACProtocol.AUTHENTICATION_FAILED, true);
    }
    Promise<Object> p = (Promise<Object>) dynCtx.getPromise(TR03112Keys.PROCESSING_CANCELLATION);
    if (p.derefNonblocking() == null) {
        // authentication finished, notify GUI
        dynCtx.put(EACProtocol.AUTHENTICATION_DONE, true);
        return response;
    } else {
        // authentication finished, notify GUI
        dynCtx.put(EACProtocol.AUTHENTICATION_DONE, false);
        response = new DIDAuthenticateResponse();
        String msg = "Authentication canceled by the user.";
        response.setResult(WSHelper.makeResultError(ECardConstants.Minor.SAL.CANCELLATION_BY_USER, msg));
        return response;
    }
}
Also used : ProtocolException(org.openecard.common.sal.protocol.exception.ProtocolException) TLVException(org.openecard.common.tlv.TLVException) EACAdditionalInputType(org.openecard.sal.protocol.eac.anytype.EACAdditionalInputType) Promise(org.openecard.common.util.Promise) DIDAuthenticateResponse(iso.std.iso_iec._24727.tech.schema.DIDAuthenticateResponse) ObjectValidatorException(org.openecard.common.interfaces.ObjectValidatorException) ObjectSchemaValidator(org.openecard.common.interfaces.ObjectSchemaValidator) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) DynamicContext(org.openecard.common.DynamicContext) EAC2OutputType(org.openecard.sal.protocol.eac.anytype.EAC2OutputType)

Example 5 with TLVException

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

the class CardUtils method readFile.

/**
 * Selects and reads a file.
 *
 * @param dispatcher Dispatcher
 * @param slotHandle Slot handle
 * @param fileID File ID
 * @return File content
 * @throws APDUException
 */
@Deprecated
public static byte[] readFile(Dispatcher dispatcher, byte[] slotHandle, byte[] fileID) throws APDUException {
    CardResponseAPDU selectResponse = selectFileWithOptions(dispatcher, slotHandle, fileID, null, FCP_RESPONSE_DATA);
    FCP fcp = null;
    try {
        fcp = new FCP(selectResponse.getData());
    } catch (TLVException e) {
        LOG.warn("Couldn't get File Control Parameters from Select response.", e);
    }
    return readFile(fcp, dispatcher, slotHandle);
}
Also used : FCP(org.openecard.common.tlv.iso7816.FCP) CardResponseAPDU(org.openecard.common.apdu.common.CardResponseAPDU) TLVException(org.openecard.common.tlv.TLVException)

Aggregations

TLVException (org.openecard.common.tlv.TLVException)8 CardResponseAPDU (org.openecard.common.apdu.common.CardResponseAPDU)4 FCP (org.openecard.common.tlv.iso7816.FCP)4 TLV (org.openecard.common.tlv.TLV)3 ProtocolException (org.openecard.common.sal.protocol.exception.ProtocolException)2 ConnectionHandleType (iso.std.iso_iec._24727.tech.schema.ConnectionHandleType)1 DIDAuthenticateResponse (iso.std.iso_iec._24727.tech.schema.DIDAuthenticateResponse)1 DataSetInfoType (iso.std.iso_iec._24727.tech.schema.DataSetInfoType)1 DataSetSelectResponse (iso.std.iso_iec._24727.tech.schema.DataSetSelectResponse)1 GeneralSecurityException (java.security.GeneralSecurityException)1 Nonnull (javax.annotation.Nonnull)1 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)1 AddonNotFoundException (org.openecard.addon.AddonNotFoundException)1 DynamicContext (org.openecard.common.DynamicContext)1 ECardException (org.openecard.common.ECardException)1 ThreadTerminateException (org.openecard.common.ThreadTerminateException)1 APDUException (org.openecard.common.apdu.exception.APDUException)1 ObjectSchemaValidator (org.openecard.common.interfaces.ObjectSchemaValidator)1 ObjectValidatorException (org.openecard.common.interfaces.ObjectValidatorException)1 Publish (org.openecard.common.interfaces.Publish)1