Search in sources :

Example 1 with ReadBinary

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

the class CardUtils method readFile.

/**
 * Reads a file.
 *
 * @param dispatcher Dispatcher
 * @param slotHandle Slot handle
 * @param fcp File Control Parameters
 * @return File content
 * @throws APDUException
 */
public static byte[] readFile(FCP fcp, Dispatcher dispatcher, byte[] slotHandle) throws APDUException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // Read 255 bytes per APDU
    byte length = (byte) 0xFF;
    // -1 indicates I don't know
    short numToRead = -1;
    if (fcp != null) {
        Long fcpNumBytes = fcp.getNumBytes();
        if (fcpNumBytes != null) {
            // more than short is not possible and besides that very unrealistic
            numToRead = fcpNumBytes.shortValue();
            // reduce readout size
            if (numToRead < 255) {
                length = (byte) numToRead;
            }
        }
    }
    boolean isRecord = isRecordEF(fcp);
    // records start at index 1
    byte i = (byte) (isRecord ? 1 : 0);
    short numRead = 0;
    try {
        CardResponseAPDU response;
        byte[] trailer;
        int lastNumRead = 0;
        boolean goAgain;
        do {
            if (!isRecord) {
                CardCommandAPDU readBinary = new ReadBinary(numRead, length);
                // 0x6A84 code for the estonian identity card. The card returns this code
                // after the last read process.
                response = readBinary.transmit(dispatcher, slotHandle, CardCommandStatus.response(0x9000, 0x6282, 0x6A84, 0x6A83, 0x6A86, 0x6B00));
            } else {
                CardCommandAPDU readRecord = new ReadRecord((byte) i);
                response = readRecord.transmit(dispatcher, slotHandle, CardCommandStatus.response(0x9000, 0x6282, 0x6A84, 0x6A83));
            }
            trailer = response.getTrailer();
            if (!Arrays.equals(trailer, new byte[] { (byte) 0x6A, (byte) 0x84 }) && !Arrays.equals(trailer, new byte[] { (byte) 0x6A, (byte) 0x83 }) && !Arrays.equals(trailer, new byte[] { (byte) 0x6A, (byte) 0x86 })) {
                byte[] data = response.getData();
                // some cards are just pure shit and return 9000 when no bytes have been read
                baos.write(data);
                lastNumRead = data.length;
                numRead += lastNumRead;
            }
            i++;
            // update length value
            goAgain = response.isNormalProcessed() && lastNumRead != 0 || (Arrays.equals(trailer, new byte[] { (byte) 0x62, (byte) 0x82 }) && isRecord);
            if (goAgain && numToRead != -1) {
                // we have a limit, enforce it
                short remainingBytes = (short) (numToRead - numRead);
                if (remainingBytes <= 0) {
                    goAgain = false;
                } else if (remainingBytes < 255) {
                    // update length when we reached the area below 255
                    length = (byte) remainingBytes;
                }
            }
        } while (goAgain);
        baos.close();
    } catch (IOException e) {
        throw new APDUException(e);
    }
    return baos.toByteArray();
}
Also used : CardCommandAPDU(org.openecard.common.apdu.common.CardCommandAPDU) APDUException(org.openecard.common.apdu.exception.APDUException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ReadBinary(org.openecard.common.apdu.ReadBinary) ReadRecord(org.openecard.common.apdu.ReadRecord) CardResponseAPDU(org.openecard.common.apdu.common.CardResponseAPDU)

Example 2 with ReadBinary

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

the class TinySAL method dsiRead.

/**
 * The DSIRead function reads out the content of a specific DSI (Data Structure for Interoperability).
 * See BSI-TR-03112-4, version 1.1.2, section 3.4.9.
 *
 * @param request DSIRead
 * @return DSIReadResponse
 */
@Publish
@Override
public DSIReadResponse dsiRead(DSIRead request) {
    DSIReadResponse response = WSHelper.makeResponse(DSIReadResponse.class, WSHelper.makeResultOK());
    try {
        ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
        CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle);
        byte[] applicationID = cardStateEntry.getCurrentCardApplication().getApplicationIdentifier();
        String dsiName = request.getDSIName();
        byte[] slotHandle = connectionHandle.getSlotHandle();
        Assert.assertIncorrectParameter(dsiName, "The parameter DSIName is empty.");
        Assert.securityConditionDataSet(cardStateEntry, applicationID, dsiName, NamedDataServiceActionName.DSI_READ);
        if (cardStateEntry.getFCPOfSelectedEF() == null) {
            throw new PrerequisitesNotSatisfiedException("No DataSet to read selected.");
        }
        CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo();
        DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSetByDsiName(dsiName);
        if (dataSetInfo == null) {
            // there is no data set which contains the given dsi name so the name should be an data set name
            dataSetInfo = cardInfoWrapper.getDataSetByName(dsiName);
            if (dataSetInfo != null) {
                if (!cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().isEmpty()) {
                    byte[] path = dataSetInfo.getDataSetPath().getEfIdOrPath();
                    byte[] fid = Arrays.copyOfRange(path, path.length - 2, path.length);
                    if (!Arrays.equals(fid, cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0))) {
                        String msg = "Wrong DataSet for reading the DSI " + dsiName + " is selected.";
                        throw new PrerequisitesNotSatisfiedException(msg);
                    }
                }
                byte[] fileContent = CardUtils.readFile(cardStateEntry.getFCPOfSelectedEF(), env.getDispatcher(), slotHandle);
                response.setDSIContent(fileContent);
            } else {
                String msg = "The given DSIName does not related to any know DSI or DataSet.";
                throw new IncorrectParameterException(msg);
            }
        } else {
            // There exists a data set with the given dsi name
            // check whether the correct file is selected
            byte[] dataSetPath = dataSetInfo.getDataSetPath().getEfIdOrPath();
            byte[] dataSetFID = new byte[] { dataSetPath[dataSetPath.length - 2], dataSetPath[dataSetPath.length - 1] };
            if (Arrays.equals(dataSetFID, cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0))) {
                DSIType dsi = cardInfoWrapper.getDSIbyName(dsiName);
                PathType dsiPath = dsi.getDSIPath();
                if (dsiPath.getTagRef() != null) {
                    TagRef tagReference = dsiPath.getTagRef();
                    byte[] tag = tagReference.getTag();
                    GetData getDataRequest;
                    if (tag.length == 2) {
                        getDataRequest = new GetData(GetData.INS_DATA, tag[0], tag[1]);
                        CardResponseAPDU cardResponse = getDataRequest.transmit(env.getDispatcher(), slotHandle, Collections.EMPTY_LIST);
                        byte[] responseData = cardResponse.getData();
                        while (cardResponse.getTrailer()[0] == (byte) 0x61) {
                            GetResponse allData = new GetResponse();
                            cardResponse = allData.transmit(env.getDispatcher(), slotHandle, Collections.EMPTY_LIST);
                            responseData = ByteUtils.concatenate(responseData, cardResponse.getData());
                        }
                        response.setDSIContent(responseData);
                    } else if (tag.length == 1) {
                        // how to determine Simple- or BER-TLV in this case correctly?
                        // Now try Simple-TLV first and if it fail try BER-TLV
                        getDataRequest = new GetData(GetData.INS_DATA, GetData.SIMPLE_TLV, tag[0]);
                        CardResponseAPDU cardResponse = getDataRequest.transmit(env.getDispatcher(), slotHandle, Collections.EMPTY_LIST);
                        byte[] responseData = cardResponse.getData();
                        // just an assumption
                        if (Arrays.equals(cardResponse.getTrailer(), new byte[] { (byte) 0x6A, (byte) 0x88 })) {
                            getDataRequest = new GetData(GetData.INS_DATA, GetData.BER_TLV_ONE_BYTE, tag[0]);
                            cardResponse = getDataRequest.transmit(env.getDispatcher(), slotHandle, Collections.EMPTY_LIST);
                            responseData = cardResponse.getData();
                        }
                        while (cardResponse.getTrailer()[0] == (byte) 0x61) {
                            GetResponse allData = new GetResponse();
                            cardResponse = allData.transmit(env.getDispatcher(), slotHandle, Collections.EMPTY_LIST);
                            responseData = ByteUtils.concatenate(responseData, cardResponse.getData());
                        }
                        response.setDSIContent(responseData);
                    }
                } else if (dsiPath.getIndex() != null) {
                    byte[] index = dsiPath.getIndex();
                    byte[] length = dsiPath.getLength();
                    List<byte[]> allowedResponse = new ArrayList<>();
                    allowedResponse.add(new byte[] { (byte) 0x90, (byte) 0x00 });
                    allowedResponse.add(new byte[] { (byte) 0x62, (byte) 0x82 });
                    if (cardStateEntry.getFCPOfSelectedEF().getDataElements().isLinear()) {
                        // in this case we use the index as record number and the length as length of record
                        ReadRecord readRecord = new ReadRecord(index[0]);
                        // NOTE: For record based files TR-0312-4 states to ignore the length field in case of records
                        CardResponseAPDU cardResponse = readRecord.transmit(env.getDispatcher(), slotHandle, allowedResponse);
                        response.setDSIContent(cardResponse.getData());
                    } else {
                        // in this case we use index as offset and length as the expected length
                        ReadBinary readBinary = new ReadBinary(ByteUtils.toShort(index), ByteUtils.toShort(length));
                        CardResponseAPDU cardResponse = readBinary.transmit(env.getDispatcher(), slotHandle, allowedResponse);
                        response.setDSIContent(cardResponse.getData());
                    }
                } else {
                    String msg = "The currently selected data set does not contain the DSI with the name " + dsiName;
                    throw new PrerequisitesNotSatisfiedException(msg);
                }
            }
        }
    } 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) CardStateEntry(org.openecard.common.sal.state.CardStateEntry) DSIType(iso.std.iso_iec._24727.tech.schema.DSIType) CardInfoWrapper(org.openecard.common.sal.state.cif.CardInfoWrapper) TagRef(iso.std.iso_iec._24727.tech.schema.PathType.TagRef) GetResponse(org.openecard.common.apdu.GetResponse) DIDGetResponse(iso.std.iso_iec._24727.tech.schema.DIDGetResponse) 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) PathType(iso.std.iso_iec._24727.tech.schema.PathType) CardApplicationPathType(iso.std.iso_iec._24727.tech.schema.CardApplicationPathType) ECardException(org.openecard.common.ECardException) PrerequisitesNotSatisfiedException(org.openecard.common.sal.exception.PrerequisitesNotSatisfiedException) ReadRecord(org.openecard.common.apdu.ReadRecord) ReadBinary(org.openecard.common.apdu.ReadBinary) GetData(org.openecard.common.apdu.GetData) DataSetInfoType(iso.std.iso_iec._24727.tech.schema.DataSetInfoType) IncorrectParameterException(org.openecard.common.sal.exception.IncorrectParameterException) DataSetList(iso.std.iso_iec._24727.tech.schema.DataSetList) DSIList(iso.std.iso_iec._24727.tech.schema.DSIList) CardApplicationList(iso.std.iso_iec._24727.tech.schema.CardApplicationList) CardApplicationServiceList(iso.std.iso_iec._24727.tech.schema.CardApplicationServiceList) ArrayList(java.util.ArrayList) DIDList(iso.std.iso_iec._24727.tech.schema.DIDList) ACLList(iso.std.iso_iec._24727.tech.schema.ACLList) List(java.util.List) CardApplicationServiceNameList(iso.std.iso_iec._24727.tech.schema.CardApplicationServiceListResponse.CardApplicationServiceNameList) CardApplicationNameList(iso.std.iso_iec._24727.tech.schema.CardApplicationListResponse.CardApplicationNameList) CardResponseAPDU(org.openecard.common.apdu.common.CardResponseAPDU) DSIReadResponse(iso.std.iso_iec._24727.tech.schema.DSIReadResponse) Publish(org.openecard.common.interfaces.Publish)

Aggregations

ReadBinary (org.openecard.common.apdu.ReadBinary)2 ReadRecord (org.openecard.common.apdu.ReadRecord)2 CardResponseAPDU (org.openecard.common.apdu.common.CardResponseAPDU)2 ACLList (iso.std.iso_iec._24727.tech.schema.ACLList)1 CardApplicationList (iso.std.iso_iec._24727.tech.schema.CardApplicationList)1 CardApplicationNameList (iso.std.iso_iec._24727.tech.schema.CardApplicationListResponse.CardApplicationNameList)1 CardApplicationPathType (iso.std.iso_iec._24727.tech.schema.CardApplicationPathType)1 CardApplicationServiceList (iso.std.iso_iec._24727.tech.schema.CardApplicationServiceList)1 CardApplicationServiceNameList (iso.std.iso_iec._24727.tech.schema.CardApplicationServiceListResponse.CardApplicationServiceNameList)1 ConnectionHandleType (iso.std.iso_iec._24727.tech.schema.ConnectionHandleType)1 DIDGetResponse (iso.std.iso_iec._24727.tech.schema.DIDGetResponse)1 DIDList (iso.std.iso_iec._24727.tech.schema.DIDList)1 DSIList (iso.std.iso_iec._24727.tech.schema.DSIList)1 DSIReadResponse (iso.std.iso_iec._24727.tech.schema.DSIReadResponse)1 DSIType (iso.std.iso_iec._24727.tech.schema.DSIType)1 DataSetInfoType (iso.std.iso_iec._24727.tech.schema.DataSetInfoType)1 DataSetList (iso.std.iso_iec._24727.tech.schema.DataSetList)1 PathType (iso.std.iso_iec._24727.tech.schema.PathType)1 TagRef (iso.std.iso_iec._24727.tech.schema.PathType.TagRef)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1