rewrite ResponseApdu

This commit is contained in:
Vincent Breitmoser
2017-10-13 16:57:12 +02:00
parent e8103d8376
commit a4af2f7f5c
9 changed files with 151 additions and 278 deletions

View File

@@ -20,7 +20,6 @@ package org.sufficientlysecure.keychain.securitytoken;
import android.nfc.Tag;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import org.sufficientlysecure.keychain.ui.base.BaseSecurityTokenActivity;
import java.io.IOException;
@@ -45,8 +44,8 @@ public class NfcTransport implements Transport {
* @throws IOException
*/
@Override
public ResponseAPDU transceive(final CommandAPDU data) throws IOException {
return new ResponseAPDU(mIsoCard.transceive(data.getBytes()));
public ResponseApdu transceive(final CommandAPDU data) throws IOException {
return ResponseApdu.fromBytes(mIsoCard.transceive(data.getBytes()));
}
/**

View File

@@ -0,0 +1,62 @@
/*
* Copyright (C) 2016 Vincent Breitmoser <look@my.amazin.horse>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sufficientlysecure.keychain.securitytoken;
import java.util.Arrays;
import com.google.auto.value.AutoValue;
/** A response APDU as defined in ISO/IEC 7816-4. */
@AutoValue
public abstract class ResponseApdu {
private static final int APDU_SW_SUCCESS = 0x9000;
public abstract byte[] getData();
public abstract int getSw1();
public abstract int getSw2();
public static ResponseApdu fromBytes(byte[] apdu) {
if (apdu.length < 2) {
throw new IllegalArgumentException("Response apdu must be 2 bytes or larger!");
}
byte[] data = Arrays.copyOfRange(apdu, 0, apdu.length - 2);
int sw1 = apdu[apdu.length -2] & 0xff;
int sw2 = apdu[apdu.length -1] & 0xff;
return new AutoValue_ResponseApdu(data, sw1, sw2);
}
public int getSw() {
return (getSw1() << 8) | getSw2();
}
public boolean isSuccess() {
return getSw() == APDU_SW_SUCCESS;
}
public byte[] toBytes() {
byte[] data = getData();
byte[] bytes = new byte[data.length + 2];
System.arraycopy(data, 0, bytes, 0, data.length);
bytes[bytes.length -2] = (byte) getSw1();
bytes[bytes.length -1] = (byte) getSw2();
return bytes;
}
}

View File

@@ -67,7 +67,6 @@ import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import org.bouncycastle.asn1.nist.NISTNamedCurves;
import org.bouncycastle.asn1.x9.ECNamedCurveTable;
import org.bouncycastle.asn1.x9.X9ECParameters;
@@ -278,7 +277,7 @@ class SCP11bSecureMessaging implements SecureMessaging {
throws SecureMessagingException, IOException {
CommandAPDU cmd;
ResponseAPDU resp;
ResponseApdu resp;
Iso7816TLV[] tlvs;
t.clearSecureMessaging();
@@ -286,7 +285,7 @@ class SCP11bSecureMessaging implements SecureMessaging {
// retrieving key algorithm
cmd = commandFactory.createGetDataCommand(0x00, OPENPGP_SECURE_MESSAGING_KEY_ATTRIBUTES_TAG);
resp = t.communicate(cmd);
if (resp.getSW() != SecurityTokenConnection.APDU_SW_SUCCESS) {
if (!resp.isSuccess()) {
throw new SecureMessagingException("failed to retrieve secure messaging key attributes");
}
tlvs = Iso7816TLV.readList(resp.getData(), true);
@@ -317,12 +316,12 @@ class SCP11bSecureMessaging implements SecureMessaging {
// retrieving certificate
cmd = commandFactory.createSelectSecureMessagingCertificateCommand();
resp = t.communicate(cmd);
if (resp.getSW() != SecurityTokenConnection.APDU_SW_SUCCESS) {
if (!resp.isSuccess()) {
throw new SecureMessagingException("failed to select secure messaging certificate");
}
cmd = commandFactory.createGetDataCardHolderCertCommand();
resp = t.communicate(cmd);
if (resp.getSW() != SecurityTokenConnection.APDU_SW_SUCCESS) {
if (!resp.isSuccess()) {
throw new SecureMessagingException("failed to retrieve secure messaging certificate");
}
@@ -331,7 +330,7 @@ class SCP11bSecureMessaging implements SecureMessaging {
} else {
cmd = commandFactory.createRetrieveSecureMessagingPublicKeyCommand();
resp = t.communicate(cmd);
if (resp.getSW() != SecurityTokenConnection.APDU_SW_SUCCESS) {
if (!resp.isSuccess()) {
throw new SecureMessagingException("failed to retrieve secure messaging public key");
}
tlvs = Iso7816TLV.readList(resp.getData(), true);
@@ -391,7 +390,7 @@ class SCP11bSecureMessaging implements SecureMessaging {
cmd = commandFactory.createInternalAuthForSecureMessagingCommand(pkout.toByteArray());
resp = t.communicate(cmd);
if (resp.getSW() != SecurityTokenConnection.APDU_SW_SUCCESS) {
if (!resp.isSuccess()) {
throw new SecureMessagingException("failed to initiate internal authenticate");
}
@@ -605,7 +604,7 @@ class SCP11bSecureMessaging implements SecureMessaging {
@Override
public ResponseAPDU verifyAndDecrypt(ResponseAPDU apdu)
public ResponseApdu verifyAndDecrypt(ResponseApdu apdu)
throws SecureMessagingException {
if (!isEstablished()) {
@@ -614,10 +613,9 @@ class SCP11bSecureMessaging implements SecureMessaging {
byte[] data = apdu.getData();
if ((data.length == 0) &&
(apdu.getSW() != 0x9000) &&
(apdu.getSW1() != 0x62) &&
(apdu.getSW1() != 0x63)) {
if ((data.length == 0) && !apdu.isSuccess() &&
(apdu.getSw1() != 0x62) &&
(apdu.getSw1() != 0x63)) {
return apdu;
}
@@ -634,8 +632,8 @@ class SCP11bSecureMessaging implements SecureMessaging {
if ((data.length - SCP11_MAC_LENGTH) > 0) {
mac.update(data, 0, data.length - SCP11_MAC_LENGTH);
}
mac.update((byte) apdu.getSW1());
mac.update((byte) apdu.getSW2());
mac.update((byte) apdu.getSw1());
mac.update((byte) apdu.getSw2());
final byte[] sig = mac.doFinal();
@@ -675,19 +673,19 @@ class SCP11bSecureMessaging implements SecureMessaging {
final byte[] datasw = new byte[i + 2];
System.arraycopy(data, 0, datasw, 0, i);
datasw[datasw.length - 2] = (byte) apdu.getSW1();
datasw[datasw.length - 1] = (byte) apdu.getSW2();
datasw[datasw.length - 2] = (byte) apdu.getSw1();
datasw[datasw.length - 1] = (byte) apdu.getSw2();
Arrays.fill(data, (byte) 0);
data = datasw;
} else {
data = new byte[2];
data[0] = (byte) apdu.getSW1();
data[1] = (byte) apdu.getSW2();
data[0] = (byte) apdu.getSw1();
data[1] = (byte) apdu.getSw2();
}
apdu = new ResponseAPDU(data);
apdu = ResponseApdu.fromBytes(data);
return apdu;

View File

@@ -17,10 +17,8 @@
package org.sufficientlysecure.keychain.securitytoken;
import java.io.IOException;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
public interface SecureMessaging {
@@ -30,5 +28,5 @@ public interface SecureMessaging {
CommandAPDU encryptAndSign(CommandAPDU apdu) throws SecureMessagingException;
ResponseAPDU verifyAndDecrypt(ResponseAPDU apdu) throws SecureMessagingException;
ResponseApdu verifyAndDecrypt(ResponseApdu apdu) throws SecureMessagingException;
}

View File

@@ -47,7 +47,6 @@ import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import org.sufficientlysecure.keychain.securitytoken.usb.UsbTransportException;
import org.sufficientlysecure.keychain.util.Log;
@@ -73,7 +72,6 @@ import java.util.List;
* For the full specs, see http://g10code.com/docs/openpgp-card-2.0.pdf
*/
public class SecurityTokenConnection {
static final int APDU_SW_SUCCESS = 0x9000;
private static final int APDU_SW1_RESPONSE_AVAILABLE = 0x61;
// Fidesmo constants
@@ -184,10 +182,10 @@ public class SecurityTokenConnection {
// Connect on smartcard layer
// Command APDU (page 51) for SELECT FILE command (page 29)
CommandAPDU select = commandFactory.createSelectFileOpenPgpCommand();
ResponseAPDU response = communicate(select); // activate connection
ResponseApdu response = communicate(select); // activate connection
if (response.getSW() != APDU_SW_SUCCESS) {
throw new CardException("Initialization failed!", response.getSW());
if (!response.isSuccess()) {
throw new CardException("Initialization failed!", response.getSw());
}
mOpenPgpCapabilities = new OpenPgpCapabilities(getData(0x00, 0x6E));
@@ -221,10 +219,10 @@ public class SecurityTokenConnection {
// Command APDU for RESET RETRY COUNTER command (page 33)
CommandAPDU changePin = commandFactory.createResetPw1Command(newPin);
ResponseAPDU response = communicate(changePin);
ResponseApdu response = communicate(changePin);
if (response.getSW() != APDU_SW_SUCCESS) {
throw new CardException("Failed to change PIN", response.getSW());
if (!response.isSuccess()) {
throw new CardException("Failed to change PIN", response.getSw());
}
}
@@ -246,10 +244,10 @@ public class SecurityTokenConnection {
byte[] pin = adminPin.toStringUnsafe().getBytes();
CommandAPDU changePin = commandFactory.createChangePw3Command(pin, newAdminPin);
ResponseAPDU response = communicate(changePin);
ResponseApdu response = communicate(changePin);
if (response.getSW() != APDU_SW_SUCCESS) {
throw new CardException("Failed to change PIN", response.getSW());
if (!response.isSuccess()) {
throw new CardException("Failed to change PIN", response.getSw());
}
}
@@ -326,10 +324,10 @@ public class SecurityTokenConnection {
}
CommandAPDU command = commandFactory.createDecipherCommand(data);
ResponseAPDU response = communicate(command);
ResponseApdu response = communicate(command);
if (response.getSW() != APDU_SW_SUCCESS) {
throw new CardException("Deciphering with Security token failed on receive", response.getSW());
if (!response.isSuccess()) {
throw new CardException("Deciphering with Security token failed on receive", response.getSw());
}
switch (mOpenPgpCapabilities.getFormatForKeyType(KeyType.ENCRYPT).keyFormatType()) {
@@ -394,9 +392,9 @@ public class SecurityTokenConnection {
private void verifyPinForSignature() throws IOException {
byte[] pin = mPin.toStringUnsafe().getBytes();
ResponseAPDU response = communicate(commandFactory.createVerifyPw1ForSignatureCommand(pin));
if (response.getSW() != APDU_SW_SUCCESS) {
throw new CardException("Bad PIN!", response.getSW());
ResponseApdu response = communicate(commandFactory.createVerifyPw1ForSignatureCommand(pin));
if (!response.isSuccess()) {
throw new CardException("Bad PIN!", response.getSw());
}
mPw1ValidatedForSignature = true;
@@ -409,9 +407,9 @@ public class SecurityTokenConnection {
byte[] pin = mPin.toStringUnsafe().getBytes();
// Command APDU for VERIFY command (page 32)
ResponseAPDU response = communicate(commandFactory.createVerifyPw1ForOtherCommand(pin));
if (response.getSW() != APDU_SW_SUCCESS) {
throw new CardException("Bad PIN!", response.getSW());
ResponseApdu response = communicate(commandFactory.createVerifyPw1ForOtherCommand(pin));
if (!response.isSuccess()) {
throw new CardException("Bad PIN!", response.getSw());
}
mPw1ValidatedForDecrypt = true;
@@ -422,10 +420,10 @@ public class SecurityTokenConnection {
*/
private void verifyAdminPin(Passphrase adminPin) throws IOException {
// Command APDU for VERIFY command (page 32)
ResponseAPDU response =
ResponseApdu response =
communicate(commandFactory.createVerifyPw3Command(adminPin.toStringUnsafe().getBytes()));
if (response.getSW() != APDU_SW_SUCCESS) {
throw new CardException("Bad PIN!", response.getSW());
if (!response.isSuccess()) {
throw new CardException("Bad PIN!", response.getSw());
}
mPw3Validated = true;
@@ -453,10 +451,10 @@ public class SecurityTokenConnection {
}
CommandAPDU command = commandFactory.createPutDataCommand(dataObject, data);
ResponseAPDU response = communicate(command); // put data
ResponseApdu response = communicate(command); // put data
if (response.getSW() != APDU_SW_SUCCESS) {
throw new CardException("Failed to put data.", response.getSW());
if (!response.isSuccess()) {
throw new CardException("Failed to put data.", response.getSw());
}
}
@@ -552,10 +550,10 @@ public class SecurityTokenConnection {
}
CommandAPDU apdu = commandFactory.createPutKeyCommand(keyBytes);
ResponseAPDU response = communicate(apdu);
ResponseApdu response = communicate(apdu);
if (response.getSW() != APDU_SW_SUCCESS) {
throw new CardException("Key export to Security Token failed", response.getSW());
if (!response.isSuccess()) {
throw new CardException("Key export to Security Token failed", response.getSw());
}
}
@@ -567,10 +565,10 @@ public class SecurityTokenConnection {
*/
public byte[] getFingerprints() throws IOException {
CommandAPDU apdu = commandFactory.createGetDataCommand(0x00, 0x6E);
ResponseAPDU response = communicate(apdu);
ResponseApdu response = communicate(apdu);
if (response.getSW() != APDU_SW_SUCCESS) {
throw new CardException("Failed to get fingerprints", response.getSW());
if (!response.isSuccess()) {
throw new CardException("Failed to get fingerprints", response.getSw());
}
Iso7816TLV[] tlvList = Iso7816TLV.readList(response.getData(), true);
@@ -614,9 +612,9 @@ public class SecurityTokenConnection {
}
private byte[] getData(int p1, int p2) throws IOException {
ResponseAPDU response = communicate(commandFactory.createGetDataCommand(p1, p2));
if (response.getSW() != APDU_SW_SUCCESS) {
throw new CardException("Failed to get pw status bytes", response.getSW());
ResponseApdu response = communicate(commandFactory.createGetDataCommand(p1, p2));
if (!response.isSuccess()) {
throw new CardException("Failed to get pw status bytes", response.getSw());
}
return response.getData();
}
@@ -697,10 +695,10 @@ public class SecurityTokenConnection {
// Command APDU for PERFORM SECURITY OPERATION: COMPUTE DIGITAL SIGNATURE (page 37)
CommandAPDU command = commandFactory.createComputeDigitalSignatureCommand(data);
ResponseAPDU response = communicate(command);
ResponseApdu response = communicate(command);
if (response.getSW() != APDU_SW_SUCCESS) {
throw new CardException("Failed to sign", response.getSW());
if (!response.isSuccess()) {
throw new CardException("Failed to sign", response.getSw());
}
if (!mOpenPgpCapabilities.isPw1ValidForMultipleSignatures()) {
@@ -750,7 +748,7 @@ public class SecurityTokenConnection {
* @return response from the card
* @throws IOException
*/
ResponseAPDU communicate(CommandAPDU apdu) throws IOException {
ResponseApdu communicate(CommandAPDU apdu) throws IOException {
if ((mSecureMessaging != null) && mSecureMessaging.isEstablished()) {
try {
apdu = mSecureMessaging.encryptAndSign(apdu);
@@ -760,7 +758,7 @@ public class SecurityTokenConnection {
}
}
ResponseAPDU lastResponse = null;
ResponseApdu lastResponse = null;
// Transmit
if (mCardCapabilities.hasExtended()) {
lastResponse = mTransport.transceive(apdu);
@@ -774,8 +772,8 @@ public class SecurityTokenConnection {
lastResponse = mTransport.transceive(chainedApdu);
boolean isLastCommand = i < totalCommands - 1;
if (isLastCommand && lastResponse.getSW() != APDU_SW_SUCCESS) {
throw new UsbTransportException("Failed to chain apdu (last SW: " + lastResponse.getSW() + ")");
if (isLastCommand && !lastResponse.isSuccess()) {
throw new UsbTransportException("Failed to chain apdu (last SW: " + lastResponse.getSw() + ")");
}
}
}
@@ -787,17 +785,17 @@ public class SecurityTokenConnection {
result.write(lastResponse.getData());
// Receive
while (lastResponse.getSW1() == APDU_SW1_RESPONSE_AVAILABLE) {
while (lastResponse.getSw1() == APDU_SW1_RESPONSE_AVAILABLE) {
// GET RESPONSE ISO/IEC 7816-4 par.7.6.1
CommandAPDU getResponse = commandFactory.createGetResponseCommand(lastResponse.getSW2());
CommandAPDU getResponse = commandFactory.createGetResponseCommand(lastResponse.getSw2());
lastResponse = mTransport.transceive(getResponse);
result.write(lastResponse.getData());
}
result.write(lastResponse.getSW1());
result.write(lastResponse.getSW2());
result.write(lastResponse.getSw1());
result.write(lastResponse.getSw2());
lastResponse = new ResponseAPDU(result.toByteArray());
lastResponse = ResponseApdu.fromBytes(result.toByteArray());
if ((mSecureMessaging != null) && mSecureMessaging.isEstablished()) {
try {
@@ -817,7 +815,7 @@ public class SecurityTokenConnection {
// By trying to select any apps that have the Fidesmo AID prefix we can
// see if it is a Fidesmo device or not
CommandAPDU apdu = commandFactory.createSelectFileCommand(FIDESMO_APPS_AID_PREFIX);
return communicate(apdu).getSW() == APDU_SW_SUCCESS;
return communicate(apdu).isSuccess();
} catch (IOException e) {
Log.e(Constants.TAG, "Card communication failed!", e);
}
@@ -849,9 +847,9 @@ public class SecurityTokenConnection {
}
CommandAPDU apdu = commandFactory.createGenerateKeyCommand(slot);
ResponseAPDU response = communicate(apdu);
ResponseApdu response = communicate(apdu);
if (response.getSW() != APDU_SW_SUCCESS) {
if (!response.isSuccess()) {
throw new IOException("On-card key generation failed");
}
@@ -868,9 +866,9 @@ public class SecurityTokenConnection {
byte[] pin = "XXXXXX".getBytes();
for (int i = 0; i <= 4; i++) {
// Command APDU for VERIFY command (page 32)
ResponseAPDU response = communicate(commandFactory.createVerifyPw1ForSignatureCommand(pin));
if (response.getSW() == APDU_SW_SUCCESS) {
throw new CardException("Should never happen, XXXXXX has been accepted!", response.getSW());
ResponseApdu response = communicate(commandFactory.createVerifyPw1ForSignatureCommand(pin));
if (response.isSuccess()) {
throw new CardException("Should never happen, XXXXXX has been accepted!", response.getSw());
}
}
@@ -878,9 +876,9 @@ public class SecurityTokenConnection {
byte[] adminPin = "XXXXXXXX".getBytes();
for (int i = 0; i <= 4; i++) {
// Command APDU for VERIFY command (page 32)
ResponseAPDU response = communicate(commandFactory.createVerifyPw3Command(adminPin));
if (response.getSW() == APDU_SW_SUCCESS) { // Should NOT accept!
throw new CardException("Should never happen, XXXXXXXX has been accepted", response.getSW());
ResponseApdu response = communicate(commandFactory.createVerifyPw3Command(adminPin));
if (response.isSuccess()) { // Should NOT accept!
throw new CardException("Should never happen, XXXXXXXX has been accepted", response.getSw());
}
}
@@ -892,13 +890,13 @@ public class SecurityTokenConnection {
// If a token is in a bad state and reactivate1 fails, it could still be reactivated with reactivate2
CommandAPDU reactivate1 = commandFactory.createReactivate1Command();
CommandAPDU reactivate2 = commandFactory.createReactivate2Command();
ResponseAPDU response1 = communicate(reactivate1);
ResponseAPDU response2 = communicate(reactivate2);
if (response1.getSW() != APDU_SW_SUCCESS) {
throw new CardException("Reactivating failed!", response1.getSW());
ResponseApdu response1 = communicate(reactivate1);
ResponseApdu response2 = communicate(reactivate2);
if (!response1.isSuccess()) {
throw new CardException("Reactivating failed!", response1.getSw());
}
if (response2.getSW() != APDU_SW_SUCCESS) {
throw new CardException("Reactivating failed!", response2.getSW());
if (!response2.isSuccess()) {
throw new CardException("Reactivating failed!", response2.getSw());
}
}

View File

@@ -18,7 +18,6 @@
package org.sufficientlysecure.keychain.securitytoken;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import java.io.IOException;
@@ -32,7 +31,7 @@ public interface Transport {
* @return received data
* @throws IOException
*/
ResponseAPDU transceive(CommandAPDU data) throws IOException;
ResponseApdu transceive(CommandAPDU data) throws IOException;
/**
* Disconnect and release connection

View File

@@ -30,7 +30,7 @@ import android.util.Pair;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.securitytoken.Transport;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import org.sufficientlysecure.keychain.securitytoken.ResponseApdu;
import org.sufficientlysecure.keychain.securitytoken.usb.tpdu.T1ShortApduProtocol;
import org.sufficientlysecure.keychain.securitytoken.usb.tpdu.T1TpduProtocol;
import org.sufficientlysecure.keychain.util.Log;
@@ -183,8 +183,8 @@ public class UsbTransport implements Transport {
* @return received data
*/
@Override
public ResponseAPDU transceive(CommandAPDU data) throws UsbTransportException {
return new ResponseAPDU(ccidTransportProtocol.transceive(data.getBytes()));
public ResponseApdu transceive(CommandAPDU data) throws UsbTransportException {
return ResponseApdu.fromBytes(ccidTransportProtocol.transceive(data.getBytes()));
}
@Override