Merge pull request #2186 from open-keychain/apdu-refactor

Refactor OpenPGP applet communication code
This commit is contained in:
Dominik Schürmann
2017-10-26 12:26:55 +02:00
committed by GitHub
25 changed files with 1094 additions and 1198 deletions

View File

@@ -21,7 +21,8 @@ import org.sufficientlysecure.keychain.securitytoken.usb.UsbTransportException;
import java.nio.ByteBuffer;
public class CardCapabilities {
@SuppressWarnings("WeakerAccess")
class CardCapabilities {
private static final int MASK_CHAINING = 1 << 7;
private static final int MASK_EXTENDED = 1 << 6;

View File

@@ -0,0 +1,245 @@
/*
* 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 command APDU following the structure defined in ISO/IEC 7816-4.
* It consists of a four byte header and a conditional body of variable length.
*/
@AutoValue
public abstract class CommandApdu {
public abstract int getCLA();
public abstract int getINS();
public abstract int getP1();
public abstract int getP2();
public abstract byte[] getData();
public abstract int getNe();
public static CommandApdu create(byte[] apdu, int apduOffset, int apduLength) {
return fromBytes(Arrays.copyOfRange(apdu, apduOffset, apduOffset + apduLength));
}
public static CommandApdu create(int cla, int ins, int p1, int p2) {
return create(cla, ins, p1, p2, null, 0);
}
public static CommandApdu create(int cla, int ins, int p1, int p2, int ne) {
return create(cla, ins, p1, p2, null, ne);
}
public static CommandApdu create(int cla, int ins, int p1, int p2, byte[] data) {
return create(cla, ins, p1, p2, data, 0);
}
public static CommandApdu create(int cla, int ins, int p1, int p2, byte[] data, int dataOffset, int dataLength) {
if (data != null) {
data = Arrays.copyOfRange(data, dataOffset, dataOffset + dataLength);
}
return create(cla, ins, p1, p2, data, 0);
}
public static CommandApdu create(int cla, int ins, int p1, int p2, byte[] data, int dataOffset, int dataLength,
int ne) {
if (data != null) {
data = Arrays.copyOfRange(data, dataOffset, dataOffset + dataLength);
}
return create(cla, ins, p1, p2, data, ne);
}
public static CommandApdu create(int cla, int ins, int p1, int p2, byte[] data, int ne) {
if (ne < 0) {
throw new IllegalArgumentException("ne must not be negative");
}
if (ne > 65536) {
throw new IllegalArgumentException("ne is too large");
}
if (data == null) {
data = new byte[0];
}
return new AutoValue_CommandApdu(cla, ins, p1, p2, data, ne);
}
public static CommandApdu fromBytes(byte[] apdu, int offset, int length) {
return fromBytes(Arrays.copyOfRange(apdu, offset, offset + length));
}
/**
* Command APDU encoding options:
* <p>
* case 1: |CLA|INS|P1 |P2 | len = 4
* case 2s: |CLA|INS|P1 |P2 |LE | len = 5
* case 3s: |CLA|INS|P1 |P2 |LC |...BODY...| len = 6..260
* case 4s: |CLA|INS|P1 |P2 |LC |...BODY...|LE | len = 7..261
* case 2e: |CLA|INS|P1 |P2 |00 |LE1|LE2| len = 7
* case 3e: |CLA|INS|P1 |P2 |00 |LC1|LC2|...BODY...| len = 8..65542
* case 4e: |CLA|INS|P1 |P2 |00 |LC1|LC2|...BODY...|LE1|LE2| len =10..65544
* <p>
* LE, LE1, LE2 may be 0x00.
* LC must not be 0x00 and LC1|LC2 must not be 0x00|0x00
*/
public static CommandApdu fromBytes(byte[] apdu) {
if (apdu.length < 4) {
throw new IllegalArgumentException("apdu must be at least 4 bytes long");
}
int cla = apdu[0] & 0xff;
int ins = apdu[1] & 0xff;
int p1 = apdu[2] & 0xff;
int p2 = apdu[3] & 0xff;
final Integer dataOffset;
final Integer dataLength;
final int ne;
if (apdu.length == 4) {
// case 1
dataOffset = null;
dataLength = null;
ne = 0;
} else if (apdu.length == 5) {
// case 2s
dataOffset = null;
dataLength = null;
ne = (apdu[4] == 0) ? 256 : (apdu[4] & 0xff);
} else if (apdu[4] != 0) {
dataOffset = 5;
dataLength = apdu[4] & 0xff;
if (apdu.length == 4 + 1 + dataLength) {
// case 3s
ne = 0;
} else {
// case 4s
int l2 = apdu[apdu.length - 1] & 0xff;
ne = (l2 == 0) ? 256 : l2;
}
} else {
int l2 = ((apdu[5] & 0xff) << 8) | (apdu[6] & 0xff);
if (apdu.length == 7) {
// case 2e
dataOffset = null;
dataLength = null;
ne = (l2 == 0) ? 65536 : l2;
} else {
dataOffset = 7;
dataLength = l2;
if (apdu.length == 4 + 3 + l2) {
// case 3e
ne = 0;
} else {
// case 4e
int leOfs = apdu.length - 2;
int le = ((apdu[leOfs] & 0xff) << 8) | (apdu[leOfs + 1] & 0xff);
ne = (le == 0) ? 65536 : le;
}
}
}
byte[] data;
if (dataOffset != null) {
data = Arrays.copyOfRange(apdu, dataOffset, dataOffset + dataLength);
} else {
data = new byte[0];
}
return new AutoValue_CommandApdu(cla, ins, p1, p2, data, ne);
}
public byte[] toBytes() {
final byte[] apdu;
byte[] data = getData();
int ne = getNe();
if (data.length == 0) {
if (ne == 0) {
// case 1
apdu = new byte[4];
} else {
// case 2s or 2e
if (ne <= 256) {
// case 2s
apdu = new byte[5];
apdu[4] = (ne != 256) ? (byte) ne : 0;
} else {
// case 2e
apdu = new byte[7];
if (ne != 65536) {
apdu[5] = (byte) (ne >> 8);
apdu[6] = (byte) ne;
} else {
apdu[5] = 0;
apdu[6] = 0;
}
}
}
} else {
if (ne == 0) {
// case 3s or 3e
if (data.length <= 255) {
// case 3s
apdu = new byte[4 + 1 + data.length];
apdu[4] = (byte) data.length;
System.arraycopy(data, 0, apdu, 5, data.length);
} else {
// case 3e
apdu = new byte[4 + 3 + data.length];
apdu[4] = 0;
apdu[5] = (byte) (data.length >> 8);
apdu[6] = (byte) data.length;
System.arraycopy(data, 0, apdu, 7, data.length);
}
} else {
if (data.length <= 255 && ne <= 256) {
// case 4s
apdu = new byte[4 + 2 + data.length];
apdu[4] = (byte) data.length;
System.arraycopy(data, 0, apdu, 5, data.length);
apdu[apdu.length - 1] = (ne != 256) ? (byte) ne : 0;
} else {
// case 4e
apdu = new byte[4 + 5 + data.length];
apdu[4] = 0;
apdu[5] = (byte) (data.length >> 8);
apdu[6] = (byte) data.length;
System.arraycopy(data, 0, apdu, 7, data.length);
if (ne != 65536) {
apdu[apdu.length - 2] = (byte) (ne >> 8);
apdu[apdu.length - 1] = (byte) ne;
} else {
apdu[apdu.length - 2] = 0;
apdu[apdu.length - 1] = 0;
}
}
}
}
apdu[0] = (byte) getCLA();
apdu[1] = (byte) getINS();
apdu[2] = (byte) getP1();
apdu[3] = (byte) getP2();
return apdu;
}
}

View File

@@ -25,18 +25,18 @@ import org.sufficientlysecure.keychain.ui.CreateSecurityTokenAlgorithmFragment;
public abstract class KeyFormat {
public enum KeyFormatType {
enum KeyFormatType {
RSAKeyFormatType,
ECKeyFormatType
};
}
private final KeyFormatType mKeyFormatType;
public KeyFormat(final KeyFormatType keyFormatType) {
KeyFormat(final KeyFormatType keyFormatType) {
mKeyFormatType = keyFormatType;
}
public final KeyFormatType keyFormatType() {
final KeyFormatType keyFormatType() {
return mKeyFormatType;
}

View File

@@ -18,9 +18,10 @@
package org.sufficientlysecure.keychain.securitytoken;
import android.nfc.Tag;
import android.util.Log;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import org.bouncycastle.util.encoders.Hex;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.ui.base.BaseSecurityTokenActivity;
import java.io.IOException;
@@ -45,8 +46,18 @@ 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 {
byte[] rawCommand = data.toBytes();
if (Constants.DEBUG) {
Log.d(Constants.TAG, "nfc out: " + Hex.toHexString(rawCommand));
}
byte[] rawResponse = mIsoCard.transceive(rawCommand);
if (Constants.DEBUG) {
Log.d(Constants.TAG, "nfc in: " + Hex.toHexString(rawResponse));
}
return ResponseApdu.fromBytes(rawResponse);
}
/**

View File

@@ -21,12 +21,12 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class OpenPgpCapabilities {
@SuppressWarnings("unused") // just expose all included data
class OpenPgpCapabilities {
private final static int MASK_SM = 1 << 7;
private final static int MASK_KEY_IMPORT = 1 << 5;
private final static int MASK_ATTRIBUTES_CHANGABLE = 1 << 2;
private boolean mPw1ValidForMultipleSignatures;
private byte[] mAid;
private byte[] mHistoricalBytes;
@@ -39,13 +39,15 @@ public class OpenPgpCapabilities {
private int mMaxRspLen;
private Map<KeyType, KeyFormat> mKeyFormats;
private byte[] mFingerprints;
private byte[] mPwStatusBytes;
public OpenPgpCapabilities(byte[] data) throws IOException {
OpenPgpCapabilities(byte[] data) throws IOException {
mKeyFormats = new HashMap<>();
updateWithData(data);
}
public void updateWithData(byte[] data) throws IOException {
void updateWithData(byte[] data) throws IOException {
Iso7816TLV[] tlvs = Iso7816TLV.readList(data, true);
if (tlvs.length == 1 && tlvs[0].mT == 0x6E) {
tlvs = ((Iso7816TLV.Iso7816CompositeTLV) tlvs[0]).mSubs;
@@ -75,7 +77,10 @@ public class OpenPgpCapabilities {
mKeyFormats.put(KeyType.AUTH, KeyFormat.fromBytes(tlv.mV));
break;
case 0xC4:
mPw1ValidForMultipleSignatures = tlv.mV[0] == 1;
mPwStatusBytes = tlv.mV;
break;
case 0xC5:
mFingerprints = tlv.mV;
break;
}
}
@@ -97,7 +102,10 @@ public class OpenPgpCapabilities {
mKeyFormats.put(KeyType.AUTH, KeyFormat.fromBytes(tlv.mV));
break;
case 0xC4:
mPw1ValidForMultipleSignatures = tlv.mV[0] == 1;
mPwStatusBytes = tlv.mV;
break;
case 0xC5:
mFingerprints = tlv.mV;
break;
}
}
@@ -114,47 +122,55 @@ public class OpenPgpCapabilities {
mMaxRspLen = (v[8] << 8) + v[9];
}
public boolean isPw1ValidForMultipleSignatures() {
return mPw1ValidForMultipleSignatures;
}
public byte[] getAid() {
byte[] getAid() {
return mAid;
}
public byte[] getHistoricalBytes() {
byte[] getPwStatusBytes() {
return mPwStatusBytes;
}
boolean isPw1ValidForMultipleSignatures() {
return mPwStatusBytes[0] == 1;
}
byte[] getHistoricalBytes() {
return mHistoricalBytes;
}
public boolean isHasSM() {
boolean isHasSM() {
return mHasSM;
}
public boolean isAttributesChangable() {
boolean isAttributesChangable() {
return mAttriburesChangable;
}
public boolean isHasKeyImport() {
boolean isHasKeyImport() {
return mHasKeyImport;
}
public boolean isHasAESSM() {
boolean isHasAESSM() {
return isHasSM() && ((mSMType == 1) || (mSMType == 2));
}
public boolean isHasSCP11bSM() {
boolean isHasSCP11bSM() {
return isHasSM() && (mSMType == 3);
}
public int getMaxCmdLen() {
int getMaxCmdLen() {
return mMaxCmdLen;
}
public int getMaxRspLen() {
int getMaxRspLen() {
return mMaxRspLen;
}
public KeyFormat getFormatForKeyType(KeyType keyType) {
KeyFormat getFormatForKeyType(KeyType keyType) {
return mKeyFormats.get(keyType);
}
public byte[] getFingerprints() {
return mFingerprints;
}
}

View File

@@ -0,0 +1,219 @@
package org.sufficientlysecure.keychain.securitytoken;
import java.util.ArrayList;
import java.util.List;
import android.support.annotation.NonNull;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Hex;
class OpenPgpCommandApduFactory {
private static final int MAX_APDU_NC = 255;
private static final int MAX_APDU_NC_EXT = 65535;
private static final int MAX_APDU_NE = 256;
private static final int MAX_APDU_NE_EXT = 65536;
private static final int CLA = 0x00;
private static final int MASK_CLA_CHAINING = 1 << 4;
private static final int INS_SELECT_FILE = 0xA4;
private static final int P1_SELECT_FILE = 0x04;
private static final byte[] AID_SELECT_FILE_OPENPGP = Hex.decode("D27600012401");
private static final int INS_ACTIVATE_FILE = 0x44;
private static final int INS_TERMINATE_DF = 0xE6;
private static final int INS_GET_RESPONSE = 0xC0;
private static final int INS_INTERNAL_AUTHENTICATE = 0x88;
private static final int P1_INTERNAL_AUTH_SECURE_MESSAGING = 0x01;
private static final int INS_VERIFY = 0x20;
private static final int P2_VERIFY_PW1_SIGN = 0x81;
private static final int P2_VERIFY_PW1_OTHER = 0x82;
private static final int P2_VERIFY_PW3 = 0x83;
private static final int INS_CHANGE_REFERENCE_DATA = 0x24;
private static final int P2_CHANGE_REFERENCE_DATA_PW1 = 0x81;
private static final int P2_CHANGE_REFERENCE_DATA_PW3 = 0x83;
private static final int INS_RESET_RETRY_COUNTER = 0x2C;
private static final int P1_RESET_RETRY_COUNTER_NEW_PW = 0x02;
private static final int P2_RESET_RETRY_COUNTER = 0x81;
private static final int INS_PERFORM_SECURITY_OPERATION = 0x2A;
private static final int P1_PSO_DECIPHER = 0x80;
private static final int P1_PSO_COMPUTE_DIGITAL_SIGNATURE = 0x9E;
private static final int P2_PSO_DECIPHER = 0x86;
private static final int P2_PSO_COMPUTE_DIGITAL_SIGNATURE = 0x9A;
private static final int INS_SELECT_DATA = 0xA5;
private static final int P1_SELECT_DATA_FOURTH = 0x03;
private static final int P2_SELECT_DATA = 0x04;
private static final byte[] CP_SELECT_DATA_CARD_HOLDER_CERT = Hex.decode("60045C027F21");
private static final int INS_GET_DATA = 0xCA;
private static final int P1_GET_DATA_CARD_HOLDER_CERT = 0x7F;
private static final int P2_GET_DATA_CARD_HOLDER_CERT = 0x21;
private static final int INS_PUT_DATA = 0xDA;
private static final int INS_PUT_DATA_ODD = 0xDB;
private static final int P1_PUT_DATA_ODD_KEY = 0x3F;
private static final int P2_PUT_DATA_ODD_KEY = 0xFF;
private static final int INS_GENERATE_ASYMMETRIC_KEY_PAIR = 0x47;
private static final int P1_GAKP_GENERATE = 0x80;
private static final int P1_GAKP_READ_PUBKEY_TEMPLATE = 0x81;
private static final byte[] CRT_GAKP_SECURE_MESSAGING = Hex.decode("A600");
private static final int P1_EMPTY = 0x00;
private static final int P2_EMPTY = 0x00;
@NonNull
CommandApdu createPutDataCommand(int dataObject, byte[] data) {
return CommandApdu.create(CLA, INS_PUT_DATA, (dataObject & 0xFF00) >> 8, dataObject & 0xFF, data);
}
@NonNull
CommandApdu createPutKeyCommand(byte[] keyBytes) {
// the odd PUT DATA INS is for compliance with ISO 7816-8. This is used only to put key data on the card
return CommandApdu.create(CLA, INS_PUT_DATA_ODD, P1_PUT_DATA_ODD_KEY, P2_PUT_DATA_ODD_KEY, keyBytes);
}
@NonNull
CommandApdu createComputeDigitalSignatureCommand(byte[] data) {
return CommandApdu.create(CLA, INS_PERFORM_SECURITY_OPERATION, P1_PSO_COMPUTE_DIGITAL_SIGNATURE,
P2_PSO_COMPUTE_DIGITAL_SIGNATURE, data, MAX_APDU_NE_EXT);
}
@NonNull
CommandApdu createDecipherCommand(byte[] data) {
return CommandApdu.create(CLA, INS_PERFORM_SECURITY_OPERATION, P1_PSO_DECIPHER, P2_PSO_DECIPHER, data,
MAX_APDU_NE_EXT);
}
@NonNull
CommandApdu createChangePw3Command(byte[] adminPin, byte[] newAdminPin) {
return CommandApdu.create(CLA, INS_CHANGE_REFERENCE_DATA, P1_EMPTY,
P2_CHANGE_REFERENCE_DATA_PW3, Arrays.concatenate(adminPin, newAdminPin));
}
@NonNull
CommandApdu createResetPw1Command(byte[] newPin) {
return CommandApdu.create(CLA, INS_RESET_RETRY_COUNTER, P1_RESET_RETRY_COUNTER_NEW_PW,
P2_RESET_RETRY_COUNTER, newPin);
}
@NonNull
CommandApdu createGetDataCommand(int p1, int p2) {
return CommandApdu.create(CLA, INS_GET_DATA, p1, p2, MAX_APDU_NE_EXT);
}
@NonNull
CommandApdu createGetResponseCommand(int lastResponseSw2) {
return CommandApdu.create(CLA, INS_GET_RESPONSE, P1_EMPTY, P2_EMPTY, lastResponseSw2);
}
@NonNull
CommandApdu createVerifyPw1ForSignatureCommand(byte[] pin) {
return CommandApdu.create(CLA, INS_VERIFY, P1_EMPTY, P2_VERIFY_PW1_SIGN, pin);
}
@NonNull
CommandApdu createVerifyPw1ForOtherCommand(byte[] pin) {
return CommandApdu.create(CLA, INS_VERIFY, P1_EMPTY, P2_VERIFY_PW1_OTHER, pin);
}
@NonNull
CommandApdu createVerifyPw3Command(byte[] pin) {
return CommandApdu.create(CLA, INS_VERIFY, P1_EMPTY, P2_VERIFY_PW3, pin);
}
@NonNull
CommandApdu createSelectFileOpenPgpCommand() {
return CommandApdu.create(CLA, INS_SELECT_FILE, P1_SELECT_FILE, P2_EMPTY, AID_SELECT_FILE_OPENPGP);
}
@NonNull
CommandApdu createSelectFileCommand(String fileAid) {
return CommandApdu.create(CLA, INS_SELECT_FILE, P1_SELECT_FILE, P2_EMPTY, Hex.decode(fileAid));
}
@NonNull
CommandApdu createReactivate2Command() {
return CommandApdu.create(CLA, INS_ACTIVATE_FILE, P1_EMPTY, P2_EMPTY);
}
@NonNull
CommandApdu createReactivate1Command() {
return CommandApdu.create(CLA, INS_TERMINATE_DF, P1_EMPTY, P2_EMPTY);
}
@NonNull
CommandApdu createInternalAuthForSecureMessagingCommand(byte[] authData) {
return CommandApdu.create(CLA, INS_INTERNAL_AUTHENTICATE, P1_INTERNAL_AUTH_SECURE_MESSAGING, P2_EMPTY, authData,
MAX_APDU_NE_EXT);
}
@NonNull
CommandApdu createGenerateKeyCommand(int slot) {
return CommandApdu.create(CLA, INS_GENERATE_ASYMMETRIC_KEY_PAIR,
P1_GAKP_GENERATE, P2_EMPTY, new byte[] { (byte) slot, 0x00 }, MAX_APDU_NE_EXT);
}
@NonNull
CommandApdu createRetrieveSecureMessagingPublicKeyCommand() {
// see https://github.com/ANSSI-FR/SmartPGP/blob/master/secure_messaging/smartpgp_sm.pdf
return CommandApdu.create(CLA, INS_GENERATE_ASYMMETRIC_KEY_PAIR, P1_GAKP_READ_PUBKEY_TEMPLATE, P2_EMPTY,
CRT_GAKP_SECURE_MESSAGING, MAX_APDU_NE_EXT);
}
@NonNull
CommandApdu createSelectSecureMessagingCertificateCommand() {
// see https://github.com/ANSSI-FR/SmartPGP/blob/master/secure_messaging/smartpgp_sm.pdf
// this command selects the fourth occurence of data tag 7F21
return CommandApdu.create(CLA, INS_SELECT_DATA, P1_SELECT_DATA_FOURTH, P2_SELECT_DATA,
CP_SELECT_DATA_CARD_HOLDER_CERT);
}
@NonNull
CommandApdu createGetDataCardHolderCertCommand() {
return createGetDataCommand(P1_GET_DATA_CARD_HOLDER_CERT, P2_GET_DATA_CARD_HOLDER_CERT);
}
@NonNull
CommandApdu createShortApdu(CommandApdu apdu) {
int ne = Math.min(apdu.getNe(), MAX_APDU_NE);
return CommandApdu.create(apdu.getCLA(), apdu.getINS(), apdu.getP1(), apdu.getP2(), apdu.getData(), ne);
}
@NonNull
List<CommandApdu> createChainedApdus(CommandApdu apdu) {
ArrayList<CommandApdu> result = new ArrayList<>();
int offset = 0;
byte[] data = apdu.getData();
int ne = Math.min(apdu.getNe(), MAX_APDU_NE);
while (offset < data.length) {
int curLen = Math.min(MAX_APDU_NC, data.length - offset);
boolean last = offset + curLen >= data.length;
int cla = apdu.getCLA() + (last ? 0 : MASK_CLA_CHAINING);
CommandApdu cmd =
CommandApdu.create(cla, apdu.getINS(), apdu.getP1(), apdu.getP2(), data, offset, curLen, ne);
result.add(cmd);
offset += curLen;
}
return result;
}
boolean isSuitableForShortApdu(CommandApdu apdu) {
return apdu.getData().length <= MAX_APDU_NC;
}
}

View File

@@ -0,0 +1,63 @@
/*
* 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
@SuppressWarnings("WeakerAccess")
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

@@ -17,17 +17,6 @@
package org.sufficientlysecure.keychain.securitytoken;
import android.content.Context;
import android.support.annotation.NonNull;
import org.bouncycastle.asn1.nist.NISTNamedCurves;
import org.bouncycastle.asn1.x9.ECNamedCurveTable;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.Arrays;
import org.sufficientlysecure.keychain.ui.SettingsSmartPGPAuthoritiesActivity;
import org.sufficientlysecure.keychain.util.Preferences;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -65,6 +54,9 @@ import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.util.ArrayList;
import android.content.Context;
import android.support.annotation.NonNull;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
@@ -74,14 +66,19 @@ import javax.crypto.NoSuchPaddingException;
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;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.Arrays;
import org.sufficientlysecure.keychain.ui.SettingsSmartPGPAuthoritiesActivity;
import org.sufficientlysecure.keychain.util.Preferences;
class SCP11bSecureMessaging implements SecureMessaging {
private static final byte OPENPGP_SECURE_MESSAGING_CLA_MASK = (byte)0x04;
private static final byte[] OPENPGP_SECURE_MESSAGING_KEY_CRT = new byte[] { (byte)0xA6, (byte)0 };
private static final byte OPENPGP_SECURE_MESSAGING_KEY_ATTRIBUTES_TAG = (byte)0xD4;
private static final int AES_BLOCK_SIZE = 128 / 8;
@@ -152,7 +149,7 @@ class SCP11bSecureMessaging implements SecureMessaging {
&& (mMacChaining != null);
}
private static final ECParameterSpec getAlgorithmParameterSpec(final ECKeyFormat kf)
private static ECParameterSpec getAlgorithmParameterSpec(final ECKeyFormat kf)
throws NoSuchProviderException, NoSuchAlgorithmException, InvalidParameterSpecException {
final AlgorithmParameters algoParams = AlgorithmParameters.getInstance(SCP11B_KEY_AGREEMENT_KEY_ALGO, PROVIDER);
@@ -275,20 +272,19 @@ class SCP11bSecureMessaging implements SecureMessaging {
}
public static void establish(final SecurityTokenHelper t, final Context ctx)
static void establish(final SecurityTokenConnection t, final Context ctx, OpenPgpCommandApduFactory commandFactory)
throws SecureMessagingException, IOException {
CommandAPDU cmd;
ResponseAPDU resp;
CommandApdu cmd;
ResponseApdu resp;
Iso7816TLV[] tlvs;
t.clearSecureMessaging();
// retrieving key algorithm
cmd = new CommandAPDU(0, (byte)0xCA, (byte)0x00,
OPENPGP_SECURE_MESSAGING_KEY_ATTRIBUTES_TAG, SecurityTokenHelper.MAX_APDU_NE_EXT);
cmd = commandFactory.createGetDataCommand(0x00, OPENPGP_SECURE_MESSAGING_KEY_ATTRIBUTES_TAG);
resp = t.communicate(cmd);
if (resp.getSW() != SecurityTokenHelper.APDU_SW_SUCCESS) {
if (!resp.isSuccess()) {
throw new SecureMessagingException("failed to retrieve secure messaging key attributes");
}
tlvs = Iso7816TLV.readList(resp.getData(), true);
@@ -317,26 +313,23 @@ class SCP11bSecureMessaging implements SecureMessaging {
if (prefs != null && prefs.getExperimentalSmartPGPAuthoritiesEnable()) {
// retrieving certificate
cmd = new CommandAPDU(0, (byte) 0xA5, (byte) 0x03, (byte) 0x04,
new byte[]{(byte) 0x60, (byte) 0x04, (byte) 0x5C, (byte) 0x02, (byte) 0x7F, (byte) 0x21});
cmd = commandFactory.createSelectSecureMessagingCertificateCommand();
resp = t.communicate(cmd);
if (resp.getSW() != SecurityTokenHelper.APDU_SW_SUCCESS) {
if (!resp.isSuccess()) {
throw new SecureMessagingException("failed to select secure messaging certificate");
}
cmd = new CommandAPDU(0, (byte) 0xCA, (byte) 0x7F, (byte) 0x21, SecurityTokenHelper.MAX_APDU_NE_EXT);
cmd = commandFactory.createGetDataCardHolderCertCommand();
resp = t.communicate(cmd);
if (resp.getSW() != SecurityTokenHelper.APDU_SW_SUCCESS) {
if (!resp.isSuccess()) {
throw new SecureMessagingException("failed to retrieve secure messaging certificate");
}
pkcard = verifyCertificate(ctx, eckf, resp.getData());
} else {
// retrieving public key
cmd = new CommandAPDU(0, (byte) 0x47, (byte) 0x81, (byte) 0x00,
OPENPGP_SECURE_MESSAGING_KEY_CRT, SecurityTokenHelper.MAX_APDU_NE_EXT);
cmd = commandFactory.createRetrieveSecureMessagingPublicKeyCommand();
resp = t.communicate(cmd);
if (resp.getSW() != SecurityTokenHelper.APDU_SW_SUCCESS) {
if (!resp.isSuccess()) {
throw new SecureMessagingException("failed to retrieve secure messaging public key");
}
tlvs = Iso7816TLV.readList(resp.getData(), true);
@@ -394,11 +387,9 @@ class SCP11bSecureMessaging implements SecureMessaging {
pkout.writeTo(bout);
pkout = bout;
// internal authenticate
cmd = new CommandAPDU(0, (byte)0x88, (byte)0x01, (byte)0x0, pkout.toByteArray(),
SecurityTokenHelper.MAX_APDU_NE_EXT);
cmd = commandFactory.createInternalAuthForSecureMessagingCommand(pkout.toByteArray());
resp = t.communicate(cmd);
if (resp.getSW() != SecurityTokenHelper.APDU_SW_SUCCESS) {
if (!resp.isSuccess()) {
throw new SecureMessagingException("failed to initiate internal authenticate");
}
@@ -509,7 +500,7 @@ class SCP11bSecureMessaging implements SecureMessaging {
@Override
public CommandAPDU encryptAndSign(CommandAPDU apdu)
public CommandApdu encryptAndSign(CommandApdu apdu)
throws SecureMessagingException {
if (!isEstablished()) {
@@ -587,7 +578,7 @@ class SCP11bSecureMessaging implements SecureMessaging {
}
odata[ooff++] = (byte) 0;
apdu = new CommandAPDU(odata, 0, ooff);
apdu = CommandApdu.fromBytes(odata, 0, ooff);
Arrays.fill(odata, (byte)0);
@@ -612,7 +603,7 @@ class SCP11bSecureMessaging implements SecureMessaging {
@Override
public ResponseAPDU verifyAndDecrypt(ResponseAPDU apdu)
public ResponseApdu verifyAndDecrypt(ResponseApdu apdu)
throws SecureMessagingException {
if (!isEstablished()) {
@@ -621,10 +612,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;
}
@@ -641,8 +631,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();
@@ -682,19 +672,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,6 @@
package org.sufficientlysecure.keychain.securitytoken;
import java.io.IOException;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
public interface SecureMessaging {
@@ -28,7 +24,7 @@ public interface SecureMessaging {
boolean isEstablished();
CommandAPDU encryptAndSign(CommandAPDU apdu) throws SecureMessagingException;
CommandApdu encryptAndSign(CommandApdu apdu) throws SecureMessagingException;
ResponseAPDU verifyAndDecrypt(ResponseAPDU apdu) throws SecureMessagingException;
ResponseApdu verifyAndDecrypt(ResponseApdu apdu) throws SecureMessagingException;
}

View File

@@ -23,6 +23,7 @@ package org.sufficientlysecure.keychain.securitytoken;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1Integer;
@@ -46,8 +47,6 @@ import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
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;
@@ -64,53 +63,55 @@ import java.security.NoSuchAlgorithmException;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.util.List;
/**
* This class provides a communication interface to OpenPGP applications on ISO SmartCard compliant
* devices.
* For the full specs, see http://g10code.com/docs/openpgp-card-2.0.pdf
*/
public class SecurityTokenHelper {
private static final int MAX_APDU_NC = 255;
private static final int MAX_APDU_NC_EXT = 65535;
private static final int MAX_APDU_NE = 256;
static final int MAX_APDU_NE_EXT = 65536;
static final int APDU_SW_SUCCESS = 0x9000;
public class SecurityTokenConnection {
private static final int APDU_SW1_RESPONSE_AVAILABLE = 0x61;
private static final int MASK_CLA_CHAINING = 1 << 4;
// Fidesmo constants
private static final String FIDESMO_APPS_AID_PREFIX = "A000000617";
private static final byte[] BLANK_FINGERPRINT = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
private static SecurityTokenConnection sCachedInstance;
private final JcaKeyFingerprintCalculator fingerprintCalculator = new JcaKeyFingerprintCalculator();
private Transport mTransport;
@NonNull
private final Transport mTransport;
@NonNull
private final Passphrase mPin;
private final OpenPgpCommandApduFactory commandFactory;
private CardCapabilities mCardCapabilities;
private OpenPgpCapabilities mOpenPgpCapabilities;
private SecureMessaging mSecureMessaging;
private Passphrase mPin;
private Passphrase mAdminPin;
private boolean mPw1ValidatedForSignature;
private boolean mPw1ValidatedForDecrypt; // Mode 82 does other things; consider renaming?
private boolean mPw3Validated;
private SecurityTokenHelper() {
public static SecurityTokenConnection getInstanceForTransport(Transport transport, Passphrase pin) {
if (sCachedInstance == null || !sCachedInstance.isPersistentConnectionAllowed() ||
!sCachedInstance.isConnected() || !sCachedInstance.mTransport.equals(transport)) {
sCachedInstance = new SecurityTokenConnection(transport, pin, new OpenPgpCommandApduFactory());
}
return sCachedInstance;
}
public static double parseOpenPgpVersion(final byte[] aid) {
float minv = aid[7];
while (minv > 0) minv /= 10.0;
return aid[6] + minv;
}
@VisibleForTesting
SecurityTokenConnection(@NonNull Transport transport, @NonNull Passphrase pin,
OpenPgpCommandApduFactory commandFactory) {
this.mTransport = transport;
this.mPin = pin;
public static SecurityTokenHelper getInstance() {
return LazyHolder.SECURITY_TOKEN_HELPER;
this.commandFactory = commandFactory;
}
private String getHolderName(byte[] name) {
@@ -126,23 +127,7 @@ public class SecurityTokenHelper {
}
}
public Passphrase getPin() {
return mPin;
}
public void setPin(final Passphrase pin) {
this.mPin = pin;
}
public Passphrase getAdminPin() {
return mAdminPin;
}
public void setAdminPin(final Passphrase adminPin) {
this.mAdminPin = adminPin;
}
public void changeKey(CanonicalizedSecretKey secretKey, Passphrase passphrase) throws IOException {
public void changeKey(CanonicalizedSecretKey secretKey, Passphrase passphrase, Passphrase adminPin) throws IOException {
long keyGenerationTimestamp = secretKey.getCreationTime().getTime() / 1000;
byte[] timestampBytes = ByteBuffer.allocate(4).putInt((int) keyGenerationTimestamp).array();
KeyType keyType = KeyType.from(secretKey);
@@ -160,9 +145,9 @@ public class SecurityTokenHelper {
keyType.toString()));
}
putKey(keyType, secretKey, passphrase);
putData(keyType.getFingerprintObjectId(), secretKey.getFingerprint());
putData(keyType.getTimestampObjectId(), timestampBytes);
putKey(keyType, secretKey, passphrase, adminPin);
putData(adminPin, keyType.getFingerprintObjectId(), secretKey.getFingerprint());
putData(adminPin, keyType.getTimestampObjectId(), timestampBytes);
}
private boolean isSlotEmpty(KeyType keyType) throws IOException {
@@ -179,12 +164,19 @@ public class SecurityTokenHelper {
return java.util.Arrays.equals(getKeyFingerprint(keyType), fingerprint);
}
public void connectIfNecessary(Context context) throws IOException {
if (isConnected()) {
return;
}
connectToDevice(context);
}
/**
* Connect to device and select pgp applet
*
* @throws IOException
*/
public void connectToDevice(final Context ctx) throws IOException {
@VisibleForTesting
void connectToDevice(Context context) throws IOException {
// Connect on transport layer
mCardCapabilities = new CardCapabilities();
@@ -192,15 +184,15 @@ public class SecurityTokenHelper {
// Connect on smartcard layer
// Command APDU (page 51) for SELECT FILE command (page 29)
CommandAPDU select = new CommandAPDU(0x00, 0xA4, 0x04, 0x00, Hex.decode("D27600012401"));
ResponseAPDU response = communicate(select); // activate connection
CommandApdu select = commandFactory.createSelectFileOpenPgpCommand();
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));
mCardCapabilities = new CardCapabilities(mOpenPgpCapabilities.getHistoricalBytes());
OpenPgpCapabilities openPgpCapabilities = new OpenPgpCapabilities(getData(0x00, 0x6E));
setConnectionCapabilities(openPgpCapabilities);
mPw1ValidatedForSignature = false;
mPw1ValidatedForDecrypt = false;
@@ -208,21 +200,24 @@ public class SecurityTokenHelper {
if (mOpenPgpCapabilities.isHasSCP11bSM()) {
try {
SCP11bSecureMessaging.establish(this, ctx);
SCP11bSecureMessaging.establish(this, context, commandFactory);
} catch (SecureMessagingException e) {
mSecureMessaging = null;
Log.e(Constants.TAG, "failed to establish secure messaging", e);
}
}
}
public void resetPin(String newPinStr) throws IOException {
if (!mPw3Validated) {
verifyPin(0x83); // (Verify PW1 with mode 82 for decryption)
}
@VisibleForTesting
void setConnectionCapabilities(OpenPgpCapabilities openPgpCapabilities) throws IOException {
this.mOpenPgpCapabilities = openPgpCapabilities;
this.mCardCapabilities = new CardCapabilities(openPgpCapabilities.getHistoricalBytes());
}
byte[] newPin = newPinStr.getBytes();
public void resetPin(byte[] newPin, Passphrase adminPin) throws IOException {
if (!mPw3Validated) {
verifyAdminPin(adminPin);
}
final int MAX_PW1_LENGTH_INDEX = 1;
byte[] pwStatusBytes = getPwStatusBytes();
@@ -231,52 +226,36 @@ public class SecurityTokenHelper {
}
// Command APDU for RESET RETRY COUNTER command (page 33)
CommandAPDU changePin = new CommandAPDU(0x00, 0x2C, 0x02, 0x81, newPin);
ResponseAPDU response = communicate(changePin);
CommandApdu changePin = commandFactory.createResetPw1Command(newPin);
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());
}
}
/**
* Modifies the user's PW1 or PW3. Before sending, the new PIN will be validated for
* Modifies the user's PW3. Before sending, the new PIN will be validated for
* conformance to the token's requirements for key length.
*
* @param pw For PW1, this is 0x81. For PW3 (Admin PIN), mode is 0x83.
* @param newPin The new PW1 or PW3.
* @param newAdminPin The new PW3.
*/
public void modifyPin(int pw, byte[] newPin) throws IOException {
final int MAX_PW1_LENGTH_INDEX = 1;
public void modifyPw3Pin(byte[] newAdminPin, Passphrase adminPin) throws IOException {
final int MAX_PW3_LENGTH_INDEX = 3;
byte[] pwStatusBytes = getPwStatusBytes();
if (pw == 0x81) {
if (newPin.length < 6 || newPin.length > pwStatusBytes[MAX_PW1_LENGTH_INDEX]) {
throw new IOException("Invalid PIN length");
}
} else if (pw == 0x83) {
if (newPin.length < 8 || newPin.length > pwStatusBytes[MAX_PW3_LENGTH_INDEX]) {
throw new IOException("Invalid PIN length");
}
} else {
throw new IOException("Invalid PW index for modify PIN operation");
if (newAdminPin.length < 8 || newAdminPin.length > pwStatusBytes[MAX_PW3_LENGTH_INDEX]) {
throw new IOException("Invalid PIN length");
}
byte[] pin;
if (pw == 0x83) {
pin = mAdminPin.toStringUnsafe().getBytes();
} else {
pin = mPin.toStringUnsafe().getBytes();
}
byte[] pin = adminPin.toStringUnsafe().getBytes();
// Command APDU for CHANGE REFERENCE DATA command (page 32)
CommandAPDU changePin = new CommandAPDU(0x00, 0x24, 0x00, pw, Arrays.concatenate(pin, newPin));
ResponseAPDU response = communicate(changePin);
CommandApdu changePin = commandFactory.createChangePw3Command(pin, newAdminPin);
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());
}
}
@@ -293,7 +272,7 @@ public class SecurityTokenHelper {
final KeyFormat kf = mOpenPgpCapabilities.getFormatForKeyType(KeyType.ENCRYPT);
if (!mPw1ValidatedForDecrypt) {
verifyPin(0x82); // (Verify PW1 with mode 82 for decryption)
verifyPinForOther();
}
byte[] data;
@@ -352,11 +331,11 @@ public class SecurityTokenHelper {
throw new CardException("Unknown encryption key type!");
}
CommandAPDU command = new CommandAPDU(0x00, 0x2A, 0x80, 0x86, data, MAX_APDU_NE_EXT);
ResponseAPDU response = communicate(command);
CommandApdu command = commandFactory.createDecipherCommand(data);
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()) {
@@ -416,34 +395,46 @@ public class SecurityTokenHelper {
}
/**
* Verifies the user's PW1 or PW3 with the appropriate mode.
*
* @param mode For PW1, this is 0x81 for signing, 0x82 for everything else.
* For PW3 (Admin PIN), mode is 0x83.
* Verifies the user's PW1 with the appropriate mode.
*/
private void verifyPin(int mode) throws IOException {
if (mPin != null || mode == 0x83) {
private void verifyPinForSignature() throws IOException {
byte[] pin = mPin.toStringUnsafe().getBytes();
byte[] pin;
if (mode == 0x83) {
pin = mAdminPin.toStringUnsafe().getBytes();
} else {
pin = mPin.toStringUnsafe().getBytes();
}
ResponseAPDU response = tryPin(mode, pin);// login
if (response.getSW() != APDU_SW_SUCCESS) {
throw new CardException("Bad PIN!", response.getSW());
}
if (mode == 0x81) {
mPw1ValidatedForSignature = true;
} else if (mode == 0x82) {
mPw1ValidatedForDecrypt = true;
} else if (mode == 0x83) {
mPw3Validated = true;
}
ResponseApdu response = communicate(commandFactory.createVerifyPw1ForSignatureCommand(pin));
if (!response.isSuccess()) {
throw new CardException("Bad PIN!", response.getSw());
}
mPw1ValidatedForSignature = true;
}
/**
* Verifies the user's PW1 with the appropriate mode.
*/
private void verifyPinForOther() throws IOException {
byte[] pin = mPin.toStringUnsafe().getBytes();
// Command APDU for VERIFY command (page 32)
ResponseApdu response = communicate(commandFactory.createVerifyPw1ForOtherCommand(pin));
if (!response.isSuccess()) {
throw new CardException("Bad PIN!", response.getSw());
}
mPw1ValidatedForDecrypt = true;
}
/**
* Verifies the user's PW1 or PW3 with the appropriate mode.
*/
private void verifyAdminPin(Passphrase adminPin) throws IOException {
// Command APDU for VERIFY command (page 32)
ResponseApdu response =
communicate(commandFactory.createVerifyPw3Command(adminPin.toStringUnsafe().getBytes()));
if (!response.isSuccess()) {
throw new CardException("Bad PIN!", response.getSw());
}
mPw3Validated = true;
}
/**
@@ -454,28 +445,28 @@ public class SecurityTokenHelper {
* @param dataObject The data object to be stored.
* @param data The data to store in the object
*/
private void putData(int dataObject, byte[] data) throws IOException {
private void putData(Passphrase adminPin, int dataObject, byte[] data) throws IOException {
if (data.length > 254) {
throw new IOException("Cannot PUT DATA with length > 254");
}
// TODO use admin pin regardless, if we have it?
if (dataObject == 0x0101 || dataObject == 0x0103) {
if (!mPw1ValidatedForDecrypt) {
verifyPin(0x82); // (Verify PW1 for non-signing operations)
verifyPinForOther();
}
} else if (!mPw3Validated) {
verifyPin(0x83); // (Verify PW3)
verifyAdminPin(adminPin);
}
CommandAPDU command = new CommandAPDU(0x00, 0xDA, (dataObject & 0xFF00) >> 8, dataObject & 0xFF, data);
ResponseAPDU response = communicate(command); // put data
CommandApdu command = commandFactory.createPutDataCommand(dataObject, 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());
}
}
private void setKeyAttributes(final KeyType slot, final CanonicalizedSecretKey secretKey)
private void setKeyAttributes(Passphrase adminPin, final KeyType slot, final CanonicalizedSecretKey secretKey)
throws IOException {
if (mOpenPgpCapabilities.isAttributesChangable()) {
@@ -493,7 +484,7 @@ public class SecurityTokenHelper {
try {
putData(tag, SecurityTokenUtils.attributesFromSecretKey(slot, secretKey));
putData(adminPin, tag, SecurityTokenUtils.attributesFromSecretKey(slot, secretKey));
mOpenPgpCapabilities.updateWithData(getData(0x00, tag));
@@ -512,14 +503,14 @@ public class SecurityTokenHelper {
* 0xB8: Decipherment Key
* 0xA4: Authentication Key
*/
private void putKey(KeyType slot, CanonicalizedSecretKey secretKey, Passphrase passphrase)
private void putKey(KeyType slot, CanonicalizedSecretKey secretKey, Passphrase passphrase, Passphrase adminPin)
throws IOException {
RSAPrivateCrtKey crtSecretKey;
ECPrivateKey ecSecretKey;
ECPublicKey ecPublicKey;
if (!mPw3Validated) {
verifyPin(0x83); // (Verify PW3 with mode 83)
verifyAdminPin(adminPin);
}
// Now we're ready to communicate with the token.
@@ -528,7 +519,7 @@ public class SecurityTokenHelper {
try {
secretKey.unlock(passphrase);
setKeyAttributes(slot, secretKey);
setKeyAttributes(adminPin, slot, secretKey);
switch (mOpenPgpCapabilities.getFormatForKeyType(slot).keyFormatType()) {
case RSAKeyFormatType:
@@ -566,11 +557,11 @@ public class SecurityTokenHelper {
throw new IOException(e.getMessage());
}
CommandAPDU apdu = new CommandAPDU(0x00, 0xDB, 0x3F, 0xFF, keyBytes);
ResponseAPDU response = communicate(apdu);
CommandApdu apdu = commandFactory.createPutKeyCommand(keyBytes);
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());
}
}
@@ -581,29 +572,7 @@ public class SecurityTokenHelper {
* @return The fingerprints of all subkeys in a contiguous byte array.
*/
public byte[] getFingerprints() throws IOException {
CommandAPDU apdu = new CommandAPDU(0x00, 0xCA, 0x00, 0x6E, MAX_APDU_NE_EXT);
ResponseAPDU response = communicate(apdu);
if (response.getSW() != APDU_SW_SUCCESS) {
throw new CardException("Failed to get fingerprints", response.getSW());
}
Iso7816TLV[] tlvList = Iso7816TLV.readList(response.getData(), true);
Iso7816TLV fingerPrintTlv = null;
for (Iso7816TLV tlv : tlvList) {
Log.d(Constants.TAG, "nfcGetFingerprints() Iso7816TLV tlv data:\n" + tlv.prettyPrint());
Iso7816TLV matchingTlv = Iso7816TLV.findRecursive(tlv, 0xc5);
if (matchingTlv != null) {
fingerPrintTlv = matchingTlv;
}
}
if (fingerPrintTlv == null) {
return null;
}
return fingerPrintTlv.mV;
return mOpenPgpCapabilities.getFingerprints();
}
/**
@@ -612,11 +581,11 @@ public class SecurityTokenHelper {
* @return Seven bytes in fixed format, plus 0x9000 status word at the end.
*/
private byte[] getPwStatusBytes() throws IOException {
return getData(0x00, 0xC4);
return mOpenPgpCapabilities.getPwStatusBytes();
}
public byte[] getAid() throws IOException {
return getData(0x00, 0x4F);
return mOpenPgpCapabilities.getAid();
}
public String getUrl() throws IOException {
@@ -629,9 +598,9 @@ public class SecurityTokenHelper {
}
private byte[] getData(int p1, int p2) throws IOException {
ResponseAPDU response = communicate(new CommandAPDU(0x00, 0xCA, p1, p2, MAX_APDU_NE_EXT));
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();
}
@@ -644,7 +613,7 @@ public class SecurityTokenHelper {
*/
public byte[] calculateSignature(byte[] hash, int hashAlgo) throws IOException {
if (!mPw1ValidatedForSignature) {
verifyPin(0x81); // (Verify PW1 with mode 81 for signing)
verifyPinForSignature();
}
byte[] dsi;
@@ -711,11 +680,11 @@ public class SecurityTokenHelper {
}
// Command APDU for PERFORM SECURITY OPERATION: COMPUTE DIGITAL SIGNATURE (page 37)
CommandAPDU command = new CommandAPDU(0x00, 0x2A, 0x9E, 0x9A, data, MAX_APDU_NE_EXT);
ResponseAPDU response = communicate(command);
CommandApdu command = commandFactory.createComputeDigitalSignatureCommand(data);
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()) {
@@ -756,7 +725,6 @@ public class SecurityTokenHelper {
return signature;
}
/**
* Transceives APDU
* Splits extended APDU into short APDUs and chains them if necessary
@@ -766,7 +734,7 @@ public class SecurityTokenHelper {
* @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);
@@ -776,53 +744,44 @@ public class SecurityTokenHelper {
}
}
ByteArrayOutputStream result = new ByteArrayOutputStream();
ResponseAPDU lastResponse = null;
ResponseApdu lastResponse = null;
// Transmit
if (mCardCapabilities.hasExtended()) {
lastResponse = mTransport.transceive(apdu);
} else if (apdu.getData().length <= MAX_APDU_NC) {
int ne = Math.min(apdu.getNe(), MAX_APDU_NE);
lastResponse = mTransport.transceive(new CommandAPDU(apdu.getCLA(), apdu.getINS(),
apdu.getP1(), apdu.getP2(), apdu.getData(), ne));
} else if (apdu.getData().length > MAX_APDU_NC && mCardCapabilities.hasChaining()) {
int offset = 0;
byte[] data = apdu.getData();
int ne = Math.min(apdu.getNe(), MAX_APDU_NE);
while (offset < data.length) {
int curLen = Math.min(MAX_APDU_NC, data.length - offset);
boolean last = offset + curLen >= data.length;
int cla = apdu.getCLA() + (last ? 0 : MASK_CLA_CHAINING);
} else if (commandFactory.isSuitableForShortApdu(apdu)) {
CommandApdu shortApdu = commandFactory.createShortApdu(apdu);
lastResponse = mTransport.transceive(shortApdu);
} else if (mCardCapabilities.hasChaining()) {
List<CommandApdu> chainedApdus = commandFactory.createChainedApdus(apdu);
for (int i = 0, totalCommands = chainedApdus.size(); i < totalCommands; i++) {
CommandApdu chainedApdu = chainedApdus.get(i);
lastResponse = mTransport.transceive(chainedApdu);
lastResponse = mTransport.transceive(new CommandAPDU(cla, apdu.getINS(), apdu.getP1(),
apdu.getP2(), data, offset, curLen, ne));
if (!last && lastResponse.getSW() != APDU_SW_SUCCESS) {
throw new UsbTransportException("Failed to chain apdu (last SW: " + lastResponse.getSW() + ")");
boolean isLastCommand = i < totalCommands - 1;
if (isLastCommand && !lastResponse.isSuccess()) {
throw new UsbTransportException("Failed to chain apdu (last SW: " + lastResponse.getSw() + ")");
}
offset += curLen;
}
}
if (lastResponse == null) {
throw new UsbTransportException("Can't transmit command");
}
ByteArrayOutputStream result = new ByteArrayOutputStream();
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 = new CommandAPDU(0x00, 0xC0, 0x00, 0x00, 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 {
@@ -836,22 +795,13 @@ public class SecurityTokenHelper {
return lastResponse;
}
public Transport getTransport() {
return mTransport;
}
public void setTransport(Transport mTransport) {
clearSecureMessaging();
this.mTransport = mTransport;
}
public boolean isFidesmoToken() {
if (isConnected()) { // Check if we can still talk to the card
try {
// 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 = new CommandAPDU(0x00, 0xA4, 0x04, 0x00, Hex.decode(FIDESMO_APPS_AID_PREFIX));
return communicate(apdu).getSW() == APDU_SW_SUCCESS;
CommandApdu apdu = commandFactory.createSelectFileCommand(FIDESMO_APPS_AID_PREFIX);
return communicate(apdu).isSuccess();
} catch (IOException e) {
Log.e(Constants.TAG, "Card communication failed!", e);
}
@@ -873,30 +823,25 @@ public class SecurityTokenHelper {
* @return the public key data objects, in TLV format. For RSA this will be the public modulus
* (0x81) and exponent (0x82). These may come out of order; proper TLV parsing is required.
*/
public byte[] generateKey(int slot) throws IOException {
public byte[] generateKey(Passphrase adminPin, int slot) throws IOException {
if (slot != 0xB6 && slot != 0xB8 && slot != 0xA4) {
throw new IOException("Invalid key slot");
}
if (!mPw3Validated) {
verifyPin(0x83); // (Verify PW3 with mode 83)
verifyAdminPin(adminPin);
}
CommandAPDU apdu = new CommandAPDU(0x00, 0x47, 0x80, 0x00, new byte[]{(byte) slot, 0x00}, MAX_APDU_NE_EXT);
ResponseAPDU response = communicate(apdu);
CommandApdu apdu = commandFactory.createGenerateKeyCommand(slot);
ResponseApdu response = communicate(apdu);
if (response.getSW() != APDU_SW_SUCCESS) {
if (!response.isSuccess()) {
throw new IOException("On-card key generation failed");
}
return response.getData();
}
private ResponseAPDU tryPin(int mode, byte[] pin) throws IOException {
// Command APDU for VERIFY command (page 32)
return communicate(new CommandAPDU(0x00, 0x20, 0x00, mode, pin));
}
/**
* Resets security token, which deletes all keys and data objects.
* This works by entering a wrong PIN and then Admin PIN 4 times respectively.
@@ -906,18 +851,20 @@ public class SecurityTokenHelper {
// try wrong PIN 4 times until counter goes to C0
byte[] pin = "XXXXXX".getBytes();
for (int i = 0; i <= 4; i++) {
ResponseAPDU response = tryPin(0x81, pin);
if (response.getSW() == APDU_SW_SUCCESS) { // Should NOT accept!
throw new CardException("Should never happen, XXXXXX has been accepted!", response.getSW());
// Command APDU for VERIFY command (page 32)
ResponseApdu response = communicate(commandFactory.createVerifyPw1ForSignatureCommand(pin));
if (response.isSuccess()) {
throw new CardException("Should never happen, XXXXXX has been accepted!", response.getSw());
}
}
// try wrong Admin PIN 4 times until counter goes to C0
byte[] adminPin = "XXXXXXXX".getBytes();
for (int i = 0; i <= 4; i++) {
ResponseAPDU response = tryPin(0x83, adminPin);
if (response.getSW() == APDU_SW_SUCCESS) { // Should NOT accept!
throw new CardException("Should never happen, XXXXXXXX has been accepted", response.getSW());
// Command APDU for VERIFY command (page 32)
ResponseApdu response = communicate(commandFactory.createVerifyPw3Command(adminPin));
if (response.isSuccess()) { // Should NOT accept!
throw new CardException("Should never happen, XXXXXXXX has been accepted", response.getSw());
}
}
@@ -927,15 +874,15 @@ public class SecurityTokenHelper {
// reactivate token!
// NOTE: keep the order here! First execute _both_ reactivate commands. Before checking _both_ responses
// If a token is in a bad state and reactivate1 fails, it could still be reactivated with reactivate2
CommandAPDU reactivate1 = new CommandAPDU(0x00, 0xE6, 0x00, 0x00);
CommandAPDU reactivate2 = new CommandAPDU(0x00, 0x44, 0x00, 0x00);
ResponseAPDU response1 = communicate(reactivate1);
ResponseAPDU response2 = communicate(reactivate2);
if (response1.getSW() != APDU_SW_SUCCESS) {
throw new CardException("Reactivating failed!", response1.getSW());
CommandApdu reactivate1 = commandFactory.createReactivate1Command();
CommandApdu reactivate2 = commandFactory.createReactivate2Command();
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());
}
}
@@ -962,14 +909,12 @@ public class SecurityTokenHelper {
}
public boolean isPersistentConnectionAllowed() {
return mTransport != null &&
mTransport.isPersistentConnectionAllowed() &&
(mSecureMessaging == null ||
!mSecureMessaging.isEstablished());
return mTransport.isPersistentConnectionAllowed() &&
(mSecureMessaging == null || !mSecureMessaging.isEstablished());
}
public boolean isConnected() {
return mTransport != null && mTransport.isConnected();
return mTransport.isConnected();
}
public void clearSecureMessaging() {
@@ -1006,7 +951,9 @@ public class SecurityTokenHelper {
return SecurityTokenInfo.create(fingerprints, aid, userId, url, pwInfo[4], pwInfo[6]);
}
private static class LazyHolder {
private static final SecurityTokenHelper SECURITY_TOKEN_HELPER = new SecurityTokenHelper();
public static double parseOpenPgpVersion(final byte[] aid) {
float minv = aid[7];
while (minv > 0) minv /= 10.0;
return aid[6] + minv;
}
}

View File

@@ -33,8 +33,8 @@ import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPrivateCrtKey;
public class SecurityTokenUtils {
public static byte[] attributesFromSecretKey(final KeyType slot, final CanonicalizedSecretKey secretKey) throws IOException, PgpGeneralException {
class SecurityTokenUtils {
static byte[] attributesFromSecretKey(final KeyType slot, final CanonicalizedSecretKey secretKey) throws IOException, PgpGeneralException {
if (secretKey.isRSA()) {
final int mModulusLength = secretKey.getBitStrength();
final int mExponentLength = secretKey.getSecurityTokenRSASecretKey().getPublicExponent().bitLength();
@@ -46,7 +46,7 @@ public class SecurityTokenUtils {
attrs[i++] = (byte) (mModulusLength & 0xff);
attrs[i++] = (byte) ((mExponentLength >> 8) & 0xff);
attrs[i++] = (byte) (mExponentLength & 0xff);
attrs[i++] = RSAKeyFormat.RSAAlgorithmFormat.CRT_WITH_MODULUS.getValue();
attrs[i] = RSAKeyFormat.RSAAlgorithmFormat.CRT_WITH_MODULUS.getValue();
return attrs;
} else if (secretKey.isEC()) {
@@ -70,8 +70,8 @@ public class SecurityTokenUtils {
}
public static byte[] createRSAPrivKeyTemplate(RSAPrivateCrtKey secretKey, KeyType slot,
RSAKeyFormat format) throws IOException {
static byte[] createRSAPrivKeyTemplate(RSAPrivateCrtKey secretKey, KeyType slot,
RSAKeyFormat format) throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream(),
template = new ByteArrayOutputStream(),
data = new ByteArrayOutputStream(),
@@ -138,8 +138,8 @@ public class SecurityTokenUtils {
return res.toByteArray();
}
public static byte[] createECPrivKeyTemplate(ECPrivateKey secretKey, ECPublicKey publicKey, KeyType slot,
ECKeyFormat format) throws IOException {
static byte[] createECPrivKeyTemplate(ECPrivateKey secretKey, ECPublicKey publicKey, KeyType slot,
ECKeyFormat format) throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream(),
template = new ByteArrayOutputStream(),
data = new ByteArrayOutputStream(),
@@ -184,7 +184,7 @@ public class SecurityTokenUtils {
return res.toByteArray();
}
public static byte[] encodeLength(int len) {
static byte[] encodeLength(int len) {
if (len < 0) {
throw new IllegalArgumentException("length is negative");
} else if (len >= 16777216) {
@@ -214,7 +214,7 @@ public class SecurityTokenUtils {
return res;
}
public static void writeBits(ByteArrayOutputStream stream, BigInteger value, int width) {
static void writeBits(ByteArrayOutputStream stream, BigInteger value, int width) {
if (value.signum() == -1) {
throw new IllegalArgumentException("value is negative");
} else if (width <= 0) {

View File

@@ -17,9 +17,6 @@
package org.sufficientlysecure.keychain.securitytoken;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import java.io.IOException;
/**
@@ -32,7 +29,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

@@ -29,8 +29,8 @@ 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.CommandApdu;
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.toBytes()));
}
@Override

View File

@@ -32,6 +32,7 @@ import android.support.v4.app.TaskStackBuilder;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.securitytoken.KeyFormat;
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenInfo;
import org.sufficientlysecure.keychain.ui.base.BaseSecurityTokenActivity;
import org.sufficientlysecure.keychain.ui.token.ManageSecurityTokenFragment;
@@ -133,17 +134,17 @@ public class CreateKeyActivity extends BaseSecurityTokenActivity {
}
@Override
protected void doSecurityTokenInBackground() throws IOException {
protected void doSecurityTokenInBackground(SecurityTokenConnection stConnection) throws IOException {
if (mCurrentFragment instanceof SecurityTokenListenerFragment) {
((SecurityTokenListenerFragment) mCurrentFragment).doSecurityTokenInBackground();
return;
}
tokenInfo = mSecurityTokenHelper.getTokenInfo();
tokenInfo = stConnection.getTokenInfo();
}
@Override
protected void onSecurityTokenPostExecute() {
protected void onSecurityTokenPostExecute(SecurityTokenConnection stConnection) {
handleTokenInfo(tokenInfo);
}

View File

@@ -32,7 +32,7 @@ import android.widget.TextView;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.securitytoken.KeyFormat;
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenHelper;
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
import org.sufficientlysecure.keychain.ui.CreateKeyActivity.FragAction;
import org.sufficientlysecure.keychain.util.Choice;
@@ -100,7 +100,7 @@ public class CreateSecurityTokenAlgorithmFragment extends Fragment {
choices.add(new Choice<>(SupportedKeyType.RSA_4096, getResources().getString(
R.string.rsa_4096), getResources().getString(R.string.rsa_4096_description_html)));
final double version = SecurityTokenHelper.parseOpenPgpVersion(mCreateKeyActivity.tokenInfo.getAid());
final double version = SecurityTokenConnection.parseOpenPgpVersion(mCreateKeyActivity.tokenInfo.getAid());
if (version >= 3.0) {
choices.add(new Choice<>(SupportedKeyType.ECC_P256, getResources().getString(

View File

@@ -17,7 +17,6 @@
package org.sufficientlysecure.keychain.ui;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
@@ -31,7 +30,7 @@ import android.widget.TextView;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenHelper;
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
import org.sufficientlysecure.keychain.ui.CreateKeyActivity.FragAction;
import org.sufficientlysecure.keychain.util.Passphrase;
@@ -206,7 +205,7 @@ public class CreateSecurityTokenPinFragment extends Fragment {
mCreateKeyActivity.mSecurityTokenPin = new Passphrase(mPin.getText().toString());
final double version = SecurityTokenHelper.parseOpenPgpVersion(mCreateKeyActivity.tokenInfo.getAid());
final double version = SecurityTokenConnection.parseOpenPgpVersion(mCreateKeyActivity.tokenInfo.getAid());
Fragment frag;
if (version >= 3.0) {

View File

@@ -32,6 +32,7 @@ import android.widget.ViewAnimator;
import nordpol.android.NfcGuideView;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenInfo;
import org.sufficientlysecure.keychain.service.input.SecurityTokenChangePinParcel;
import org.sufficientlysecure.keychain.ui.base.BaseSecurityTokenActivity;
@@ -138,15 +139,15 @@ public class SecurityTokenChangePinOperationActivity extends BaseSecurityTokenAc
}
@Override
protected void doSecurityTokenInBackground() throws IOException {
mSecurityTokenHelper.setAdminPin(new Passphrase(changePinInput.getAdminPin()));
mSecurityTokenHelper.resetPin(changePinInput.getNewPin());
protected void doSecurityTokenInBackground(SecurityTokenConnection stConnection) throws IOException {
Passphrase adminPin = new Passphrase(changePinInput.getAdminPin());
stConnection.resetPin(changePinInput.getNewPin().getBytes(), adminPin);
resultTokenInfo = mSecurityTokenHelper.getTokenInfo();
resultTokenInfo = stConnection.getTokenInfo();
}
@Override
protected final void onSecurityTokenPostExecute() {
protected final void onSecurityTokenPostExecute(final SecurityTokenConnection stConnection) {
Intent result = new Intent();
result.putExtra(RESULT_TOKEN_INFO, resultTokenInfo);
setResult(RESULT_OK, result);
@@ -156,17 +157,17 @@ public class SecurityTokenChangePinOperationActivity extends BaseSecurityTokenAc
nfcGuideView.setCurrentStatus(NfcGuideView.NfcGuideViewStatus.DONE);
if (mSecurityTokenHelper.isPersistentConnectionAllowed()) {
if (stConnection.isPersistentConnectionAllowed()) {
// Just close
finish();
} else {
mSecurityTokenHelper.clearSecureMessaging();
stConnection.clearSecureMessaging();
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
// check all 200ms if Security Token has been taken away
while (true) {
if (isSecurityTokenConnected()) {
if (stConnection.isConnected()) {
try {
Thread.sleep(200);
} catch (InterruptedException ignored) {

View File

@@ -44,6 +44,7 @@ import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKeyRing;
import org.sufficientlysecure.keychain.provider.KeyRepository;
import org.sufficientlysecure.keychain.provider.KeychainContract;
import org.sufficientlysecure.keychain.securitytoken.KeyType;
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenInfo;
import org.sufficientlysecure.keychain.service.PassphraseCacheService;
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
@@ -185,12 +186,12 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
}
@Override
protected void doSecurityTokenInBackground() throws IOException {
protected void doSecurityTokenInBackground(SecurityTokenConnection stConnection) throws IOException {
switch (mRequiredInput.mType) {
case SECURITY_TOKEN_DECRYPT: {
long tokenKeyId = KeyFormattingUtils.getKeyIdFromFingerprint(
mSecurityTokenHelper.getKeyFingerprint(KeyType.ENCRYPT));
stConnection.getKeyFingerprint(KeyType.ENCRYPT));
if (tokenKeyId != mRequiredInput.getSubKeyId()) {
throw new IOException(getString(R.string.error_wrong_security_token));
@@ -208,14 +209,15 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
for (int i = 0; i < mRequiredInput.mInputData.length; i++) {
byte[] encryptedSessionKey = mRequiredInput.mInputData[i];
byte[] decryptedSessionKey = mSecurityTokenHelper.decryptSessionKey(encryptedSessionKey, publicKeyRing.getPublicKey(tokenKeyId));
byte[] decryptedSessionKey = stConnection
.decryptSessionKey(encryptedSessionKey, publicKeyRing.getPublicKey(tokenKeyId));
mInputParcel = mInputParcel.withCryptoData(encryptedSessionKey, decryptedSessionKey);
}
break;
}
case SECURITY_TOKEN_SIGN: {
long tokenKeyId = KeyFormattingUtils.getKeyIdFromFingerprint(
mSecurityTokenHelper.getKeyFingerprint(KeyType.SIGN));
stConnection.getKeyFingerprint(KeyType.SIGN));
if (tokenKeyId != mRequiredInput.getSubKeyId()) {
throw new IOException(getString(R.string.error_wrong_security_token));
@@ -226,15 +228,13 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
for (int i = 0; i < mRequiredInput.mInputData.length; i++) {
byte[] hash = mRequiredInput.mInputData[i];
int algo = mRequiredInput.mSignAlgos[i];
byte[] signedHash = mSecurityTokenHelper.calculateSignature(hash, algo);
byte[] signedHash = stConnection.calculateSignature(hash, algo);
mInputParcel = mInputParcel.withCryptoData(hash, signedHash);
}
break;
}
case SECURITY_TOKEN_MOVE_KEY_TO_CARD: {
// TODO: assume PIN and Admin PIN to be default for this operation
mSecurityTokenHelper.setPin(new Passphrase("123456"));
mSecurityTokenHelper.setAdminPin(new Passphrase("12345678"));
Passphrase adminPin = new Passphrase("12345678");
KeyRepository keyRepository =
KeyRepository.create(this);
@@ -256,7 +256,7 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
long subkeyId = buf.getLong();
CanonicalizedSecretKey key = secretKeyRing.getSecretKey(subkeyId);
byte[] tokenSerialNumber = Arrays.copyOf(mSecurityTokenHelper.getAid(), 16);
byte[] tokenSerialNumber = Arrays.copyOf(stConnection.getAid(), 16);
Passphrase passphrase;
try {
@@ -266,21 +266,21 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
throw new IOException("Unable to get cached passphrase!");
}
mSecurityTokenHelper.changeKey(key, passphrase);
stConnection.changeKey(key, passphrase, adminPin);
// TODO: Is this really used anywhere?
mInputParcel = mInputParcel.withCryptoData(subkeyBytes, tokenSerialNumber);
}
// change PINs afterwards
mSecurityTokenHelper.modifyPin(0x81, newPin);
mSecurityTokenHelper.modifyPin(0x83, newAdminPin);
stConnection.resetPin(newPin, adminPin);
stConnection.modifyPw3Pin(newAdminPin, adminPin);
break;
}
case SECURITY_TOKEN_RESET_CARD: {
mSecurityTokenHelper.resetAndWipeToken();
mResultTokenInfo = mSecurityTokenHelper.getTokenInfo();
stConnection.resetAndWipeToken();
mResultTokenInfo = stConnection.getTokenInfo();
break;
}
@@ -292,7 +292,7 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
}
@Override
protected final void onSecurityTokenPostExecute() {
protected final void onSecurityTokenPostExecute(final SecurityTokenConnection stConnection) {
handleResult(mInputParcel);
// show finish
@@ -300,17 +300,17 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
nfcGuideView.setCurrentStatus(NfcGuideView.NfcGuideViewStatus.DONE);
if (mSecurityTokenHelper.isPersistentConnectionAllowed()) {
if (stConnection.isPersistentConnectionAllowed()) {
// Just close
finish();
} else {
mSecurityTokenHelper.clearSecureMessaging();
stConnection.clearSecureMessaging();
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
// check all 200ms if Security Token has been taken away
while (true) {
if (isSecurityTokenConnected()) {
if (stConnection.isConnected()) {
try {
Thread.sleep(200);
} catch (InterruptedException ignored) {

View File

@@ -15,6 +15,7 @@ import android.view.animation.DecelerateInterpolator;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.securitytoken.NfcSweetspotData;
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
import org.sufficientlysecure.keychain.ui.base.BaseSecurityTokenActivity;
@@ -88,7 +89,7 @@ public class ShowNfcSweetspotActivity extends BaseSecurityTokenActivity {
}
@Override
protected void onSecurityTokenPostExecute() {
protected void onSecurityTokenPostExecute(SecurityTokenConnection stConnection) {
Intent result = new Intent();
result.putExtra(EXTRA_TOKEN_INFO, tokenInfo);
setResult(Activity.RESULT_OK, result);

View File

@@ -43,7 +43,7 @@ import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.securitytoken.CardException;
import org.sufficientlysecure.keychain.securitytoken.NfcTransport;
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenHelper;
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenInfo;
import org.sufficientlysecure.keychain.securitytoken.Transport;
import org.sufficientlysecure.keychain.securitytoken.UsbConnectionDispatcher;
@@ -68,12 +68,12 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
private static final String FIDESMO_APP_PACKAGE = "com.fidesmo.sec.android";
protected SecurityTokenHelper mSecurityTokenHelper = SecurityTokenHelper.getInstance();
protected TagDispatcher mNfcTagDispatcher;
protected UsbConnectionDispatcher mUsbDispatcher;
private boolean mTagHandlingEnabled;
protected SecurityTokenInfo tokenInfo;
private Passphrase mCachedPin;
/**
* Override to change UI before SecurityToken handling (UI thread)
@@ -84,15 +84,15 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
/**
* Override to implement SecurityToken operations (background thread)
*/
protected void doSecurityTokenInBackground() throws IOException {
tokenInfo = mSecurityTokenHelper.getTokenInfo();
protected void doSecurityTokenInBackground(SecurityTokenConnection stConnection) throws IOException {
tokenInfo = stConnection.getTokenInfo();
Log.d(Constants.TAG, "Security Token: " + tokenInfo);
}
/**
* Override to handle result of SecurityToken operations (UI thread)
*/
protected void onSecurityTokenPostExecute() {
protected void onSecurityTokenPostExecute(SecurityTokenConnection stConnection) {
Intent intent = new Intent(this, CreateKeyActivity.class);
intent.putExtra(CreateKeyActivity.EXTRA_SECURITY_TOKEN_INFO, tokenInfo);
startActivity(intent);
@@ -138,6 +138,10 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
// Actual Security Token operations are executed in doInBackground to not block the UI thread
if (!mTagHandlingEnabled)
return;
final SecurityTokenConnection stConnection =
SecurityTokenConnection.getInstanceForTransport(transport, mCachedPin);
new AsyncTask<Void, Void, IOException>() {
@Override
protected void onPreExecute() {
@@ -148,7 +152,9 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
@Override
protected IOException doInBackground(Void... params) {
try {
handleSecurityToken(transport, BaseSecurityTokenActivity.this);
stConnection.connectIfNecessary(getBaseContext());
handleSecurityToken(stConnection);
} catch (IOException e) {
return e;
}
@@ -161,11 +167,11 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
super.onPostExecute(exception);
if (exception != null) {
handleSecurityTokenError(exception);
handleSecurityTokenError(stConnection, exception);
return;
}
onSecurityTokenPostExecute();
onSecurityTokenPostExecute(stConnection);
}
}.execute();
}
@@ -223,7 +229,7 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
mNfcTagDispatcher.interceptIntent(intent);
}
private void handleSecurityTokenError(IOException e) {
private void handleSecurityTokenError(SecurityTokenConnection stConnection, IOException e) {
if (e instanceof TagLostException) {
onSecurityTokenError(getString(R.string.security_token_error_tag_lost));
@@ -250,7 +256,7 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
SecurityTokenInfo tokeninfo = null;
try {
tokeninfo = mSecurityTokenHelper.getTokenInfo();
tokeninfo = stConnection.getTokenInfo();
} catch (IOException e2) {
// don't care
}
@@ -260,6 +266,8 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
return;
}
Log.d(Constants.TAG, "security token exception", e);
// Otherwise, all status codes are fixed values.
switch (status) {
@@ -271,7 +279,7 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
case 0x6982: {
SecurityTokenInfo tokeninfo = null;
try {
tokeninfo = mSecurityTokenHelper.getTokenInfo();
tokeninfo = stConnection.getTokenInfo();
} catch (IOException e2) {
// don't care
}
@@ -325,7 +333,7 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
}
// 6A82 app not installed on security token!
case 0x6A82: {
if (mSecurityTokenHelper.isFidesmoToken()) {
if (stConnection.isFidesmoToken()) {
// Check if the Fidesmo app is installed
if (isAndroidAppInstalled(FIDESMO_APP_PACKAGE)) {
promptFidesmoPgpInstall();
@@ -391,12 +399,11 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
}
protected void obtainSecurityTokenPin(RequiredInputParcel requiredInput) {
try {
Passphrase passphrase = PassphraseCacheService.getCachedPassphrase(this,
requiredInput.getMasterKeyId(), requiredInput.getSubKeyId());
if (passphrase != null) {
mSecurityTokenHelper.setPin(passphrase);
mCachedPin = passphrase;
return;
}
@@ -421,7 +428,7 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
return;
}
CryptoInputParcel input = data.getParcelableExtra(PassphraseDialogActivity.RESULT_CRYPTO_INPUT);
mSecurityTokenHelper.setPin(input.getPassphrase());
mCachedPin = input.getPassphrase();
break;
}
default:
@@ -429,19 +436,8 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
}
}
protected void handleSecurityToken(Transport transport, Context ctx) throws IOException {
// Don't reconnect if device was already connected
if (!(mSecurityTokenHelper.isPersistentConnectionAllowed()
&& mSecurityTokenHelper.isConnected()
&& mSecurityTokenHelper.getTransport().equals(transport))) {
mSecurityTokenHelper.setTransport(transport);
mSecurityTokenHelper.connectToDevice(ctx);
}
doSecurityTokenInBackground();
}
public boolean isSecurityTokenConnected() {
return mSecurityTokenHelper.isConnected();
protected void handleSecurityToken(SecurityTokenConnection stConnection) throws IOException {
doSecurityTokenInBackground(stConnection);
}
public static class IsoDepNotSupportedException extends IOException {
@@ -500,10 +496,6 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
mUsbDispatcher.onStart();
}
public SecurityTokenHelper getSecurityTokenHelper() {
return mSecurityTokenHelper;
}
/**
* Run Security Token routines if last used token is connected and supports
* persistent connections

View File

@@ -79,6 +79,7 @@ import org.sufficientlysecure.keychain.provider.KeyRepository;
import org.sufficientlysecure.keychain.provider.KeyRepository.NotFoundException;
import org.sufficientlysecure.keychain.provider.KeychainContract;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
import org.sufficientlysecure.keychain.service.ChangeUnlockParcel;
import org.sufficientlysecure.keychain.service.ImportKeyringParcel;
import org.sufficientlysecure.keychain.service.input.RequiredInputParcel;
@@ -619,8 +620,8 @@ public class ViewKeyActivity extends BaseSecurityTokenActivity implements
}
@Override
protected void onSecurityTokenPostExecute() {
super.onSecurityTokenPostExecute();
protected void onSecurityTokenPostExecute(SecurityTokenConnection stConnection) {
super.onSecurityTokenPostExecute(stConnection);
finish();
}