Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions modules/bitgo/test/v2/unit/internal/opengpgUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,39 @@ describe('OpenGPG Utils Tests', function () {
isValid.should.be.true();
});

it('should reject a proof whose subkey binding is not signed by the primary key', async function () {
const uForged = crypto.randomBytes(32).toString('hex');
const Q = secp256k1.pointFromScalar(Buffer.from(uForged, 'hex'), false);
// openpgp typings omit the runtime oid.write()/computeFingerprintAndKeyID() used to
// hand-assemble packets here
const oid = [0x2b, 0x81, 0x04, 0x00, 0x0a] as unknown as { write: () => Uint8Array };
oid.write = () => new Uint8Array(Buffer.from('052b8104000a', 'hex'));
const subkey = new openpgp.PublicSubkeyPacket();
subkey.algorithm = openpgp.enums.publicKey.ecdsa;
subkey.publicParams = { oid, Q };
const subkeyWithFingerprint = subkey as unknown as { computeFingerprintAndKeyID(): Promise<void> };
await subkeyWithFingerprint.computeFingerprintAndKeyID();
const binding = new openpgp.SignaturePacket();
binding.signatureType = openpgp.enums.signature.subkeyBinding;
binding.publicKeyAlgorithm = openpgp.enums.publicKey.ecdsa;
binding.hashAlgorithm = openpgp.enums.hash.sha256;
binding.keyFlags = new Uint8Array([openpgp.enums.keyFlags.authentication]);
const senderKeyObj = await openpgp.readKey({ armoredKey: senderKey.publicKey });
const recipientKeyObj = await openpgp.readPrivateKey({ armoredKey: recipientKey.privateKey });
// openpgp types PrivateKey.keyPacket as a union; signing needs the primary secret packet
const attackerSecretPacket = recipientKeyObj.keyPacket as unknown as openpgp.SecretKeyPacket;
// openpgp types sign()'s data as bytes only; subkeyBinding signing takes {key, bind} at runtime
const bindingData = { key: senderKeyObj.keyPacket, bind: subkey } as unknown as Uint8Array;
await binding.sign(attackerSecretPacket, bindingData, new Date());
const forged = new openpgp.PacketList();
senderKeyObj.toPacketList().forEach((p) => forged.push(p));
forged.push(subkey);
forged.push(binding);
const forgedProof = openpgp.armor(openpgp.enums.armor.publicKey, forged.write());
const isValid = await openpgpUtils.verifyShareProof(senderKey.publicKey, forgedProof, uForged, 'ecdsa');
isValid.should.be.false();
});

it('should be able to detect sender is an attacker', async function () {
const uValue = crypto.randomBytes(32).toString('hex');
const proof = await openpgpUtils.createShareProof(otherKey.privateKey, uValue, 'ecdsa');
Expand Down Expand Up @@ -183,6 +216,53 @@ describe('OpenGPG Utils Tests', function () {
isValid.should.be.false();
});

it('should reject the proof when a foreign certification is applied after the genuine one', async function () {
const sharedData1 = crypto.randomBytes(32).toString('hex');
const sharedData2 = crypto.randomBytes(32).toString('hex');
const dataToProofArray = [
{ name: 's1', value: sharedData1 },
{ name: 's2', value: sharedData2 },
];
const proof = await openpgpUtils.createSharedDataProof(
senderKey.privateKey,
otherKey.publicKey,
dataToProofArray
);
const attacked = await openpgpUtils.createSharedDataProof(recipientKey.privateKey, proof, [
{ name: 's1', value: sharedData1 },
{ name: 's2', value: sharedData2 },
]);
const isValid = await openpgpUtils.verifySharedDataProof(senderKey.publicKey, attacked, dataToProofArray);
isValid.should.be.false();
});

it('should accept the proof when a foreign certification without notations is applied after the genuine one', async function () {
const sharedData1 = crypto.randomBytes(32).toString('hex');
const sharedData2 = crypto.randomBytes(32).toString('hex');
const dataToProofArray = [
{ name: 's1', value: sharedData1 },
{ name: 's2', value: sharedData2 },
];
const proof = await openpgpUtils.createSharedDataProof(
senderKey.privateKey,
otherKey.publicKey,
dataToProofArray
);
const peerCertified = await openpgpUtils.createSharedDataProof(recipientKey.privateKey, proof, []);
const isValid = await openpgpUtils.verifySharedDataProof(senderKey.publicKey, peerCertified, dataToProofArray);
isValid.should.be.true();
});

it('should reject a proof whose only verified certification carries no notations', async function () {
const dataToProofArray = [
{ name: 's1', value: crypto.randomBytes(32).toString('hex') },
{ name: 's2', value: crypto.randomBytes(32).toString('hex') },
];
const proof = await openpgpUtils.createSharedDataProof(senderKey.privateKey, otherKey.publicKey, []);
const isValid = await openpgpUtils.verifySharedDataProof(senderKey.publicKey, proof, dataToProofArray);
isValid.should.be.false();
});

it('should be able verify data proof if created in the future', async function () {
const sharedData1 = crypto.randomBytes(32).toString('hex');
const sharedData2 = crypto.randomBytes(32).toString('hex');
Expand Down
59 changes: 59 additions & 0 deletions modules/bitgo/test/v2/unit/tss/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,4 +165,63 @@ describe('commonVerifyWalletSignature', function () {
Buffer.from(returnedRawNotations[i].value).toString().should.equal(rawNotations[i].value);
}
});

it('throws error when a foreign certification is applied after the genuine one', async function () {
const rawNotations = [
{ name: '', value: '1234' },
{ name: '', value: gpgKey2Id },
{ name: '', value: gpgKey2Id },
{ name: '', value: '5678' },
{ name: '', value: '9012' },
];
const certified = await createSharedDataProof(gpgKey1.privateKey, gpgKey2.publicKey, rawNotations);
const attacked = await createSharedDataProof(gpgKey3.privateKey, certified, rawNotations);
const signature = await openpgp.readKey({ armoredKey: attacked });

await commonTssMethods
.commonVerifyWalletSignature({
walletSignature: signature,
bitgoPub: key1Actual,
commonKeychain: '1234',
userKeyId: gpgKey2Id,
backupKeyId: gpgKey2Id,
})
.should.be.rejectedWith('Invalid HSM GPG signature');
});

it('throws error when the wallet key has no third-party certification', async function () {
const signature = await openpgp.readKey({ armoredKey: gpgKey2.publicKey });

await commonTssMethods
.commonVerifyWalletSignature({
walletSignature: signature,
bitgoPub: key1Actual,
commonKeychain: '',
userKeyId: '',
backupKeyId: '',
})
.should.be.rejectedWith('Invalid HSM GPG signature');
});

it('succeeds when a foreign certification without notations is applied after the genuine one', async function () {
const rawNotations = [
{ name: '', value: '1234' },
{ name: '', value: gpgKey2Id },
{ name: '', value: gpgKey2Id },
{ name: '', value: '5678' },
{ name: '', value: '9012' },
];
const certified = await createSharedDataProof(gpgKey1.privateKey, gpgKey2.publicKey, rawNotations);
const peerCertified = await createSharedDataProof(gpgKey3.privateKey, certified, []);
const signature = await openpgp.readKey({ armoredKey: peerCertified });

const returnedRawNotations = await commonTssMethods.commonVerifyWalletSignature({
walletSignature: signature,
bitgoPub: key1Actual,
commonKeychain: '1234',
userKeyId: gpgKey2Id,
backupKeyId: gpgKey2Id,
});
Buffer.from(returnedRawNotations[0].value).toString().should.equal('1234');
});
});
13 changes: 5 additions & 8 deletions modules/sdk-core/src/bitgo/tss/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { MPCAlgorithm } from '../baseCoin';
import {
RequestType,
TxRequest,
verifyPrimaryUserWrapper,
getVerifiedCertifications,
SignatureShareRecord,
SignatureShareType,
CommitmentShareRecord,
Expand Down Expand Up @@ -286,16 +286,13 @@ export async function commonVerifyWalletSignature(params: {
throw new Error('Invalid HSM GPG signature');
}

const verificationResult = await verifyPrimaryUserWrapper(walletSignature, bitgoPub, false);
const isValid = verificationResult.some((result) => result.valid);
if (!isValid) {
const primaryUser = await walletSignature.getPrimaryUser();
const verifiedCertifications = await getVerifiedCertifications(primaryUser, bitgoPub);
if (!verifiedCertifications || verifiedCertifications.length === 0) {
throw new Error('Invalid HSM GPG signature');
}
const primaryUser = await walletSignature.getPrimaryUser();

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore the rawNotations property is missing from the type but it actually exists
const rawNotations: { value: Uint8Array }[] = primaryUser.user.otherCertifications[0].rawNotations;
const rawNotations: { value: Uint8Array }[] = verifiedCertifications[0].rawNotations;

assert(rawNotations.length === 5, 'invalid wallet signatures');

Expand Down
56 changes: 48 additions & 8 deletions modules/sdk-core/src/bitgo/utils/opengpgUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,42 @@ export async function verifyPrimaryUserWrapper(
}
}

type CertificateVerifier = (cert: pgp.SignaturePacket, keys: Key[], date: Date | null) => Promise<true | null>;

/**
* Returns the primary user's third-party certifications that were issued and validly signed by certifierPub, or null
* if any certification carrying notations does not verify against certifierPub. Certifications without notations
* carry no readable data and are tolerated regardless of issuer. openpgp 5.11.3 exposes User.verifyCertificate at
* runtime but not in its TypeScript typings, hence the cast.
* @param primaryUser primary user of the key whose certifications are checked.
* @param certifierPub public key every certification carrying notations must be signed by.
* @return the certifications that verify against certifierPub, or null on any unverified notation-bearing
* certification; empty when the key carries no third-party certifications.
*/
export async function getVerifiedCertifications(
primaryUser: { user: pgp.User },
certifierPub: Key
): Promise<pgp.SignaturePacket[] | null> {
// User.verifyCertificate exists at runtime but not in openpgp's typings
const userWithVerify = primaryUser.user as unknown as { verifyCertificate: CertificateVerifier };
const verifyCertificate = userWithVerify.verifyCertificate.bind(primaryUser.user);
const certifications = primaryUser.user.otherCertifications ?? [];
const verified: pgp.SignaturePacket[] = [];
for (const certification of certifications) {
const result = await verifyCertificate(certification, [certifierPub], null).catch(() => null);
if (result !== true) {
if (!certification.rawNotations?.length) {
continue;
}
return null;
}
if (certification.rawNotations?.length) {
verified.push(certification);
}
}
return verified;
}

/**
* Verify an Eddsa or Ecdsa KeyShare Proof.
*
Expand All @@ -105,6 +141,14 @@ export async function verifyShareProof(
return false;
}
const proofSubkeys = decodedProof.getSubkeys()[1];
// The Q below is only trusted if the subkey binding signature is valid for the primary key;
// otherwise an attacker could attach an arbitrary subkey to the sender's public key packets.
try {
// Date checks are skipped: creator and verifier clocks may be skewed.
await proofSubkeys.verify(null as unknown as undefined);
} catch {
return false;
}
Comment thread
vibhavgo marked this conversation as resolved.
Resolved
if (algo === 'eddsa') {
const decodedUValueProof = Buffer.from(proofSubkeys.keyPacket.publicParams['Q'].slice(1)).toString('hex');
const rawUValueProof = Buffer.from(
Expand Down Expand Up @@ -135,17 +179,13 @@ export async function verifySharedDataProof(
): Promise<boolean> {
const senderPubKey = await pgp.readKey({ armoredKey: senderPubKeyArm });
const signedKey = await pgp.readKey({ armoredKey: keyWithNotation });
if (
!(await verifyPrimaryUserWrapper(signedKey, senderPubKey, false).then((values) =>
_.some(values, (value) => value.valid)
))
) {
const primaryUser = await signedKey.getPrimaryUser(null as unknown as undefined);
const verifiedCertifications = await getVerifiedCertifications(primaryUser, senderPubKey);
if (!verifiedCertifications || verifiedCertifications.length === 0) {
return false;
}
const primaryUser = await signedKey.getPrimaryUser(null as unknown as undefined);
const anyInvalidProof = _.some(
// @ts-ignore
primaryUser.user.otherCertifications[0].rawNotations,
verifiedCertifications[0].rawNotations,
Comment thread
vibhavgo marked this conversation as resolved.
Resolved
(notation) => dataToVerify.find((i) => i.name === notation.name)?.value !== Buffer.from(notation.value).toString()
);
return !anyInvalidProof;
Expand Down
Loading