Search in sources :

Example 6 with CardResponseAPDU

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

the class PACEStep method perform.

@Override
public DIDAuthenticateResponse perform(DIDAuthenticate request, Map<String, Object> internalData) {
    // get context to save values in
    DynamicContext dynCtx = DynamicContext.getInstance(TR03112Keys.INSTANCE_KEY);
    DIDAuthenticate didAuthenticate = request;
    DIDAuthenticateResponse response = new DIDAuthenticateResponse();
    ConnectionHandleType conHandle = (ConnectionHandleType) dynCtx.get(TR03112Keys.CONNECTION_HANDLE);
    try {
        ObjectSchemaValidator valid = (ObjectSchemaValidator) dynCtx.getPromise(EACProtocol.SCHEMA_VALIDATOR).deref();
        boolean messageValid = valid.validateObject(request);
        if (!messageValid) {
            String msg = "Validation of the EAC1InputType message failed.";
            LOG.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 EAC1InputType message failed due to invalid input data.";
        LOG.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.";
        LOG.error(msg, ex);
        dynCtx.put(EACProtocol.AUTHENTICATION_FAILED, true);
        response.setResult(WSHelper.makeResultError(ECardConstants.Minor.App.INT_ERROR, msg));
        return response;
    }
    if (!ByteUtils.compare(conHandle.getSlotHandle(), didAuthenticate.getConnectionHandle().getSlotHandle())) {
        String msg = "Invalid connection handle given in DIDAuthenticate message.";
        Result r = WSHelper.makeResultError(ECardConstants.Minor.SAL.UNKNOWN_HANDLE, msg);
        response.setResult(r);
        dynCtx.put(EACProtocol.AUTHENTICATION_FAILED, true);
        return response;
    }
    byte[] slotHandle = conHandle.getSlotHandle();
    dynCtx.put(EACProtocol.SLOT_HANDLE, slotHandle);
    dynCtx.put(EACProtocol.DISPATCHER, dispatcher);
    try {
        EAC1InputType eac1Input = new EAC1InputType(didAuthenticate.getAuthenticationProtocolData());
        EAC1OutputType eac1Output = eac1Input.getOutputType();
        AuthenticatedAuxiliaryData aad = new AuthenticatedAuxiliaryData(eac1Input.getAuthenticatedAuxiliaryData());
        byte pinID = PasswordID.valueOf(didAuthenticate.getDIDName()).getByte();
        final String passwordType = PasswordID.parse(pinID).getString();
        // determine PACE capabilities of the terminal
        boolean nativePace = genericPACESupport(conHandle);
        dynCtx.put(EACProtocol.IS_NATIVE_PACE, nativePace);
        // Certificate chain
        CardVerifiableCertificateChain certChain = new CardVerifiableCertificateChain(eac1Input.getCertificates());
        byte[] rawCertificateDescription = eac1Input.getCertificateDescription();
        CertificateDescription certDescription = CertificateDescription.getInstance(rawCertificateDescription);
        // put CertificateDescription into DynamicContext which is needed for later checks
        dynCtx.put(TR03112Keys.ESERVICE_CERTIFICATE_DESC, certDescription);
        // according to BSI-INSTANCE_KEY-7 we MUST perform some checks immediately after receiving the eService cert
        Result activationChecksResult = performChecks(certDescription, dynCtx);
        if (!ECardConstants.Major.OK.equals(activationChecksResult.getResultMajor())) {
            response.setResult(activationChecksResult);
            dynCtx.put(EACProtocol.AUTHENTICATION_FAILED, true);
            return response;
        }
        CHAT requiredCHAT = new CHAT(eac1Input.getRequiredCHAT());
        CHAT optionalCHAT = new CHAT(eac1Input.getOptionalCHAT());
        // get the PACEMarker
        CardStateEntry cardState = (CardStateEntry) internalData.get(EACConstants.IDATA_CARD_STATE_ENTRY);
        PACEMarkerType paceMarker = getPaceMarker(cardState, passwordType);
        dynCtx.put(EACProtocol.PACE_MARKER, paceMarker);
        // Verify that the certificate description matches the terminal certificate
        CardVerifiableCertificate taCert = certChain.getTerminalCertificate();
        CardVerifiableCertificateVerifier.verify(taCert, certDescription);
        // Verify that the required CHAT matches the terminal certificate's CHAT
        CHAT taCHAT = taCert.getCHAT();
        // an other role.
        if (taCHAT.getRole() != CHAT.Role.AUTHENTICATION_TERMINAL) {
            String msg = "Unsupported terminal type in Terminal Certificate referenced. Refernced terminal type is " + taCHAT.getRole().toString() + ".";
            response.setResult(WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, msg));
            dynCtx.put(EACProtocol.AUTHENTICATION_FAILED, true);
            return response;
        }
        CHATVerifier.verfiy(taCHAT, requiredCHAT);
        // remove overlapping values from optional chat
        optionalCHAT.restrictAccessRights(taCHAT);
        // Prepare data in DIDAuthenticate for GUI
        final EACData eacData = new EACData();
        eacData.didRequest = didAuthenticate;
        eacData.certificate = certChain.getTerminalCertificate();
        eacData.certificateDescription = certDescription;
        eacData.rawCertificateDescription = rawCertificateDescription;
        eacData.transactionInfo = eac1Input.getTransactionInfo();
        eacData.requiredCHAT = requiredCHAT;
        eacData.optionalCHAT = optionalCHAT;
        eacData.selectedCHAT = requiredCHAT;
        eacData.aad = aad;
        eacData.pinID = pinID;
        eacData.passwordType = passwordType;
        dynCtx.put(EACProtocol.EAC_DATA, eacData);
        // get initial pin status
        InputAPDUInfoType input = new InputAPDUInfoType();
        input.setInputAPDU(new byte[] { (byte) 0x00, (byte) 0x22, (byte) 0xC1, (byte) 0xA4, (byte) 0x0F, (byte) 0x80, (byte) 0x0A, (byte) 0x04, (byte) 0x00, (byte) 0x7F, (byte) 0x00, (byte) 0x07, (byte) 0x02, (byte) 0x02, (byte) 0x04, (byte) 0x02, (byte) 0x02, (byte) 0x83, (byte) 0x01, (byte) 0x03 });
        input.getAcceptableStatusCode().addAll(EacPinStatus.getCodes());
        Transmit transmit = new Transmit();
        transmit.setSlotHandle(slotHandle);
        transmit.getInputAPDUInfo().add(input);
        TransmitResponse pinCheckResponse = (TransmitResponse) dispatcher.safeDeliver(transmit);
        WSHelper.checkResult(pinCheckResponse);
        byte[] output = pinCheckResponse.getOutputAPDU().get(0);
        CardResponseAPDU outputApdu = new CardResponseAPDU(output);
        byte[] status = outputApdu.getStatusBytes();
        dynCtx.put(EACProtocol.PIN_STATUS, EacPinStatus.fromCode(status));
        // define GUI depending on the PIN status
        final UserConsentDescription uc = new UserConsentDescription(LANG.translationForKey(TITLE));
        final CardMonitor cardMon;
        uc.setDialogType("EAC");
        // create GUI and init executor
        cardMon = new CardMonitor();
        CardRemovedFilter filter = new CardRemovedFilter(conHandle.getIFDName(), conHandle.getSlotIndex());
        eventDispatcher.add(cardMon, filter);
        CVCStep cvcStep = new CVCStep(eacData);
        cvcStep.setBackgroundTask(cardMon);
        CVCStepAction cvcStepAction = new CVCStepAction(cvcStep);
        cvcStep.setAction(cvcStepAction);
        uc.getSteps().add(cvcStep);
        uc.getSteps().add(CHATStep.createDummy());
        uc.getSteps().add(PINStep.createDummy(passwordType));
        ProcessingStep procStep = new ProcessingStep();
        ProcessingStepAction procStepAction = new ProcessingStepAction(procStep);
        procStep.setAction(procStepAction);
        uc.getSteps().add(procStep);
        Thread guiThread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    // get context here because it is thread local
                    DynamicContext dynCtx = DynamicContext.getInstance(TR03112Keys.INSTANCE_KEY);
                    if (!uc.getSteps().isEmpty()) {
                        UserConsentNavigator navigator = gui.obtainNavigator(uc);
                        dynCtx.put(TR03112Keys.OPEN_USER_CONSENT_NAVIGATOR, navigator);
                        ExecutionEngine exec = new ExecutionEngine(navigator);
                        ResultStatus guiResult = exec.process();
                        dynCtx.put(EACProtocol.GUI_RESULT, guiResult);
                        if (guiResult == ResultStatus.CANCEL) {
                            Promise<Object> pPaceSuccessful = dynCtx.getPromise(EACProtocol.PACE_EXCEPTION);
                            if (!pPaceSuccessful.isDelivered()) {
                                pPaceSuccessful.deliver(WSHelper.createException(WSHelper.makeResultError(ECardConstants.Minor.SAL.CANCELLATION_BY_USER, "User canceled the PACE dialog.")));
                            }
                        }
                    }
                } finally {
                    if (cardMon != null) {
                        eventDispatcher.del(cardMon);
                    }
                }
            }
        }, "EAC-GUI");
        guiThread.start();
        // wait for PACE to finish
        Promise<Object> pPaceException = dynCtx.getPromise(EACProtocol.PACE_EXCEPTION);
        Object pPaceError = pPaceException.deref();
        if (pPaceError != null) {
            if (pPaceError instanceof WSHelper.WSException) {
                response.setResult(((WSHelper.WSException) pPaceError).getResult());
                return response;
            } else if (pPaceError instanceof DispatcherException | pPaceError instanceof InvocationTargetException) {
                String msg = "Internal error while PACE authentication.";
                Result r = WSHelper.makeResultError(ECardConstants.Minor.App.INT_ERROR, msg);
                response.setResult(r);
                return response;
            } else {
                String msg = "Unknown error while PACE authentication.";
                Result r = WSHelper.makeResultError(ECardConstants.Minor.App.UNKNOWN_ERROR, msg);
                response.setResult(r);
                return response;
            }
        }
        // get challenge from card
        TerminalAuthentication ta = new TerminalAuthentication(dispatcher, slotHandle);
        byte[] challenge = ta.getChallenge();
        // prepare DIDAuthenticationResponse
        DIDAuthenticationDataType data = eacData.paceResponse.getAuthenticationProtocolData();
        AuthDataMap paceOutputMap = new AuthDataMap(data);
        // int retryCounter = Integer.valueOf(paceOutputMap.getContentAsString(PACEOutputType.RETRY_COUNTER));
        byte[] efCardAccess = paceOutputMap.getContentAsBytes(PACEOutputType.EF_CARD_ACCESS);
        byte[] currentCAR = paceOutputMap.getContentAsBytes(PACEOutputType.CURRENT_CAR);
        byte[] previousCAR = paceOutputMap.getContentAsBytes(PACEOutputType.PREVIOUS_CAR);
        byte[] idpicc = paceOutputMap.getContentAsBytes(PACEOutputType.ID_PICC);
        // Store SecurityInfos
        SecurityInfos securityInfos = SecurityInfos.getInstance(efCardAccess);
        internalData.put(EACConstants.IDATA_SECURITY_INFOS, securityInfos);
        // Store additional data
        internalData.put(EACConstants.IDATA_AUTHENTICATED_AUXILIARY_DATA, aad);
        internalData.put(EACConstants.IDATA_CERTIFICATES, certChain);
        internalData.put(EACConstants.IDATA_CURRENT_CAR, currentCAR);
        internalData.put(EACConstants.IDATA_PREVIOUS_CAR, previousCAR);
        internalData.put(EACConstants.IDATA_CHALLENGE, challenge);
        // Create response
        // eac1Output.setRetryCounter(retryCounter);
        eac1Output.setCHAT(eacData.selectedCHAT.toByteArray());
        eac1Output.setCurrentCAR(currentCAR);
        eac1Output.setPreviousCAR(previousCAR);
        eac1Output.setEFCardAccess(efCardAccess);
        eac1Output.setIDPICC(idpicc);
        eac1Output.setChallenge(challenge);
        response.setResult(WSHelper.makeResultOK());
        response.setAuthenticationProtocolData(eac1Output.getAuthDataType());
    } catch (CertificateException ex) {
        LOG.error(ex.getMessage(), ex);
        String msg = ex.getMessage();
        response.setResult(WSHelper.makeResultError(ECardConstants.Minor.SAL.EAC.DOC_VALID_FAILED, msg));
        dynCtx.put(EACProtocol.AUTHENTICATION_FAILED, true);
    } catch (WSHelper.WSException e) {
        LOG.error(e.getMessage(), e);
        response.setResult(e.getResult());
        dynCtx.put(EACProtocol.AUTHENTICATION_FAILED, true);
    } catch (ElementParsingException ex) {
        LOG.error(ex.getMessage(), ex);
        response.setResult(WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, ex.getMessage()));
        dynCtx.put(EACProtocol.AUTHENTICATION_FAILED, true);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        response.setResult(WSHelper.makeResultUnknownError(e.getMessage()));
        dynCtx.put(EACProtocol.AUTHENTICATION_FAILED, true);
    }
    return response;
}
Also used : ConnectionHandleType(iso.std.iso_iec._24727.tech.schema.ConnectionHandleType) PACEMarkerType(org.openecard.sal.protocol.eac.anytype.PACEMarkerType) ProcessingStepAction(org.openecard.sal.protocol.eac.gui.ProcessingStepAction) CertificateException(java.security.cert.CertificateException) CardMonitor(org.openecard.sal.protocol.eac.gui.CardMonitor) UserConsentNavigator(org.openecard.gui.UserConsentNavigator) Result(oasis.names.tc.dss._1_0.core.schema.Result) ObjectValidatorException(org.openecard.common.interfaces.ObjectValidatorException) ObjectSchemaValidator(org.openecard.common.interfaces.ObjectSchemaValidator) UserConsentDescription(org.openecard.gui.definition.UserConsentDescription) DispatcherException(org.openecard.common.interfaces.DispatcherException) DIDAuthenticationDataType(iso.std.iso_iec._24727.tech.schema.DIDAuthenticationDataType) InvocationTargetException(java.lang.reflect.InvocationTargetException) Promise(org.openecard.common.util.Promise) ExecutionEngine(org.openecard.gui.executor.ExecutionEngine) AuthenticatedAuxiliaryData(org.openecard.crypto.common.asn1.eac.AuthenticatedAuxiliaryData) CardVerifiableCertificate(org.openecard.crypto.common.asn1.cvc.CardVerifiableCertificate) AuthDataMap(org.openecard.common.anytype.AuthDataMap) CVCStepAction(org.openecard.sal.protocol.eac.gui.CVCStepAction) DynamicContext(org.openecard.common.DynamicContext) CardRemovedFilter(org.openecard.sal.protocol.eac.gui.CardRemovedFilter) CardStateEntry(org.openecard.common.sal.state.CardStateEntry) CVCStep(org.openecard.sal.protocol.eac.gui.CVCStep) CHAT(org.openecard.crypto.common.asn1.cvc.CHAT) InputAPDUInfoType(iso.std.iso_iec._24727.tech.schema.InputAPDUInfoType) ElementParsingException(org.openecard.sal.protocol.eac.anytype.ElementParsingException) EAC1OutputType(org.openecard.sal.protocol.eac.anytype.EAC1OutputType) CardResponseAPDU(org.openecard.common.apdu.common.CardResponseAPDU) CardVerifiableCertificateChain(org.openecard.crypto.common.asn1.cvc.CardVerifiableCertificateChain) EAC1InputType(org.openecard.sal.protocol.eac.anytype.EAC1InputType) WSHelper(org.openecard.common.WSHelper) DIDAuthenticate(iso.std.iso_iec._24727.tech.schema.DIDAuthenticate) Transmit(iso.std.iso_iec._24727.tech.schema.Transmit) ResultStatus(org.openecard.gui.ResultStatus) SecurityInfos(org.openecard.crypto.common.asn1.eac.SecurityInfos) CertificateDescription(org.openecard.crypto.common.asn1.cvc.CertificateDescription) ProcessingStep(org.openecard.sal.protocol.eac.gui.ProcessingStep) DispatcherException(org.openecard.common.interfaces.DispatcherException) ObjectValidatorException(org.openecard.common.interfaces.ObjectValidatorException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ElementParsingException(org.openecard.sal.protocol.eac.anytype.ElementParsingException) MalformedURLException(java.net.MalformedURLException) CertificateException(java.security.cert.CertificateException) DIDAuthenticateResponse(iso.std.iso_iec._24727.tech.schema.DIDAuthenticateResponse) TransmitResponse(iso.std.iso_iec._24727.tech.schema.TransmitResponse)

Example 7 with CardResponseAPDU

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

the class DIDAuthenticateStep method perform.

@Override
public DIDAuthenticateResponse perform(DIDAuthenticate request, Map<String, Object> internalData) {
    DIDAuthenticateResponse response = WSHelper.makeResponse(DIDAuthenticateResponse.class, WSHelper.makeResultOK());
    char[] rawPIN = null;
    try {
        ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
        String didName = SALUtils.getDIDName(request);
        CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(internalData, connectionHandle);
        PINCompareDIDAuthenticateInputType pinCompareInput = new PINCompareDIDAuthenticateInputType(request.getAuthenticationProtocolData());
        PINCompareDIDAuthenticateOutputType pinCompareOutput = pinCompareInput.getOutputType();
        byte[] cardApplication;
        if (request.getDIDScope() != null && request.getDIDScope().equals(DIDScopeType.GLOBAL)) {
            cardApplication = cardStateEntry.getInfo().getApplicationIdByDidName(request.getDIDName(), request.getDIDScope());
        } else {
            cardApplication = connectionHandle.getCardApplication();
        }
        Assert.securityConditionDID(cardStateEntry, cardApplication, didName, DifferentialIdentityServiceActionName.DID_AUTHENTICATE);
        DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplication);
        PINCompareMarkerType pinCompareMarker = new PINCompareMarkerType(didStructure.getDIDMarker());
        byte keyRef = pinCompareMarker.getPINRef().getKeyRef()[0];
        byte[] slotHandle = connectionHandle.getSlotHandle();
        PasswordAttributesType attributes = pinCompareMarker.getPasswordAttributes();
        rawPIN = pinCompareInput.getPIN();
        // delete pin from memory of the structure
        pinCompareInput.setPIN(null);
        byte[] template = new byte[] { 0x00, 0x20, 0x00, keyRef };
        byte[] responseCode;
        // with [ISO7816-4] (Section 7.5.6).
        if (rawPIN == null || rawPIN.length == 0) {
            VerifyUser verify = new VerifyUser();
            verify.setSlotHandle(slotHandle);
            InputUnitType inputUnit = new InputUnitType();
            verify.setInputUnit(inputUnit);
            PinInputType pinInput = new PinInputType();
            inputUnit.setPinInput(pinInput);
            pinInput.setIndex(BigInteger.ZERO);
            pinInput.setPasswordAttributes(attributes);
            verify.setTemplate(template);
            VerifyUserResponse verifyR = (VerifyUserResponse) dispatcher.safeDeliver(verify);
            WSHelper.checkResult(verifyR);
            responseCode = verifyR.getResponse();
        } else {
            Transmit verifyTransmit = PINUtils.buildVerifyTransmit(rawPIN, attributes, template, slotHandle);
            try {
                TransmitResponse transResp = (TransmitResponse) dispatcher.safeDeliver(verifyTransmit);
                WSHelper.checkResult(transResp);
                responseCode = transResp.getOutputAPDU().get(0);
            } finally {
                // blank PIN APDU
                for (InputAPDUInfoType apdu : verifyTransmit.getInputAPDUInfo()) {
                    byte[] rawApdu = apdu.getInputAPDU();
                    if (rawApdu != null) {
                        java.util.Arrays.fill(rawApdu, (byte) 0);
                    }
                }
            }
        }
        CardResponseAPDU verifyResponseAPDU = new CardResponseAPDU(responseCode);
        if (verifyResponseAPDU.isWarningProcessed()) {
            pinCompareOutput.setRetryCounter(new BigInteger(Integer.toString((verifyResponseAPDU.getSW2() & 0x0F))));
        }
        cardStateEntry.addAuthenticated(didName, cardApplication);
        response.setAuthenticationProtocolData(pinCompareOutput.getAuthDataType());
    } catch (ECardException e) {
        LOG.error(e.getMessage(), e);
        response.setResult(e.getResult());
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        LOG.error(e.getMessage(), e);
        response.setResult(WSHelper.makeResult(e));
    } finally {
        if (rawPIN != null) {
            Arrays.fill(rawPIN, ' ');
        }
    }
    return response;
}
Also used : ConnectionHandleType(iso.std.iso_iec._24727.tech.schema.ConnectionHandleType) CardStateEntry(org.openecard.common.sal.state.CardStateEntry) Transmit(iso.std.iso_iec._24727.tech.schema.Transmit) PasswordAttributesType(iso.std.iso_iec._24727.tech.schema.PasswordAttributesType) VerifyUserResponse(iso.std.iso_iec._24727.tech.schema.VerifyUserResponse) PINCompareMarkerType(org.openecard.common.anytype.pin.PINCompareMarkerType) InputAPDUInfoType(iso.std.iso_iec._24727.tech.schema.InputAPDUInfoType) PINCompareDIDAuthenticateInputType(org.openecard.common.anytype.pin.PINCompareDIDAuthenticateInputType) ECardException(org.openecard.common.ECardException) ECardException(org.openecard.common.ECardException) DIDAuthenticateResponse(iso.std.iso_iec._24727.tech.schema.DIDAuthenticateResponse) InputUnitType(iso.std.iso_iec._24727.tech.schema.InputUnitType) TransmitResponse(iso.std.iso_iec._24727.tech.schema.TransmitResponse) BigInteger(java.math.BigInteger) DIDStructureType(iso.std.iso_iec._24727.tech.schema.DIDStructureType) VerifyUser(iso.std.iso_iec._24727.tech.schema.VerifyUser) CardResponseAPDU(org.openecard.common.apdu.common.CardResponseAPDU) PINCompareDIDAuthenticateOutputType(org.openecard.common.anytype.pin.PINCompareDIDAuthenticateOutputType) PinInputType(iso.std.iso_iec._24727.tech.schema.PinInputType)

Example 8 with CardResponseAPDU

use of org.openecard.common.apdu.common.CardResponseAPDU 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 9 with CardResponseAPDU

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

the class ChipAuthentication method generalAuthenticate.

/**
 * Performs a General Authenticate.
 * Sends an General Authenticate APDU. (Protocol step 2)
 * See BSI-TR-03110, version 2.10, part 3, B.11.2.
 *
 * @param key Ephemeral Public Key
 * @return Response APDU
 * @throws ProtocolException
 */
public byte[] generalAuthenticate(byte[] key) throws ProtocolException {
    try {
        if (key[0] != (byte) 0x04) {
            key = ByteUtils.concatenate((byte) 0x04, key);
        }
        CardCommandAPDU generalAuthenticate = new GeneralAuthenticate((byte) 0x80, key);
        CardResponseAPDU response = generalAuthenticate.transmit(dispatcher, slotHandle);
        return response.getData();
    } catch (APDUException e) {
        throw new ProtocolException(e.getResult());
    }
}
Also used : CardCommandAPDU(org.openecard.common.apdu.common.CardCommandAPDU) ProtocolException(org.openecard.common.sal.protocol.exception.ProtocolException) APDUException(org.openecard.common.apdu.exception.APDUException) CardResponseAPDU(org.openecard.common.apdu.common.CardResponseAPDU) GeneralAuthenticate(org.openecard.common.apdu.GeneralAuthenticate)

Example 10 with CardResponseAPDU

use of org.openecard.common.apdu.common.CardResponseAPDU 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)

Aggregations

CardResponseAPDU (org.openecard.common.apdu.common.CardResponseAPDU)24 CardCommandAPDU (org.openecard.common.apdu.common.CardCommandAPDU)9 ConnectionHandleType (iso.std.iso_iec._24727.tech.schema.ConnectionHandleType)7 CardStateEntry (org.openecard.common.sal.state.CardStateEntry)7 ECardException (org.openecard.common.ECardException)6 APDUException (org.openecard.common.apdu.exception.APDUException)6 Select (org.openecard.common.apdu.Select)5 TLVException (org.openecard.common.tlv.TLVException)4 FCP (org.openecard.common.tlv.iso7816.FCP)4 InputAPDUInfoType (iso.std.iso_iec._24727.tech.schema.InputAPDUInfoType)3 Transmit (iso.std.iso_iec._24727.tech.schema.Transmit)3 TransmitResponse (iso.std.iso_iec._24727.tech.schema.TransmitResponse)3 BigInteger (java.math.BigInteger)3 ArrayList (java.util.ArrayList)3 CardApplicationPathType (iso.std.iso_iec._24727.tech.schema.CardApplicationPathType)2 CardApplicationSelect (iso.std.iso_iec._24727.tech.schema.CardApplicationSelect)2 DIDAuthenticateResponse (iso.std.iso_iec._24727.tech.schema.DIDAuthenticateResponse)2 DIDStructureType (iso.std.iso_iec._24727.tech.schema.DIDStructureType)2 DataSetInfoType (iso.std.iso_iec._24727.tech.schema.DataSetInfoType)2 DataSetSelect (iso.std.iso_iec._24727.tech.schema.DataSetSelect)2