diff --git a/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/IdemiaWithPace.java b/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/IdemiaWithPace.java index 17c6308..0b81da1 100644 --- a/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/IdemiaWithPace.java +++ b/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/IdemiaWithPace.java @@ -6,122 +6,27 @@ import static org.bouncycastle.util.Arrays.concatenate; -import android.annotation.SuppressLint; - -import androidx.annotation.NonNull; - -import org.bouncycastle.crypto.BlockCipher; -import org.bouncycastle.crypto.engines.AESEngine; -import org.bouncycastle.crypto.macs.CMac; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.jce.ECNamedCurveTable; -import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec; -import org.bouncycastle.math.ec.ECPoint; -import org.bouncycastle.math.ec.WNafUtil; -import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.encoders.Hex; import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.security.GeneralSecurityException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; import java.util.Arrays; import java.util.List; -import java.util.Locale; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; import ee.ria.DigiDoc.smartcardreader.ApduResponseException; import ee.ria.DigiDoc.smartcardreader.SmartCardReaderException; -import ee.ria.DigiDoc.smartcardreader.nfc.ApduEncryptor; import ee.ria.DigiDoc.smartcardreader.nfc.NfcSmartCardReader; import ee.ria.DigiDoc.utilsLib.logging.LoggingUtil; /** * IdemiaWithPace extends Idemia APDU protocol with Secure Messaging and PACE capabilities - * enabling the use over NFC. It must implement the ApduEncryptor interface so that - * NfcSmartCardReader class has an oracle to encrypt C-APDUs and decrypt R-APDUs - * so that the Idemia APDU protocol can remain mostly unchanged + * enabling the use over NFC * @noinspection FieldCanBeLocal, SameParameterValue */ -class IdemiaWithPace extends Idemia implements TokenWithPace, ApduEncryptor { +class IdemiaWithPace extends Idemia implements TokenWithPace { private static final String TAG = IdemiaWithPace.class.getName(); - /** - * Last bytes for padding used in establishing encryption key, - * MAC key and nonce decryption key - */ - final private byte PADDING_ENCK = 0x01; - final private byte PADDING_MACK = 0x02; - final private byte PADDING_NONCE_DECRYPTION = 0x03; - - /** - * Padding indicator used in SM - */ - final private byte PADDING_SM = (byte)0x80; - - /** - * CLA, Plain - */ - final private byte CLA_ISO = (byte)0x00; - - /** - * CLA, Plain, command chaining - */ - final private byte CLA_CHAIN = (byte)0x10; - - /** - * INS, General Authenticate - */ - final private byte INS_GA = (byte)0x86; - - /** - * INS, Manage Security Environment - */ - final private byte INS_MSE = (byte)0x22; - - /** - * Supported SM data objects - */ - final private byte DO85 = (byte)0x85; - final private byte DO87 = (byte)0x87; - final private byte DO8E = (byte)0x8E; - final private byte DO97 = (byte) 0x97; - final private byte DO99 = (byte) 0x99; - - /** - * Length of MAC - */ - final private byte MAC_LENGTH = 8; - /** - * Shared encryption key agreed over PACE - */ - private byte[] keyEnc; - - /** - * Shared MAC key agreed over PACE - */ - private byte[] keyMAC; - - /** - * PACE send sequence counter - */ - private final byte[] ssc; - /** - * Block size used in padding secure messages - */ - private final int BLOCK_SIZE = 16; + private static final int PACE_NONCE_BYTES = 32; /** * NfcSmartCardReader to provide the encryption/decryption for @@ -131,9 +36,6 @@ class IdemiaWithPace extends Idemia implements TokenWithPace, ApduEncryptor { protected Byte authKeyRef = (byte) 0x81; protected Byte signKeyRef = (byte) 0x9F; - protected String paceEcSpec; - protected byte paceDomainParam; - /** * Initialize ID1 token with NfcSmartCardReader * @param reader @@ -141,7 +43,6 @@ class IdemiaWithPace extends Idemia implements TokenWithPace, ApduEncryptor { IdemiaWithPace(NfcSmartCardReader reader) { super(reader); nfcReader = reader; - ssc = new byte[BLOCK_SIZE]; } /** @@ -150,23 +51,10 @@ class IdemiaWithPace extends Idemia implements TokenWithPace, ApduEncryptor { * @throws SmartCardReaderException */ public void tunnel(String can) throws SmartCardReaderException { - try { - byte[][] keys = establishPace(can.getBytes(StandardCharsets.UTF_8)); - keyEnc = keys[0]; - keyMAC = keys[1]; - // In case we were successful we notify the card that from now on - // everything is encrypted - nfcReader.setApduEncryptor(this); - } catch (SmartCardReaderException ex) { - if (ex instanceof ApduResponseException aex) { - if ((aex.sw1 == (byte) 0x63) && (aex.sw2 == 0x00)) { - throw new PaceTunnelException(ex); - } - } - throw ex; - } catch (Exception ex) { - throw new SmartCardReaderException("Could not establish tunnel", ex); - } + PaceTunnel.open(nfcReader, () -> { + selectMainAid(); + return readPaceProfileFromCard(); + }, can); } /** @@ -180,18 +68,14 @@ protected void selectMainAid() throws SmartCardReaderException { byte[] data = new byte[] { (byte) 0xA0, 0x00, 0x00, 0x00, 0x77, 0x01, 0x08, 0x00, 0x07, 0x00, 0x00, (byte) 0xFE, 0x00, 0x00, 0x01, 0x00}; - reader.transmit(CLA_ISO, 0xA4, 0x04, 0x0C, data, null); + reader.transmit(0x00, 0xA4, 0x04, 0x0C, data, null); } /** * Read PACE domain parameter and EC curve from EF.CardAccess. * Accessible before PACE, in plaintext. */ - private void readPaceParametersFromCard() throws SmartCardReaderException { - if (paceEcSpec != null) { - return; - } - + private PaceTunnel.Profile readPaceProfileFromCard() throws SmartCardReaderException { reader.transmit(0x00, 0xA4, 0x02, 0x0C, new byte[]{0x01, 0x1C}, null); byte[] cardAccess = readBinaryFile(); byte paramId = parsePaceParameterId(cardAccess); @@ -200,592 +84,24 @@ private void readPaceParametersFromCard() throws SmartCardReaderException { throw new SmartCardReaderException("Failed to read PACE parameters from EF.CardAccess"); } - paceDomainParam = paramId; - paceEcSpec = domainParamToCurveName(paramId); + String curveName = domainParamToCurveName(paramId); - if (paceEcSpec == null) { + if (curveName == null) { throw new SmartCardReaderException( "Unsupported PACE domain parameter: 0x" + Integer.toHexString(paramId & 0xFF) ); } LoggingUtil.Companion.debugLog(TAG, - String.format("PACE parameters read from EF.CardAccess: paramId=0x%02X, curve=%s", paramId, paceEcSpec), + String.format("PACE parameters read from EF.CardAccess: paramId=0x%02X, curve=%s", paramId, curveName), null ); - } - - /** - * Set MSE Authentication Template - * - * @throws SmartCardReaderException - */ - private void setMSEAuthenticationTemplate() throws SmartCardReaderException { - byte[] data = new byte[] { - (byte)0x80, 0x0A, 0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, - 0x02, 0x04, 0x02, 0x04, (byte)0x83, 0x01, 0x02, (byte)0x84, 0x01, paceDomainParam}; - reader.transmit(CLA_ISO, INS_MSE, 0xC1, 0xA4, data, 0x00); - } - - /** - * Get GA Nonce - * @return - * @throws SmartCardReaderException - */ - private byte[] getGAGetNonce() throws SmartCardReaderException { - byte[] data = new byte[] {0x7C, 0x00}; - return reader.transmit(CLA_CHAIN, INS_GA, 0x00, 0x00, data, 0x00); - } - - /** - * GA Map Nonce - * @param publicKey - * @return - * @throws SmartCardReaderException - */ - private byte[] getGAMapNonce(byte[] publicKey) throws SmartCardReaderException { - byte[] prefix = new byte[] {0x7c, 0x43, (byte)0x81, 0x41}; - byte[] data = concatenate(prefix, publicKey); - return reader.transmit(CLA_CHAIN, INS_GA, 0x00, 0x00, data, 0x00); - } - - /** - * GA Key Agreement - * - * @param publicKey - * @return - * @throws SmartCardReaderException - */ - private byte[] getGAKeyAgreement(byte[] publicKey) throws SmartCardReaderException { - byte[] prefix = new byte[] {0x7c, 0x43, (byte)0x83, 0x41}; - byte[] data = concatenate(prefix, publicKey); - return reader.transmit(CLA_CHAIN, INS_GA, 0x00, 0x00, data, 0x00); - } - - /** - * GA Mutual Authentication - * @param mac - * @return - * @throws SmartCardReaderException - */ - private byte[] getGAMutualAuthentication(byte[] mac) throws SmartCardReaderException { - byte[] prefix = new byte[] {0x7C, 0x0A, (byte)0x85, 0x08}; - byte[] data = concatenate(prefix, mac); - return reader.transmit(CLA_ISO, INS_GA, 0x00, 0x00, data, 0x00); - } - - /** - * Get Data for MAC - * @param publicKey - * @return - */ - private byte[] getDataForMac(byte[] publicKey) { - byte[] prefix = new byte[] { - 0x7f, 0x49, 0x4f, 0x06, 0x0a, 0x04, 0x00, 0x7f, - 0x00, 0x07, 0x02, 0x02, 0x04, 0x02, 0x04, (byte)0x86, 0x41}; - return concatenate(prefix, publicKey); - } - - /** - * Creates a cipher key - * - * @param basis the array to be used as the basis for the key - * @param lastByte the last byte in the appended padding - * @return the constructed key - */ - private byte[] createKey(byte[] basis, byte lastByte) throws NoSuchAlgorithmException { - byte[] padding = new byte[] {0x00, 0x00, 0x00, lastByte}; - byte[] padded = concatenate(basis, padding); - MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); - return messageDigest.digest(padded); - } - - /** - * Decrypts the nonce - * - * @param encryptedNonce the encrypted nonce received from the chip - * @param CAN the card access number provided by the user - * @return the decrypted nonce - */ - private byte[] decryptNonce(byte[] encryptedNonce, byte[] CAN) throws - NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, - IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { - byte[] decryptionKey = createKey(CAN, PADDING_NONCE_DECRYPTION); - Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); - cipher.init(Cipher.DECRYPT_MODE, - new SecretKeySpec(decryptionKey, "AES"), - new IvParameterSpec(new byte[BLOCK_SIZE])); - return cipher.doFinal(encryptedNonce); - } - - /** - * Calculates the message authentication code - * - * @param data the byte array on which the CMAC algorithm is performed - * @param keyMAC the key for performing CMAC - * @return MAC - */ - private byte[] getMAC(byte[] data, byte[] keyMAC) { - BlockCipher blockCipher = AESEngine.newInstance(); - CMac cmac = new CMac(blockCipher); - cmac.init(new KeyParameter(keyMAC)); - cmac.update(data, 0, data.length); - byte[] MAC = new byte[cmac.getMacSize()]; - cmac.doFinal(MAC, 0); - return Arrays.copyOf(MAC, MAC_LENGTH); - } - - /** - * Check that response has specific header bytes - * @param header - * @param response - */ - private static void validateHeader(byte[] response, byte[] header) throws - SmartCardReaderException { - - if (header.length > response.length) { - throw new SmartCardReaderException( - "Response length is shorter than expected header length"); - } - - for (int i = 0; i < header.length; i++) { - if (header[i] != response[i]) { - throw new SmartCardReaderException( - "Unexpected byte at index " + i + " in the APDU header"); - } - } - } - - /** - * Assert a response is exactly the expected length. Used after validateHeader - * to catch malformed PACE GA responses early with a clear message, instead of - * surfacing as opaque crypto errors from downstream decode/decrypt steps. - */ - private static void validateResponseLength(byte[] response, int expected, String stage) - throws SmartCardReaderException { - if (response.length != expected) { - throw new SmartCardReaderException( - "Unexpected " + stage + " response length: " + response.length - + " (expected " + expected + ")"); - } - } - - /** - * Generate private key in range [1, N-1] - */ - private static BigInteger generateRandomPrivateKey(ECNamedCurveParameterSpec spec) { - SecureRandom random = new SecureRandom(); - BigInteger n = spec.getN(); - int nBitLength = n.bitLength(); - int minWeight = nBitLength >>> 2; - - BigInteger d; - for (; ; ) { - d = BigIntegers.createRandomBigInteger(nBitLength, random); - - if (isOutOfRangeD(d, n)) { - continue; - } - - if (WNafUtil.getNafWeight(d) < minWeight) { - continue; - } - - break; - } - - return d; - } - - private static boolean isOutOfRangeD(BigInteger d, BigInteger n) { - return d.compareTo(BigInteger.ONE) < 0 || (d.compareTo(n) >= 0); - } - - /** - * PACE Key-Exchange with ID1 - * - * @param can the card access number - */ - private byte[][] establishPace(byte[] can) throws - NoSuchPaddingException, InvalidAlgorithmParameterException, - NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, - InvalidKeyException, SmartCardReaderException { - - selectMainAid(); - - readPaceParametersFromCard(); - setMSEAuthenticationTemplate(); - - byte[] response = getGAGetNonce(); - - byte[] gaGetNonceResponseHeader = new byte[] {0x7C, 0x22, (byte)0x80, 0x20}; - validateHeader(response, gaGetNonceResponseHeader); - // Encrypted nonce is always 32 bytes for the AES-CBC-CMAC-256 PACE variant - // (header byte 0x20 = 32). Catch malformed/truncated responses here so the - // failure surfaces with a clear message rather than as a downstream - // IllegalBlockSizeException from the AES decrypt. - validateResponseLength(response, gaGetNonceResponseHeader.length + 32, "GA Get Nonce"); - byte[] decryptedNonce = decryptNonce( - Arrays.copyOfRange( - response, gaGetNonceResponseHeader.length, response.length), - can); - - // generate an EC keypair and exchange public keys with the chip - ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(paceEcSpec); - - // Uncompressed point encoding: 0x04 || X || Y, both coords curve-sized. - // 65 bytes for the 256-bit curves, 97 bytes for 384-bit. - int pointBytes = 1 + 2 * ((spec.getCurve().getFieldSize() + 7) / 8); - - BigInteger privateKey = generateRandomPrivateKey(spec); - - ECPoint publicKey = spec.getG().multiply(privateKey).normalize(); - response = getGAMapNonce(publicKey.getEncoded(false)); - - // Extract bytes from R-APDU to represent card public key - byte[] gaMapNonceHeader = new byte[] {0x7C, 0x43, (byte)0x82, 0x41}; - validateHeader(response, gaMapNonceHeader); - validateResponseLength(response, gaMapNonceHeader.length + pointBytes, "GA Map Nonce"); - ECPoint cardPublicKey = spec.getCurve().decodePoint( - Arrays.copyOfRange(response, gaMapNonceHeader.length, response.length)); - - // calculate the new base point, use it to generate a new keypair - // and exchange public keys - ECPoint sharedSecret = cardPublicKey.multiply(privateKey); - ECPoint mappedECBasePoint = spec.getG().multiply( - new BigInteger(1, decryptedNonce)).add(sharedSecret).normalize(); - - privateKey = generateRandomPrivateKey(spec); - publicKey = mappedECBasePoint.multiply(privateKey).normalize(); - response = getGAKeyAgreement(publicKey.getEncoded(false)); - - // Extract 65 bytes from R-APDU to represent card public key - byte[] gaKeyAgreementHeader = new byte[] {0x7C, 0x43, (byte)0x84, 0x41}; - validateHeader(response, gaKeyAgreementHeader); - validateResponseLength(response, gaKeyAgreementHeader.length + pointBytes, "GA Key Agreement"); - cardPublicKey = spec.getCurve().decodePoint( - Arrays.copyOfRange(response, gaKeyAgreementHeader.length, response.length)); - - // generate the session keys and exchange MACs to verify them - byte[] secret = cardPublicKey.multiply(privateKey). - normalize().getAffineXCoord().getEncoded(); - - byte[] keyEnc = createKey(secret, PADDING_ENCK); - byte[] keyMAC = createKey(secret, PADDING_MACK); - byte[] MAC = getMAC(getDataForMac(cardPublicKey.getEncoded(false)), keyMAC); - response = getGAMutualAuthentication(MAC); - - byte[] gaMutualAuthenticationHeader = new byte[] {0x7C, 0x0A, (byte)0x86, 0x08}; - validateHeader(response, gaMutualAuthenticationHeader); - validateResponseLength(response, gaMutualAuthenticationHeader.length + MAC_LENGTH, - "GA Mutual Authentication"); - - // verify chip's MAC and return session keys - MAC = getMAC(getDataForMac(publicKey.getEncoded(false)), keyMAC); - byte[] cardMac = Arrays.copyOfRange(response, - gaMutualAuthenticationHeader.length, - gaMutualAuthenticationHeader.length + MAC_LENGTH); - if (!Arrays.equals(cardMac, MAC)) { - throw new SmartCardReaderException("Could not verify chip's MAC."); - } - return new byte[][]{keyEnc, keyMAC}; - - } - - /** - * Encrypt/Decrypt data with the agreed key - * - * @param data - data to be encrypted/decrypted - * @param mode - encrypt or decrypt? - * @return - * @throws NoSuchPaddingException - * @throws NoSuchAlgorithmException - * @throws InvalidKeyException - * @throws BadPaddingException - * @throws IllegalBlockSizeException - * @throws InvalidAlgorithmParameterException - */ - private byte[] encdecData(byte[] data, int mode) throws - NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, - BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { - SecretKeySpec secretKeySpec = new SecretKeySpec(keyEnc, "AES"); - @SuppressLint("GetInstance") Cipher cipher = Cipher.getInstance( - "AES/ECB/PKCS5Padding"); - cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); - byte[] iv = Arrays.copyOf(cipher.doFinal(ssc), BLOCK_SIZE); - cipher = Cipher.getInstance("AES/CBC/NoPadding"); - cipher.init(mode, secretKeySpec, new IvParameterSpec(iv)); - return cipher.doFinal(data); - } - - private byte[] encryptData(byte[] data) throws - NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, - BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { - return encdecData(data, Cipher.ENCRYPT_MODE); - } - - private byte[] decryptData(byte[] data) throws - NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, - BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { - return encdecData(data, Cipher.DECRYPT_MODE); - } - - /** - * Pad data to the block-size with 8000* - * - * @param data - * @param blockSize - * @return - */ - private byte[] pad(byte[] data, int blockSize) { - int padLen = (blockSize - data.length % blockSize); - byte[] result = new byte[data.length + padLen]; - System.arraycopy(data, 0, result, 0, data.length); - result[data.length] = PADDING_SM; - return result; - } - - /** - * Unpad data that has been padded to the block size by 8000* - * - * @param data - * @return - */ - private byte[] unpad(byte[] data) { - for (int i = data.length - 1; i >= 0; i--) { - if (data[i] == PADDING_SM) { - byte[] ret = new byte[i]; - System.arraycopy(data, 0, ret, 0, i); - return ret; - } - } - - return data; - } - - /** - * For Debugging - bouncy does not survive nulls - * @param data - * @return - */ - private String toHexString(byte[] data) { - if (data == null) { - return "NULL"; - } - return Hex.toHexString(data); - } - /** - * Encrypt C-APDU and protect with MAC - * - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param le - * @return - * @throws GeneralSecurityException - */ - public byte[] encryptAndMac(int cla, int ins, int p1, int p2, byte[] data, Integer le) - throws GeneralSecurityException { - LoggingUtil.Companion.debugLog(TAG, String.format("C-APDU to encrypt: 0x%02X 0x%02X 0x%02X 0x%02X", - (byte)cla, (byte)ins, (byte)p1, (byte)p2), null); - - incrementSSC(ssc); - byte[] maskedHeader = new byte[] { - (byte)((byte)cla | 0x0C), (byte) ins, (byte) p1, (byte) p2 }; - byte[] do8587 = getDo8587(ins, data); - byte[] do97 = getDo97(le); - byte[] do8e = getDo8e(maskedHeader, do8587, do97); - - byte newLength = 0; - newLength += (byte) do8587.length; - newLength += (byte) do97.length; - newLength += (byte) do8e.length; - - byte[] result = concatenate(new byte[][] { - maskedHeader, - new byte[] {newLength}, - do8587, - do97, - do8e, - new byte[] {0x00} - }); - incrementSSC(ssc); - LoggingUtil.Companion.debugLog(TAG, String.format("Encrypted C-APDU: %s", toHexString(result)), null); - return result; - } + byte[] mseAuthenticationTemplate = new byte[] { + (byte) 0x80, 0x0A, 0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, + 0x02, 0x04, 0x02, 0x04, (byte) 0x83, 0x01, 0x02, (byte) 0x84, 0x01, paramId}; - /** - * Calculate DO8E object - * - * @param maskedHeader - * @param do8587 - * @param do97 - * @return - */ - @NonNull - private byte[] getDo8e(byte[] maskedHeader, byte[] do8587, byte[] do97) { - byte[] paddedMaskedHeader = pad(maskedHeader, BLOCK_SIZE); - byte[] macData = concatenate(ssc, paddedMaskedHeader, do8587, do97); - byte[] paddedMacData = macData; - if (macData.length % BLOCK_SIZE != 0) { - paddedMacData = pad(macData, BLOCK_SIZE); - } - return concatenate(new byte[] {DO8E, MAC_LENGTH}, getMAC(paddedMacData, keyMAC)); - } - - /** - * Calculate DO97 object - * - * @param le - * @return - */ - @NonNull - private byte[] getDo97(Integer le) { - byte[] do97 = new byte[]{}; - if (le != null) { - do97 = new byte[]{DO97, 0x01, le.byteValue()}; - } - return do97; - } - - /** - * Calculate DO85/DO87 object - * - * @param ins - * @param data - * @return - * @throws NoSuchPaddingException - * @throws NoSuchAlgorithmException - * @throws InvalidKeyException - * @throws BadPaddingException - * @throws IllegalBlockSizeException - * @throws InvalidAlgorithmParameterException - */ - @NonNull - private byte[] getDo8587(int ins, byte[] data) throws - NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, - BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { - byte[] do8587 = new byte[]{}; - - if (data != null && data.length > 0) { - byte[] paddedData; - paddedData = pad(data, BLOCK_SIZE); - byte[] dataEncrypted = encryptData(paddedData); - if (ins % 2 == 0) { - do8587 = concatenate(new byte[]{DO87, (byte) (dataEncrypted.length + 1), 0x01}, - dataEncrypted); - } else { - do8587 = concatenate(new byte[]{DO85, (byte) dataEncrypted.length}, dataEncrypted); - } - } - return do8587; - } - - /** - * Validate R-APDU, check MAC and decrypt data if present. Only return data. - * - * @param response - * @return - * @throws GeneralSecurityException - * @throws SmartCardReaderException - */ - public byte[] decryptAndVerify(byte[] response) throws - GeneralSecurityException, SmartCardReaderException { - - LoggingUtil.Companion.debugLog(TAG, String.format("Encrypted R-APDU: %s", Hex.toHexString(response)), null); - - // result shall be decrypted data or empty - byte[] result = new byte[]{}; - - int currentByte = 0; - if ((response[currentByte] == DO87) || (response[currentByte] == DO85)) { - - boolean skip87header = (response[currentByte] == DO87); - - currentByte += 1; - - int size = response[currentByte] & 0xFF; - LoggingUtil.Companion.debugLog(TAG, String.format(Locale.ENGLISH, "Encrypted data size %d ", size), null); - - currentByte += 1; - - if (size > 0x80) { - int sizeLen = size & 0x0F; - byte[] sizeBytes = new byte[sizeLen]; - System.arraycopy(response, currentByte, sizeBytes, 0, sizeLen); - size = new BigInteger(1, sizeBytes).intValue(); - LoggingUtil.Companion.debugLog(TAG, String.format(Locale.ENGLISH,"size bytes %d, size %d", sizeLen, size), null); - currentByte += sizeLen; - } - - if (skip87header) { - if (response[currentByte] != (byte) 0x01) { - throw new SmartCardReaderException("Invalid encryption header"); - } - currentByte += 1; // skip encryption header - size -= 1; - } - - result = decryptData( - Arrays.copyOfRange(response, currentByte, currentByte + size)); - currentByte += size; - } - - if (response[currentByte] == DO99) { - if (!Hex.toHexString(response, currentByte, 4).equals("99029000")) { - throw new SmartCardReaderException("Invalid status"); - } - currentByte += 4; - } - - int macStart = currentByte; - if (response[currentByte] != DO8E) { - LoggingUtil.Companion.debugLog(TAG, String.format(Locale.ENGLISH, "0x%02X, %d", response[currentByte], currentByte), null); - throw new SmartCardReaderException("Missing MAC"); - } - currentByte += 1; - - if (response[currentByte] != MAC_LENGTH) { - throw new SmartCardReaderException("Unsupported MAC length"); - } - currentByte += 1; - - byte[] cardMac = Arrays.copyOfRange( - response, currentByte, currentByte + MAC_LENGTH); - currentByte += MAC_LENGTH; - - byte[] rdata = Arrays.copyOfRange(response, 0, macStart); - byte[] macData = pad(concatenate(ssc, rdata), BLOCK_SIZE); - byte[] ourMac = getMAC(macData, keyMAC); - LoggingUtil.Companion.debugLog(TAG, String.format("Card MAC: %s, our MAC: %s", - Hex.toHexString(cardMac), Hex.toHexString(ourMac)), null); - - if (!Arrays.equals(cardMac, ourMac)) { - throw new SmartCardReaderException("Could not verify chip's MAC."); - } - - if (response.length - currentByte != 2) { - throw new SmartCardReaderException("Malformed R-APDU"); - } - - LoggingUtil.Companion.debugLog(TAG, String.format("Decrypted data: %s", Hex.toHexString(result)), null); - return unpad(result); - } - - /** - * Increment send sequence counter - * @param ssc - */ - private static void incrementSSC(byte[] ssc) { - for (int i = ssc.length - 1; i >= 0; i--) { - ssc[i]++; - if (ssc[i] != 0) { - break; - } - } + return new PaceTunnel.Profile(curveName, PACE_NONCE_BYTES, 0x00, mseAuthenticationTemplate); } /** diff --git a/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/PaceTunnel.java b/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/PaceTunnel.java new file mode 100644 index 0000000..b56f310 --- /dev/null +++ b/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/PaceTunnel.java @@ -0,0 +1,677 @@ +// SPDX-FileCopyrightText: Estonian Information System Authority +// SPDX-FileCopyrightText: 2026 Stagnation OÜ +// SPDX-License-Identifier: LGPL-2.1-or-later + +package ee.ria.DigiDoc.idcard; + +import static ee.ria.DigiDoc.idcard.TLV.encodeTLV; +import static org.bouncycastle.util.Arrays.concatenate; + +import android.annotation.SuppressLint; + +import androidx.annotation.NonNull; + +import org.bouncycastle.crypto.BlockCipher; +import org.bouncycastle.crypto.engines.AESEngine; +import org.bouncycastle.crypto.macs.CMac; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.jce.ECNamedCurveTable; +import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec; +import org.bouncycastle.math.ec.ECPoint; +import org.bouncycastle.math.ec.WNafUtil; +import org.bouncycastle.util.BigIntegers; +import org.bouncycastle.util.encoders.Hex; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Locale; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import ee.ria.DigiDoc.smartcardreader.ApduResponseException; +import ee.ria.DigiDoc.smartcardreader.SmartCardReader; +import ee.ria.DigiDoc.smartcardreader.SmartCardReaderException; +import ee.ria.DigiDoc.smartcardreader.nfc.ApduEncryptor; +import ee.ria.DigiDoc.smartcardreader.nfc.NfcSmartCardReader; +import ee.ria.DigiDoc.utilsLib.logging.LoggingUtil; + +/** + * PACE key-exchange and Secure Messaging, shared by every card. It must implement the + * ApduEncryptor interface so that NfcSmartCardReader class has an oracle to encrypt + * C-APDUs and decrypt R-APDUs so that each card's APDU protocol can remain mostly + * unchanged + * @noinspection FieldCanBeLocal, SameParameterValue + */ +final class PaceTunnel implements ApduEncryptor { + private static final String TAG = PaceTunnel.class.getName(); + + /** + * Last bytes for padding used in establishing encryption key, + * MAC key and nonce decryption key + */ + private static final byte PADDING_ENCK = 0x01; + private static final byte PADDING_MACK = 0x02; + private static final byte PADDING_NONCE_DECRYPTION = 0x03; + + /** + * Padding indicator used in SM + */ + private static final byte PADDING_SM = (byte) 0x80; + + /** + * CLA, Plain + */ + private static final byte CLA_ISO = (byte) 0x00; + + /** + * CLA, Plain, command chaining + */ + private static final byte CLA_CHAIN = (byte) 0x10; + + /** + * INS, General Authenticate + */ + private static final byte INS_GA = (byte) 0x86; + + /** + * INS, Manage Security Environment + */ + private static final byte INS_MSE = (byte) 0x22; + + /** + * Supported SM data objects + */ + private static final byte DO85 = (byte) 0x85; + private static final byte DO87 = (byte) 0x87; + private static final byte DO8E = (byte) 0x8E; + private static final byte DO97 = (byte) 0x97; + private static final byte DO99 = (byte) 0x99; + + /** + * Length of MAC + */ + private static final byte MAC_LENGTH = 8; + + /** + * Block size used in padding secure messages + */ + private static final int BLOCK_SIZE = 16; + + record Profile(String curveName, int nonceBytes, Integer generalAuthenticateLe, + byte[] mseAuthenticationTemplate) {} + + interface ProfileSource { + Profile resolve() throws SmartCardReaderException; + } + + private final SmartCardReader reader; + private final Profile profile; + + /** + * PACE send sequence counter + */ + private final byte[] ssc = new byte[BLOCK_SIZE]; + + /** + * Shared encryption key agreed over PACE + */ + private byte[] keyEnc; + + /** + * Shared MAC key agreed over PACE + */ + private byte[] keyMAC; + + PaceTunnel(SmartCardReader reader, Profile profile) { + this.reader = reader; + this.profile = profile; + } + + /** + * Start PACE key-exchange with CAN + * @param can + * @throws SmartCardReaderException + */ + static PaceTunnel open(NfcSmartCardReader reader, ProfileSource source, String can) + throws SmartCardReaderException { + try { + PaceTunnel tunnel = new PaceTunnel(reader, source.resolve()); + tunnel.establish(can.getBytes(StandardCharsets.UTF_8)); + // In case we were successful we notify the card that from now on + // everything is encrypted + reader.setApduEncryptor(tunnel); + return tunnel; + } catch (SmartCardReaderException ex) { + if (ex instanceof ApduResponseException aex) { + if ((aex.sw1 == (byte) 0x63) && (aex.sw2 == 0x00)) { + throw new PaceTunnelException(ex); + } + } + throw ex; + } catch (Exception ex) { + throw new SmartCardReaderException("Could not establish tunnel", ex); + } + } + + // ---- handshake ---- + + /** + * PACE Key-Exchange + * + * @param can the card access number + */ + private void establish(byte[] can) throws + NoSuchPaddingException, InvalidAlgorithmParameterException, + NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, + InvalidKeyException, SmartCardReaderException { + + setMSEAuthenticationTemplate(); + + byte[] response = getGAGetNonce(); + + int nonceBytes = profile.nonceBytes(); + byte[] gaGetNonceResponseHeader = new byte[] { + 0x7C, (byte) (2 + nonceBytes), (byte) 0x80, (byte) nonceBytes}; + validateHeader(response, gaGetNonceResponseHeader); + // Catch malformed/truncated responses here so the failure surfaces with a + // clear message rather than as a downstream IllegalBlockSizeException from + // the AES decrypt. + validateResponseLength(response, gaGetNonceResponseHeader.length + nonceBytes, + "GA Get Nonce"); + byte[] decryptedNonce = decryptNonce( + Arrays.copyOfRange( + response, gaGetNonceResponseHeader.length, response.length), + can); + + // generate an EC keypair and exchange public keys with the chip + ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(profile.curveName()); + + // Uncompressed point encoding: 0x04 || X || Y, both coords curve-sized. + // 65 bytes for the 256-bit curves, 97 bytes for 384-bit. + int pointBytes = 1 + 2 * ((spec.getCurve().getFieldSize() + 7) / 8); + + BigInteger privateKey = generateRandomPrivateKey(spec); + + ECPoint publicKey = spec.getG().multiply(privateKey).normalize(); + response = getGAMapNonce(publicKey.getEncoded(false)); + + // Extract bytes from R-APDU to represent card public key + byte[] gaMapNonceHeader = generalAuthenticateHeader((byte) 0x82, pointBytes); + validateHeader(response, gaMapNonceHeader); + validateResponseLength(response, gaMapNonceHeader.length + pointBytes, "GA Map Nonce"); + ECPoint cardPublicKey = spec.getCurve().decodePoint( + Arrays.copyOfRange(response, gaMapNonceHeader.length, response.length)); + + // calculate the new base point, use it to generate a new keypair + // and exchange public keys + ECPoint sharedSecret = cardPublicKey.multiply(privateKey); + ECPoint mappedECBasePoint = spec.getG().multiply( + new BigInteger(1, decryptedNonce)).add(sharedSecret).normalize(); + + privateKey = generateRandomPrivateKey(spec); + publicKey = mappedECBasePoint.multiply(privateKey).normalize(); + response = getGAKeyAgreement(publicKey.getEncoded(false)); + + // Extract the curve-sized point from R-APDU to represent card public key + byte[] gaKeyAgreementHeader = generalAuthenticateHeader((byte) 0x84, pointBytes); + validateHeader(response, gaKeyAgreementHeader); + validateResponseLength(response, gaKeyAgreementHeader.length + pointBytes, + "GA Key Agreement"); + cardPublicKey = spec.getCurve().decodePoint( + Arrays.copyOfRange(response, gaKeyAgreementHeader.length, response.length)); + + // generate the session keys and exchange MACs to verify them + byte[] secret = cardPublicKey.multiply(privateKey). + normalize().getAffineXCoord().getEncoded(); + + keyEnc = createKey(secret, PADDING_ENCK); + keyMAC = createKey(secret, PADDING_MACK); + byte[] MAC = getMAC(getDataForMac(cardPublicKey.getEncoded(false), pointBytes), keyMAC); + response = getGAMutualAuthentication(MAC); + + byte[] gaMutualAuthenticationHeader = generalAuthenticateHeader((byte) 0x86, MAC_LENGTH); + validateHeader(response, gaMutualAuthenticationHeader); + validateResponseLength(response, gaMutualAuthenticationHeader.length + MAC_LENGTH, + "GA Mutual Authentication"); + + // verify chip's MAC + MAC = getMAC(getDataForMac(publicKey.getEncoded(false), pointBytes), keyMAC); + byte[] cardMac = Arrays.copyOfRange(response, + gaMutualAuthenticationHeader.length, + gaMutualAuthenticationHeader.length + MAC_LENGTH); + if (!Arrays.equals(cardMac, MAC)) { + throw new SmartCardReaderException("Could not verify chip's MAC."); + } + } + + private static byte[] generalAuthenticateHeader(byte dataObject, int payloadBytes) { + return new byte[] {0x7C, (byte) (2 + payloadBytes), dataObject, (byte) payloadBytes}; + } + + /** + * Set MSE Authentication Template + */ + private void setMSEAuthenticationTemplate() throws SmartCardReaderException { + reader.transmit(CLA_ISO, INS_MSE, 0xC1, 0xA4, profile.mseAuthenticationTemplate(), 0x00); + } + + /** + * Get GA Nonce + */ + private byte[] getGAGetNonce() throws SmartCardReaderException { + byte[] data = new byte[] {0x7C, 0x00}; + return reader.transmit(CLA_CHAIN, INS_GA, 0x00, 0x00, data, + profile.generalAuthenticateLe()); + } + + /** + * GA Map Nonce + */ + private byte[] getGAMapNonce(byte[] publicKey) throws SmartCardReaderException { + return generalAuthenticate(CLA_CHAIN, (byte) 0x81, publicKey); + } + + /** + * GA Key Agreement + */ + private byte[] getGAKeyAgreement(byte[] publicKey) throws SmartCardReaderException { + return generalAuthenticate(CLA_CHAIN, (byte) 0x83, publicKey); + } + + /** + * GA Mutual Authentication + */ + private byte[] getGAMutualAuthentication(byte[] mac) throws SmartCardReaderException { + return generalAuthenticate(CLA_ISO, (byte) 0x85, mac); + } + + private byte[] generalAuthenticate(byte cla, byte dataObject, byte[] payload) + throws SmartCardReaderException { + byte[] data = encodeTLV(0x7c, encodeTLV(dataObject, payload)); + return reader.transmit(cla, INS_GA, 0x00, 0x00, data, profile.generalAuthenticateLe()); + } + + /** + * Get Data for MAC + */ + private static byte[] getDataForMac(byte[] publicKey, int pointBytes) { + byte[] prefix = new byte[] { + 0x7f, 0x49, (byte) (pointBytes + 14), 0x06, 0x0a, 0x04, 0x00, 0x7f, + 0x00, 0x07, 0x02, 0x02, 0x04, 0x02, 0x04, (byte) 0x86, (byte) pointBytes}; + return concatenate(prefix, publicKey); + } + + /** + * Creates a cipher key + * + * @param basis the array to be used as the basis for the key + * @param lastByte the last byte in the appended padding + * @return the constructed key + */ + private byte[] createKey(byte[] basis, byte lastByte) throws NoSuchAlgorithmException { + byte[] padding = new byte[] {0x00, 0x00, 0x00, lastByte}; + byte[] padded = concatenate(basis, padding); + MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); + return messageDigest.digest(padded); + } + + /** + * Decrypts the nonce + * + * @param encryptedNonce the encrypted nonce received from the chip + * @param CAN the card access number provided by the user + * @return the decrypted nonce + */ + private byte[] decryptNonce(byte[] encryptedNonce, byte[] CAN) throws + NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, + IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { + byte[] decryptionKey = createKey(CAN, PADDING_NONCE_DECRYPTION); + Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, + new SecretKeySpec(decryptionKey, "AES"), + new IvParameterSpec(new byte[BLOCK_SIZE])); + return cipher.doFinal(encryptedNonce); + } + + /** + * Calculates the message authentication code + * + * @param data the byte array on which the CMAC algorithm is performed + * @param keyMAC the key for performing CMAC + * @return MAC + */ + private byte[] getMAC(byte[] data, byte[] keyMAC) { + BlockCipher blockCipher = AESEngine.newInstance(); + CMac cmac = new CMac(blockCipher); + cmac.init(new KeyParameter(keyMAC)); + cmac.update(data, 0, data.length); + byte[] MAC = new byte[cmac.getMacSize()]; + cmac.doFinal(MAC, 0); + return Arrays.copyOf(MAC, MAC_LENGTH); + } + + /** + * Check that response has specific header bytes + */ + private static void validateHeader(byte[] response, byte[] header) throws + SmartCardReaderException { + + if (header.length > response.length) { + throw new SmartCardReaderException( + "Response length is shorter than expected header length"); + } + + for (int i = 0; i < header.length; i++) { + if (header[i] != response[i]) { + throw new SmartCardReaderException( + "Unexpected byte at index " + i + " in the APDU header"); + } + } + } + + /** + * Assert a response is exactly the expected length. Used after validateHeader + * to catch malformed PACE GA responses early with a clear message, instead of + * surfacing as opaque crypto errors from downstream decode/decrypt steps. + */ + private static void validateResponseLength(byte[] response, int expected, String stage) + throws SmartCardReaderException { + if (response.length != expected) { + throw new SmartCardReaderException( + "Unexpected " + stage + " response length: " + response.length + + " (expected " + expected + ")"); + } + } + + /** + * Generate private key in range [1, N-1] + */ + private static BigInteger generateRandomPrivateKey(ECNamedCurveParameterSpec spec) { + SecureRandom random = new SecureRandom(); + BigInteger n = spec.getN(); + int nBitLength = n.bitLength(); + int minWeight = nBitLength >>> 2; + + BigInteger d; + for (; ; ) { + d = BigIntegers.createRandomBigInteger(nBitLength, random); + + if (isOutOfRangeD(d, n)) { + continue; + } + + if (WNafUtil.getNafWeight(d) < minWeight) { + continue; + } + + break; + } + + return d; + } + + private static boolean isOutOfRangeD(BigInteger d, BigInteger n) { + return d.compareTo(BigInteger.ONE) < 0 || (d.compareTo(n) >= 0); + } + + // ---- secure messaging ---- + + /** + * Encrypt/Decrypt data with the agreed key + * + * @param data - data to be encrypted/decrypted + * @param mode - encrypt or decrypt? + */ + private byte[] encdecData(byte[] data, int mode) throws + NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, + BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { + SecretKeySpec secretKeySpec = new SecretKeySpec(keyEnc, "AES"); + @SuppressLint("GetInstance") Cipher cipher = Cipher.getInstance( + "AES/ECB/PKCS5Padding"); + cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); + byte[] iv = Arrays.copyOf(cipher.doFinal(ssc), BLOCK_SIZE); + cipher = Cipher.getInstance("AES/CBC/NoPadding"); + cipher.init(mode, secretKeySpec, new IvParameterSpec(iv)); + return cipher.doFinal(data); + } + + private byte[] encryptData(byte[] data) throws + NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, + BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { + return encdecData(data, Cipher.ENCRYPT_MODE); + } + + private byte[] decryptData(byte[] data) throws + NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, + BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { + return encdecData(data, Cipher.DECRYPT_MODE); + } + + /** + * Pad data to the block-size with 8000* + */ + private byte[] pad(byte[] data, int blockSize) { + int padLen = (blockSize - data.length % blockSize); + byte[] result = new byte[data.length + padLen]; + System.arraycopy(data, 0, result, 0, data.length); + result[data.length] = PADDING_SM; + return result; + } + + /** + * Unpad data that has been padded to the block size by 8000* + */ + private byte[] unpad(byte[] data) { + for (int i = data.length - 1; i >= 0; i--) { + if (data[i] == PADDING_SM) { + byte[] ret = new byte[i]; + System.arraycopy(data, 0, ret, 0, i); + return ret; + } + } + + return data; + } + + /** + * For Debugging - bouncy does not survive nulls + */ + private String toHexString(byte[] data) { + if (data == null) { + return "NULL"; + } + return Hex.toHexString(data); + } + + /** + * Encrypt C-APDU and protect with MAC + */ + public byte[] encryptAndMac(int cla, int ins, int p1, int p2, byte[] data, Integer le) + throws GeneralSecurityException { + LoggingUtil.Companion.debugLog(TAG, String.format("C-APDU to encrypt: 0x%02X 0x%02X 0x%02X 0x%02X", + (byte)cla, (byte)ins, (byte)p1, (byte)p2), null); + + incrementSSC(ssc); + byte[] maskedHeader = new byte[] { + (byte)((byte)cla | 0x0C), (byte) ins, (byte) p1, (byte) p2 }; + byte[] do8587 = getDo8587(ins, data); + byte[] do97 = getDo97(le); + byte[] do8e = getDo8e(maskedHeader, do8587, do97); + + byte newLength = 0; + newLength += (byte) do8587.length; + newLength += (byte) do97.length; + newLength += (byte) do8e.length; + + byte[] result = concatenate(new byte[][] { + maskedHeader, + new byte[] {newLength}, + do8587, + do97, + do8e, + new byte[] {0x00} + }); + incrementSSC(ssc); + LoggingUtil.Companion.debugLog(TAG, String.format("Encrypted C-APDU: %s", toHexString(result)), null); + return result; + } + + /** + * Calculate DO8E object + */ + @NonNull + private byte[] getDo8e(byte[] maskedHeader, byte[] do8587, byte[] do97) { + byte[] paddedMaskedHeader = pad(maskedHeader, BLOCK_SIZE); + byte[] macData = concatenate(ssc, paddedMaskedHeader, do8587, do97); + byte[] paddedMacData = macData; + if (macData.length % BLOCK_SIZE != 0) { + paddedMacData = pad(macData, BLOCK_SIZE); + } + return concatenate(new byte[] {DO8E, MAC_LENGTH}, getMAC(paddedMacData, keyMAC)); + } + + /** + * Calculate DO97 object + */ + @NonNull + private byte[] getDo97(Integer le) { + byte[] do97 = new byte[]{}; + if (le != null) { + do97 = new byte[]{DO97, 0x01, le.byteValue()}; + } + return do97; + } + + /** + * Calculate DO85/DO87 object + */ + @NonNull + private byte[] getDo8587(int ins, byte[] data) throws + NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, + BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { + byte[] do8587 = new byte[]{}; + + if (data != null && data.length > 0) { + byte[] paddedData; + paddedData = pad(data, BLOCK_SIZE); + byte[] dataEncrypted = encryptData(paddedData); + if (ins % 2 == 0) { + do8587 = concatenate(new byte[]{DO87, (byte) (dataEncrypted.length + 1), 0x01}, + dataEncrypted); + } else { + do8587 = concatenate(new byte[]{DO85, (byte) dataEncrypted.length}, dataEncrypted); + } + } + return do8587; + } + + /** + * Validate R-APDU, check MAC and decrypt data if present. Only return data. + */ + public byte[] decryptAndVerify(byte[] response) throws + GeneralSecurityException, SmartCardReaderException { + + LoggingUtil.Companion.debugLog(TAG, String.format("Encrypted R-APDU: %s", Hex.toHexString(response)), null); + + // result shall be decrypted data or empty + byte[] result = new byte[]{}; + + int currentByte = 0; + if ((response[currentByte] == DO87) || (response[currentByte] == DO85)) { + + boolean skip87header = (response[currentByte] == DO87); + + currentByte += 1; + + int size = response[currentByte] & 0xFF; + LoggingUtil.Companion.debugLog(TAG, String.format(Locale.ENGLISH, "Encrypted data size %d ", size), null); + + currentByte += 1; + + if (size > 0x80) { + int sizeLen = size & 0x0F; + byte[] sizeBytes = new byte[sizeLen]; + System.arraycopy(response, currentByte, sizeBytes, 0, sizeLen); + size = new BigInteger(1, sizeBytes).intValue(); + LoggingUtil.Companion.debugLog(TAG, String.format(Locale.ENGLISH,"size bytes %d, size %d", sizeLen, size), null); + currentByte += sizeLen; + } + + if (skip87header) { + if (response[currentByte] != (byte) 0x01) { + throw new SmartCardReaderException("Invalid encryption header"); + } + currentByte += 1; // skip encryption header + size -= 1; + } + + result = decryptData( + Arrays.copyOfRange(response, currentByte, currentByte + size)); + currentByte += size; + } + + if (response[currentByte] == DO99) { + if (!Hex.toHexString(response, currentByte, 4).equals("99029000")) { + throw new SmartCardReaderException("Invalid status"); + } + currentByte += 4; + } + + int macStart = currentByte; + if (response[currentByte] != DO8E) { + LoggingUtil.Companion.debugLog(TAG, String.format(Locale.ENGLISH, "0x%02X, %d", response[currentByte], currentByte), null); + throw new SmartCardReaderException("Missing MAC"); + } + currentByte += 1; + + if (response[currentByte] != MAC_LENGTH) { + throw new SmartCardReaderException("Unsupported MAC length"); + } + currentByte += 1; + + byte[] cardMac = Arrays.copyOfRange( + response, currentByte, currentByte + MAC_LENGTH); + currentByte += MAC_LENGTH; + + byte[] rdata = Arrays.copyOfRange(response, 0, macStart); + byte[] macData = pad(concatenate(ssc, rdata), BLOCK_SIZE); + byte[] ourMac = getMAC(macData, keyMAC); + LoggingUtil.Companion.debugLog(TAG, String.format("Card MAC: %s, our MAC: %s", + Hex.toHexString(cardMac), Hex.toHexString(ourMac)), null); + + if (!Arrays.equals(cardMac, ourMac)) { + throw new SmartCardReaderException("Could not verify chip's MAC."); + } + + if (response.length - currentByte != 2) { + throw new SmartCardReaderException("Malformed R-APDU"); + } + + LoggingUtil.Companion.debugLog(TAG, String.format("Decrypted data: %s", Hex.toHexString(result)), null); + return unpad(result); + } + + /** + * Increment send sequence counter + */ + private static void incrementSSC(byte[] ssc) { + for (int i = ssc.length - 1; i >= 0; i--) { + ssc[i]++; + if (ssc[i] != 0) { + break; + } + } + } +} diff --git a/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/ThalesWithPace.java b/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/ThalesWithPace.java index debb130..bf6f38c 100644 --- a/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/ThalesWithPace.java +++ b/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/ThalesWithPace.java @@ -3,122 +3,23 @@ package ee.ria.DigiDoc.idcard; -import static org.bouncycastle.util.Arrays.concatenate; -import static ee.ria.DigiDoc.idcard.TLV.encodeTLV; - -import android.annotation.SuppressLint; - -import androidx.annotation.NonNull; - -import org.bouncycastle.crypto.BlockCipher; -import org.bouncycastle.crypto.engines.AESEngine; -import org.bouncycastle.crypto.macs.CMac; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.jce.ECNamedCurveTable; -import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec; -import org.bouncycastle.math.ec.ECPoint; -import org.bouncycastle.math.ec.WNafUtil; -import org.bouncycastle.util.BigIntegers; -import org.bouncycastle.util.encoders.Hex; - -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.security.GeneralSecurityException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.Arrays; -import java.util.Locale; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import ee.ria.DigiDoc.smartcardreader.ApduResponseException; import ee.ria.DigiDoc.smartcardreader.SmartCardReaderException; -import ee.ria.DigiDoc.smartcardreader.nfc.ApduEncryptor; import ee.ria.DigiDoc.smartcardreader.nfc.NfcSmartCardReader; -import ee.ria.DigiDoc.utilsLib.logging.LoggingUtil; /** * ThalesWithPace extends Thales APDU protocol with Secure Messaging and PACE capabilities - * enabling the use over NFC. It must implement the ApduEncryptor interface so that - * NfcSmartCardReader class has an oracle to encrypt C-APDUs and decrypt R-APDUs - * so that the Thales APDU protocol can remain mostly unchanged + * enabling the use over NFC * @noinspection FieldCanBeLocal, SameParameterValue */ -class ThalesWithPace extends Thales implements TokenWithPace, ApduEncryptor { - private static final String TAG = ThalesWithPace.class.getName(); - /** - * Last bytes for padding used in establishing encryption key, - * MAC key and nonce decryption key - */ - final private byte PADDING_ENCK = 0x01; - final private byte PADDING_MACK = 0x02; - final private byte PADDING_NONCE_DECRYPTION = 0x03; - - /** - * Padding indicator used in SM - */ - final private byte PADDING_SM = (byte)0x80; - - /** - * CLA, Plain - */ - final private byte CLA_ISO = (byte)0x00; - - /** - * CLA, Plain, command chaining - */ - final private byte CLA_CHAIN = (byte)0x10; - - /** - * INS, General Authenticate - */ - final private byte INS_GA = (byte)0x86; +class ThalesWithPace extends Thales implements TokenWithPace { - /** - * INS, Manage Security Environment - */ - final private byte INS_MSE = (byte)0x22; - - /** - * Supported SM data objects - */ - final private byte DO85 = (byte)0x85; - final private byte DO87 = (byte)0x87; - final private byte DO8E = (byte)0x8E; - final private byte DO97 = (byte) 0x97; - final private byte DO99 = (byte) 0x99; - - /** - * Length of MAC - */ - final private byte MAC_LENGTH = 8; - /** - * Shared encryption key agreed over PACE - */ - private byte[] keyEnc; - - /** - * Shared MAC key agreed over PACE - */ - private byte[] keyMAC; - - /** - * PACE send sequence counter - */ - private final byte[] ssc; - - /** - * Block size used in padding secure messages - */ - private final int BLOCK_SIZE = 16; + private static final PaceTunnel.Profile PACE_PROFILE = new PaceTunnel.Profile( + "brainpoolP384r1", + 16, + 0x100, + new byte[] { + (byte) 0x80, 0x0A, 0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, + 0x02, 0x04, 0x02, 0x04, (byte) 0x83, 0x01, 0x02}); /** * NfcSmartCardReader to provide the encryption/decryption for @@ -126,13 +27,12 @@ class ThalesWithPace extends Thales implements TokenWithPace, ApduEncryptor { private final NfcSmartCardReader nfcReader; /** - * Initialize ID1 token with NfcSmartCardReader + * Initialize Thales token with NfcSmartCardReader * @param reader */ ThalesWithPace(NfcSmartCardReader reader) { super(reader); nfcReader = reader; - ssc = new byte[BLOCK_SIZE]; } /** @@ -141,23 +41,10 @@ class ThalesWithPace extends Thales implements TokenWithPace, ApduEncryptor { * @throws SmartCardReaderException */ public void tunnel(String can) throws SmartCardReaderException { - try { - byte[][] keys = establishPace(can.getBytes(StandardCharsets.UTF_8)); - keyEnc = keys[0]; - keyMAC = keys[1]; - // In case we were successful we notify the card that from now on - // everything is encrypted - nfcReader.setApduEncryptor(this); - } catch (SmartCardReaderException ex) { - if (ex instanceof ApduResponseException aex) { - if ((aex.sw1 == (byte) 0x63) && (aex.sw2 == 0x00)) { - throw new PaceTunnelException(ex); - } - } - throw ex; - } catch (Exception ex) { - throw new SmartCardReaderException("Could not establish tunnel", ex); - } + PaceTunnel.open(nfcReader, () -> { + reader.transmit(0x00, 0xA4, 0x02, 0x0C, new byte[]{0x01, 0x1C}, null); + return PACE_PROFILE; + }, can); selectMainAid(); } @@ -172,547 +59,4 @@ protected void selectMainAid() throws SmartCardReaderException { reader.transmit(0x00, 0xA4, 0x04, 0x0C, new byte[] {(byte)0xA0, 0x00, 0x00, 0x00, 0x63, 0x50, 0x4B, 0x43, 0x53, 0x2D, 0x31, 0x35}, null); // Master AID: A0000000181002030000000000000001 } - - /** - * Set MSE Authentication Template - * - * @throws SmartCardReaderException - */ - private void setMSEAuthenticationTemplate() throws SmartCardReaderException { - byte[] data = new byte[] { - (byte)0x80, 0x0A, 0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, - 0x02, 0x04, 0x02, 0x04, (byte)0x83, 0x01, 0x02}; - reader.transmit(CLA_ISO, INS_MSE, 0xC1, 0xA4, data, 0x00); - } - - /** - * Get GA Nonce - * @return - * @throws SmartCardReaderException - */ - private byte[] getGAGetNonce() throws SmartCardReaderException { - byte[] data = new byte[] {0x7C, 0x00}; - return reader.transmit(CLA_CHAIN, INS_GA, 0x00, 0x00, data, 0x100); - } - - /** - * GA Map Nonce - * @param publicKey - * @return - * @throws SmartCardReaderException - */ - private byte[] getGAMapNonce(byte[] publicKey) throws SmartCardReaderException { - byte[] data = encodeTLV(0x7c, encodeTLV((byte)0x81, publicKey)); - return reader.transmit(CLA_CHAIN, INS_GA, 0x00, 0x00, data, 0x100); - } - - /** - * GA Key Agreement - * - * @param publicKey - * @return - * @throws SmartCardReaderException - */ - private byte[] getGAKeyAgreement(byte[] publicKey) throws SmartCardReaderException { - byte[] data = encodeTLV(0x7c, encodeTLV((byte)0x83, publicKey)); - return reader.transmit(CLA_CHAIN, INS_GA, 0x00, 0x00, data, 0x100); - } - - /** - * GA Mutual Authentication - * @param mac - * @return - * @throws SmartCardReaderException - */ - private byte[] getGAMutualAuthentication(byte[] mac) throws SmartCardReaderException { - byte[] data = encodeTLV(0x7c, encodeTLV((byte)0x85, mac)); - return reader.transmit(CLA_ISO, INS_GA, 0x00, 0x00, data, 0x100); - } - - /** - * Get Data for MAC - * @param publicKey - * @return - */ - private byte[] getDataForMac(byte[] publicKey) { - byte[] prefix = new byte[] { - 0x7f, 0x49, 0x6f, 0x06, 0x0a, 0x04, 0x00, 0x7f, - 0x00, 0x07, 0x02, 0x02, 0x04, 0x02, 0x04, (byte)0x86, 0x61}; - return concatenate(prefix, publicKey); - } - - /** - * Creates a cipher key - * - * @param basis the array to be used as the basis for the key - * @param lastByte the last byte in the appended padding - * @return the constructed key - */ - private byte[] createKey(byte[] basis, byte lastByte) throws NoSuchAlgorithmException { - byte[] padding = new byte[] {0x00, 0x00, 0x00, lastByte}; - byte[] padded = concatenate(basis, padding); - MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); - return messageDigest.digest(padded); - } - - /** - * Decrypts the nonce - * - * @param encryptedNonce the encrypted nonce received from the chip - * @param CAN the card access number provided by the user - * @return the decrypted nonce - */ - private byte[] decryptNonce(byte[] encryptedNonce, byte[] CAN) throws - NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, - IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { - byte[] decryptionKey = createKey(CAN, PADDING_NONCE_DECRYPTION); - Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); - cipher.init(Cipher.DECRYPT_MODE, - new SecretKeySpec(decryptionKey, "AES"), - new IvParameterSpec(new byte[BLOCK_SIZE])); - return cipher.doFinal(encryptedNonce); - } - - /** - * Calculates the message authentication code - * - * @param data the byte array on which the CMAC algorithm is performed - * @param keyMAC the key for performing CMAC - * @return MAC - */ - private byte[] getMAC(byte[] data, byte[] keyMAC) { - BlockCipher blockCipher = AESEngine.newInstance(); - CMac cmac = new CMac(blockCipher); - cmac.init(new KeyParameter(keyMAC)); - cmac.update(data, 0, data.length); - byte[] MAC = new byte[cmac.getMacSize()]; - cmac.doFinal(MAC, 0); - return Arrays.copyOf(MAC, MAC_LENGTH); - } - - /** - * Check that response has specific header bytes - * @param header - * @param response - */ - private static void validateHeader(byte[] response, byte[] header) throws - SmartCardReaderException { - - if (header.length > response.length) { - throw new SmartCardReaderException( - "Response length is shorter than expected header length"); - } - - for (int i = 0; i < header.length; i++) { - if (header[i] != response[i]) { - throw new SmartCardReaderException( - "Unexpected byte at index " + i + " in the APDU header"); - } - } - } - - /** - * Generate private key in range [1, N-1] - */ - private static BigInteger generateRandomPrivateKey(ECNamedCurveParameterSpec spec) { - SecureRandom random = new SecureRandom(); - BigInteger n = spec.getN(); - int nBitLength = n.bitLength(); - int minWeight = nBitLength >>> 2; - - BigInteger d; - for (; ; ) { - d = BigIntegers.createRandomBigInteger(nBitLength, random); - - if (isOutOfRangeD(d, n)) { - continue; - } - - if (WNafUtil.getNafWeight(d) < minWeight) { - continue; - } - - break; - } - - return d; - } - - private static boolean isOutOfRangeD(BigInteger d, BigInteger n) { - return d.compareTo(BigInteger.ONE) < 0 || (d.compareTo(n) >= 0); - } - - /** - * PACE Key-Exchange with Thales - * - * @param can the card access number - */ - private byte[][] establishPace(byte[] can) throws - NoSuchPaddingException, InvalidAlgorithmParameterException, - NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, - InvalidKeyException, SmartCardReaderException { - - // selectMainAid(); - - reader.transmit(CLA_ISO, 0xA4, 0x02, 0x0C, new byte[]{0x01, 0x1C}, null); - - setMSEAuthenticationTemplate(); - - byte[] response = getGAGetNonce(); - - byte[] gaGetNonceResponseHeader = new byte[] {0x7C, 0x12, (byte)0x80, 0x10}; - validateHeader(response, gaGetNonceResponseHeader); - byte[] decryptedNonce = decryptNonce( - Arrays.copyOfRange( - response, gaGetNonceResponseHeader.length, response.length), - can); - - // generate an EC keypair and exchange public keys with the chip - ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("brainpoolP384r1"); - - BigInteger privateKey = generateRandomPrivateKey(spec); - - ECPoint publicKey = spec.getG().multiply(privateKey).normalize(); - response = getGAMapNonce(publicKey.getEncoded(false)); - - // Extract bytes from R-APDU to represent card public key - byte[] gaMapNonceHeader = new byte[] {0x7C, 0x63, (byte)0x82, 0x61}; - validateHeader(response, gaMapNonceHeader); - ECPoint cardPublicKey = spec.getCurve().decodePoint( - Arrays.copyOfRange(response, gaMapNonceHeader.length, response.length)); - - // calculate the new base point, use it to generate a new keypair - // and exchange public keys - ECPoint sharedSecret = cardPublicKey.multiply(privateKey); - ECPoint mappedECBasePoint = spec.getG().multiply( - new BigInteger(1, decryptedNonce)).add(sharedSecret).normalize(); - - privateKey = generateRandomPrivateKey(spec); - publicKey = mappedECBasePoint.multiply(privateKey).normalize(); - response = getGAKeyAgreement(publicKey.getEncoded(false)); - - // Extract 65 bytes from R-APDU to represent card public key - byte[] gaKeyAgreementHeader = new byte[] {0x7C, 0x63, (byte)0x84, 0x61}; - validateHeader(response, gaKeyAgreementHeader); - cardPublicKey = spec.getCurve().decodePoint( - Arrays.copyOfRange(response, gaKeyAgreementHeader.length, response.length)); - - // generate the session keys and exchange MACs to verify them - byte[] secret = cardPublicKey.multiply(privateKey). - normalize().getAffineXCoord().getEncoded(); - - byte[] keyEnc = createKey(secret, PADDING_ENCK); - byte[] keyMAC = createKey(secret, PADDING_MACK); - byte[] MAC = getMAC(getDataForMac(cardPublicKey.getEncoded(false)), keyMAC); - response = getGAMutualAuthentication(MAC); - - byte[] gaMutualAuthenticationHeader = new byte[] {0x7C, 0x0A, (byte)0x86, 0x08}; - validateHeader(response, gaMutualAuthenticationHeader); - - // verify chip's MAC and return session keys - MAC = getMAC(getDataForMac(publicKey.getEncoded(false)), keyMAC); - if (!Hex.toHexString(response, - gaMutualAuthenticationHeader.length, MAC_LENGTH).equals(Hex.toHexString(MAC))) { - throw new SmartCardReaderException("Could not verify chip's MAC."); - } - return new byte[][]{keyEnc, keyMAC}; - } - - /** - * Encrypt/Decrypt data with the agreed key - * - * @param data - data to be encrypted/decrypted - * @param mode - encrypt or decrypt? - * @return - * @throws NoSuchPaddingException - * @throws NoSuchAlgorithmException - * @throws InvalidKeyException - * @throws BadPaddingException - * @throws IllegalBlockSizeException - * @throws InvalidAlgorithmParameterException - */ - private byte[] encdecData(byte[] data, int mode) throws - NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, - BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { - SecretKeySpec secretKeySpec = new SecretKeySpec(keyEnc, "AES"); - @SuppressLint("GetInstance") Cipher cipher = Cipher.getInstance( - "AES/ECB/PKCS5Padding"); - cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); - byte[] iv = Arrays.copyOf(cipher.doFinal(ssc), BLOCK_SIZE); - cipher = Cipher.getInstance("AES/CBC/NoPadding"); - cipher.init(mode, secretKeySpec, new IvParameterSpec(iv)); - return cipher.doFinal(data); - } - - private byte[] encryptData(byte[] data) throws - NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, - BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { - return encdecData(data, Cipher.ENCRYPT_MODE); - } - - private byte[] decryptData(byte[] data) throws - NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, - BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { - return encdecData(data, Cipher.DECRYPT_MODE); - } - - /** - * Pad data to the block-size with 8000* - * - * @param data - * @param blockSize - * @return - */ - private byte[] pad(byte[] data, int blockSize) { - int padLen = (blockSize - data.length % blockSize); - byte[] result = new byte[data.length + padLen]; - System.arraycopy(data, 0, result, 0, data.length); - result[data.length] = PADDING_SM; - return result; - } - - /** - * Unpad data that has been padded to the block size by 8000* - * - * @param data - * @return - */ - private byte[] unpad(byte[] data) { - for (int i = data.length - 1; i >= 0; i--) { - if (data[i] == PADDING_SM) { - byte[] ret = new byte[i]; - System.arraycopy(data, 0, ret, 0, i); - return ret; - } - } - - return data; - } - - /** - * For Debugging - bouncy does not survive nulls - * @param data - * @return - */ - private String toHexString(byte[] data) { - if (data == null) { - return "NULL"; - } - return Hex.toHexString(data); - } - - /** - * Encrypt C-APDU and protect with MAC - * - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param le - * @return - * @throws GeneralSecurityException - */ - public byte[] encryptAndMac(int cla, int ins, int p1, int p2, byte[] data, Integer le) - throws GeneralSecurityException { - LoggingUtil.Companion.debugLog(TAG, String.format("C-APDU to encrypt: 0x%02X 0x%02X 0x%02X 0x%02X", - (byte)cla, (byte)ins, (byte)p1, (byte)p2), null); - - incrementSSC(ssc); - byte[] maskedHeader = new byte[] { - (byte)((byte)cla | 0x0C), (byte) ins, (byte) p1, (byte) p2 }; - byte[] do8587 = getDo8587(ins, data); - byte[] do97 = getDo97(le); - byte[] do8e = getDo8e(maskedHeader, do8587, do97); - - byte newLength = 0; - newLength += (byte) do8587.length; - newLength += (byte) do97.length; - newLength += (byte) do8e.length; - - byte[] result = concatenate(new byte[][] { - maskedHeader, - new byte[] {newLength}, - do8587, - do97, - do8e, - new byte[] {0x00} - }); - incrementSSC(ssc); - LoggingUtil.Companion.debugLog(TAG, String.format("Encrypted C-APDU: %s", toHexString(result)), null); - return result; - } - - /** - * Calculate DO8E object - * - * @param maskedHeader - * @param do8587 - * @param do97 - * @return - */ - @NonNull - private byte[] getDo8e(byte[] maskedHeader, byte[] do8587, byte[] do97) { - byte[] paddedMaskedHeader = pad(maskedHeader, BLOCK_SIZE); - byte[] macData = concatenate(ssc, paddedMaskedHeader, do8587, do97); - byte[] paddedMacData = macData; - if (macData.length % BLOCK_SIZE != 0) { - paddedMacData = pad(macData, BLOCK_SIZE); - } - return concatenate(new byte[] {DO8E, MAC_LENGTH}, getMAC(paddedMacData, keyMAC)); - } - - /** - * Calculate DO97 object - * - * @param le - * @return - */ - @NonNull - private byte[] getDo97(Integer le) { - byte[] do97 = new byte[]{}; - if (le != null) { - do97 = new byte[]{DO97, 0x01, le.byteValue()}; - } - return do97; - } - - /** - * Calculate DO85/DO87 object - * - * @param ins - * @param data - * @return - * @throws NoSuchPaddingException - * @throws NoSuchAlgorithmException - * @throws InvalidKeyException - * @throws BadPaddingException - * @throws IllegalBlockSizeException - * @throws InvalidAlgorithmParameterException - */ - @NonNull - private byte[] getDo8587(int ins, byte[] data) throws - NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, - BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { - byte[] do8587 = new byte[]{}; - - if (data != null && data.length > 0) { - byte[] paddedData; - paddedData = pad(data, BLOCK_SIZE); - byte[] dataEncrypted = encryptData(paddedData); - if (ins % 2 == 0) { - do8587 = concatenate(new byte[]{DO87, (byte) (dataEncrypted.length + 1), 0x01}, - dataEncrypted); - } else { - do8587 = concatenate(new byte[]{DO85, (byte) dataEncrypted.length}, dataEncrypted); - } - } - return do8587; - } - - /** - * Validate R-APDU, check MAC and decrypt data if present. Only return data. - * - * @param response - * @return - * @throws GeneralSecurityException - * @throws SmartCardReaderException - */ - - public byte[] decryptAndVerify(byte[] response) throws - GeneralSecurityException, SmartCardReaderException { - - LoggingUtil.Companion.debugLog(TAG, String.format("Encrypted R-APDU: %s", Hex.toHexString(response)), null); - - // result shall be decrypted data or empty - byte[] result = new byte[]{}; - - int currentByte = 0; - if ((response[currentByte] == DO87) || (response[currentByte] == DO85)) { - - boolean skip87header = (response[currentByte] == DO87); - - currentByte += 1; - - int size = response[currentByte] & 0xFF; - LoggingUtil.Companion.debugLog(TAG, String.format(Locale.ENGLISH, "Encrypted data size %d ", size), null); - - currentByte += 1; - - if (size > 0x80) { - int sizeLen = size & 0x0F; - byte[] sizeBytes = new byte[sizeLen]; - System.arraycopy(response, currentByte, sizeBytes, 0, sizeLen); - size = new BigInteger(1, sizeBytes).intValue(); - LoggingUtil.Companion.debugLog(TAG, String.format(Locale.ENGLISH,"size bytes %d, size %d", sizeLen, size), null); - currentByte += sizeLen; - } - - if (skip87header) { - if (response[currentByte] != (byte) 0x01) { - throw new SmartCardReaderException("Invalid encryption header"); - } - currentByte += 1; // skip encryption header - size -= 1; - } - - result = decryptData( - Arrays.copyOfRange(response, currentByte, currentByte + size)); - currentByte += size; - } - - if (response[currentByte] == DO99) { - if (!Hex.toHexString(response, currentByte, 4).equals("99029000")) { - throw new SmartCardReaderException("Invalid status"); - } - currentByte += 4; - } - - int macStart = currentByte; - if (response[currentByte] != DO8E) { - LoggingUtil.Companion.debugLog(TAG, String.format(Locale.ENGLISH,"0x%02X, %d", response[currentByte], currentByte), null); - throw new SmartCardReaderException("Missing MAC"); - } - currentByte += 1; - - if (response[currentByte] != MAC_LENGTH) { - throw new SmartCardReaderException("Unsupported MAC length"); - } - currentByte += 1; - - byte[] cardMac = Arrays.copyOfRange( - response, currentByte, currentByte + MAC_LENGTH); - currentByte += MAC_LENGTH; - - byte[] rdata = Arrays.copyOfRange(response, 0, macStart); - byte[] macData = pad(concatenate(ssc, rdata), BLOCK_SIZE); - byte[] ourMac = getMAC(macData, keyMAC); - LoggingUtil.Companion.debugLog(TAG, String.format("Card MAC: %s, our MAC: %s", - Hex.toHexString(cardMac), Hex.toHexString(ourMac)), null); - - if (!Hex.toHexString(cardMac).equals(Hex.toHexString(ourMac))) { - throw new RuntimeException("Could not verify chip's MAC."); - } - - if (response.length - currentByte != 2) { - throw new SmartCardReaderException("Malformed R-APDU"); - } - - LoggingUtil.Companion.debugLog(TAG, String.format("Decrypted data: %s", Hex.toHexString(result)), null); - return unpad(result); - } - - /** - * Increment send sequence counter - * @param ssc - */ - public static void incrementSSC(byte[] ssc) { - for (int i = ssc.length - 1; i >= 0; i--) { - ssc[i]++; - if (ssc[i] != 0) { - break; - } - } - } - } diff --git a/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/SecureMessagingHelpersTest.java b/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/SecureMessagingHelpersTest.java index ea188d9..a7e952c 100644 --- a/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/SecureMessagingHelpersTest.java +++ b/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/SecureMessagingHelpersTest.java @@ -19,11 +19,11 @@ import java.math.BigInteger; /** - * Golden-vector tests for the IDEMIA secure-messaging / PACE helpers that + * Golden-vector tests for the shared secure-messaging / PACE helpers that * are pure functions or work off only fields without reaching the * card. The whole point of these tests is to be brittle in the right way: * any refactor that moves these helpers (e.g. into a shared - * AbstractPaceWithSecureMessaging) MUST produce byte-identical output for + * PaceTunnel) MUST produce byte-identical output for * the same inputs, otherwise the wire-level conversation with the chip * changes and PACE breaks. * @@ -35,12 +35,13 @@ */ public final class SecureMessagingHelpersTest { - private IdemiaWithPace token; + private PaceTunnel token; @BeforeEach public void setUp() { // Helpers tested here do not touch the reader. - token = new IdemiaWithPace(mock(NfcSmartCardReader.class)); + token = new PaceTunnel(mock(NfcSmartCardReader.class), + new PaceTunnel.Profile("brainpoolP256r1", 32, 0x00, new byte[0])); } // -------- incrementSSC -------- @@ -261,7 +262,7 @@ public void generateRandomPrivateKey_isInRangeForBrainpoolP256r1() { private Object invoke(String name, Class[] paramTypes, Object... args) { try { - Method m = IdemiaWithPace.class.getDeclaredMethod(name, paramTypes); + Method m = PaceTunnel.class.getDeclaredMethod(name, paramTypes); m.setAccessible(true); return m.invoke(token, args); } catch (InvocationTargetException e) { @@ -275,7 +276,7 @@ private Object invoke(String name, Class[] paramTypes, Object... args) { private void invokeStaticVoid(String name, Class[] paramTypes, Object... args) { try { - Method m = IdemiaWithPace.class.getDeclaredMethod(name, paramTypes); + Method m = PaceTunnel.class.getDeclaredMethod(name, paramTypes); m.setAccessible(true); m.invoke(null, args); } catch (InvocationTargetException e) { @@ -288,7 +289,7 @@ private void invokeStaticVoid(String name, Class[] paramTypes, Object... args private static BigInteger invokeGenerateRandomPrivateKey(ECNamedCurveParameterSpec spec) { try { - Method m = IdemiaWithPace.class.getDeclaredMethod( + Method m = PaceTunnel.class.getDeclaredMethod( "generateRandomPrivateKey", ECNamedCurveParameterSpec.class); m.setAccessible(true); return (BigInteger) m.invoke(null, spec);