From b1223325ec4c213218a1881eceaa1400fbac2ca9 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Sun, 25 Oct 2026 03:28:02 +0000 Subject: [PATCH 1/2] Add draft BIP-EXFIL single-signer Schnorr primitives --- main/CMakeLists.txt | 3 +- main/amalgamated.c | 1 + main/anti_exfil.c | 137 ++++++++++++++++++++++++++++++ main/anti_exfil.h | 14 +++ test_anti_exfil.py | 81 ++++++++++++++++++ test_data/anti_exfil_vectors.json | 90 ++++++++++++++++++++ 6 files changed, 325 insertions(+), 1 deletion(-) create mode 100644 main/anti_exfil.c create mode 100644 main/anti_exfil.h create mode 100644 test_anti_exfil.py create mode 100644 test_data/anti_exfil_vectors.json diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index 84db8935..9087604a 100755 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -29,13 +29,14 @@ endif() if(CONFIG_AMALGAMATED_BUILD) set(wallydir "${PROJECT_DIR}/components/libwally-core") list(APPEND wallydirs "${wallydir}" "${wallydir}/upstream" "${wallydir}/upstream/src" "${wallydir}/upstream/src/ccan") - set(secpdir "${wallydir}/upstream/src/secp256k1/include") endif() if(CONFIG_LOG_WIFI) list(APPEND extra_priv_requires "esp_wifi") endif() +set(secpdir "${PROJECT_DIR}/components/libwally-core/upstream/src/secp256k1/include") + idf_component_register(SRC_DIRS "." "attestation" "fonts" diff --git a/main/amalgamated.c b/main/amalgamated.c index ab5641b5..ba941859 100644 --- a/main/amalgamated.c +++ b/main/amalgamated.c @@ -24,6 +24,7 @@ void __wrap_abort(void); #define HAVE_BUILTIN_POPCOUNT 1 #include "../components/libwally-core/upstream/src/amalgamation/combined.c" +#include "./anti_exfil.c" #include "./aes.c" #include "./assets.c" #include "./attestation/attestation.c" diff --git a/main/anti_exfil.c b/main/anti_exfil.c new file mode 100644 index 00000000..37ca4f8b --- /dev/null +++ b/main/anti_exfil.c @@ -0,0 +1,137 @@ +#ifndef AMALGAMATED_BUILD +#include "anti_exfil.h" + +#include +#include +#include + +static void ae_clear(void* data, size_t len) +{ + volatile unsigned char* p = data; + while (len--) { + *p++ = 0; + } +} + +/* SHA256 results are below 2^256, so at most one subtraction is needed. + * Select the reduced scalar without branching on secret nonce material. */ +static void ae_reduce(unsigned char scalar[32]) +{ + static const unsigned char order[32] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, + 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41 }; + unsigned char reduced[32]; + unsigned int borrow = 0; + for (size_t i = 32; i-- > 0;) { + const unsigned int difference = (unsigned int)scalar[i] - order[i] - borrow; + reduced[i] = difference & 0xff; + borrow = (difference >> 8) & 1; + } + const unsigned int mask = 0 - borrow; + for (size_t i = 0; i < 32; ++i) { + scalar[i] = (scalar[i] & mask) | (reduced[i] & ~mask); + } + ae_clear(reduced, sizeof(reduced)); +} + +typedef struct { + const secp256k1_context* ctx; + const unsigned char* commitment; + const unsigned char* entropy; +} ae_nonce_data; + +/* libsecp passes the even-Y normalized secret/public key to this callback. */ +static int ae_nonce(unsigned char* nonce32, const unsigned char* msg, size_t msglen, + const unsigned char* key32, const unsigned char* xonly32, const unsigned char* algo, + size_t algolen, void* data) +{ + const ae_nonce_data* session = data; + unsigned char aux[32], preimage[96]; + int ok = msglen == 32 && algo != NULL && algolen != 0; + if (ok) { + ok = secp256k1_tagged_sha256(session->ctx, aux, (const unsigned char*)"BIP0340/aux", 11, + session->commitment, 32); + } + if (ok) { + for (size_t i = 0; i < 32; ++i) { + preimage[i] = key32[i] ^ aux[i]; + } + memcpy(preimage + 32, xonly32, 32); + memcpy(preimage + 64, msg, 32); + ok = secp256k1_tagged_sha256(session->ctx, nonce32, (const unsigned char*)"BIP-EXFIL/nonce", 15, + preimage, sizeof(preimage)); + } + if (ok) { + ae_reduce(nonce32); + ok = secp256k1_ec_seckey_verify(session->ctx, nonce32); + } + if (ok && session->entropy) { + ok = secp256k1_ec_seckey_verify(session->ctx, session->entropy) + && secp256k1_ec_seckey_tweak_add(session->ctx, nonce32, session->entropy); + } + ae_clear(aux, sizeof(aux)); + ae_clear(preimage, sizeof(preimage)); + if (!ok) { + ae_clear(nonce32, 32); + } + return ok; +} + +int jade_anti_exfil_commit(const secp256k1_context* ctx, unsigned char nonce33[33], + const unsigned char secret32[32], const unsigned char msg32[32], const unsigned char commitment32[32]) +{ + secp256k1_keypair keypair; + secp256k1_xonly_pubkey pubkey; + secp256k1_pubkey nonce; + unsigned char normalized[32], xonly[32], scalar[32]; + int parity = 0; + size_t len = 33; + ae_nonce_data data = { ctx, commitment32, NULL }; + int ok = secp256k1_keypair_create(ctx, &keypair, secret32) + && secp256k1_keypair_xonly_pub(ctx, &pubkey, &parity, &keypair) + && secp256k1_xonly_pubkey_serialize(ctx, xonly, &pubkey); + memcpy(normalized, secret32, 32); + if (ok && parity) { + ok = secp256k1_ec_seckey_negate(ctx, normalized); + } + if (ok) { + ok = ae_nonce(scalar, msg32, 32, normalized, xonly, (const unsigned char*)"BIP0340/nonce", 13, &data) + && secp256k1_ec_pubkey_create(ctx, &nonce, scalar) + && secp256k1_ec_pubkey_serialize(ctx, nonce33, &len, &nonce, SECP256K1_EC_COMPRESSED); + } + ae_clear(normalized, sizeof(normalized)); + ae_clear(scalar, sizeof(scalar)); + ae_clear(&keypair, sizeof(keypair)); + if (!ok) { + ae_clear(nonce33, 33); + } + return ok; +} + +int jade_anti_exfil_sign(const secp256k1_context* ctx, unsigned char signature64[64], + const unsigned char secret32[32], const unsigned char msg32[32], const unsigned char commitment32[32], + const unsigned char nonce33[33], const unsigned char entropy32[32]) +{ + unsigned char commitment[32], nonce[33]; + secp256k1_keypair keypair; + secp256k1_xonly_pubkey pubkey; + ae_nonce_data data = { ctx, commitment32, entropy32 }; + secp256k1_schnorrsig_extraparams params = SECP256K1_SCHNORRSIG_EXTRAPARAMS_INIT; + params.noncefp = ae_nonce; + params.ndata = &data; + int ok = secp256k1_ec_seckey_verify(ctx, entropy32) + && secp256k1_tagged_sha256(ctx, commitment, (const unsigned char*)"BIP-EXFIL/host", 14, entropy32, 32) + && memcmp(commitment, commitment32, 32) == 0 + && jade_anti_exfil_commit(ctx, nonce, secret32, msg32, commitment32) + && memcmp(nonce, nonce33, 33) == 0 + && secp256k1_keypair_create(ctx, &keypair, secret32) + && secp256k1_keypair_xonly_pub(ctx, &pubkey, NULL, &keypair) + && secp256k1_schnorrsig_sign_custom(ctx, signature64, msg32, 32, &keypair, ¶ms) + && secp256k1_schnorrsig_verify(ctx, signature64, msg32, 32, &pubkey); + ae_clear(&keypair, sizeof(keypair)); + if (!ok) { + ae_clear(signature64, 64); + } + return ok; +} +#endif // AMALGAMATED_BUILD diff --git a/main/anti_exfil.h b/main/anti_exfil.h new file mode 100644 index 00000000..e71dba96 --- /dev/null +++ b/main/anti_exfil.h @@ -0,0 +1,14 @@ +#ifndef JADE_ANTI_EXFIL_H +#define JADE_ANTI_EXFIL_H + +#include + +/* Draft BIP-EXFIL. All keys are actual, already Taproot-tweaked signing keys. + * The full compressed nonce (including parity) must be retained between rounds. */ +int jade_anti_exfil_commit(const secp256k1_context* ctx, unsigned char nonce33[33], + const unsigned char secret32[32], const unsigned char msg32[32], const unsigned char commitment32[32]); +int jade_anti_exfil_sign(const secp256k1_context* ctx, unsigned char signature64[64], + const unsigned char secret32[32], const unsigned char msg32[32], const unsigned char commitment32[32], + const unsigned char nonce33[33], const unsigned char entropy32[32]); + +#endif diff --git a/test_anti_exfil.py b/test_anti_exfil.py new file mode 100644 index 00000000..16ced670 --- /dev/null +++ b/test_anti_exfil.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Run the BIP-EXFIL shared vectors using Jade's actual libsecp dependency. + +Uses a native compiler; ESP-IDF and a device are not needed. Integration tests +must additionally exercise sign_psbt on the firmware emulator. +""" +import ctypes +import json +from pathlib import Path +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parent +SECP = ROOT / 'components/libwally-core/upstream/src/secp256k1' + + +class TestAntiExfil(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory() + library = Path(cls.tmp.name) / 'anti_exfil.so' + wrapper = Path(cls.tmp.name) / 'wrapper.c' + wrapper.write_text('#include "' + str(ROOT / 'main/anti_exfil.c') + '"\n' + 'void test_reduce(unsigned char scalar[32]) { ae_reduce(scalar); }\n') + subprocess.run(['cc', '-shared', '-fPIC', '-O2', '-DENABLE_MODULE_EXTRAKEYS=1', + '-DENABLE_MODULE_SCHNORRSIG=1', '-DECMULT_WINDOW_SIZE=8', + '-I' + str(SECP / 'include'), str(wrapper), + *(str(SECP / 'src' / name) for name in + ('secp256k1.c', 'precomputed_ecmult.c', 'precomputed_ecmult_gen.c')), + '-o', str(library)], check=True) + cls.lib = ctypes.CDLL(str(library)) + cls.lib.secp256k1_context_create.argtypes = [ctypes.c_uint] + cls.lib.secp256k1_context_create.restype = ctypes.c_void_p + cls.lib.secp256k1_context_destroy.argtypes = [ctypes.c_void_p] + cls.lib.jade_anti_exfil_commit.argtypes = [ctypes.c_void_p] + [ctypes.c_char_p] * 4 + cls.lib.jade_anti_exfil_sign.argtypes = [ctypes.c_void_p] + [ctypes.c_char_p] * 6 + cls.ctx = cls.lib.secp256k1_context_create(1) + cls.vectors = json.loads((ROOT / 'test_data/anti_exfil_vectors.json').read_text()) + + @classmethod + def tearDownClass(cls): + cls.lib.secp256k1_context_destroy(cls.ctx) + cls.tmp.cleanup() + + def test_scalar_reduction_boundaries(self): + order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 + self.lib.test_reduce.argtypes = [ctypes.c_char_p] + for value in (0, 1, order - 1, order, order + 1, 2**256 - 1): + scalar = ctypes.create_string_buffer(value.to_bytes(32, 'big'), 32) + self.lib.test_reduce(scalar) + self.assertEqual(int.from_bytes(scalar.raw, 'big'), value % order) + + def test_vectors_and_transcript_rejection(self): + for vector in self.vectors: + with self.subTest(vector=vector['index']): + key, msg, commitment, entropy, expected_nonce, expected_sig = ( + bytes.fromhex(vector[name]) for name in + ('secret_key', 'message', 'host_commitment', 'host_nonce', 'signer_nonce', 'signature')) + nonce = ctypes.create_string_buffer(33) + sig = ctypes.create_string_buffer(64) + self.assertEqual(self.lib.jade_anti_exfil_commit(self.ctx, nonce, key, msg, commitment), 1) + self.assertEqual(nonce.raw, expected_nonce) + args = [key, msg, commitment, expected_nonce, entropy] + self.assertEqual(self.lib.jade_anti_exfil_sign(self.ctx, sig, *args), 1) + self.assertEqual(sig.raw, expected_sig) + # A replacement of any part of a committed session must fail. + for index in range(len(args)): + bad = args.copy() + bad[index] = bytes([bad[index][0] ^ 1]) + bad[index][1:] + self.assertEqual(self.lib.jade_anti_exfil_sign(self.ctx, sig, *bad), 0) + self.assertEqual(sig.raw, bytes(64)) + for invalid in (bytes(32), bytes.fromhex('ff' * 32), + bytes.fromhex('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141')): + self.assertEqual(self.lib.jade_anti_exfil_sign( + self.ctx, sig, key, msg, commitment, expected_nonce, invalid), 0) + self.assertEqual(sig.raw, bytes(64)) + + +if __name__ == '__main__': + unittest.main() diff --git a/test_data/anti_exfil_vectors.json b/test_data/anti_exfil_vectors.json new file mode 100644 index 00000000..d9587f07 --- /dev/null +++ b/test_data/anti_exfil_vectors.json @@ -0,0 +1,90 @@ +[ + { + "index": 0, + "secret_key": "0000000000000000000000000000000000000000000000000000000000000001", + "public_key": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "message": "0000000000000000000000000000000000000000000000000000000000000000", + "host_nonce": "0000000000000000000000000000000000000000000000000000000000000001", + "host_commitment": "2547d8aa53b5e89d2bbe2a4d1853cfbae1d98105b57f03e6cf555c141776780a", + "signer_nonce": "0327ce12dc839961dcfdec901a3110809c0890aeb8a3527549ea7e54b5c0f93dac", + "signature": "7fe10d622cf4a75e39715e7fea452228788e27e766faad12a7e4525e779d23bbb94bc96ae14de5c4be23683bf284d8399d8b92943736b443086c356016626141", + "negated": true + }, + { + "index": 1, + "secret_key": "0000000000000000000000000000000000000000000000000000000000000003", + "public_key": "f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9", + "message": "0101010101010101010101010101010101010101010101010101010101010101", + "host_nonce": "0000000000000000000000000000000000000000000000000000000000000002", + "host_commitment": "0317de3d5927275e3dd18a99eb6e314e1f314322c385e1804c3cc0cf17570f96", + "signer_nonce": "02f8dd7048d09602edb02f6fbf743697d6aaab2927e42fcec2e44b706d9d120c42", + "signature": "0a531170e638dc06579794731ea3fea09d79bac7503ebc9ecd04f13d389d3ea70d45a151c85714d42faa504fd86edae959a2253c046e9b8d01034d3610fa2540", + "negated": false + }, + { + "index": 2, + "secret_key": "0000000000000000000000000000000000000000000000000000000000000006", + "public_key": "fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556", + "message": "0202020202020202020202020202020202020202020202020202020202020202", + "host_nonce": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140", + "host_commitment": "c6a415487f22d3eb78ac30ac560f632039ba9ed41f63390364262ea15278a193", + "signer_nonce": "02db71c56805915075a24af4fe0136d63e0efd3bbfd476e8b93f3c9565290c834b", + "signature": "9341a1c8dc62acd9b624e62d5dd442bf7e0cd92018c797d53c67bc3adab141e2df34807e965ddd487e69dd21cb3790eae74427f7d00d53a35066de1e22581567", + "negated": false + }, + { + "index": 3, + "secret_key": "000000000000000000000000000000000000000000000000000000000000001f", + "public_key": "6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4", + "message": "0303030303030303030303030303030303030303030303030303030303030303", + "host_nonce": "0000000000000000000000000000000000000000000000000000000000000100", + "host_commitment": "eaf14500f7bb699ca7f58bb00827fbf26e17f81770572ff2e87f2115296cdfad", + "signer_nonce": "02cfb27a17b532f5bf0870b766846d1c1b05a9390b0b523ef09d0f73c3463f7070", + "signature": "52a2955a27bd03713517e3342618c15eb36cc37d87eb63cd3f2d884c924d85cae05b5f2b63c217a551141b2f65a5acca15a8eec031b20241dc7a5b0b64e9189c", + "negated": true + }, + { + "index": 4, + "secret_key": "00000000000000000000000000000000000000000000000000000000deadbeef", + "public_key": "76d2fdf1302d1fa9556f4df94ec84cefba6d482e54f47c6c2a238c1baa560f0e", + "message": "0404040404040404040404040404040404040404040404040404040404040404", + "host_nonce": "0000000000000000000000000000000000000000000000000123456789abcdef", + "host_commitment": "1d601741395abb46e03cba6631f48c06a0051d8d7068df9697478eaf3ad96b04", + "signer_nonce": "02108d8a97497aa273bebb4706c1d88b146808809a8b5a42533a5bca9e161bd92a", + "signature": "fc1ee9154aa5541b64b5816fc4c897eb99af8b756e50a9a48d82fe2f64139fbbff8de3339f4d4a5376b79bb272f87a53127b71c3ae06343cc2044eecb96ffad3", + "negated": true + }, + { + "index": 5, + "secret_key": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140", + "public_key": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "message": "0505050505050505050505050505050505050505050505050505050505050505", + "host_nonce": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd036413f", + "host_commitment": "38ebca2170719ecc673123b1cc48d1d91fc3ec435b7187e0e59dcf2c428cb471", + "signer_nonce": "032a62d0682e9f557c9978b4e9f1696f0e3ffbb1af5640b879bb6630fc5a39ba53", + "signature": "49f4d4e4fa2e9c0eb3956df6389ec36337560e2a4f505cd7a3cf183d49665d0e7122e55538755d32016354b70a3aa0721bc384b3ad81fa2286d7ea13affdd1f6", + "negated": false + }, + { + "index": 6, + "secret_key": "000000000000000000000000000000000000000000000000000000000012d687", + "public_key": "8208f5abf04066bad1db9d46f8bcf5a6cc11d0558ab523e7bd3c0ec08bdb782f", + "message": "0606060606060606060606060606060606060606060606060606060606060606", + "host_nonce": "0000000000000000000000000000000000000000000000000000000000000011", + "host_commitment": "ef5fdf83feea1cb5bd266718149fdac62968d991352a39ed7f2c589c8c3aeb88", + "signer_nonce": "021f42904577acbd9e6e1b57f08630efe443b5bf707a9e2e7222650d5fe1129232", + "signature": "b078dd4e584adfd5ec8f04c08198a109597d8eda260e6b674df393ad9109d8902f9e0d7d868629d0349fd2ca3afd3da80d66a6af868fc9b010205b6cb6754817", + "negated": true + }, + { + "index": 7, + "secret_key": "0000000000000000000000000000000000000000000000000000000087654321", + "public_key": "5b151e6105c1cd768e2e70e1b8eb53910cce816f6e50614824177ee7ac4fc846", + "message": "0707070707070707070707070707070707070707070707070707070707070707", + "host_nonce": "0000000000000000000000000000000000000000000000000000000000abcdef", + "host_commitment": "a58864f76cb577c648398cd806964bd1c38de20d9773aaaa244ba990e2fb985e", + "signer_nonce": "034cdab88e1b055ed8572f03c4a44c031a7ea551bfa911311d64b62f7db4cb5e04", + "signature": "8a235e3cf29eda31b0f254c54d1e6e112eab3ec574cfacd1c36d5b25f7ee3400e985a6eaa45b0c171c8fbb2be231b26a4670247c734a4548b269a50976a4a865", + "negated": false + } +] From ff8b53fe615251a8b6631b4c61c4247346d00a55 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Sun, 25 Oct 2026 09:20:04 +0000 Subject: [PATCH 2/2] Implement two-round Taproot anti-exfil in native PSBT signing --- docs/anti-exfil.rst | 38 ++++++++++ docs/index.rst | 5 ++ main/process/sign_psbt.c | 159 ++++++++++++++++++++++++++++++++++++++- main/versioninfo.c | 5 +- 4 files changed, 202 insertions(+), 5 deletions(-) create mode 100644 docs/anti-exfil.rst diff --git a/docs/anti-exfil.rst b/docs/anti-exfil.rst new file mode 100644 index 00000000..bf2e136b --- /dev/null +++ b/docs/anti-exfil.rst @@ -0,0 +1,38 @@ +Draft Taproot anti-exfiltration +============================== + +This experimental firmware implements the single-signer BIP-EXFIL protocol via +``sign_psbt``. ``get_version_info`` reports ``JADE_TAPROOT_ANTI_EXFIL: true``. +Hosts must require that capability before sending an anti-exfil request; released +firmware does not recognize these fields and could sign normally. + +The provisional input key is ``fc 02 61 65 <32-byte output key>``. +Subtype 0 carries the host commitment, subtype 1 the full compressed signer +nonce, and subtype 2 the host entropy. See the BIP draft for the exact tagged +hashes and encoding. BIP assignment will change the domains and test vectors. + +The first invocation carries only commitments and returns public nonces without +signatures. After retaining those nonces, the host adds entropy to a second +invocation. The signer recomputes and checks the original commitment and nonce, +adds the host scalar, and verifies the BIP340 signature before releasing it. +Nothing secret is retained across calls. Retry the identical session; never +restart automatically with fresh entropy after a failure. + +Before using a signature, the host must independently select the output key and +BIP341 message, verify the BIP340 signature and ``sig.r == x(R0 + rho*G)``, and +reject changed transaction, UTXO, transcript, sighash, or extra-signature data. +Transport participation alone is not anti-exfil verification. HWI enforces these +host checks around the native PSBT adapter. + +This first implementation requires every input to be a BIP86 key-path input +owned by this device and carrying a request for the same round. PSBT v0 and v2, +SIGHASH_DEFAULT and SIGHASH_ALL are supported. Script paths, merkle roots, +pre-existing signatures, mixed rounds, and fields outside input maps are rejected. +The actual tweaked signing public key must match the requested output key. +Each invocation retains the ordinary transaction and fee review. + +``python3 test_anti_exfil.py`` compiles the actual bundled libsecp dependency +natively and checks the BIP's shared vectors and transcript rejection. HWI's +``jade_test_suite(..., anti_exfil=True)`` additionally exercises the real QEMU +firmware, reconnects between rounds, submits altered transcripts directly to +firmware, verifies both inputs, and broadcasts and mines the result. diff --git a/docs/index.rst b/docs/index.rst index cdada62a..c2a465e1 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -2304,3 +2304,8 @@ Indices and tables * :ref:`genindex` * :ref:`modindex` * :ref:`search` + +.. toctree:: + :maxdepth: 1 + + anti-exfil diff --git a/main/process/sign_psbt.c b/main/process/sign_psbt.c index 4130f36c..5831d756 100644 --- a/main/process/sign_psbt.c +++ b/main/process/sign_psbt.c @@ -1,4 +1,5 @@ #ifndef AMALGAMATED_BUILD +#include "../anti_exfil.h" #include "../button_events.h" #include "../descriptor.h" #include "../jade_assert.h" @@ -716,6 +717,151 @@ network_t network_from_psbt_type(struct wally_psbt* psbt) // Sign a psbt/pset - the passed wally psbt struct is updated with any signatures. // Returns 0 if no errors occurred - does not necessarily indicate that signatures were added. +/* Experimental BIP-EXFIL PSBT namespace: fc 02 'a' 'e' subtype output-key. + * Keep this separate from the existing ECDSA sign-to-contract protocol. */ +static bool ae_psbt_namespace(const struct wally_map_item* item) +{ + if (!item->key || item->key_len < 4 || item->key[0] != 0xfc) { + return false; + } + size_t offset = 2; + uint64_t len = item->key[1]; + if (len >= 0xfd) { + const size_t size = len == 0xfd ? 2 : len == 0xfe ? 4 : 8; + if (item->key_len < size + 2) { + return false; + } + len = 0; + for (size_t i = 0; i < size; ++i) { + len |= (uint64_t)item->key[2 + i] << (8 * i); + } + offset += size; + } + return len == 2 && item->key_len >= offset + 2 && item->key[offset] == 'a' && item->key[offset + 1] == 'e'; +} + +static bool ae_psbt_map_has_fields(const struct wally_map* map) +{ + for (size_t i = 0; i < map->num_items; ++i) { + if (ae_psbt_namespace(&map->items[i])) { + return true; + } + } + return false; +} + +/* Return -1 for malformed fields, 0 for no request, or the protocol round. + * The first implementation requires all inputs to belong to this signer and to + * carry anti-exfil requests, so an AE invocation cannot release other signatures. */ +static int ae_psbt_input_round(const struct wally_psbt_input* input, + const unsigned char output_key[32], const struct wally_map_item* fields[3]) +{ + memset(fields, 0, 3 * sizeof(*fields)); + for (size_t i = 0; i < input->unknowns.num_items; ++i) { + const struct wally_map_item* item = &input->unknowns.items[i]; + if (!ae_psbt_namespace(item)) { + continue; + } + if (item->key_len != 37 || item->key[1] != 2 || item->key[4] > 2 + || memcmp(item->key + 5, output_key, 32) != 0) { + return -1; + } + const size_t subtype = item->key[4]; + if (fields[subtype] || item->value_len != (subtype == 1 ? 33 : 32)) { + return -1; + } + fields[subtype] = item; + } + if (!fields[0] && !fields[1] && !fields[2]) { + return 0; + } + for (size_t i = 0; i < input->taproot_leaf_hashes.num_items; ++i) { + if (input->taproot_leaf_hashes.items[i].value_len) { + return -1; // Script-path derivations are outside this protocol implementation. + } + } + if (!fields[0] || (!fields[1] != !fields[2]) || input->signatures.num_items + || input->taproot_leaf_signatures.num_items || input->taproot_leaf_scripts.num_items + || input->final_witness || wally_map_get_integer(&input->psbt_fields, 0x07) + || wally_map_get_integer(&input->psbt_fields, 0x08) + || wally_map_get_integer(&input->psbt_fields, 0x13) + || wally_map_get_integer(&input->psbt_fields, 0x18) || input->sighash > 1) { + return -1; + } + return fields[2] ? 2 : 1; +} + +static int ae_psbt_round(struct wally_psbt* psbt) +{ + if (ae_psbt_map_has_fields(&psbt->unknowns)) { + return -1; + } + for (size_t i = 0; i < psbt->num_outputs; ++i) { + if (ae_psbt_map_has_fields(&psbt->outputs[i].unknowns)) { + return -1; + } + } + bool requested = false; + for (size_t i = 0; i < psbt->num_inputs; ++i) { + requested |= ae_psbt_map_has_fields(&psbt->inputs[i].unknowns); + } + if (!requested) { + return 0; + } + int round = 0; + key_iter iter; + for (size_t i = 0; i < psbt->num_inputs; ++i) { + const struct wally_tx_output* utxo = NULL; + const struct wally_map_item* fields[3]; + if (wally_psbt_get_input_best_utxo(psbt, i, &utxo) != WALLY_OK || !utxo || utxo->script_len != 34 + || utxo->script[0] != 0x51 || utxo->script[1] != 0x20 + || !key_iter_input_begin_public(psbt, i, &iter) || !iter.is_taproot + || key_iter_get_num_keys(&iter) != 1) { + return -1; + } + const int input_round = ae_psbt_input_round(&psbt->inputs[i], utxo->script + 2, fields); + if (input_round < 1 || (round && round != input_round)) { + return -1; + } + round = input_round; + } + return round; +} + +static bool ae_psbt_sign_input(struct wally_psbt* psbt, size_t index, const key_iter* iter, + const unsigned char txhash[32], int round) +{ + struct wally_psbt_input* input = &psbt->inputs[index]; + const struct wally_tx_output* utxo = NULL; + const struct wally_map_item* fields[3]; + unsigned char secret[32], pubkey[33], nonce[33], signature[65], nonce_key[37]; + const secp256k1_context* ctx = wally_get_secp_context(); + bool ok = wally_psbt_get_input_best_utxo(psbt, index, &utxo) == WALLY_OK && utxo + && ae_psbt_input_round(input, utxo->script + 2, fields) == round + && wally_ec_private_key_bip341_tweak(iter->hdkey.priv_key + 1, 32, NULL, 0, 0, secret, 32) == WALLY_OK + && wally_ec_public_key_from_private_key(secret, 32, pubkey, sizeof(pubkey)) == WALLY_OK + && memcmp(pubkey + 1, utxo->script + 2, 32) == 0; + if (ok && round == 1) { + ok = jade_anti_exfil_commit(ctx, nonce, secret, txhash, fields[0]->value); + if (ok) { + memcpy(nonce_key, fields[0]->key, sizeof(nonce_key)); + nonce_key[4] = 1; + ok = wally_map_add(&input->unknowns, nonce_key, sizeof(nonce_key), nonce, sizeof(nonce)) == WALLY_OK; + } + } else if (ok) { + ok = jade_anti_exfil_sign(ctx, signature, secret, txhash, fields[0]->value, fields[1]->value, fields[2]->value); + if (ok) { + size_t sig_len = 64; + if (input->sighash) { + signature[sig_len++] = input->sighash; + } + ok = wally_psbt_input_set_taproot_signature(input, signature, sig_len) == WALLY_OK; + } + } + sodium_memzero(secret, sizeof(secret)); + return ok; +} + // Returns an rpc/message error code on error, and the error string should be populated. int sign_psbt(jade_process_t* process, CborValue* params, const network_t network_id, struct wally_psbt* psbt, const char** errmsg) @@ -732,6 +878,11 @@ int sign_psbt(jade_process_t* process, CborValue* params, const network_t networ return CBOR_RPC_BAD_PARAMETERS; } const bool for_liquid = is_elements; + const int anti_exfil_round = ae_psbt_round(psbt); + if (anti_exfil_round < 0 || (anti_exfil_round && for_liquid)) { + *errmsg = "Invalid or unsupported anti-exfil request"; + return CBOR_RPC_BAD_PARAMETERS; + } // Liquid: Optional ELIP-0101 genesis blockhash can override test network defaults. // Defers to params_genesis_hash() for validation (only needed for Lisuid/PSET). size_t has_genesis_blockhash = 0; @@ -1101,9 +1252,11 @@ int sign_psbt(jade_process_t* process, CborValue* params, const network_t networ while (iter.is_valid) { // Sign the input with this key const uint32_t sign_flags = EC_FLAG_GRIND_R | (for_liquid ? EC_FLAG_ELEMENTS : 0); - if (wally_psbt_sign_input_bip32( - psbt, index, iter.key_index, txhash, sizeof(txhash), &iter.hdkey, sign_flags) - != WALLY_OK) { + const bool signed_ok = anti_exfil_round + ? ae_psbt_sign_input(psbt, index, &iter, txhash, anti_exfil_round) + : wally_psbt_sign_input_bip32( + psbt, index, iter.key_index, txhash, sizeof(txhash), &iter.hdkey, sign_flags) == WALLY_OK; + if (!signed_ok) { *errmsg = "Failed to generate signature"; retval = CBOR_RPC_INTERNAL_ERROR; goto cleanup; diff --git a/main/versioninfo.c b/main/versioninfo.c index ebd16daf..810c0ac2 100644 --- a/main/versioninfo.c +++ b/main/versioninfo.c @@ -52,9 +52,9 @@ void build_version_info_reply(const void* ctx, CborEncoder* container) const jade_msg_source_t* const source = (const jade_msg_source_t*)ctx; #ifdef CONFIG_DEBUG_MODE - const uint8_t num_version_fields = 23; + const uint8_t num_version_fields = 24; #else - const uint8_t num_version_fields = 16; + const uint8_t num_version_fields = 17; #endif CborEncoder map_encoder; @@ -63,6 +63,7 @@ void build_version_info_reply(const void* ctx, CborEncoder* container) add_string_to_map(&map_encoder, "JADE_VERSION", running_app_info.version); add_uint_to_map(&map_encoder, "JADE_OTA_MAX_CHUNK", JADE_OTA_BUF_SIZE); + add_boolean_to_map(&map_encoder, "JADE_TAPROOT_ANTI_EXFIL", true); // Config - eg. ble/radio enabled in build, or not // defined in ota_defines.h