Merge pull request #2252 from open-keychain/refactor-securitytoken-ops
Refactor SecurityToken ops
This commit is contained in:
@@ -25,7 +25,7 @@ import org.sufficientlysecure.keychain.ui.CreateSecurityTokenAlgorithmFragment;
|
||||
|
||||
public abstract class KeyFormat {
|
||||
|
||||
enum KeyFormatType {
|
||||
public enum KeyFormatType {
|
||||
RSAKeyFormatType,
|
||||
ECKeyFormatType
|
||||
}
|
||||
@@ -36,7 +36,7 @@ public abstract class KeyFormat {
|
||||
mKeyFormatType = keyFormatType;
|
||||
}
|
||||
|
||||
final KeyFormatType keyFormatType() {
|
||||
public final KeyFormatType keyFormatType() {
|
||||
return mKeyFormatType;
|
||||
}
|
||||
|
||||
|
||||
@@ -18,159 +18,231 @@
|
||||
package org.sufficientlysecure.keychain.securitytoken;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
import android.support.annotation.NonNull;
|
||||
|
||||
import com.google.auto.value.AutoValue;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
|
||||
@SuppressWarnings("unused") // just expose all included data
|
||||
class OpenPgpCapabilities {
|
||||
@AutoValue
|
||||
public abstract 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 byte[] mAid;
|
||||
private byte[] mHistoricalBytes;
|
||||
private static final int MAX_PW1_LENGTH_INDEX = 1;
|
||||
private static final int MAX_PW3_LENGTH_INDEX = 3;
|
||||
|
||||
private boolean mHasSM;
|
||||
private boolean mAttriburesChangable;
|
||||
private boolean mHasKeyImport;
|
||||
public abstract byte[] getAid();
|
||||
abstract byte[] getHistoricalBytes();
|
||||
|
||||
private int mSMType;
|
||||
private int mMaxCmdLen;
|
||||
private int mMaxRspLen;
|
||||
@Nullable
|
||||
@SuppressWarnings("mutable")
|
||||
public abstract byte[] getFingerprintSign();
|
||||
@Nullable
|
||||
@SuppressWarnings("mutable")
|
||||
public abstract byte[] getFingerprintEncrypt();
|
||||
@Nullable
|
||||
@SuppressWarnings("mutable")
|
||||
public abstract byte[] getFingerprintAuth();
|
||||
public abstract byte[] getPwStatusBytes();
|
||||
|
||||
private Map<KeyType, KeyFormat> mKeyFormats;
|
||||
private byte[] mFingerprints;
|
||||
private byte[] mPwStatusBytes;
|
||||
public abstract KeyFormat getSignKeyFormat();
|
||||
public abstract KeyFormat getEncryptKeyFormat();
|
||||
public abstract KeyFormat getAuthKeyFormat();
|
||||
|
||||
OpenPgpCapabilities(byte[] data) throws IOException {
|
||||
mKeyFormats = new HashMap<>();
|
||||
updateWithData(data);
|
||||
abstract boolean isHasKeyImport();
|
||||
public abstract boolean isAttributesChangable();
|
||||
|
||||
abstract boolean isHasSM();
|
||||
abstract boolean isHasAesSm();
|
||||
abstract boolean isHasScp11bSm();
|
||||
|
||||
@Nullable
|
||||
abstract Integer getMaxCmdLen();
|
||||
@Nullable
|
||||
abstract Integer getMaxRspLen();
|
||||
|
||||
public static OpenPgpCapabilities fromBytes(byte[] rawOpenPgpCapabilities) throws IOException {
|
||||
Iso7816TLV[] parsedTlvData = Iso7816TLV.readList(rawOpenPgpCapabilities, true);
|
||||
return new AutoValue_OpenPgpCapabilities.Builder().updateWithTLV(parsedTlvData).build();
|
||||
}
|
||||
|
||||
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;
|
||||
public KeyFormat getFormatForKeyType(@NonNull KeyType keyType) {
|
||||
switch (keyType) {
|
||||
case SIGN: return getSignKeyFormat();
|
||||
case ENCRYPT: return getEncryptKeyFormat();
|
||||
case AUTH: return getAuthKeyFormat();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
for (Iso7816TLV tlv : tlvs) {
|
||||
switch (tlv.mT) {
|
||||
case 0x4F:
|
||||
mAid = tlv.mV;
|
||||
break;
|
||||
case 0x5F52:
|
||||
mHistoricalBytes = tlv.mV;
|
||||
break;
|
||||
case 0x73:
|
||||
parseDdo((Iso7816TLV.Iso7816CompositeTLV) tlv);
|
||||
break;
|
||||
case 0xC0:
|
||||
parseExtendedCaps(tlv.mV);
|
||||
break;
|
||||
case 0xC1:
|
||||
mKeyFormats.put(KeyType.SIGN, KeyFormat.fromBytes(tlv.mV));
|
||||
break;
|
||||
case 0xC2:
|
||||
mKeyFormats.put(KeyType.ENCRYPT, KeyFormat.fromBytes(tlv.mV));
|
||||
break;
|
||||
case 0xC3:
|
||||
mKeyFormats.put(KeyType.AUTH, KeyFormat.fromBytes(tlv.mV));
|
||||
break;
|
||||
case 0xC4:
|
||||
mPwStatusBytes = tlv.mV;
|
||||
break;
|
||||
case 0xC5:
|
||||
mFingerprints = tlv.mV;
|
||||
break;
|
||||
}
|
||||
@Nullable
|
||||
public byte[] getKeyFingerprint(@NonNull KeyType keyType) {
|
||||
switch (keyType) {
|
||||
case SIGN: return getFingerprintSign();
|
||||
case ENCRYPT: return getFingerprintEncrypt();
|
||||
case AUTH: return getFingerprintAuth();
|
||||
}
|
||||
}
|
||||
|
||||
private void parseDdo(Iso7816TLV.Iso7816CompositeTLV tlvs) {
|
||||
for (Iso7816TLV tlv : tlvs.mSubs) {
|
||||
switch (tlv.mT) {
|
||||
case 0xC0:
|
||||
parseExtendedCaps(tlv.mV);
|
||||
break;
|
||||
case 0xC1:
|
||||
mKeyFormats.put(KeyType.SIGN, KeyFormat.fromBytes(tlv.mV));
|
||||
break;
|
||||
case 0xC2:
|
||||
mKeyFormats.put(KeyType.ENCRYPT, KeyFormat.fromBytes(tlv.mV));
|
||||
break;
|
||||
case 0xC3:
|
||||
mKeyFormats.put(KeyType.AUTH, KeyFormat.fromBytes(tlv.mV));
|
||||
break;
|
||||
case 0xC4:
|
||||
mPwStatusBytes = tlv.mV;
|
||||
break;
|
||||
case 0xC5:
|
||||
mFingerprints = tlv.mV;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void parseExtendedCaps(byte[] v) {
|
||||
mHasSM = (v[0] & MASK_SM) != 0;
|
||||
mHasKeyImport = (v[0] & MASK_KEY_IMPORT) != 0;
|
||||
mAttriburesChangable = (v[0] & MASK_ATTRIBUTES_CHANGABLE) != 0;
|
||||
|
||||
mSMType = v[1];
|
||||
|
||||
mMaxCmdLen = (v[6] << 8) + v[7];
|
||||
mMaxRspLen = (v[8] << 8) + v[9];
|
||||
}
|
||||
|
||||
byte[] getAid() {
|
||||
return mAid;
|
||||
}
|
||||
|
||||
byte[] getPwStatusBytes() {
|
||||
return mPwStatusBytes;
|
||||
return null;
|
||||
}
|
||||
|
||||
boolean isPw1ValidForMultipleSignatures() {
|
||||
return mPwStatusBytes[0] == 1;
|
||||
return getPwStatusBytes()[0] == 1;
|
||||
}
|
||||
|
||||
byte[] getHistoricalBytes() {
|
||||
return mHistoricalBytes;
|
||||
public int getPw1MaxLength() {
|
||||
return getPwStatusBytes()[MAX_PW1_LENGTH_INDEX];
|
||||
}
|
||||
|
||||
boolean isHasSM() {
|
||||
return mHasSM;
|
||||
public int getPw3MaxLength() {
|
||||
return getPwStatusBytes()[MAX_PW3_LENGTH_INDEX];
|
||||
}
|
||||
|
||||
boolean isAttributesChangable() {
|
||||
return mAttriburesChangable;
|
||||
public int getPw1TriesLeft() {
|
||||
return getPwStatusBytes()[4];
|
||||
}
|
||||
|
||||
boolean isHasKeyImport() {
|
||||
return mHasKeyImport;
|
||||
public int getPw3TriesLeft() {
|
||||
return getPwStatusBytes()[6];
|
||||
}
|
||||
|
||||
boolean isHasAESSM() {
|
||||
return isHasSM() && ((mSMType == 1) || (mSMType == 2));
|
||||
}
|
||||
@AutoValue.Builder
|
||||
@SuppressWarnings("UnusedReturnValue")
|
||||
abstract static class Builder {
|
||||
abstract Builder aid(byte[] mV);
|
||||
abstract Builder historicalBytes(byte[] historicalBytes);
|
||||
|
||||
boolean isHasSCP11bSM() {
|
||||
return isHasSM() && (mSMType == 3);
|
||||
}
|
||||
abstract Builder fingerprintSign(byte[] fingerprint);
|
||||
abstract Builder fingerprintEncrypt(byte[] fingerprint);
|
||||
abstract Builder fingerprintAuth(byte[] fingerprint);
|
||||
|
||||
int getMaxCmdLen() {
|
||||
return mMaxCmdLen;
|
||||
}
|
||||
abstract Builder pwStatusBytes(byte[] mV);
|
||||
abstract Builder authKeyFormat(KeyFormat keyFormat);
|
||||
abstract Builder encryptKeyFormat(KeyFormat keyFormat);
|
||||
abstract Builder signKeyFormat(KeyFormat keyFormat);
|
||||
|
||||
int getMaxRspLen() {
|
||||
return mMaxRspLen;
|
||||
}
|
||||
|
||||
KeyFormat getFormatForKeyType(KeyType keyType) {
|
||||
return mKeyFormats.get(keyType);
|
||||
}
|
||||
abstract Builder hasKeyImport(boolean hasKeyImport);
|
||||
abstract Builder attributesChangable(boolean attributesChangable);
|
||||
|
||||
abstract Builder hasSM(boolean hasSm);
|
||||
abstract Builder hasAesSm(boolean hasAesSm);
|
||||
abstract Builder hasScp11bSm(boolean hasScp11bSm);
|
||||
|
||||
abstract Builder maxCmdLen(Integer maxCommandLen);
|
||||
abstract Builder maxRspLen(Integer MaxResponseLen);
|
||||
|
||||
abstract OpenPgpCapabilities build();
|
||||
|
||||
public Builder() {
|
||||
hasKeyImport(false);
|
||||
attributesChangable(false);
|
||||
hasSM(false);
|
||||
hasAesSm(false);
|
||||
hasScp11bSm(false);
|
||||
}
|
||||
|
||||
Builder updateWithTLV(Iso7816TLV[] tlvs) {
|
||||
if (tlvs.length == 1 && tlvs[0].mT == 0x6E) {
|
||||
tlvs = ((Iso7816TLV.Iso7816CompositeTLV) tlvs[0]).mSubs;
|
||||
}
|
||||
|
||||
for (Iso7816TLV tlv : tlvs) {
|
||||
switch (tlv.mT) {
|
||||
case 0x4F:
|
||||
aid(tlv.mV);
|
||||
break;
|
||||
case 0x5F52:
|
||||
historicalBytes(tlv.mV);
|
||||
break;
|
||||
case 0x73:
|
||||
parseDdo((Iso7816TLV.Iso7816CompositeTLV) tlv);
|
||||
break;
|
||||
case 0xC0:
|
||||
parseExtendedCaps(tlv.mV);
|
||||
break;
|
||||
case 0xC1:
|
||||
signKeyFormat(KeyFormat.fromBytes(tlv.mV));
|
||||
break;
|
||||
case 0xC2:
|
||||
encryptKeyFormat(KeyFormat.fromBytes(tlv.mV));
|
||||
break;
|
||||
case 0xC3:
|
||||
authKeyFormat(KeyFormat.fromBytes(tlv.mV));
|
||||
break;
|
||||
case 0xC4:
|
||||
pwStatusBytes(tlv.mV);
|
||||
break;
|
||||
case 0xC5:
|
||||
parseFingerprints(tlv.mV);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
private void parseDdo(Iso7816TLV.Iso7816CompositeTLV tlvs) {
|
||||
for (Iso7816TLV tlv : tlvs.mSubs) {
|
||||
switch (tlv.mT) {
|
||||
case 0xC0:
|
||||
parseExtendedCaps(tlv.mV);
|
||||
break;
|
||||
case 0xC1:
|
||||
signKeyFormat(KeyFormat.fromBytes(tlv.mV));
|
||||
break;
|
||||
case 0xC2:
|
||||
encryptKeyFormat(KeyFormat.fromBytes(tlv.mV));
|
||||
break;
|
||||
case 0xC3:
|
||||
authKeyFormat(KeyFormat.fromBytes(tlv.mV));
|
||||
break;
|
||||
case 0xC4:
|
||||
pwStatusBytes(tlv.mV);
|
||||
break;
|
||||
case 0xC5:
|
||||
parseFingerprints(tlv.mV);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void parseFingerprints(byte[] mV) {
|
||||
ByteBuffer fpBuf = ByteBuffer.wrap(mV);
|
||||
|
||||
byte[] buf;
|
||||
|
||||
buf = new byte[20];
|
||||
fpBuf.get(buf);
|
||||
fingerprintSign(buf);
|
||||
|
||||
buf = new byte[20];
|
||||
fpBuf.get(buf);
|
||||
fingerprintEncrypt(buf);
|
||||
|
||||
buf = new byte[20];
|
||||
fpBuf.get(buf);
|
||||
fingerprintAuth(buf);
|
||||
}
|
||||
|
||||
private void parseExtendedCaps(byte[] v) {
|
||||
hasKeyImport((v[0] & MASK_KEY_IMPORT) != 0);
|
||||
attributesChangable((v[0] & MASK_ATTRIBUTES_CHANGABLE) != 0);
|
||||
|
||||
if ((v[0] & MASK_SM) != 0) {
|
||||
hasSM(true);
|
||||
int smType = v[1];
|
||||
hasAesSm(smType == 1 || smType == 2);
|
||||
hasScp11bSm(smType == 3);
|
||||
}
|
||||
|
||||
maxCmdLen((v[6] << 8) + v[7]);
|
||||
maxRspLen((v[8] << 8) + v[9]);
|
||||
}
|
||||
|
||||
public byte[] getFingerprints() {
|
||||
return mFingerprints;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ import org.bouncycastle.util.Arrays;
|
||||
import org.bouncycastle.util.encoders.Hex;
|
||||
|
||||
|
||||
class OpenPgpCommandApduFactory {
|
||||
public class OpenPgpCommandApduFactory {
|
||||
private static final int MAX_APDU_NC = 255;
|
||||
private static final int MAX_APDU_NC_EXT = 65535;
|
||||
|
||||
@@ -90,66 +90,11 @@ class OpenPgpCommandApduFactory {
|
||||
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);
|
||||
@@ -161,12 +106,67 @@ class OpenPgpCommandApduFactory {
|
||||
}
|
||||
|
||||
@NonNull
|
||||
CommandApdu createReactivate1Command() {
|
||||
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
|
||||
public CommandApdu createPutDataCommand(int dataObject, byte[] data) {
|
||||
return CommandApdu.create(CLA, INS_PUT_DATA, (dataObject & 0xFF00) >> 8, dataObject & 0xFF, data);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public 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
|
||||
public 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
|
||||
public CommandApdu createDecipherCommand(byte[] data) {
|
||||
return CommandApdu.create(CLA, INS_PERFORM_SECURITY_OPERATION, P1_PSO_DECIPHER, P2_PSO_DECIPHER, data,
|
||||
MAX_APDU_NE_EXT);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public 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
|
||||
public CommandApdu createResetPw1Command(byte[] newPin) {
|
||||
return CommandApdu.create(CLA, INS_RESET_RETRY_COUNTER, P1_RESET_RETRY_COUNTER_NEW_PW,
|
||||
P2_RESET_RETRY_COUNTER, newPin);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public CommandApdu createVerifyPw1ForSignatureCommand(byte[] pin) {
|
||||
return CommandApdu.create(CLA, INS_VERIFY, P1_EMPTY, P2_VERIFY_PW1_SIGN, pin);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public CommandApdu createVerifyPw3Command(byte[] pin) {
|
||||
return CommandApdu.create(CLA, INS_VERIFY, P1_EMPTY, P2_VERIFY_PW3, pin);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public CommandApdu createReactivate1Command() {
|
||||
return CommandApdu.create(CLA, INS_TERMINATE_DF, P1_EMPTY, P2_EMPTY);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
CommandApdu createReactivate2Command() {
|
||||
public CommandApdu createReactivate2Command() {
|
||||
return CommandApdu.create(CLA, INS_ACTIVATE_FILE, P1_EMPTY, P2_EMPTY);
|
||||
}
|
||||
|
||||
@@ -177,12 +177,12 @@ class OpenPgpCommandApduFactory {
|
||||
}
|
||||
|
||||
@NonNull
|
||||
CommandApdu createInternalAuthCommand(byte[] authData) {
|
||||
public CommandApdu createInternalAuthCommand(byte[] authData) {
|
||||
return CommandApdu.create(CLA, INS_INTERNAL_AUTHENTICATE, P1_EMPTY, P2_EMPTY, authData, MAX_APDU_NE_EXT);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
CommandApdu createGenerateKeyCommand(int slot) {
|
||||
public 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);
|
||||
}
|
||||
|
||||
@@ -55,6 +55,7 @@ import java.security.spec.InvalidParameterSpecException;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import android.content.Context;
|
||||
import android.support.annotation.CheckResult;
|
||||
import android.support.annotation.NonNull;
|
||||
|
||||
import javax.crypto.BadPaddingException;
|
||||
@@ -272,7 +273,9 @@ class SCP11bSecureMessaging implements SecureMessaging {
|
||||
}
|
||||
|
||||
|
||||
static void establish(final SecurityTokenConnection t, final Context ctx, OpenPgpCommandApduFactory commandFactory)
|
||||
@CheckResult
|
||||
static SecureMessaging establish(final SecurityTokenConnection t, final Context ctx,
|
||||
OpenPgpCommandApduFactory commandFactory)
|
||||
throws SecureMessagingException, IOException {
|
||||
|
||||
CommandApdu cmd;
|
||||
@@ -478,7 +481,7 @@ class SCP11bSecureMessaging implements SecureMessaging {
|
||||
final SCP11bSecureMessaging sm = new SCP11bSecureMessaging();
|
||||
sm.setKeys(sEnc, sMac, sRmac, receipt);
|
||||
|
||||
t.setSecureMessaging(sm);
|
||||
return sm;
|
||||
|
||||
} catch (InvalidKeySpecException e) {
|
||||
throw new SecureMessagingException("invalid key specification : " + e.getMessage());
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -166,6 +166,13 @@ public abstract class SecurityTokenInfo implements Parcelable {
|
||||
return Version.create(matcher.group(1));
|
||||
}
|
||||
|
||||
public double getOpenPgpVersion() {
|
||||
byte[] aid = getAid();
|
||||
float minv = aid[7];
|
||||
while (minv > 0) minv /= 10.0;
|
||||
return aid[6] + minv;
|
||||
}
|
||||
|
||||
@AutoValue
|
||||
public static abstract class Version implements Comparable<Version> {
|
||||
|
||||
|
||||
@@ -32,8 +32,9 @@ import java.security.interfaces.ECPublicKey;
|
||||
import java.security.interfaces.RSAPrivateCrtKey;
|
||||
|
||||
|
||||
class SecurityTokenUtils {
|
||||
static byte[] attributesFromSecretKey(KeyType slot, CanonicalizedSecretKey secretKey, KeyFormat formatForKeyType)
|
||||
public class SecurityTokenUtils {
|
||||
public static byte[] attributesFromSecretKey(KeyType slot, CanonicalizedSecretKey secretKey,
|
||||
KeyFormat formatForKeyType)
|
||||
throws IOException {
|
||||
if (secretKey.isRSA()) {
|
||||
return attributesForRsaKey(secretKey.getBitStrength(), (RSAKeyFormat) formatForKeyType);
|
||||
@@ -73,7 +74,7 @@ class SecurityTokenUtils {
|
||||
return attrs;
|
||||
}
|
||||
|
||||
static byte[] createRSAPrivKeyTemplate(RSAPrivateCrtKey secretKey, KeyType slot,
|
||||
public static byte[] createRSAPrivKeyTemplate(RSAPrivateCrtKey secretKey, KeyType slot,
|
||||
RSAKeyFormat format) throws IOException {
|
||||
ByteArrayOutputStream stream = new ByteArrayOutputStream(),
|
||||
template = new ByteArrayOutputStream(),
|
||||
@@ -141,7 +142,7 @@ class SecurityTokenUtils {
|
||||
return res.toByteArray();
|
||||
}
|
||||
|
||||
static byte[] createECPrivKeyTemplate(ECPrivateKey secretKey, ECPublicKey publicKey, KeyType slot,
|
||||
public static byte[] createECPrivKeyTemplate(ECPrivateKey secretKey, ECPublicKey publicKey, KeyType slot,
|
||||
ECKeyFormat format) throws IOException {
|
||||
ByteArrayOutputStream stream = new ByteArrayOutputStream(),
|
||||
template = new ByteArrayOutputStream(),
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* Copyright (C) 2018 Schürmann & Breitmoser GbR
|
||||
*
|
||||
* 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.operations;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.sufficientlysecure.keychain.securitytoken.CommandApdu;
|
||||
import org.sufficientlysecure.keychain.securitytoken.ResponseApdu;
|
||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
|
||||
import org.sufficientlysecure.keychain.util.Passphrase;
|
||||
|
||||
|
||||
public class GenerateKeyTokenOp {
|
||||
private final SecurityTokenConnection connection;
|
||||
|
||||
public static GenerateKeyTokenOp create(SecurityTokenConnection connection) {
|
||||
return new GenerateKeyTokenOp(connection);
|
||||
}
|
||||
|
||||
private GenerateKeyTokenOp(SecurityTokenConnection connection) {
|
||||
this.connection = connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a key on the card in the given slot. If the slot is 0xB6 (the signature key),
|
||||
* this command also has the effect of resetting the digital signature counter.
|
||||
* NOTE: This does not set the key fingerprint data object! After calling this command, you
|
||||
* must construct a public key packet using the returned public key data objects, compute the
|
||||
* key fingerprint, and store it on the card using: putData(0xC8, key.getFingerprint())
|
||||
*
|
||||
* @param slot The slot on the card where the key should be generated:
|
||||
* 0xB6: Signature Key
|
||||
* 0xB8: Decipherment Key
|
||||
* 0xA4: Authentication Key
|
||||
* @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(Passphrase adminPin, int slot) throws IOException {
|
||||
if (slot != 0xB6 && slot != 0xB8 && slot != 0xA4) {
|
||||
throw new IOException("Invalid key slot");
|
||||
}
|
||||
|
||||
connection.verifyAdminPin(adminPin);
|
||||
|
||||
CommandApdu apdu = connection.getCommandFactory().createGenerateKeyCommand(slot);
|
||||
ResponseApdu response = connection.communicate(apdu);
|
||||
|
||||
if (!response.isSuccess()) {
|
||||
throw new IOException("On-card key generation failed");
|
||||
}
|
||||
|
||||
return response.getData();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* Copyright (C) 2018 Schürmann & Breitmoser GbR
|
||||
*
|
||||
* 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.operations;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.sufficientlysecure.keychain.securitytoken.CardException;
|
||||
import org.sufficientlysecure.keychain.securitytoken.CommandApdu;
|
||||
import org.sufficientlysecure.keychain.securitytoken.ResponseApdu;
|
||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
|
||||
import org.sufficientlysecure.keychain.util.Passphrase;
|
||||
|
||||
|
||||
public class ModifyPinTokenOp {
|
||||
private static final int MIN_PW3_LENGTH = 8;
|
||||
|
||||
private final SecurityTokenConnection connection;
|
||||
private final Passphrase adminPin;
|
||||
|
||||
public static ModifyPinTokenOp create(SecurityTokenConnection connection, Passphrase adminPin) {
|
||||
return new ModifyPinTokenOp(connection, adminPin);
|
||||
}
|
||||
|
||||
private ModifyPinTokenOp(SecurityTokenConnection connection,
|
||||
Passphrase adminPin) {
|
||||
this.connection = connection;
|
||||
this.adminPin = adminPin;
|
||||
}
|
||||
|
||||
public void modifyPw1andPw3Pins(byte[] newPin, byte[] newAdminPin) throws IOException {
|
||||
// Order is important for Gnuk, otherwise it will be set up in "admin less mode".
|
||||
// http://www.fsij.org/doc-gnuk/gnuk-passphrase-setting.html#set-up-pw1-pw3-and-reset-code
|
||||
modifyPw3Pin(newAdminPin);
|
||||
modifyPw1PinWithEffectiveAdminPin(new Passphrase(new String(newAdminPin)), newPin);
|
||||
}
|
||||
|
||||
public void modifyPw1Pin(byte[] newPin) throws IOException {
|
||||
modifyPw1PinWithEffectiveAdminPin(adminPin, newPin);
|
||||
}
|
||||
|
||||
private void modifyPw1PinWithEffectiveAdminPin(Passphrase effectiveAdminPin, byte[] newPin) throws IOException {
|
||||
connection.verifyAdminPin(effectiveAdminPin);
|
||||
|
||||
int maxPw1Length = connection.getOpenPgpCapabilities().getPw3MaxLength();
|
||||
if (newPin.length < 6 || newPin.length > maxPw1Length) {
|
||||
throw new IOException("Invalid PIN length");
|
||||
}
|
||||
|
||||
CommandApdu changePin = connection.getCommandFactory().createResetPw1Command(newPin);
|
||||
ResponseApdu response = connection.communicate(changePin);
|
||||
|
||||
if (!response.isSuccess()) {
|
||||
throw new CardException("Failed to change PIN", response.getSw());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Modifies the user's PW3. Before sending, the new PIN will be validated for
|
||||
* conformance to the token's requirements for key length.
|
||||
*/
|
||||
private void modifyPw3Pin(byte[] newAdminPin) throws IOException {
|
||||
int maxPw3Length = connection.getOpenPgpCapabilities().getPw3MaxLength();
|
||||
|
||||
if (newAdminPin.length < MIN_PW3_LENGTH || newAdminPin.length > maxPw3Length) {
|
||||
throw new IOException("Invalid PIN length");
|
||||
}
|
||||
|
||||
byte[] pin = adminPin.toStringUnsafe().getBytes();
|
||||
|
||||
CommandApdu changePin = connection.getCommandFactory().createChangePw3Command(pin, newAdminPin);
|
||||
ResponseApdu response = connection.communicate(changePin);
|
||||
|
||||
connection.invalidatePw3();
|
||||
|
||||
if (!response.isSuccess()) {
|
||||
throw new CardException("Failed to change PIN", response.getSw());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
/*
|
||||
* Copyright (C) 2018 Schürmann & Breitmoser GbR
|
||||
*
|
||||
* 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.operations;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.Key;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import android.support.annotation.NonNull;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.NoSuchPaddingException;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.bouncycastle.asn1.nist.NISTNamedCurves;
|
||||
import org.bouncycastle.asn1.x9.X9ECParameters;
|
||||
import org.bouncycastle.jcajce.util.MessageDigestUtils;
|
||||
import org.bouncycastle.math.ec.ECPoint;
|
||||
import org.bouncycastle.openpgp.PGPException;
|
||||
import org.bouncycastle.openpgp.operator.PGPPad;
|
||||
import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator;
|
||||
import org.bouncycastle.util.Arrays;
|
||||
import org.bouncycastle.util.encoders.Hex;
|
||||
import org.sufficientlysecure.keychain.pgp.CanonicalizedPublicKey;
|
||||
import org.sufficientlysecure.keychain.securitytoken.CardException;
|
||||
import org.sufficientlysecure.keychain.securitytoken.CommandApdu;
|
||||
import org.sufficientlysecure.keychain.securitytoken.ECKeyFormat;
|
||||
import org.sufficientlysecure.keychain.securitytoken.KeyFormat;
|
||||
import org.sufficientlysecure.keychain.securitytoken.KeyType;
|
||||
import org.sufficientlysecure.keychain.securitytoken.ResponseApdu;
|
||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
|
||||
|
||||
|
||||
/** This class implements the PSO:DECIPHER operation, as specified in OpenPGP card spec / 7.2.11 (p52 in v3.0.1).
|
||||
*
|
||||
* See https://www.g10code.com/docs/openpgp-card-3.0.pdf
|
||||
*/
|
||||
public class PsoDecryptTokenOp {
|
||||
private final SecurityTokenConnection connection;
|
||||
private final JcaKeyFingerprintCalculator fingerprintCalculator;
|
||||
|
||||
public static PsoDecryptTokenOp create(SecurityTokenConnection connection) {
|
||||
return new PsoDecryptTokenOp(connection, new JcaKeyFingerprintCalculator());
|
||||
}
|
||||
|
||||
private PsoDecryptTokenOp(SecurityTokenConnection connection,
|
||||
JcaKeyFingerprintCalculator jcaKeyFingerprintCalculator) {
|
||||
this.connection = connection;
|
||||
this.fingerprintCalculator = jcaKeyFingerprintCalculator;
|
||||
}
|
||||
|
||||
public byte[] verifyAndDecryptSessionKey(@NonNull byte[] encryptedSessionKeyMpi, CanonicalizedPublicKey publicKey)
|
||||
throws IOException {
|
||||
connection.verifyPinForOther();
|
||||
|
||||
KeyFormat kf = connection.getOpenPgpCapabilities().getEncryptKeyFormat();
|
||||
switch (kf.keyFormatType()) {
|
||||
case RSAKeyFormatType:
|
||||
return decryptSessionKeyRsa(encryptedSessionKeyMpi);
|
||||
|
||||
case ECKeyFormatType:
|
||||
return decryptSessionKeyEcdh(encryptedSessionKeyMpi, (ECKeyFormat) kf, publicKey);
|
||||
|
||||
default:
|
||||
throw new CardException("Unknown encryption key type!");
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] decryptSessionKeyRsa(byte[] encryptedSessionKeyMpi) throws IOException {
|
||||
int mpiLength = getMpiLength(encryptedSessionKeyMpi);
|
||||
if (mpiLength != encryptedSessionKeyMpi.length - 2) {
|
||||
throw new IOException("Malformed RSA session key!");
|
||||
}
|
||||
|
||||
byte[] psoDecipherPayload = new byte[mpiLength + 1];
|
||||
psoDecipherPayload[0] = (byte) 0x00; // RSA Padding Indicator Byte
|
||||
System.arraycopy(encryptedSessionKeyMpi, 2, psoDecipherPayload, 1, mpiLength);
|
||||
|
||||
CommandApdu command = connection.getCommandFactory().createDecipherCommand(psoDecipherPayload);
|
||||
ResponseApdu response = connection.communicate(command);
|
||||
|
||||
if (!response.isSuccess()) {
|
||||
throw new CardException("Deciphering with Security token failed on receive", response.getSw());
|
||||
}
|
||||
|
||||
return response.getData();
|
||||
}
|
||||
|
||||
private byte[] decryptSessionKeyEcdh(byte[] encryptedSessionKeyMpi, ECKeyFormat eckf, CanonicalizedPublicKey publicKey)
|
||||
throws IOException {
|
||||
int mpiLength = getMpiLength(encryptedSessionKeyMpi);
|
||||
byte[] encryptedPoint = Arrays.copyOfRange(encryptedSessionKeyMpi, 2, mpiLength);
|
||||
|
||||
X9ECParameters x9Params = NISTNamedCurves.getByOID(eckf.getCurveOID());
|
||||
ECPoint p = x9Params.getCurve().decodePoint(encryptedPoint);
|
||||
if (!p.isValid()) {
|
||||
throw new CardException("Invalid EC point!");
|
||||
}
|
||||
|
||||
byte[] psoDecipherPayload = p.getEncoded(false);
|
||||
|
||||
byte[] dataLen;
|
||||
if (psoDecipherPayload.length < 128) {
|
||||
dataLen = new byte[]{(byte) psoDecipherPayload.length};
|
||||
} else {
|
||||
dataLen = new byte[]{(byte) 0x81, (byte) psoDecipherPayload.length};
|
||||
}
|
||||
psoDecipherPayload = Arrays.concatenate(Hex.decode("86"), dataLen, psoDecipherPayload);
|
||||
|
||||
if (psoDecipherPayload.length < 128) {
|
||||
dataLen = new byte[]{(byte) psoDecipherPayload.length};
|
||||
} else {
|
||||
dataLen = new byte[]{(byte) 0x81, (byte) psoDecipherPayload.length};
|
||||
}
|
||||
psoDecipherPayload = Arrays.concatenate(Hex.decode("7F49"), dataLen, psoDecipherPayload);
|
||||
|
||||
if (psoDecipherPayload.length < 128) {
|
||||
dataLen = new byte[]{(byte) psoDecipherPayload.length};
|
||||
} else {
|
||||
dataLen = new byte[]{(byte) 0x81, (byte) psoDecipherPayload.length};
|
||||
}
|
||||
psoDecipherPayload = Arrays.concatenate(Hex.decode("A6"), dataLen, psoDecipherPayload);
|
||||
|
||||
CommandApdu command = connection.getCommandFactory().createDecipherCommand(psoDecipherPayload);
|
||||
ResponseApdu response = connection.communicate(command);
|
||||
|
||||
if (!response.isSuccess()) {
|
||||
throw new CardException("Deciphering with Security token failed on receive", response.getSw());
|
||||
}
|
||||
|
||||
/* From 3.x OpenPGP card specification :
|
||||
In case of ECDH the card supports a partial decrypt only.
|
||||
With its own private key and the given public key the card calculates a shared secret
|
||||
in compliance with the Elliptic Curve Key Agreement Scheme from Diffie-Hellman.
|
||||
The shared secret is returned in the response, all other calculation for deciphering
|
||||
are done outside of the card.
|
||||
|
||||
The shared secret obtained is a KEK (Key Encryption Key) that is used to wrap the
|
||||
session key.
|
||||
|
||||
From rfc6637#section-13 :
|
||||
This document explicitly discourages the use of algorithms other than AES as a KEK algorithm.
|
||||
*/
|
||||
byte[] keyEncryptionKey = response.getData();
|
||||
|
||||
final byte[] keyEnc = new byte[encryptedSessionKeyMpi[mpiLength + 2]];
|
||||
|
||||
System.arraycopy(encryptedSessionKeyMpi, 2 + mpiLength + 1, keyEnc, 0, keyEnc.length);
|
||||
|
||||
try {
|
||||
final MessageDigest kdf = MessageDigest.getInstance(MessageDigestUtils.getDigestName(publicKey.getSecurityTokenHashAlgorithm()));
|
||||
|
||||
kdf.update(new byte[]{(byte) 0, (byte) 0, (byte) 0, (byte) 1});
|
||||
kdf.update(keyEncryptionKey);
|
||||
kdf.update(publicKey.createUserKeyingMaterial(fingerprintCalculator));
|
||||
|
||||
byte[] kek = kdf.digest();
|
||||
Cipher c = Cipher.getInstance("AESWrap");
|
||||
|
||||
c.init(Cipher.UNWRAP_MODE, new SecretKeySpec(kek, 0, publicKey.getSecurityTokenSymmetricKeySize() / 8, "AES"));
|
||||
|
||||
Key paddedSessionKey = c.unwrap(keyEnc, "Session", Cipher.SECRET_KEY);
|
||||
|
||||
Arrays.fill(kek, (byte) 0);
|
||||
|
||||
return PGPPad.unpadSessionData(paddedSessionKey.getEncoded());
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new CardException("Unknown digest/encryption algorithm!");
|
||||
} catch (NoSuchPaddingException e) {
|
||||
throw new CardException("Unknown padding algorithm!");
|
||||
} catch (PGPException e) {
|
||||
throw new CardException(e.getMessage());
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new CardException("Invalid KEK!");
|
||||
}
|
||||
}
|
||||
|
||||
private int getMpiLength(byte[] multiPrecisionInteger) {
|
||||
return ((((multiPrecisionInteger[0] & 0xff) << 8) + (multiPrecisionInteger[1] & 0xff)) + 7) / 8;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Copyright (C) 2018 Schürmann & Breitmoser GbR
|
||||
*
|
||||
* 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.operations;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.sufficientlysecure.keychain.securitytoken.CardException;
|
||||
import org.sufficientlysecure.keychain.securitytoken.CommandApdu;
|
||||
import org.sufficientlysecure.keychain.securitytoken.ResponseApdu;
|
||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
|
||||
|
||||
|
||||
public class ResetAndWipeTokenOp {
|
||||
private static final byte[] INVALID_PIN = "XXXXXXXXXXX".getBytes();
|
||||
|
||||
private final SecurityTokenConnection connection;
|
||||
|
||||
public static ResetAndWipeTokenOp create(SecurityTokenConnection connection) {
|
||||
return new ResetAndWipeTokenOp(connection);
|
||||
}
|
||||
|
||||
private ResetAndWipeTokenOp(SecurityTokenConnection connection) {
|
||||
this.connection = connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets security token, which deletes all keys and data objects.
|
||||
* This works by entering a wrong PIN and then Admin PIN 4 times respectively.
|
||||
* Afterwards, the token is reactivated.
|
||||
*/
|
||||
public void resetAndWipeToken() throws IOException {
|
||||
exhausePw1Tries();
|
||||
exhaustPw3Tries();
|
||||
|
||||
// secure messaging must be disabled before reactivation
|
||||
connection.clearSecureMessaging();
|
||||
|
||||
// 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 = connection.getCommandFactory().createReactivate1Command();
|
||||
connection.communicate(reactivate1);
|
||||
|
||||
CommandApdu reactivate2 = connection.getCommandFactory().createReactivate2Command();
|
||||
ResponseApdu response2 = connection.communicate(reactivate2);
|
||||
if (!response2.isSuccess()) {
|
||||
throw new CardException("Reactivating failed!", response2.getSw());
|
||||
}
|
||||
|
||||
connection.refreshConnectionCapabilities();
|
||||
}
|
||||
|
||||
private void exhausePw1Tries() throws IOException {
|
||||
CommandApdu verifyPw1ForSignatureCommand =
|
||||
connection.getCommandFactory().createVerifyPw1ForSignatureCommand(INVALID_PIN);
|
||||
|
||||
int pw1TriesLeft = Math.max(3, connection.getOpenPgpCapabilities().getPw1TriesLeft());
|
||||
for (int i = 0; i < pw1TriesLeft; i++) {
|
||||
ResponseApdu response = connection.communicate(verifyPw1ForSignatureCommand);
|
||||
if (response.isSuccess()) {
|
||||
throw new CardException("Should never happen, PIN XXXXXXXX has been accepted!", response.getSw());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void exhaustPw3Tries() throws IOException {
|
||||
CommandApdu verifyPw3Command = connection.getCommandFactory().createVerifyPw3Command(INVALID_PIN);
|
||||
|
||||
int pw3TriesLeft = Math.max(3, connection.getOpenPgpCapabilities().getPw3TriesLeft());
|
||||
for (int i = 0; i < pw3TriesLeft; i++) {
|
||||
ResponseApdu response = connection.communicate(verifyPw3Command);
|
||||
if (response.isSuccess()) { // Should NOT accept!
|
||||
throw new CardException("Should never happen, PIN XXXXXXXX has been accepted!", response.getSw());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
/*
|
||||
* Copyright (C) 2018 Schürmann & Breitmoser GbR
|
||||
*
|
||||
* 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.operations;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.interfaces.ECPrivateKey;
|
||||
import java.security.interfaces.ECPublicKey;
|
||||
import java.security.interfaces.RSAPrivateCrtKey;
|
||||
import java.util.Arrays;
|
||||
|
||||
import android.support.annotation.VisibleForTesting;
|
||||
|
||||
import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey;
|
||||
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
|
||||
import org.sufficientlysecure.keychain.securitytoken.CardException;
|
||||
import org.sufficientlysecure.keychain.securitytoken.CommandApdu;
|
||||
import org.sufficientlysecure.keychain.securitytoken.ECKeyFormat;
|
||||
import org.sufficientlysecure.keychain.securitytoken.KeyFormat;
|
||||
import org.sufficientlysecure.keychain.securitytoken.KeyType;
|
||||
import org.sufficientlysecure.keychain.securitytoken.OpenPgpCapabilities;
|
||||
import org.sufficientlysecure.keychain.securitytoken.RSAKeyFormat;
|
||||
import org.sufficientlysecure.keychain.securitytoken.ResponseApdu;
|
||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
|
||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenUtils;
|
||||
import org.sufficientlysecure.keychain.util.Passphrase;
|
||||
|
||||
|
||||
public class SecurityTokenChangeKeyTokenOp {
|
||||
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 final SecurityTokenConnection connection;
|
||||
|
||||
public static SecurityTokenChangeKeyTokenOp create(SecurityTokenConnection stConnection) {
|
||||
return new SecurityTokenChangeKeyTokenOp(stConnection);
|
||||
}
|
||||
|
||||
private SecurityTokenChangeKeyTokenOp(SecurityTokenConnection connection) {
|
||||
this.connection = connection;
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
if (keyType == null) {
|
||||
throw new IOException("Inappropriate key flags for smart card key.");
|
||||
}
|
||||
|
||||
// Slot is empty, or contains this key already. PUT KEY operation is safe
|
||||
boolean canPutKey = isSlotEmpty(keyType)
|
||||
|| keyMatchesFingerPrint(keyType, secretKey.getFingerprint());
|
||||
|
||||
if (!canPutKey) {
|
||||
throw new IOException(String.format("Key slot occupied; card must be reset to put new %s key.",
|
||||
keyType.toString()));
|
||||
}
|
||||
|
||||
putKey(keyType, secretKey, passphrase, adminPin);
|
||||
putData(adminPin, keyType.getFingerprintObjectId(), secretKey.getFingerprint());
|
||||
putData(adminPin, keyType.getTimestampObjectId(), timestampBytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts a key on the token in the given slot.
|
||||
*
|
||||
* @param slot The slot on the token where the key should be stored:
|
||||
* 0xB6: Signature Key
|
||||
* 0xB8: Decipherment Key
|
||||
* 0xA4: Authentication Key
|
||||
*/
|
||||
@VisibleForTesting
|
||||
void putKey(KeyType slot, CanonicalizedSecretKey secretKey, Passphrase passphrase, Passphrase adminPin)
|
||||
throws IOException {
|
||||
RSAPrivateCrtKey crtSecretKey;
|
||||
ECPrivateKey ecSecretKey;
|
||||
ECPublicKey ecPublicKey;
|
||||
|
||||
connection.verifyAdminPin(adminPin);
|
||||
|
||||
// Now we're ready to communicate with the token.
|
||||
byte[] keyBytes;
|
||||
|
||||
try {
|
||||
secretKey.unlock(passphrase);
|
||||
|
||||
OpenPgpCapabilities openPgpCapabilities = connection.getOpenPgpCapabilities();
|
||||
|
||||
setKeyAttributes(adminPin, slot, SecurityTokenUtils.attributesFromSecretKey(slot, secretKey,
|
||||
openPgpCapabilities.getFormatForKeyType(slot)));
|
||||
|
||||
KeyFormat formatForKeyType = openPgpCapabilities.getFormatForKeyType(slot);
|
||||
switch (formatForKeyType.keyFormatType()) {
|
||||
case RSAKeyFormatType:
|
||||
if (!secretKey.isRSA()) {
|
||||
throw new IOException("Security Token not configured for RSA key.");
|
||||
}
|
||||
crtSecretKey = secretKey.getSecurityTokenRSASecretKey();
|
||||
|
||||
// Should happen only rarely; all GnuPG keys since 2006 use public exponent 65537.
|
||||
if (!crtSecretKey.getPublicExponent().equals(new BigInteger("65537"))) {
|
||||
throw new IOException("Invalid public exponent for smart Security Token.");
|
||||
}
|
||||
|
||||
keyBytes = SecurityTokenUtils.createRSAPrivKeyTemplate(crtSecretKey, slot,
|
||||
(RSAKeyFormat) formatForKeyType);
|
||||
break;
|
||||
|
||||
case ECKeyFormatType:
|
||||
if (!secretKey.isEC()) {
|
||||
throw new IOException("Security Token not configured for EC key.");
|
||||
}
|
||||
|
||||
secretKey.unlock(passphrase);
|
||||
ecSecretKey = secretKey.getSecurityTokenECSecretKey();
|
||||
ecPublicKey = secretKey.getSecurityTokenECPublicKey();
|
||||
|
||||
keyBytes = SecurityTokenUtils.createECPrivKeyTemplate(ecSecretKey, ecPublicKey, slot,
|
||||
(ECKeyFormat) formatForKeyType);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new IOException("Key type unsupported by security token.");
|
||||
}
|
||||
} catch (PgpGeneralException e) {
|
||||
throw new IOException(e.getMessage());
|
||||
}
|
||||
|
||||
CommandApdu apdu = connection.getCommandFactory().createPutKeyCommand(keyBytes);
|
||||
ResponseApdu response = connection.communicate(apdu);
|
||||
|
||||
if (!response.isSuccess()) {
|
||||
throw new CardException("Key export to Security Token failed", response.getSw());
|
||||
}
|
||||
}
|
||||
|
||||
private void setKeyAttributes(Passphrase adminPin, KeyType keyType, byte[] data) throws IOException {
|
||||
if (!connection.getOpenPgpCapabilities().isAttributesChangable()) {
|
||||
return;
|
||||
}
|
||||
|
||||
putData(adminPin, keyType.getAlgoAttributeSlot(), data);
|
||||
|
||||
connection.refreshConnectionCapabilities();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores a data object on the token. Automatically validates the proper PIN for the operation.
|
||||
* Supported for all data objects < 255 bytes in length. Only the cardholder certificate
|
||||
* (0x7F21) can exceed this length.
|
||||
*
|
||||
* @param dataObject The data object to be stored.
|
||||
* @param data The data to store in the object
|
||||
*/
|
||||
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) {
|
||||
connection.verifyPinForOther();
|
||||
} else {
|
||||
connection.verifyAdminPin(adminPin);
|
||||
}
|
||||
|
||||
CommandApdu command = connection.getCommandFactory().createPutDataCommand(dataObject, data);
|
||||
ResponseApdu response = connection.communicate(command);
|
||||
|
||||
if (!response.isSuccess()) {
|
||||
throw new CardException("Failed to put data.", response.getSw());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isSlotEmpty(KeyType keyType) throws IOException {
|
||||
// Note: special case: This should not happen, but happens with
|
||||
// https://github.com/FluffyKaon/OpenPGP-Card, thus for now assume true
|
||||
if (connection.getOpenPgpCapabilities().getKeyFingerprint(keyType) == null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return keyMatchesFingerPrint(keyType, BLANK_FINGERPRINT);
|
||||
}
|
||||
|
||||
private boolean keyMatchesFingerPrint(KeyType keyType, byte[] expectedFingerprint) throws IOException {
|
||||
byte[] actualFp = connection.getOpenPgpCapabilities().getKeyFingerprint(keyType);
|
||||
return Arrays.equals(actualFp, expectedFingerprint);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
/*
|
||||
* Copyright (C) 2018 Schürmann & Breitmoser GbR
|
||||
*
|
||||
* 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.operations;
|
||||
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.bouncycastle.asn1.ASN1Encodable;
|
||||
import org.bouncycastle.asn1.ASN1Integer;
|
||||
import org.bouncycastle.asn1.ASN1OutputStream;
|
||||
import org.bouncycastle.asn1.DERSequence;
|
||||
import org.bouncycastle.bcpg.HashAlgorithmTags;
|
||||
import org.bouncycastle.util.Arrays;
|
||||
import org.bouncycastle.util.encoders.Hex;
|
||||
import org.sufficientlysecure.keychain.Constants;
|
||||
import org.sufficientlysecure.keychain.securitytoken.CardException;
|
||||
import org.sufficientlysecure.keychain.securitytoken.CommandApdu;
|
||||
import org.sufficientlysecure.keychain.securitytoken.KeyFormat;
|
||||
import org.sufficientlysecure.keychain.securitytoken.KeyType;
|
||||
import org.sufficientlysecure.keychain.securitytoken.OpenPgpCapabilities;
|
||||
import org.sufficientlysecure.keychain.securitytoken.RSAKeyFormat;
|
||||
import org.sufficientlysecure.keychain.securitytoken.ResponseApdu;
|
||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
|
||||
import org.sufficientlysecure.keychain.util.Log;
|
||||
|
||||
|
||||
public class SecurityTokenPsoSignTokenOp {
|
||||
private final SecurityTokenConnection connection;
|
||||
|
||||
public static SecurityTokenPsoSignTokenOp create(SecurityTokenConnection connection) {
|
||||
return new SecurityTokenPsoSignTokenOp(connection);
|
||||
}
|
||||
|
||||
private SecurityTokenPsoSignTokenOp(SecurityTokenConnection connection) {
|
||||
this.connection = connection;
|
||||
}
|
||||
|
||||
private byte[] prepareDsi(byte[] hash, int hashAlgo) throws IOException {
|
||||
byte[] dsi;
|
||||
|
||||
Log.i(Constants.TAG, "Hash: " + hashAlgo);
|
||||
switch (hashAlgo) {
|
||||
case HashAlgorithmTags.SHA1:
|
||||
if (hash.length != 20) {
|
||||
throw new IOException("Bad hash length (" + hash.length + ", expected 10!");
|
||||
}
|
||||
dsi = Arrays.concatenate(Hex.decode(
|
||||
"3021" // Tag/Length of Sequence, the 0x21 includes all following 33 bytes
|
||||
+ "3009" // Tag/Length of Sequence, the 0x09 are the following header bytes
|
||||
+ "0605" + "2B0E03021A" // OID of SHA1
|
||||
+ "0500" // TLV coding of ZERO
|
||||
+ "0414"), hash); // 0x14 are 20 hash bytes
|
||||
break;
|
||||
case HashAlgorithmTags.RIPEMD160:
|
||||
if (hash.length != 20) {
|
||||
throw new IOException("Bad hash length (" + hash.length + ", expected 20!");
|
||||
}
|
||||
dsi = Arrays.concatenate(Hex.decode("3021300906052B2403020105000414"), hash);
|
||||
break;
|
||||
case HashAlgorithmTags.SHA224:
|
||||
if (hash.length != 28) {
|
||||
throw new IOException("Bad hash length (" + hash.length + ", expected 28!");
|
||||
}
|
||||
dsi = Arrays.concatenate(Hex.decode("302D300D06096086480165030402040500041C"), hash);
|
||||
break;
|
||||
case HashAlgorithmTags.SHA256:
|
||||
if (hash.length != 32) {
|
||||
throw new IOException("Bad hash length (" + hash.length + ", expected 32!");
|
||||
}
|
||||
dsi = Arrays.concatenate(Hex.decode("3031300D060960864801650304020105000420"), hash);
|
||||
break;
|
||||
case HashAlgorithmTags.SHA384:
|
||||
if (hash.length != 48) {
|
||||
throw new IOException("Bad hash length (" + hash.length + ", expected 48!");
|
||||
}
|
||||
dsi = Arrays.concatenate(Hex.decode("3041300D060960864801650304020205000430"), hash);
|
||||
break;
|
||||
case HashAlgorithmTags.SHA512:
|
||||
if (hash.length != 64) {
|
||||
throw new IOException("Bad hash length (" + hash.length + ", expected 64!");
|
||||
}
|
||||
dsi = Arrays.concatenate(Hex.decode("3051300D060960864801650304020305000440"), hash);
|
||||
break;
|
||||
default:
|
||||
throw new IOException("Not supported hash algo!");
|
||||
}
|
||||
return dsi;
|
||||
}
|
||||
|
||||
private byte[] prepareData(byte[] hash, int hashAlgo, KeyFormat keyFormat) throws IOException {
|
||||
byte[] data;
|
||||
switch (keyFormat.keyFormatType()) {
|
||||
case RSAKeyFormatType:
|
||||
data = prepareDsi(hash, hashAlgo);
|
||||
break;
|
||||
case ECKeyFormatType:
|
||||
data = hash;
|
||||
break;
|
||||
default:
|
||||
throw new IOException("Not supported key type!");
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
private byte[] encodeSignature(byte[] signature, KeyFormat keyFormat) throws IOException {
|
||||
// Make sure the signature we received is actually the expected number of bytes long!
|
||||
switch (keyFormat.keyFormatType()) {
|
||||
case RSAKeyFormatType:
|
||||
// no encoding necessary
|
||||
int modulusLength = ((RSAKeyFormat) keyFormat).getModulusLength();
|
||||
if (signature.length != (modulusLength / 8)) {
|
||||
throw new IOException("Bad signature length! Expected " + (modulusLength / 8) +
|
||||
" bytes, got " + signature.length);
|
||||
}
|
||||
break;
|
||||
|
||||
case ECKeyFormatType:
|
||||
// "plain" encoding, see https://github.com/open-keychain/open-keychain/issues/2108
|
||||
if (signature.length % 2 != 0) {
|
||||
throw new IOException("Bad signature length!");
|
||||
}
|
||||
final byte[] br = new byte[signature.length / 2];
|
||||
final byte[] bs = new byte[signature.length / 2];
|
||||
for (int i = 0; i < br.length; ++i) {
|
||||
br[i] = signature[i];
|
||||
bs[i] = signature[br.length + i];
|
||||
}
|
||||
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ASN1OutputStream out = new ASN1OutputStream(baos);
|
||||
out.writeObject(new DERSequence(new ASN1Encodable[] { new ASN1Integer(br), new ASN1Integer(bs) }));
|
||||
out.flush();
|
||||
signature = baos.toByteArray();
|
||||
break;
|
||||
}
|
||||
return signature;
|
||||
}
|
||||
|
||||
/**
|
||||
* Call COMPUTE DIGITAL SIGNATURE command and returns the MPI value
|
||||
*
|
||||
* @param hash the hash for signing
|
||||
* @return a big integer representing the MPI for the given hash
|
||||
*/
|
||||
public byte[] calculateSignature(byte[] hash, int hashAlgo) throws IOException {
|
||||
connection.verifyPinForSignature();
|
||||
|
||||
OpenPgpCapabilities openPgpCapabilities = connection.getOpenPgpCapabilities();
|
||||
KeyFormat signKeyFormat = openPgpCapabilities.getSignKeyFormat();
|
||||
|
||||
byte[] data = prepareData(hash, hashAlgo, signKeyFormat);
|
||||
|
||||
// Command APDU for PERFORM SECURITY OPERATION: COMPUTE DIGITAL SIGNATURE (page 37)
|
||||
CommandApdu command = connection.getCommandFactory().createComputeDigitalSignatureCommand(data);
|
||||
ResponseApdu response = connection.communicate(command);
|
||||
|
||||
connection.invalidateSingleUsePw1();
|
||||
|
||||
if (!response.isSuccess()) {
|
||||
throw new CardException("Failed to sign", response.getSw());
|
||||
}
|
||||
|
||||
return encodeSignature(response.getData(), signKeyFormat);
|
||||
}
|
||||
|
||||
/**
|
||||
* Call INTERNAL AUTHENTICATE command and returns the MPI value
|
||||
*
|
||||
* @param hash the hash for signing
|
||||
* @return a big integer representing the MPI for the given hash
|
||||
*/
|
||||
public byte[] calculateAuthenticationSignature(byte[] hash, int hashAlgo) throws IOException {
|
||||
connection.verifyPinForOther();
|
||||
|
||||
OpenPgpCapabilities openPgpCapabilities = connection.getOpenPgpCapabilities();
|
||||
KeyFormat authKeyFormat = openPgpCapabilities.getAuthKeyFormat();
|
||||
|
||||
byte[] data = prepareData(hash, hashAlgo, authKeyFormat);
|
||||
|
||||
// Command APDU for INTERNAL AUTHENTICATE (page 55)
|
||||
CommandApdu command = connection.getCommandFactory().createInternalAuthCommand(data);
|
||||
ResponseApdu response = connection.communicate(command);
|
||||
|
||||
if (!response.isSuccess()) {
|
||||
throw new CardException("Failed to sign", response.getSw());
|
||||
}
|
||||
|
||||
return encodeSignature(response.getData(), authKeyFormat);
|
||||
}
|
||||
}
|
||||
@@ -140,7 +140,7 @@ public class CreateKeyActivity extends BaseSecurityTokenActivity {
|
||||
return;
|
||||
}
|
||||
|
||||
tokenInfo = stConnection.getTokenInfo();
|
||||
tokenInfo = stConnection.readTokenInfo();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -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 = SecurityTokenConnection.parseOpenPgpVersion(mCreateKeyActivity.tokenInfo.getAid());
|
||||
final double version = mCreateKeyActivity.tokenInfo.getOpenPgpVersion();
|
||||
|
||||
if (version >= 3.0) {
|
||||
choices.add(new Choice<>(SupportedKeyType.ECC_P256, getResources().getString(
|
||||
|
||||
@@ -205,7 +205,7 @@ public class CreateSecurityTokenPinFragment extends Fragment {
|
||||
|
||||
mCreateKeyActivity.mSecurityTokenPin = new Passphrase(mPin.getText().toString());
|
||||
|
||||
final double version = SecurityTokenConnection.parseOpenPgpVersion(mCreateKeyActivity.tokenInfo.getAid());
|
||||
final double version = mCreateKeyActivity.tokenInfo.getOpenPgpVersion();
|
||||
|
||||
Fragment frag;
|
||||
if (version >= 3.0) {
|
||||
|
||||
@@ -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.operations.ModifyPinTokenOp;
|
||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
|
||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenInfo;
|
||||
import org.sufficientlysecure.keychain.service.input.SecurityTokenChangePinParcel;
|
||||
@@ -141,9 +142,9 @@ public class SecurityTokenChangePinOperationActivity extends BaseSecurityTokenAc
|
||||
@Override
|
||||
protected void doSecurityTokenInBackground(SecurityTokenConnection stConnection) throws IOException {
|
||||
Passphrase adminPin = new Passphrase(changePinInput.getAdminPin());
|
||||
stConnection.resetPin(changePinInput.getNewPin().getBytes(), adminPin);
|
||||
ModifyPinTokenOp.create(stConnection, adminPin).modifyPw1Pin(changePinInput.getNewPin().getBytes());
|
||||
|
||||
resultTokenInfo = stConnection.getTokenInfo();
|
||||
resultTokenInfo = stConnection.readTokenInfo();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -39,9 +39,13 @@ import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey;
|
||||
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.operations.ModifyPinTokenOp;
|
||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection;
|
||||
import org.sufficientlysecure.keychain.securitytoken.SecurityTokenInfo;
|
||||
import org.sufficientlysecure.keychain.securitytoken.operations.PsoDecryptTokenOp;
|
||||
import org.sufficientlysecure.keychain.securitytoken.operations.SecurityTokenPsoSignTokenOp;
|
||||
import org.sufficientlysecure.keychain.securitytoken.operations.SecurityTokenChangeKeyTokenOp;
|
||||
import org.sufficientlysecure.keychain.securitytoken.operations.ResetAndWipeTokenOp;
|
||||
import org.sufficientlysecure.keychain.service.PassphraseCacheService;
|
||||
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
|
||||
import org.sufficientlysecure.keychain.service.input.RequiredInputParcel;
|
||||
@@ -189,7 +193,7 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
|
||||
switch (mRequiredInput.mType) {
|
||||
case SECURITY_TOKEN_DECRYPT: {
|
||||
long tokenKeyId = KeyFormattingUtils.getKeyIdFromFingerprint(
|
||||
stConnection.getKeyFingerprint(KeyType.ENCRYPT));
|
||||
stConnection.getOpenPgpCapabilities().getFingerprintEncrypt());
|
||||
|
||||
if (tokenKeyId != mRequiredInput.getSubKeyId()) {
|
||||
throw new IOException(getString(R.string.error_wrong_security_token));
|
||||
@@ -205,17 +209,18 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
|
||||
throw new IOException("Couldn't find subkey for key to token operation.");
|
||||
}
|
||||
|
||||
PsoDecryptTokenOp psoDecryptTokenOp = PsoDecryptTokenOp.create(stConnection);
|
||||
for (int i = 0; i < mRequiredInput.mInputData.length; i++) {
|
||||
byte[] encryptedSessionKey = mRequiredInput.mInputData[i];
|
||||
byte[] decryptedSessionKey = stConnection
|
||||
.decryptSessionKey(encryptedSessionKey, publicKeyRing.getPublicKey(tokenKeyId));
|
||||
byte[] decryptedSessionKey = psoDecryptTokenOp
|
||||
.verifyAndDecryptSessionKey(encryptedSessionKey, publicKeyRing.getPublicKey(tokenKeyId));
|
||||
mInputParcel = mInputParcel.withCryptoData(encryptedSessionKey, decryptedSessionKey);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case SECURITY_TOKEN_SIGN: {
|
||||
long tokenKeyId = KeyFormattingUtils.getKeyIdFromFingerprint(
|
||||
stConnection.getKeyFingerprint(KeyType.SIGN));
|
||||
stConnection.getOpenPgpCapabilities().getFingerprintSign());
|
||||
|
||||
if (tokenKeyId != mRequiredInput.getSubKeyId()) {
|
||||
throw new IOException(getString(R.string.error_wrong_security_token));
|
||||
@@ -223,26 +228,28 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
|
||||
|
||||
mInputParcel = mInputParcel.withSignatureTime(mRequiredInput.mSignatureTime);
|
||||
|
||||
SecurityTokenPsoSignTokenOp psoSignUseCase = SecurityTokenPsoSignTokenOp.create(stConnection);
|
||||
for (int i = 0; i < mRequiredInput.mInputData.length; i++) {
|
||||
byte[] hash = mRequiredInput.mInputData[i];
|
||||
int algo = mRequiredInput.mSignAlgos[i];
|
||||
byte[] signedHash = stConnection.calculateSignature(hash, algo);
|
||||
byte[] signedHash = psoSignUseCase.calculateSignature(hash, algo);
|
||||
mInputParcel = mInputParcel.withCryptoData(hash, signedHash);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case SECURITY_TOKEN_AUTH: {
|
||||
long tokenKeyId = KeyFormattingUtils.getKeyIdFromFingerprint(
|
||||
stConnection.getKeyFingerprint(KeyType.AUTH));
|
||||
stConnection.getOpenPgpCapabilities().getFingerprintAuth());
|
||||
|
||||
if (tokenKeyId != mRequiredInput.getSubKeyId()) {
|
||||
throw new IOException(getString(R.string.error_wrong_security_token));
|
||||
}
|
||||
|
||||
SecurityTokenPsoSignTokenOp psoSignUseCase = SecurityTokenPsoSignTokenOp.create(stConnection);
|
||||
for (int i = 0; i < mRequiredInput.mInputData.length; i++) {
|
||||
byte[] hash = mRequiredInput.mInputData[i];
|
||||
int algo = mRequiredInput.mSignAlgos[i];
|
||||
byte[] signedHash = stConnection.calculateAuthenticationSignature(hash, algo);
|
||||
byte[] signedHash = psoSignUseCase.calculateAuthenticationSignature(hash, algo);
|
||||
mInputParcel = mInputParcel.withCryptoData(hash, signedHash);
|
||||
|
||||
}
|
||||
@@ -272,7 +279,7 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
|
||||
long subkeyId = buf.getLong();
|
||||
|
||||
CanonicalizedSecretKey key = secretKeyRing.getSecretKey(subkeyId);
|
||||
byte[] tokenSerialNumber = Arrays.copyOf(stConnection.getAid(), 16);
|
||||
byte[] tokenSerialNumber = Arrays.copyOf(stConnection.getOpenPgpCapabilities().getAid(), 16);
|
||||
|
||||
Passphrase passphrase;
|
||||
try {
|
||||
@@ -282,25 +289,22 @@ public class SecurityTokenOperationActivity extends BaseSecurityTokenActivity {
|
||||
throw new IOException("Unable to get cached passphrase!");
|
||||
}
|
||||
|
||||
stConnection.changeKey(key, passphrase, adminPin);
|
||||
SecurityTokenChangeKeyTokenOp putKeyUseCase = SecurityTokenChangeKeyTokenOp.create(stConnection);
|
||||
putKeyUseCase.changeKey(key, passphrase, adminPin);
|
||||
|
||||
// TODO: Is this really used anywhere?
|
||||
mInputParcel = mInputParcel.withCryptoData(subkeyBytes, tokenSerialNumber);
|
||||
}
|
||||
|
||||
// First set Admin PIN, then PIN.
|
||||
// Order is important for Gnuk, otherwise it will be set up in "admin less mode".
|
||||
// http://www.fsij.org/doc-gnuk/gnuk-passphrase-setting.html#set-up-pw1-pw3-and-reset-code
|
||||
stConnection.modifyPw3Pin(newAdminPin, adminPin);
|
||||
stConnection.resetPin(newPin, new Passphrase(new String(newAdminPin)));
|
||||
ModifyPinTokenOp.create(stConnection, adminPin).modifyPw1andPw3Pins(newPin, newAdminPin);
|
||||
|
||||
SecurityTokenConnection.clearCachedConnections();
|
||||
|
||||
break;
|
||||
}
|
||||
case SECURITY_TOKEN_RESET_CARD: {
|
||||
stConnection.resetAndWipeToken();
|
||||
mResultTokenInfo = stConnection.getTokenInfo();
|
||||
ResetAndWipeTokenOp.create(stConnection).resetAndWipeToken();
|
||||
mResultTokenInfo = stConnection.readTokenInfo();
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
|
||||
* Override to implement SecurityToken operations (background thread)
|
||||
*/
|
||||
protected void doSecurityTokenInBackground(SecurityTokenConnection stConnection) throws IOException {
|
||||
tokenInfo = stConnection.getTokenInfo();
|
||||
tokenInfo = stConnection.readTokenInfo();
|
||||
Log.d(Constants.TAG, "Security Token: " + tokenInfo);
|
||||
}
|
||||
|
||||
@@ -260,7 +260,7 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
|
||||
|
||||
SecurityTokenInfo tokeninfo = null;
|
||||
try {
|
||||
tokeninfo = stConnection.getTokenInfo();
|
||||
tokeninfo = stConnection.readTokenInfo();
|
||||
} catch (IOException e2) {
|
||||
// don't care
|
||||
}
|
||||
@@ -278,7 +278,7 @@ public abstract class BaseSecurityTokenActivity extends BaseActivity
|
||||
case 0x6982: {
|
||||
SecurityTokenInfo tokeninfo = null;
|
||||
try {
|
||||
tokeninfo = stConnection.getTokenInfo();
|
||||
tokeninfo = stConnection.readTokenInfo();
|
||||
} catch (IOException e2) {
|
||||
// don't care
|
||||
}
|
||||
|
||||
@@ -20,20 +20,13 @@ package org.sufficientlysecure.keychain.ui.util;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.DigestException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Collection;
|
||||
import java.util.Locale;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.PorterDuff;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.text.Spannable;
|
||||
import android.text.SpannableStringBuilder;
|
||||
import android.text.style.ForegroundColorSpan;
|
||||
import android.view.View;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
@@ -42,7 +35,6 @@ import android.widget.ViewAnimator;
|
||||
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
|
||||
import org.bouncycastle.asn1.nist.NISTNamedCurves;
|
||||
import org.bouncycastle.asn1.teletrust.TeleTrusTNamedCurves;
|
||||
import org.bouncycastle.bcpg.HashAlgorithmTags;
|
||||
import org.bouncycastle.bcpg.PublicKeyAlgorithmTags;
|
||||
import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags;
|
||||
import org.bouncycastle.crypto.ec.CustomNamedCurves;
|
||||
@@ -52,13 +44,11 @@ import org.bouncycastle.util.encoders.Hex;
|
||||
import org.openintents.openpgp.OpenPgpDecryptionResult;
|
||||
import org.openintents.openpgp.OpenPgpSignatureResult;
|
||||
import org.openintents.openpgp.util.OpenPgpUtils;
|
||||
import org.sufficientlysecure.keychain.Constants;
|
||||
import org.sufficientlysecure.keychain.R;
|
||||
import org.sufficientlysecure.keychain.operations.results.DecryptVerifyResult;
|
||||
import org.sufficientlysecure.keychain.pgp.KeyRing;
|
||||
import org.sufficientlysecure.keychain.service.SaveKeyringParcel.Algorithm;
|
||||
import org.sufficientlysecure.keychain.service.SaveKeyringParcel.Curve;
|
||||
import org.sufficientlysecure.keychain.util.Log;
|
||||
|
||||
public class KeyFormattingUtils {
|
||||
|
||||
|
||||
Reference in New Issue
Block a user