diff --git a/.gitignore b/.gitignore index c77e1150c..fefbb094b 100644 --- a/.gitignore +++ b/.gitignore @@ -64,8 +64,8 @@ cov-int/ !client/resources/hardnested/*.bin !client/resources/hardnested_tables/*.z -!client/resources/felica_system_code_list.json -!client/resources/felica_ic_code_list.json +!client/resources/felica/ +!client/resources/felica/*.json !client/resources/calypso/ !client/resources/calypso/*.json client/src/ui/ui_image.h diff --git a/CHANGELOG.md b/CHANGELOG.md index 956fb4d4c..7ad239553 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,10 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Added CUDA version of tools/mfulc_des_brute (@C2Pwn) +- Added `hf mfu desbrute` command: native client support for ULC key recovery (@C2Pwn) - Added `hf mf sen` command: native client support for FM11RF08S SEN recovery (@C2Pwn) +- Fixed an issue where the COM port was sometimes not being selected on Windows (@boss-chifra) - Added Makefile `PLATFORM_FILE` variable to specify another Makefile.platform file (@doegox) - Added `hf calypso probecmdcompat` command (@kormax) - Added secure channel operations to `hf iclass sam` and fixed/improved I2C bus operations (@antiklesys) diff --git a/armsrc/frozen.c b/armsrc/frozen.c index b4f57aa74..1062e3ff9 100644 --- a/armsrc/frozen.c +++ b/armsrc/frozen.c @@ -541,7 +541,7 @@ static int b64dec(const char *src, int n, char *dst) { int len = 0; while (src + 3 < end) { int a = b64rev(src[0]), b = b64rev(src[1]), c = b64rev(src[2]), - d = b64rev(src[3]); + d = b64rev(src[3]); dst[len++] = (a << 2) | (b >> 4); if (src[2] != '=') { dst[len++] = (b << 4) | (c >> 2); diff --git a/client/deps/reveng/bmpbit.c b/client/deps/reveng/bmpbit.c index 522d71ecc..5c4464b41 100644 --- a/client/deps/reveng/bmpbit.c +++ b/client/deps/reveng/bmpbit.c @@ -73,10 +73,10 @@ main(int argc, char *argv[]) { setbmp(); if (BMP_BIT != bmpbit || BMP_SUB != bmpsub) { fprintf(stderr, "reveng: configuration fault. Update " - "reveng/config.h with these definitions and " - "recompile:\n" - "\t#define BMP_BIT %d\n" - "\t#define BMP_SUB %d\n", + "reveng/config.h with these definitions and " + "recompile:\n" + "\t#define BMP_BIT %d\n" + "\t#define BMP_SUB %d\n", bmpbit, bmpsub); exit(EXIT_FAILURE); } @@ -84,8 +84,8 @@ main(int argc, char *argv[]) { /* check the bitmap constant macro */ if (~(bmp_t) 0 != ~BMP_C(0)) { fprintf(stderr, "reveng: configuration fault. Edit " - "the definition of BMP_C() in config.h to " - "match BMP_T and recompile.\n"); + "the definition of BMP_C() in config.h to " + "match BMP_T and recompile.\n"); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); diff --git a/client/deps/reveng/preset.c b/client/deps/reveng/preset.c index 6f41ac9f5..1897ebcee 100644 --- a/client/deps/reveng/preset.c +++ b/client/deps/reveng/preset.c @@ -137,19 +137,19 @@ static const bmp_t b40c[] = { # else /* BMP_BIT */ static const bmp_t b40[] = { BMP_C(0x00048200) << (BMP_BIT - 32) | BMP_C(0x04) >> (39 - BMP_BIT), - BMP_C(0x09) << (BMP_BIT * 2 - 40), + BMP_C(0x09) << (BMP_BIT * 2 - 40), }; static const bmp_t b40a[] = { BMP_C(0xffffffff) << (BMP_BIT - 32) | BMP_C(0x7f) >> (39 - BMP_BIT), - BMP_C(0xff) << (BMP_BIT * 2 - 40), + BMP_C(0xff) << (BMP_BIT * 2 - 40), }; static const bmp_t b40b[] = { BMP_C(0xd4164fc6) << (BMP_BIT - 32) | BMP_C(0x23) >> (39 - BMP_BIT), - BMP_C(0x46) << (BMP_BIT * 2 - 40), + BMP_C(0x46) << (BMP_BIT * 2 - 40), }; static const bmp_t b40c[] = { BMP_C(0xc4ff8071) << (BMP_BIT - 32) | BMP_C(0x7f) >> (39 - BMP_BIT), - BMP_C(0xff) << (BMP_BIT * 2 - 40), + BMP_C(0xff) << (BMP_BIT * 2 - 40), }; # endif /* BMP_BIT */ @@ -187,43 +187,43 @@ static const bmp_t b64i[] = { # else /* BMP_BIT */ static const bmp_t b64[] = { BMP_C(0x00000000) << (BMP_BIT - 32) | BMP_C(0x0000000d) >> (63 - BMP_BIT), - BMP_C(0x0000001b) << (BMP_BIT * 2 - 64), + BMP_C(0x0000001b) << (BMP_BIT * 2 - 64), }; static const bmp_t b64a[] = { BMP_C(0xffffffff) << (BMP_BIT - 32) | BMP_C(0x7fffffff) >> (63 - BMP_BIT), - BMP_C(0xffffffff) << (BMP_BIT * 2 - 64), + BMP_C(0xffffffff) << (BMP_BIT * 2 - 64), }; static const bmp_t b64b[] = { BMP_C(0xb90956c7) << (BMP_BIT - 32) | BMP_C(0x3ad20800) >> (63 - BMP_BIT), - BMP_C(0x75a41001) << (BMP_BIT * 2 - 64), + BMP_C(0x75a41001) << (BMP_BIT * 2 - 64), }; static const bmp_t b64c[] = { BMP_C(0x53000000) << (BMP_BIT - 32) | BMP_C(0x00000000) >> (63 - BMP_BIT), - BMP_C(0x00000000) << (BMP_BIT * 2 - 64), + BMP_C(0x00000000) << (BMP_BIT * 2 - 64), }; static const bmp_t b64d[] = { BMP_C(0x42f0e1eb) << (BMP_BIT - 32) | BMP_C(0x54f51b49) >> (63 - BMP_BIT), - BMP_C(0xa9ea3693) << (BMP_BIT * 2 - 64), + BMP_C(0xa9ea3693) << (BMP_BIT * 2 - 64), }; static const bmp_t b64e[] = { BMP_C(0x6c40df5f) << (BMP_BIT - 32) | BMP_C(0x05a4b9a3) >> (63 - BMP_BIT), - BMP_C(0x0b497347) << (BMP_BIT * 2 - 64), + BMP_C(0x0b497347) << (BMP_BIT * 2 - 64), }; static const bmp_t b64f[] = { BMP_C(0x62ec59e3) << (BMP_BIT - 32) | BMP_C(0x78d27805) >> (63 - BMP_BIT), - BMP_C(0xf1a4f00a) << (BMP_BIT * 2 - 64), + BMP_C(0xf1a4f00a) << (BMP_BIT * 2 - 64), }; static const bmp_t b64g[] = { BMP_C(0xfcacbebd) << (BMP_BIT - 32) | BMP_C(0x2c98d4c9) >> (63 - BMP_BIT), - BMP_C(0x5931a992) << (BMP_BIT * 2 - 64), + BMP_C(0x5931a992) << (BMP_BIT * 2 - 64), }; static const bmp_t b64h[] = { BMP_C(0x995dc9bb) << (BMP_BIT - 32) | BMP_C(0x6f8c9cfd) >> (63 - BMP_BIT), - BMP_C(0xdf1939fa) << (BMP_BIT * 2 - 64), + BMP_C(0xdf1939fa) << (BMP_BIT * 2 - 64), }; static const bmp_t b64i[] = { BMP_C(0x49958c9a) << (BMP_BIT - 32) | BMP_C(0x5ebe9a9f) >> (63 - BMP_BIT), - BMP_C(0xbd7d353f) << (BMP_BIT * 2 - 64), + BMP_C(0xbd7d353f) << (BMP_BIT * 2 - 64), }; # endif /* BMP_BIT */ @@ -237,22 +237,22 @@ static const bmp_t b82a[] = { # elif BMP_BIT >= 41 static const bmp_t b82[] = { BMP_C(0x01846008880) << (BMP_BIT - 41) | BMP_C(0x08a00a20208) >> (81 - BMP_BIT), - BMP_C(0x11401440411) << (BMP_BIT * 2 - 82), + BMP_C(0x11401440411) << (BMP_BIT * 2 - 82), }; static const bmp_t b82a[] = { BMP_C(0x04f541fb128) << (BMP_BIT - 41) | BMP_C(0x011c00feb09) >> (81 - BMP_BIT), - BMP_C(0x023801fd612) << (BMP_BIT * 2 - 82), + BMP_C(0x023801fd612) << (BMP_BIT * 2 - 82), }; # else /* BMP_BIT */ static const bmp_t b82[] = { BMP_C(0x0c230044) << (BMP_BIT - 32) | BMP_C(0x040) >> (40 - BMP_BIT), - BMP_C(0x40450051) << (BMP_BIT * 2 - 64) | BMP_C(0x00104) >> (80 - BMP_BIT * 2), - BMP_C(0x00411) << (BMP_BIT * 3 - 82), + BMP_C(0x40450051) << (BMP_BIT * 2 - 64) | BMP_C(0x00104) >> (80 - BMP_BIT * 2), + BMP_C(0x00411) << (BMP_BIT * 3 - 82), }; static const bmp_t b82a[] = { BMP_C(0x27aa0fd8) << (BMP_BIT - 32) | BMP_C(0x094) >> (40 - BMP_BIT), - BMP_C(0x9408e007) << (BMP_BIT * 2 - 64) | BMP_C(0x0f584) >> (80 - BMP_BIT * 2), - BMP_C(0x3d612) << (BMP_BIT * 3 - 82), + BMP_C(0x9408e007) << (BMP_BIT * 2 - 64) | BMP_C(0x0f584) >> (80 - BMP_BIT * 2), + BMP_C(0x3d612) << (BMP_BIT * 3 - 82), }; # endif /* BMP_BIT */ @@ -262,215 +262,215 @@ static const bmp_t b82a[] = { /* Array of the polynomial bitmaps used in the model table. */ static const bmp_t b32[] = { BMP_C(0x000000af) << (BMP_BIT - 32), /* 0 -- 32,000000af */ - BMP_C(0x00010000) << (BMP_BIT - 32), /* 1 -- 16, 0001 */ - BMP_C(0x00020000) << (BMP_BIT - 32), /* 2 -- 15, 0001 */ - BMP_C(0x00065b00) << (BMP_BIT - 32), /* 3 -- 24, 00065b */ - BMP_C(0x007e0000) << (BMP_BIT - 32), /* 4 -- 16, 007e */ - BMP_C(0x007f0000) << (BMP_BIT - 32), /* 5 -- 16, 007f */ - BMP_C(0x03400000) << (BMP_BIT - 32), /* 6 -- 11, 01a */ - BMP_C(0x0376e6e7) << (BMP_BIT - 32), /* 7 -- 32,0376e6e7 */ - BMP_C(0x04c11db7) << (BMP_BIT - 32), /* 8 -- 32,04c11db7 */ - BMP_C(0x05890000) << (BMP_BIT - 32), /* 9 -- 16, 0589 */ - BMP_C(0x07000000) << (BMP_BIT - 32), /* 10 -- 8, 07 */ - BMP_C(0x080b0000) << (BMP_BIT - 32), /* 11 -- 16, 080b */ - BMP_C(0x09823b6e) << (BMP_BIT - 32), /* 12 -- 31,04c11db7 */ - BMP_C(0x0b3c0000) << (BMP_BIT - 32), /* 13 -- 15, 059e */ - BMP_C(0x0c000000) << (BMP_BIT - 32), /* 14 -- 6, 03 */ - BMP_C(0x0c200000) << (BMP_BIT - 32), /* 15 -- 11, 061 */ - BMP_C(0x0c780000) << (BMP_BIT - 32), /* 16 -- 14, 031e */ - BMP_C(0x0fb30000) << (BMP_BIT - 32), /* 17 -- 16, 0fb3 */ - BMP_C(0x10210000) << (BMP_BIT - 32), /* 18 -- 16, 1021 */ - BMP_C(0x12000000) << (BMP_BIT - 32), /* 19 -- 7, 09 */ - BMP_C(0x130d2afc) << (BMP_BIT - 32), /* 20 -- 30,04c34abf */ - BMP_C(0x144e6300) << (BMP_BIT - 32), /* 21 -- 24, 144e63 */ - BMP_C(0x15000000) << (BMP_BIT - 32), /* 22 -- 8, 15 */ - BMP_C(0x1697d06a) << (BMP_BIT - 32), /* 23 -- 32,1697d06a */ - BMP_C(0x17800000) << (BMP_BIT - 32), /* 24 -- 12, 178 */ - BMP_C(0x18000000) << (BMP_BIT - 32), /* 25 -- 6, 06 */ - BMP_C(0x19d3c8d8) << (BMP_BIT - 32), /* 26 -- 31,0ce9e46c */ - BMP_C(0x1c000000) << (BMP_BIT - 32), /* 27 -- 6, 07 */ - BMP_C(0x1d000000) << (BMP_BIT - 32), /* 28 -- 8, 1d */ - BMP_C(0x1d0f0000) << (BMP_BIT - 32), /* 29 -- 16, 1d0f */ - BMP_C(0x1dcf0000) << (BMP_BIT - 32), /* 30 -- 16, 1dcf */ - BMP_C(0x1edc6f41) << (BMP_BIT - 32), /* 31 -- 32,1edc6f41 */ - BMP_C(0x1f23b800) << (BMP_BIT - 32), /* 32 -- 24, 1f23b8 */ - BMP_C(0x20000000) << (BMP_BIT - 32), /* 33 -- 4, 2 */ - BMP_C(0x200fa500) << (BMP_BIT - 32), /* 34 -- 24, 200fa5 */ - BMP_C(0x20140000) << (BMP_BIT - 32), /* 35 -- 14, 0805 */ - BMP_C(0x20b40000) << (BMP_BIT - 32), /* 36 -- 14, 082d */ - BMP_C(0x20fe0000) << (BMP_BIT - 32), /* 37 -- 16, 20fe */ - BMP_C(0x21890000) << (BMP_BIT - 32), /* 38 -- 16, 2189 */ - BMP_C(0x21cf0200) << (BMP_BIT - 32), /* 39 -- 24, 21cf02 */ - BMP_C(0x23ef5200) << (BMP_BIT - 32), /* 40 -- 24, 23ef52 */ - BMP_C(0x25000000) << (BMP_BIT - 32), /* 41 -- 8, 25 */ - BMP_C(0x26000000) << (BMP_BIT - 32), /* 42 -- 8, 26 */ - BMP_C(0x26b10000) << (BMP_BIT - 32), /* 43 -- 16, 26b1 */ - BMP_C(0x27818000) << (BMP_BIT - 32), /* 44 -- 17, 04f03 */ - BMP_C(0x27d00000) << (BMP_BIT - 32), /* 45 -- 13, 04fa */ - BMP_C(0x28000000) << (BMP_BIT - 32), /* 46 -- 5, 05 */ - BMP_C(0x29b10000) << (BMP_BIT - 32), /* 47 -- 16, 29b1 */ - BMP_C(0x2f000000) << (BMP_BIT - 32), /* 48 -- 8, 2f */ - BMP_C(0x30000000) << (BMP_BIT - 32), /* 49 -- 4, 3/ 5, 6 */ - BMP_C(0x3010bf7f) << (BMP_BIT - 32), /* 50 -- 32,3010bf7f */ - BMP_C(0x31000000) << (BMP_BIT - 32), /* 51 -- 8, 31 */ - BMP_C(0x31800000) << (BMP_BIT - 32), /* 52 -- 10, 0c6 */ - BMP_C(0x31c30000) << (BMP_BIT - 32), /* 53 -- 16, 31c3 */ - BMP_C(0x328b6300) << (BMP_BIT - 32), /* 54 -- 24, 328b63 */ - BMP_C(0x34000000) << (BMP_BIT - 32), /* 55 -- 6, 0d */ - BMP_C(0x340bc6d9) << (BMP_BIT - 32), /* 56 -- 32,340bc6d9 */ - BMP_C(0x37000000) << (BMP_BIT - 32), /* 57 -- 8, 37 */ - BMP_C(0x38000000) << (BMP_BIT - 32), /* 58 -- 5, 07 */ - BMP_C(0x39000000) << (BMP_BIT - 32), /* 59 -- 8, 39 */ - BMP_C(0x3d650000) << (BMP_BIT - 32), /* 60 -- 16, 3d65 */ - BMP_C(0x3e000000) << (BMP_BIT - 32), /* 61 -- 8, 3e */ - BMP_C(0x40000000) << (BMP_BIT - 32), /* 62 -- 3, 2 */ - BMP_C(0x42000000) << (BMP_BIT - 32), /* 63 -- 8, 42 */ - BMP_C(0x44c20000) << (BMP_BIT - 32), /* 64 -- 16, 44c2 */ - BMP_C(0x45270551) << (BMP_BIT - 32), /* 65 -- 32,45270551 */ - BMP_C(0x48000000) << (BMP_BIT - 32), /* 66 -- 5, 09 */ - BMP_C(0x49000000) << (BMP_BIT - 32), /* 67 -- 8, 49 */ - BMP_C(0x4a800000) << (BMP_BIT - 32), /* 68 -- 10, 12a */ - BMP_C(0x4acc0000) << (BMP_BIT - 32), /* 69 -- 15, 2566 */ - BMP_C(0x4b000000) << (BMP_BIT - 32), /* 70 -- 8, 4b */ - BMP_C(0x4b370000) << (BMP_BIT - 32), /* 71 -- 16, 4b37 */ - BMP_C(0x4c000000) << (BMP_BIT - 32), /* 72 -- 6, 13 */ - BMP_C(0x4c060000) << (BMP_BIT - 32), /* 73 -- 16, 4c06 */ - BMP_C(0x53000000) << (BMP_BIT - 32), /* 74 -- 8, 53 */ - BMP_C(0x55000000) << (BMP_BIT - 32), /* 75 -- 8, 55 */ - BMP_C(0x55555500) << (BMP_BIT - 32), /* 76 -- 24, 555555 */ - BMP_C(0x59350000) << (BMP_BIT - 32), /* 77 -- 16, 5935 */ - BMP_C(0x5d380000) << (BMP_BIT - 32), /* 78 -- 16, 5d38 */ - BMP_C(0x5d400000) << (BMP_BIT - 32), /* 79 -- 10, 175 */ - BMP_C(0x5d6dcb00) << (BMP_BIT - 32), /* 80 -- 24, 5d6dcb */ - BMP_C(0x60000000) << (BMP_BIT - 32), /* 81 -- 3, 3 */ - BMP_C(0x60e00000) << (BMP_BIT - 32), /* 82 -- 11, 307 */ - BMP_C(0x63d00000) << (BMP_BIT - 32), /* 83 -- 16, 63d0 */ - BMP_C(0x64000000) << (BMP_BIT - 32), /* 84 -- 6, 19 */ - BMP_C(0x66400000) << (BMP_BIT - 32), /* 85 -- 10, 199 */ - BMP_C(0x66c50000) << (BMP_BIT - 32), /* 86 -- 16, 66c5 */ - BMP_C(0x6f630000) << (BMP_BIT - 32), /* 87 -- 16, 6f63 */ - BMP_C(0x6f910000) << (BMP_BIT - 32), /* 88 -- 16, 6f91 */ - BMP_C(0x70000000) << (BMP_BIT - 32), /* 89 -- 4, 7 */ - BMP_C(0x70a00000) << (BMP_BIT - 32), /* 90 -- 11, 385 */ - BMP_C(0x755b0000) << (BMP_BIT - 32), /* 91 -- 16, 755b */ - BMP_C(0x765e7680) << (BMP_BIT - 32), /* 92 -- 32,765e7680 */ - BMP_C(0x76c20800) << (BMP_BIT - 32), /* 93 -- 32, 0ed841 */ - BMP_C(0x7979bd00) << (BMP_BIT - 32), /* 94 -- 24, 7979bd */ - BMP_C(0x7e000000) << (BMP_BIT - 32), /* 95 -- 8, 7e */ - BMP_C(0x80000000) << (BMP_BIT - 32), /* 96 -- 3, 4 */ - BMP_C(0x80006300) << (BMP_BIT - 32), /* 97 -- 24, 800063 */ - BMP_C(0x80050000) << (BMP_BIT - 32), /* 98 -- 16, 8005 */ - BMP_C(0x800d0000) << (BMP_BIT - 32), /* 99 -- 16, 800d */ - BMP_C(0x800fe300) << (BMP_BIT - 32), /* 100 -- 24, 800fe3 */ - BMP_C(0x80b40000) << (BMP_BIT - 32), /* 101 -- 14, 202d */ - BMP_C(0x80c2e71c) << (BMP_BIT - 32), /* 102 -- 30,2030b9c7 */ - BMP_C(0x80f00000) << (BMP_BIT - 32), /* 103 -- 12, 80f */ - BMP_C(0x814141ab) << (BMP_BIT - 32), /* 104 -- 32,814141ab */ - BMP_C(0x8144c800) << (BMP_BIT - 32), /* 105 -- 21, 102899 */ - BMP_C(0x864cfb00) << (BMP_BIT - 32), /* 106 -- 24, 864cfb */ - BMP_C(0x87315576) << (BMP_BIT - 32), /* 107 -- 32,87315576 */ - BMP_C(0x89ec0000) << (BMP_BIT - 32), /* 108 -- 16, 89ec */ - BMP_C(0x8a000000) << (BMP_BIT - 32), /* 109 -- 7, 45 */ - BMP_C(0x8b320000) << (BMP_BIT - 32), /* 110 -- 15, 4599 */ - BMP_C(0x8bb70000) << (BMP_BIT - 32), /* 111 -- 16, 8bb7 */ - BMP_C(0x8cc00000) << (BMP_BIT - 32), /* 112 -- 10, 233 */ - BMP_C(0x904cddbf) << (BMP_BIT - 32), /* 113 -- 32,904cddbf */ - BMP_C(0x906e0000) << (BMP_BIT - 32), /* 114 -- 16, 906e */ - BMP_C(0x94000000) << (BMP_BIT - 32), /* 115 -- 8, 94 */ - BMP_C(0x97000000) << (BMP_BIT - 32), /* 116 -- 8, 97 */ - BMP_C(0x98000000) << (BMP_BIT - 32), /* 117 -- 6, 26 */ - BMP_C(0x99000000) << (BMP_BIT - 32), /* 118 -- 8, 99 */ - BMP_C(0x9b000000) << (BMP_BIT - 32), /* 119 -- 8, 9b */ - BMP_C(0x9c000000) << (BMP_BIT - 32), /* 120 -- 6, 27 */ - BMP_C(0x9d5e4de2) << (BMP_BIT - 32), /* 121 -- 31,4eaf26f1 */ - BMP_C(0x9e000000) << (BMP_BIT - 32), /* 122 -- 7, 4f */ - BMP_C(0x9ecf0000) << (BMP_BIT - 32), /* 123 -- 16, 9ecf */ - BMP_C(0xa0660000) << (BMP_BIT - 32), /* 124 -- 16, a066 */ - BMP_C(0xa0970000) << (BMP_BIT - 32), /* 125 -- 16, a097 */ - BMP_C(0xa1000000) << (BMP_BIT - 32), /* 126 -- 8, a1 */ - BMP_C(0xa3660000) << (BMP_BIT - 32), /* 127 -- 16, a366 */ - BMP_C(0xa6000000) << (BMP_BIT - 32), /* 128 -- 7, 53 */ - BMP_C(0xa7000000) << (BMP_BIT - 32), /* 129 -- 8, a7 */ - BMP_C(0xa8000000) << (BMP_BIT - 32), /* 130 -- 5, 15 */ - BMP_C(0xa8190000) << (BMP_BIT - 32), /* 131 -- 16, a819 */ - BMP_C(0xa833982b) << (BMP_BIT - 32), /* 132 -- 32,a833982b */ - BMP_C(0xabcdef00) << (BMP_BIT - 32), /* 133 -- 24, abcdef */ - BMP_C(0xac000000) << (BMP_BIT - 32), /* 134 -- 8, ac */ - BMP_C(0xaee70000) << (BMP_BIT - 32), /* 135 -- 16, aee7 */ - BMP_C(0xb0000000) << (BMP_BIT - 32), /* 136 -- 4, b */ - BMP_C(0xb0010000) << (BMP_BIT - 32), /* 137 -- 16, b001 */ - BMP_C(0xb2aa0000) << (BMP_BIT - 32), /* 138 -- 16, b2aa */ - BMP_C(0xb3400000) << (BMP_BIT - 32), /* 139 -- 12, b34 */ - BMP_C(0xb42d8000) << (BMP_BIT - 32), /* 140 -- 17, 1685b */ - BMP_C(0xb4600000) << (BMP_BIT - 32), /* 141 -- 11, 5a3 */ - BMP_C(0xb4c80000) << (BMP_BIT - 32), /* 142 -- 16, b4c8 */ - BMP_C(0xb4f3e600) << (BMP_BIT - 32), /* 143 -- 24, b4f3e6 */ - BMP_C(0xb704ce00) << (BMP_BIT - 32), /* 144 -- 24, b704ce */ - BMP_C(0xb798b438) << (BMP_BIT - 32), /* 145 -- 32,b798b438 */ - BMP_C(0xbb3d0000) << (BMP_BIT - 32), /* 146 -- 16, bb3d */ - BMP_C(0xbc000000) << (BMP_BIT - 32), /* 147 -- 6,2f/ 8,bc */ - BMP_C(0xbd0be338) << (BMP_BIT - 32), /* 148 -- 32,bd0be338 */ - BMP_C(0xbdf40000) << (BMP_BIT - 32), /* 149 -- 16, bdf4 */ - BMP_C(0xbf050000) << (BMP_BIT - 32), /* 150 -- 16, bf05 */ - BMP_C(0xc0000000) << (BMP_BIT - 32), /* 151 -- 3, 6 */ - BMP_C(0xc2000000) << (BMP_BIT - 32), /* 152 -- 7, 61 */ - BMP_C(0xc25a5600) << (BMP_BIT - 32), /* 153 -- 24, c25a56 */ - BMP_C(0xc2b70000) << (BMP_BIT - 32), /* 154 -- 16, c2b7 */ - BMP_C(0xc2b80000) << (BMP_BIT - 32), /* 155 -- 14, 30ae */ - BMP_C(0xc4000000) << (BMP_BIT - 32), /* 156 -- 8, c4 */ - BMP_C(0xc6c60000) << (BMP_BIT - 32), /* 157 -- 16, c6c6 */ - BMP_C(0xc7000000) << (BMP_BIT - 32), /* 158 -- 8, c7 */ - BMP_C(0xc704dd7b) << (BMP_BIT - 32), /* 159 -- 32,c704dd7b */ - BMP_C(0xc8000000) << (BMP_BIT - 32), /* 160 -- 5, 19 */ - BMP_C(0xc8670000) << (BMP_BIT - 32), /* 161 -- 16, c867 */ - BMP_C(0xcbf43926) << (BMP_BIT - 32), /* 162 -- 32,cbf43926 */ - BMP_C(0xcde70300) << (BMP_BIT - 32), /* 163 -- 24, cde703 */ - BMP_C(0xce3c0000) << (BMP_BIT - 32), /* 164 -- 16, ce3c */ - BMP_C(0xd0000000) << (BMP_BIT - 32), /* 165 -- 8, d0 */ - BMP_C(0xd02a0000) << (BMP_BIT - 32), /* 166 -- 15, 6815 */ - BMP_C(0xd0db0000) << (BMP_BIT - 32), /* 167 -- 16, d0db */ - BMP_C(0xd3100000) << (BMP_BIT - 32), /* 168 -- 12, d31 */ - BMP_C(0xd3be9568) << (BMP_BIT - 32), /* 169 -- 30,34efa55a */ - BMP_C(0xd4d00000) << (BMP_BIT - 32), /* 170 -- 12, d4d */ - BMP_C(0xd5000000) << (BMP_BIT - 32), /* 171 -- 8, d5 */ - BMP_C(0xd64e0000) << (BMP_BIT - 32), /* 172 -- 16, d64e */ - BMP_C(0xda000000) << (BMP_BIT - 32), /* 173 -- 8, da */ - BMP_C(0xdaf00000) << (BMP_BIT - 32), /* 174 -- 12, daf */ - BMP_C(0xdebb20e3) << (BMP_BIT - 32), /* 175 -- 32,debb20e3 */ - BMP_C(0xdf000000) << (BMP_BIT - 32), /* 176 -- 8, df */ - BMP_C(0xe0000000) << (BMP_BIT - 32), /* 177 -- 3, 7 */ - BMP_C(0xe3069283) << (BMP_BIT - 32), /* 178 -- 32,e3069283 */ - BMP_C(0xe3940000) << (BMP_BIT - 32), /* 179 -- 16, e394 */ - BMP_C(0xe5cc0000) << (BMP_BIT - 32), /* 180 -- 16, e5cc */ - BMP_C(0xe7a80000) << (BMP_BIT - 32), /* 181 -- 13, 1cf5 */ - BMP_C(0xe8000000) << (BMP_BIT - 32), /* 182 -- 6, 3a */ - BMP_C(0xea000000) << (BMP_BIT - 32), /* 183 -- 7, 75 */ - BMP_C(0xea820000) << (BMP_BIT - 32), /* 184 -- 16, ea82 */ - BMP_C(0xec000000) << (BMP_BIT - 32), /* 185 -- 6, 3b */ - BMP_C(0xf0000000) << (BMP_BIT - 32), /* 186 -- 4, f */ - BMP_C(0xf0b80000) << (BMP_BIT - 32), /* 187 -- 16, f0b8 */ - BMP_C(0xf1300000) << (BMP_BIT - 32), /* 188 -- 12, f13 */ - BMP_C(0xf4000000) << (BMP_BIT - 32), /* 189 -- 8, f4 */ - BMP_C(0xf4acfb13) << (BMP_BIT - 32), /* 190 -- 32,f4acfb13 */ - BMP_C(0xf5b00000) << (BMP_BIT - 32), /* 191 -- 12, f5b */ - BMP_C(0xf6400000) << (BMP_BIT - 32), /* 192 -- 10, 3d9 */ - BMP_C(0xf7000000) << (BMP_BIT - 32), /* 193 -- 8, f7 */ - BMP_C(0xf8000000) << (BMP_BIT - 32), /* 194 -- 5, 1f */ - BMP_C(0xfc000000) << (BMP_BIT - 32), /* 195 -- 6, 3f */ - BMP_C(0xfc891918) << (BMP_BIT - 32), /* 196 -- 32,fc891918 */ - BMP_C(0xfd000000) << (BMP_BIT - 32), /* 197 -- 8, fd */ - BMP_C(0xfe000000) << (BMP_BIT - 32), /* 198 -- 7, 7f */ - BMP_C(0xfedcba00) << (BMP_BIT - 32), /* 199 -- 24, fedcba */ - BMP_C(0xfee80000) << (BMP_BIT - 32), /* 200 -- 16, fee8 */ - BMP_C(0xff000000) << (BMP_BIT - 32), /* 201 -- 8, ff */ - BMP_C(0xffc00000) << (BMP_BIT - 32), /* 202 -- 10, 3ff */ - BMP_C(0xfff00000) << (BMP_BIT - 32), /* 203 -- 12, fff */ - BMP_C(0xfffc0000) << (BMP_BIT - 32), /* 204 -- 14, 3fff */ - BMP_C(0xffff0000) << (BMP_BIT - 32), /* 205 -- 16, ffff */ - BMP_C(0xffffff00) << (BMP_BIT - 32), /* 206 -- 24, ffffff */ - BMP_C(0xfffffffc) << (BMP_BIT - 32), /* 207 -- 30,3fffffff */ - BMP_C(0xfffffffe) << (BMP_BIT - 32), /* 208 -- 31,7fffffff */ - BMP_C(0xffffffff) << (BMP_BIT - 32), /* 209 -- 32,ffffffff */ + BMP_C(0x00010000) << (BMP_BIT - 32), /* 1 -- 16, 0001 */ + BMP_C(0x00020000) << (BMP_BIT - 32), /* 2 -- 15, 0001 */ + BMP_C(0x00065b00) << (BMP_BIT - 32), /* 3 -- 24, 00065b */ + BMP_C(0x007e0000) << (BMP_BIT - 32), /* 4 -- 16, 007e */ + BMP_C(0x007f0000) << (BMP_BIT - 32), /* 5 -- 16, 007f */ + BMP_C(0x03400000) << (BMP_BIT - 32), /* 6 -- 11, 01a */ + BMP_C(0x0376e6e7) << (BMP_BIT - 32), /* 7 -- 32,0376e6e7 */ + BMP_C(0x04c11db7) << (BMP_BIT - 32), /* 8 -- 32,04c11db7 */ + BMP_C(0x05890000) << (BMP_BIT - 32), /* 9 -- 16, 0589 */ + BMP_C(0x07000000) << (BMP_BIT - 32), /* 10 -- 8, 07 */ + BMP_C(0x080b0000) << (BMP_BIT - 32), /* 11 -- 16, 080b */ + BMP_C(0x09823b6e) << (BMP_BIT - 32), /* 12 -- 31,04c11db7 */ + BMP_C(0x0b3c0000) << (BMP_BIT - 32), /* 13 -- 15, 059e */ + BMP_C(0x0c000000) << (BMP_BIT - 32), /* 14 -- 6, 03 */ + BMP_C(0x0c200000) << (BMP_BIT - 32), /* 15 -- 11, 061 */ + BMP_C(0x0c780000) << (BMP_BIT - 32), /* 16 -- 14, 031e */ + BMP_C(0x0fb30000) << (BMP_BIT - 32), /* 17 -- 16, 0fb3 */ + BMP_C(0x10210000) << (BMP_BIT - 32), /* 18 -- 16, 1021 */ + BMP_C(0x12000000) << (BMP_BIT - 32), /* 19 -- 7, 09 */ + BMP_C(0x130d2afc) << (BMP_BIT - 32), /* 20 -- 30,04c34abf */ + BMP_C(0x144e6300) << (BMP_BIT - 32), /* 21 -- 24, 144e63 */ + BMP_C(0x15000000) << (BMP_BIT - 32), /* 22 -- 8, 15 */ + BMP_C(0x1697d06a) << (BMP_BIT - 32), /* 23 -- 32,1697d06a */ + BMP_C(0x17800000) << (BMP_BIT - 32), /* 24 -- 12, 178 */ + BMP_C(0x18000000) << (BMP_BIT - 32), /* 25 -- 6, 06 */ + BMP_C(0x19d3c8d8) << (BMP_BIT - 32), /* 26 -- 31,0ce9e46c */ + BMP_C(0x1c000000) << (BMP_BIT - 32), /* 27 -- 6, 07 */ + BMP_C(0x1d000000) << (BMP_BIT - 32), /* 28 -- 8, 1d */ + BMP_C(0x1d0f0000) << (BMP_BIT - 32), /* 29 -- 16, 1d0f */ + BMP_C(0x1dcf0000) << (BMP_BIT - 32), /* 30 -- 16, 1dcf */ + BMP_C(0x1edc6f41) << (BMP_BIT - 32), /* 31 -- 32,1edc6f41 */ + BMP_C(0x1f23b800) << (BMP_BIT - 32), /* 32 -- 24, 1f23b8 */ + BMP_C(0x20000000) << (BMP_BIT - 32), /* 33 -- 4, 2 */ + BMP_C(0x200fa500) << (BMP_BIT - 32), /* 34 -- 24, 200fa5 */ + BMP_C(0x20140000) << (BMP_BIT - 32), /* 35 -- 14, 0805 */ + BMP_C(0x20b40000) << (BMP_BIT - 32), /* 36 -- 14, 082d */ + BMP_C(0x20fe0000) << (BMP_BIT - 32), /* 37 -- 16, 20fe */ + BMP_C(0x21890000) << (BMP_BIT - 32), /* 38 -- 16, 2189 */ + BMP_C(0x21cf0200) << (BMP_BIT - 32), /* 39 -- 24, 21cf02 */ + BMP_C(0x23ef5200) << (BMP_BIT - 32), /* 40 -- 24, 23ef52 */ + BMP_C(0x25000000) << (BMP_BIT - 32), /* 41 -- 8, 25 */ + BMP_C(0x26000000) << (BMP_BIT - 32), /* 42 -- 8, 26 */ + BMP_C(0x26b10000) << (BMP_BIT - 32), /* 43 -- 16, 26b1 */ + BMP_C(0x27818000) << (BMP_BIT - 32), /* 44 -- 17, 04f03 */ + BMP_C(0x27d00000) << (BMP_BIT - 32), /* 45 -- 13, 04fa */ + BMP_C(0x28000000) << (BMP_BIT - 32), /* 46 -- 5, 05 */ + BMP_C(0x29b10000) << (BMP_BIT - 32), /* 47 -- 16, 29b1 */ + BMP_C(0x2f000000) << (BMP_BIT - 32), /* 48 -- 8, 2f */ + BMP_C(0x30000000) << (BMP_BIT - 32), /* 49 -- 4, 3/ 5, 6 */ + BMP_C(0x3010bf7f) << (BMP_BIT - 32), /* 50 -- 32,3010bf7f */ + BMP_C(0x31000000) << (BMP_BIT - 32), /* 51 -- 8, 31 */ + BMP_C(0x31800000) << (BMP_BIT - 32), /* 52 -- 10, 0c6 */ + BMP_C(0x31c30000) << (BMP_BIT - 32), /* 53 -- 16, 31c3 */ + BMP_C(0x328b6300) << (BMP_BIT - 32), /* 54 -- 24, 328b63 */ + BMP_C(0x34000000) << (BMP_BIT - 32), /* 55 -- 6, 0d */ + BMP_C(0x340bc6d9) << (BMP_BIT - 32), /* 56 -- 32,340bc6d9 */ + BMP_C(0x37000000) << (BMP_BIT - 32), /* 57 -- 8, 37 */ + BMP_C(0x38000000) << (BMP_BIT - 32), /* 58 -- 5, 07 */ + BMP_C(0x39000000) << (BMP_BIT - 32), /* 59 -- 8, 39 */ + BMP_C(0x3d650000) << (BMP_BIT - 32), /* 60 -- 16, 3d65 */ + BMP_C(0x3e000000) << (BMP_BIT - 32), /* 61 -- 8, 3e */ + BMP_C(0x40000000) << (BMP_BIT - 32), /* 62 -- 3, 2 */ + BMP_C(0x42000000) << (BMP_BIT - 32), /* 63 -- 8, 42 */ + BMP_C(0x44c20000) << (BMP_BIT - 32), /* 64 -- 16, 44c2 */ + BMP_C(0x45270551) << (BMP_BIT - 32), /* 65 -- 32,45270551 */ + BMP_C(0x48000000) << (BMP_BIT - 32), /* 66 -- 5, 09 */ + BMP_C(0x49000000) << (BMP_BIT - 32), /* 67 -- 8, 49 */ + BMP_C(0x4a800000) << (BMP_BIT - 32), /* 68 -- 10, 12a */ + BMP_C(0x4acc0000) << (BMP_BIT - 32), /* 69 -- 15, 2566 */ + BMP_C(0x4b000000) << (BMP_BIT - 32), /* 70 -- 8, 4b */ + BMP_C(0x4b370000) << (BMP_BIT - 32), /* 71 -- 16, 4b37 */ + BMP_C(0x4c000000) << (BMP_BIT - 32), /* 72 -- 6, 13 */ + BMP_C(0x4c060000) << (BMP_BIT - 32), /* 73 -- 16, 4c06 */ + BMP_C(0x53000000) << (BMP_BIT - 32), /* 74 -- 8, 53 */ + BMP_C(0x55000000) << (BMP_BIT - 32), /* 75 -- 8, 55 */ + BMP_C(0x55555500) << (BMP_BIT - 32), /* 76 -- 24, 555555 */ + BMP_C(0x59350000) << (BMP_BIT - 32), /* 77 -- 16, 5935 */ + BMP_C(0x5d380000) << (BMP_BIT - 32), /* 78 -- 16, 5d38 */ + BMP_C(0x5d400000) << (BMP_BIT - 32), /* 79 -- 10, 175 */ + BMP_C(0x5d6dcb00) << (BMP_BIT - 32), /* 80 -- 24, 5d6dcb */ + BMP_C(0x60000000) << (BMP_BIT - 32), /* 81 -- 3, 3 */ + BMP_C(0x60e00000) << (BMP_BIT - 32), /* 82 -- 11, 307 */ + BMP_C(0x63d00000) << (BMP_BIT - 32), /* 83 -- 16, 63d0 */ + BMP_C(0x64000000) << (BMP_BIT - 32), /* 84 -- 6, 19 */ + BMP_C(0x66400000) << (BMP_BIT - 32), /* 85 -- 10, 199 */ + BMP_C(0x66c50000) << (BMP_BIT - 32), /* 86 -- 16, 66c5 */ + BMP_C(0x6f630000) << (BMP_BIT - 32), /* 87 -- 16, 6f63 */ + BMP_C(0x6f910000) << (BMP_BIT - 32), /* 88 -- 16, 6f91 */ + BMP_C(0x70000000) << (BMP_BIT - 32), /* 89 -- 4, 7 */ + BMP_C(0x70a00000) << (BMP_BIT - 32), /* 90 -- 11, 385 */ + BMP_C(0x755b0000) << (BMP_BIT - 32), /* 91 -- 16, 755b */ + BMP_C(0x765e7680) << (BMP_BIT - 32), /* 92 -- 32,765e7680 */ + BMP_C(0x76c20800) << (BMP_BIT - 32), /* 93 -- 32, 0ed841 */ + BMP_C(0x7979bd00) << (BMP_BIT - 32), /* 94 -- 24, 7979bd */ + BMP_C(0x7e000000) << (BMP_BIT - 32), /* 95 -- 8, 7e */ + BMP_C(0x80000000) << (BMP_BIT - 32), /* 96 -- 3, 4 */ + BMP_C(0x80006300) << (BMP_BIT - 32), /* 97 -- 24, 800063 */ + BMP_C(0x80050000) << (BMP_BIT - 32), /* 98 -- 16, 8005 */ + BMP_C(0x800d0000) << (BMP_BIT - 32), /* 99 -- 16, 800d */ + BMP_C(0x800fe300) << (BMP_BIT - 32), /* 100 -- 24, 800fe3 */ + BMP_C(0x80b40000) << (BMP_BIT - 32), /* 101 -- 14, 202d */ + BMP_C(0x80c2e71c) << (BMP_BIT - 32), /* 102 -- 30,2030b9c7 */ + BMP_C(0x80f00000) << (BMP_BIT - 32), /* 103 -- 12, 80f */ + BMP_C(0x814141ab) << (BMP_BIT - 32), /* 104 -- 32,814141ab */ + BMP_C(0x8144c800) << (BMP_BIT - 32), /* 105 -- 21, 102899 */ + BMP_C(0x864cfb00) << (BMP_BIT - 32), /* 106 -- 24, 864cfb */ + BMP_C(0x87315576) << (BMP_BIT - 32), /* 107 -- 32,87315576 */ + BMP_C(0x89ec0000) << (BMP_BIT - 32), /* 108 -- 16, 89ec */ + BMP_C(0x8a000000) << (BMP_BIT - 32), /* 109 -- 7, 45 */ + BMP_C(0x8b320000) << (BMP_BIT - 32), /* 110 -- 15, 4599 */ + BMP_C(0x8bb70000) << (BMP_BIT - 32), /* 111 -- 16, 8bb7 */ + BMP_C(0x8cc00000) << (BMP_BIT - 32), /* 112 -- 10, 233 */ + BMP_C(0x904cddbf) << (BMP_BIT - 32), /* 113 -- 32,904cddbf */ + BMP_C(0x906e0000) << (BMP_BIT - 32), /* 114 -- 16, 906e */ + BMP_C(0x94000000) << (BMP_BIT - 32), /* 115 -- 8, 94 */ + BMP_C(0x97000000) << (BMP_BIT - 32), /* 116 -- 8, 97 */ + BMP_C(0x98000000) << (BMP_BIT - 32), /* 117 -- 6, 26 */ + BMP_C(0x99000000) << (BMP_BIT - 32), /* 118 -- 8, 99 */ + BMP_C(0x9b000000) << (BMP_BIT - 32), /* 119 -- 8, 9b */ + BMP_C(0x9c000000) << (BMP_BIT - 32), /* 120 -- 6, 27 */ + BMP_C(0x9d5e4de2) << (BMP_BIT - 32), /* 121 -- 31,4eaf26f1 */ + BMP_C(0x9e000000) << (BMP_BIT - 32), /* 122 -- 7, 4f */ + BMP_C(0x9ecf0000) << (BMP_BIT - 32), /* 123 -- 16, 9ecf */ + BMP_C(0xa0660000) << (BMP_BIT - 32), /* 124 -- 16, a066 */ + BMP_C(0xa0970000) << (BMP_BIT - 32), /* 125 -- 16, a097 */ + BMP_C(0xa1000000) << (BMP_BIT - 32), /* 126 -- 8, a1 */ + BMP_C(0xa3660000) << (BMP_BIT - 32), /* 127 -- 16, a366 */ + BMP_C(0xa6000000) << (BMP_BIT - 32), /* 128 -- 7, 53 */ + BMP_C(0xa7000000) << (BMP_BIT - 32), /* 129 -- 8, a7 */ + BMP_C(0xa8000000) << (BMP_BIT - 32), /* 130 -- 5, 15 */ + BMP_C(0xa8190000) << (BMP_BIT - 32), /* 131 -- 16, a819 */ + BMP_C(0xa833982b) << (BMP_BIT - 32), /* 132 -- 32,a833982b */ + BMP_C(0xabcdef00) << (BMP_BIT - 32), /* 133 -- 24, abcdef */ + BMP_C(0xac000000) << (BMP_BIT - 32), /* 134 -- 8, ac */ + BMP_C(0xaee70000) << (BMP_BIT - 32), /* 135 -- 16, aee7 */ + BMP_C(0xb0000000) << (BMP_BIT - 32), /* 136 -- 4, b */ + BMP_C(0xb0010000) << (BMP_BIT - 32), /* 137 -- 16, b001 */ + BMP_C(0xb2aa0000) << (BMP_BIT - 32), /* 138 -- 16, b2aa */ + BMP_C(0xb3400000) << (BMP_BIT - 32), /* 139 -- 12, b34 */ + BMP_C(0xb42d8000) << (BMP_BIT - 32), /* 140 -- 17, 1685b */ + BMP_C(0xb4600000) << (BMP_BIT - 32), /* 141 -- 11, 5a3 */ + BMP_C(0xb4c80000) << (BMP_BIT - 32), /* 142 -- 16, b4c8 */ + BMP_C(0xb4f3e600) << (BMP_BIT - 32), /* 143 -- 24, b4f3e6 */ + BMP_C(0xb704ce00) << (BMP_BIT - 32), /* 144 -- 24, b704ce */ + BMP_C(0xb798b438) << (BMP_BIT - 32), /* 145 -- 32,b798b438 */ + BMP_C(0xbb3d0000) << (BMP_BIT - 32), /* 146 -- 16, bb3d */ + BMP_C(0xbc000000) << (BMP_BIT - 32), /* 147 -- 6,2f/ 8,bc */ + BMP_C(0xbd0be338) << (BMP_BIT - 32), /* 148 -- 32,bd0be338 */ + BMP_C(0xbdf40000) << (BMP_BIT - 32), /* 149 -- 16, bdf4 */ + BMP_C(0xbf050000) << (BMP_BIT - 32), /* 150 -- 16, bf05 */ + BMP_C(0xc0000000) << (BMP_BIT - 32), /* 151 -- 3, 6 */ + BMP_C(0xc2000000) << (BMP_BIT - 32), /* 152 -- 7, 61 */ + BMP_C(0xc25a5600) << (BMP_BIT - 32), /* 153 -- 24, c25a56 */ + BMP_C(0xc2b70000) << (BMP_BIT - 32), /* 154 -- 16, c2b7 */ + BMP_C(0xc2b80000) << (BMP_BIT - 32), /* 155 -- 14, 30ae */ + BMP_C(0xc4000000) << (BMP_BIT - 32), /* 156 -- 8, c4 */ + BMP_C(0xc6c60000) << (BMP_BIT - 32), /* 157 -- 16, c6c6 */ + BMP_C(0xc7000000) << (BMP_BIT - 32), /* 158 -- 8, c7 */ + BMP_C(0xc704dd7b) << (BMP_BIT - 32), /* 159 -- 32,c704dd7b */ + BMP_C(0xc8000000) << (BMP_BIT - 32), /* 160 -- 5, 19 */ + BMP_C(0xc8670000) << (BMP_BIT - 32), /* 161 -- 16, c867 */ + BMP_C(0xcbf43926) << (BMP_BIT - 32), /* 162 -- 32,cbf43926 */ + BMP_C(0xcde70300) << (BMP_BIT - 32), /* 163 -- 24, cde703 */ + BMP_C(0xce3c0000) << (BMP_BIT - 32), /* 164 -- 16, ce3c */ + BMP_C(0xd0000000) << (BMP_BIT - 32), /* 165 -- 8, d0 */ + BMP_C(0xd02a0000) << (BMP_BIT - 32), /* 166 -- 15, 6815 */ + BMP_C(0xd0db0000) << (BMP_BIT - 32), /* 167 -- 16, d0db */ + BMP_C(0xd3100000) << (BMP_BIT - 32), /* 168 -- 12, d31 */ + BMP_C(0xd3be9568) << (BMP_BIT - 32), /* 169 -- 30,34efa55a */ + BMP_C(0xd4d00000) << (BMP_BIT - 32), /* 170 -- 12, d4d */ + BMP_C(0xd5000000) << (BMP_BIT - 32), /* 171 -- 8, d5 */ + BMP_C(0xd64e0000) << (BMP_BIT - 32), /* 172 -- 16, d64e */ + BMP_C(0xda000000) << (BMP_BIT - 32), /* 173 -- 8, da */ + BMP_C(0xdaf00000) << (BMP_BIT - 32), /* 174 -- 12, daf */ + BMP_C(0xdebb20e3) << (BMP_BIT - 32), /* 175 -- 32,debb20e3 */ + BMP_C(0xdf000000) << (BMP_BIT - 32), /* 176 -- 8, df */ + BMP_C(0xe0000000) << (BMP_BIT - 32), /* 177 -- 3, 7 */ + BMP_C(0xe3069283) << (BMP_BIT - 32), /* 178 -- 32,e3069283 */ + BMP_C(0xe3940000) << (BMP_BIT - 32), /* 179 -- 16, e394 */ + BMP_C(0xe5cc0000) << (BMP_BIT - 32), /* 180 -- 16, e5cc */ + BMP_C(0xe7a80000) << (BMP_BIT - 32), /* 181 -- 13, 1cf5 */ + BMP_C(0xe8000000) << (BMP_BIT - 32), /* 182 -- 6, 3a */ + BMP_C(0xea000000) << (BMP_BIT - 32), /* 183 -- 7, 75 */ + BMP_C(0xea820000) << (BMP_BIT - 32), /* 184 -- 16, ea82 */ + BMP_C(0xec000000) << (BMP_BIT - 32), /* 185 -- 6, 3b */ + BMP_C(0xf0000000) << (BMP_BIT - 32), /* 186 -- 4, f */ + BMP_C(0xf0b80000) << (BMP_BIT - 32), /* 187 -- 16, f0b8 */ + BMP_C(0xf1300000) << (BMP_BIT - 32), /* 188 -- 12, f13 */ + BMP_C(0xf4000000) << (BMP_BIT - 32), /* 189 -- 8, f4 */ + BMP_C(0xf4acfb13) << (BMP_BIT - 32), /* 190 -- 32,f4acfb13 */ + BMP_C(0xf5b00000) << (BMP_BIT - 32), /* 191 -- 12, f5b */ + BMP_C(0xf6400000) << (BMP_BIT - 32), /* 192 -- 10, 3d9 */ + BMP_C(0xf7000000) << (BMP_BIT - 32), /* 193 -- 8, f7 */ + BMP_C(0xf8000000) << (BMP_BIT - 32), /* 194 -- 5, 1f */ + BMP_C(0xfc000000) << (BMP_BIT - 32), /* 195 -- 6, 3f */ + BMP_C(0xfc891918) << (BMP_BIT - 32), /* 196 -- 32,fc891918 */ + BMP_C(0xfd000000) << (BMP_BIT - 32), /* 197 -- 8, fd */ + BMP_C(0xfe000000) << (BMP_BIT - 32), /* 198 -- 7, 7f */ + BMP_C(0xfedcba00) << (BMP_BIT - 32), /* 199 -- 24, fedcba */ + BMP_C(0xfee80000) << (BMP_BIT - 32), /* 200 -- 16, fee8 */ + BMP_C(0xff000000) << (BMP_BIT - 32), /* 201 -- 8, ff */ + BMP_C(0xffc00000) << (BMP_BIT - 32), /* 202 -- 10, 3ff */ + BMP_C(0xfff00000) << (BMP_BIT - 32), /* 203 -- 12, fff */ + BMP_C(0xfffc0000) << (BMP_BIT - 32), /* 204 -- 14, 3fff */ + BMP_C(0xffff0000) << (BMP_BIT - 32), /* 205 -- 16, ffff */ + BMP_C(0xffffff00) << (BMP_BIT - 32), /* 206 -- 24, ffffff */ + BMP_C(0xfffffffc) << (BMP_BIT - 32), /* 207 -- 30,3fffffff */ + BMP_C(0xfffffffe) << (BMP_BIT - 32), /* 208 -- 31,7fffffff */ + BMP_C(0xffffffff) << (BMP_BIT - 32), /* 209 -- 32,ffffffff */ }; static const struct malias aliases[]; diff --git a/client/deps/vec/vec/private/gcc.h b/client/deps/vec/vec/private/gcc.h index 4736a47e9..ef48229c3 100644 --- a/client/deps/vec/vec/private/gcc.h +++ b/client/deps/vec/vec/private/gcc.h @@ -2,9 +2,8 @@ #ifndef VEC_FN_ADD #define VEC_FN_ADD static inline union vec -vec_add (const union vec a, const union vec b) -{ - return (union vec) { .gcc.f = a.gcc.f + b.gcc.f }; + vec_add(const union vec a, const union vec b) { + return (union vec) { .gcc.f = a.gcc.f + b.gcc.f }; } #endif @@ -12,9 +11,8 @@ vec_add (const union vec a, const union vec b) #ifndef VEC_FN_IADD #define VEC_FN_IADD static inline union vec -vec_iadd (const union vec a, const union vec b) -{ - return (union vec) { .gcc.i = a.gcc.i + b.gcc.i }; + vec_iadd(const union vec a, const union vec b) { + return (union vec) { .gcc.i = a.gcc.i + b.gcc.i }; } #endif @@ -22,9 +20,8 @@ vec_iadd (const union vec a, const union vec b) #ifndef VEC_FN_UADD #define VEC_FN_UADD static inline union vec -vec_uadd (const union vec a, const union vec b) -{ - return (union vec) { .gcc.u = a.gcc.u + b.gcc.u }; + vec_uadd(const union vec a, const union vec b) { + return (union vec) { .gcc.u = a.gcc.u + b.gcc.u }; } #endif @@ -32,9 +29,8 @@ vec_uadd (const union vec a, const union vec b) #ifndef VEC_FN_SUB #define VEC_FN_SUB static inline union vec -vec_sub (const union vec a, const union vec b) -{ - return (union vec) { .gcc.f = a.gcc.f - b.gcc.f }; + vec_sub(const union vec a, const union vec b) { + return (union vec) { .gcc.f = a.gcc.f - b.gcc.f }; } #endif @@ -42,9 +38,8 @@ vec_sub (const union vec a, const union vec b) #ifndef VEC_FN_ISUB #define VEC_FN_ISUB static inline union vec -vec_isub (const union vec a, const union vec b) -{ - return (union vec) { .gcc.i = a.gcc.i - b.gcc.i }; + vec_isub(const union vec a, const union vec b) { + return (union vec) { .gcc.i = a.gcc.i - b.gcc.i }; } #endif @@ -52,9 +47,8 @@ vec_isub (const union vec a, const union vec b) #ifndef VEC_FN_USUB #define VEC_FN_USUB static inline union vec -vec_usub (const union vec a, const union vec b) -{ - return (union vec) { .gcc.u = a.gcc.u - b.gcc.u }; + vec_usub(const union vec a, const union vec b) { + return (union vec) { .gcc.u = a.gcc.u - b.gcc.u }; } #endif @@ -62,9 +56,8 @@ vec_usub (const union vec a, const union vec b) #ifndef VEC_FN_MUL #define VEC_FN_MUL static inline union vec -vec_mul (const union vec a, const union vec b) -{ - return (union vec) { .gcc.f = a.gcc.f * b.gcc.f }; + vec_mul(const union vec a, const union vec b) { + return (union vec) { .gcc.f = a.gcc.f * b.gcc.f }; } #endif @@ -72,9 +65,8 @@ vec_mul (const union vec a, const union vec b) #ifndef VEC_FN_DIV #define VEC_FN_DIV static inline union vec -vec_div (const union vec a, const union vec b) -{ - return (union vec) { .gcc.f = a.gcc.f / b.gcc.f }; + vec_div(const union vec a, const union vec b) { + return (union vec) { .gcc.f = a.gcc.f / b.gcc.f }; } #endif @@ -82,9 +74,8 @@ vec_div (const union vec a, const union vec b) #ifndef VEC_FN_AND #define VEC_FN_AND static inline union vec -vec_and (const union vec a, const union vec b) -{ - return (union vec) { .gcc.u = a.gcc.u & b.gcc.u }; + vec_and(const union vec a, const union vec b) { + return (union vec) { .gcc.u = a.gcc.u & b.gcc.u }; } #endif @@ -92,9 +83,8 @@ vec_and (const union vec a, const union vec b) #ifndef VEC_FN_OR #define VEC_FN_OR static inline union vec -vec_or (const union vec a, const union vec b) -{ - return (union vec) { .gcc.u = a.gcc.u | b.gcc.u }; + vec_or(const union vec a, const union vec b) { + return (union vec) { .gcc.u = a.gcc.u | b.gcc.u }; } #endif @@ -102,9 +92,8 @@ vec_or (const union vec a, const union vec b) #ifndef VEC_FN_XOR #define VEC_FN_XOR static inline union vec -vec_xor (const union vec a, const union vec b) -{ - return (union vec) { .gcc.u = a.gcc.u ^ b.gcc.u }; + vec_xor(const union vec a, const union vec b) { + return (union vec) { .gcc.u = a.gcc.u ^ b.gcc.u }; } #endif @@ -112,32 +101,30 @@ vec_xor (const union vec a, const union vec b) #ifndef VEC_FN_NOT #define VEC_FN_NOT static inline union vec -vec_not (const union vec v) -{ - return (union vec) { .gcc.u = ~v.gcc.u }; + vec_not(const union vec v) { + return (union vec) { .gcc.u = ~v.gcc.u }; } #endif // GCC added support for vector comparisons in version 4.8: #ifdef __GNUC__ - #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) - #define VEC_GCC_COMPARE - #endif +#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) +#define VEC_GCC_COMPARE +#endif #else - // Assume we're using clang - it's supported vector comparisons since at - // least version 3.0, possibly earlier: - #define VEC_GCC_COMPARE +// Assume we're using clang - it's supported vector comparisons since at +// least version 3.0, possibly earlier: +#define VEC_GCC_COMPARE #endif // Return float version of a == b: #ifdef VEC_GCC_COMPARE -#ifndef VEC_FN_EQ +#ifndef VEC_FN_EQ #define VEC_FN_EQ static inline union vec -vec_eq (const union vec a, const union vec b) -{ - return (union vec) { .gcc.i = a.gcc.f == b.gcc.f }; + vec_eq(const union vec a, const union vec b) { + return (union vec) { .gcc.i = a.gcc.f == b.gcc.f }; } #endif #endif @@ -147,9 +134,8 @@ vec_eq (const union vec a, const union vec b) #ifndef VEC_FN_IEQ #define VEC_FN_IEQ static inline union vec -vec_ieq (const union vec a, const union vec b) -{ - return (union vec) { .gcc.i = a.gcc.i == b.gcc.i }; + vec_ieq(const union vec a, const union vec b) { + return (union vec) { .gcc.i = a.gcc.i == b.gcc.i }; } #endif #endif @@ -159,9 +145,8 @@ vec_ieq (const union vec a, const union vec b) #ifndef VEC_FN_UEQ #define VEC_FN_UEQ static inline union vec -vec_ueq (const union vec a, const union vec b) -{ - return (union vec) { .gcc.i = a.gcc.u == b.gcc.u }; + vec_ueq(const union vec a, const union vec b) { + return (union vec) { .gcc.i = a.gcc.u == b.gcc.u }; } #endif #endif @@ -171,9 +156,8 @@ vec_ueq (const union vec a, const union vec b) #ifndef VEC_FN_LT #define VEC_FN_LT static inline union vec -vec_lt (const union vec a, const union vec b) -{ - return (union vec) { .gcc.i = a.gcc.f < b.gcc.f }; + vec_lt(const union vec a, const union vec b) { + return (union vec) { .gcc.i = a.gcc.f < b.gcc.f }; } #endif #endif @@ -183,9 +167,8 @@ vec_lt (const union vec a, const union vec b) #ifndef VEC_FN_ILT #define VEC_FN_ILT static inline union vec -vec_ilt (const union vec a, const union vec b) -{ - return (union vec) { .gcc.i = a.gcc.i < b.gcc.i }; + vec_ilt(const union vec a, const union vec b) { + return (union vec) { .gcc.i = a.gcc.i < b.gcc.i }; } #endif #endif @@ -195,9 +178,8 @@ vec_ilt (const union vec a, const union vec b) #ifndef VEC_FN_ULT #define VEC_FN_ULT static inline union vec -vec_ult (const union vec a, const union vec b) -{ - return (union vec) { .gcc.i = a.gcc.u < b.gcc.u }; + vec_ult(const union vec a, const union vec b) { + return (union vec) { .gcc.i = a.gcc.u < b.gcc.u }; } #endif #endif @@ -207,9 +189,8 @@ vec_ult (const union vec a, const union vec b) #ifndef VEC_FN_LE #define VEC_FN_LE static inline union vec -vec_le (const union vec a, const union vec b) -{ - return (union vec) { .gcc.i = a.gcc.f <= b.gcc.f }; + vec_le(const union vec a, const union vec b) { + return (union vec) { .gcc.i = a.gcc.f <= b.gcc.f }; } #endif #endif @@ -219,9 +200,8 @@ vec_le (const union vec a, const union vec b) #ifndef VEC_FN_ILE #define VEC_FN_ILE static inline union vec -vec_ile (const union vec a, const union vec b) -{ - return (union vec) { .gcc.i = a.gcc.i <= b.gcc.i }; + vec_ile(const union vec a, const union vec b) { + return (union vec) { .gcc.i = a.gcc.i <= b.gcc.i }; } #endif #endif @@ -231,9 +211,8 @@ vec_ile (const union vec a, const union vec b) #ifndef VEC_FN_ULE #define VEC_FN_ULE static inline union vec -vec_ule (const union vec a, const union vec b) -{ - return (union vec) { .gcc.i = a.gcc.u <= b.gcc.u }; + vec_ule(const union vec a, const union vec b) { + return (union vec) { .gcc.i = a.gcc.u <= b.gcc.u }; } #endif #endif @@ -243,9 +222,8 @@ vec_ule (const union vec a, const union vec b) #ifndef VEC_FN_GT #define VEC_FN_GT static inline union vec -vec_gt (const union vec a, const union vec b) -{ - return (union vec) { .gcc.i = a.gcc.f > b.gcc.f }; + vec_gt(const union vec a, const union vec b) { + return (union vec) { .gcc.i = a.gcc.f > b.gcc.f }; } #endif #endif @@ -255,9 +233,8 @@ vec_gt (const union vec a, const union vec b) #ifndef VEC_FN_IGT #define VEC_FN_IGT static inline union vec -vec_igt (const union vec a, const union vec b) -{ - return (union vec) { .gcc.i = a.gcc.i > b.gcc.i }; + vec_igt(const union vec a, const union vec b) { + return (union vec) { .gcc.i = a.gcc.i > b.gcc.i }; } #endif #endif @@ -267,9 +244,8 @@ vec_igt (const union vec a, const union vec b) #ifndef VEC_FN_UGT #define VEC_FN_UGT static inline union vec -vec_ugt (const union vec a, const union vec b) -{ - return (union vec) { .gcc.i = a.gcc.u > b.gcc.u }; + vec_ugt(const union vec a, const union vec b) { + return (union vec) { .gcc.i = a.gcc.u > b.gcc.u }; } #endif #endif @@ -279,9 +255,8 @@ vec_ugt (const union vec a, const union vec b) #ifndef VEC_FN_GE #define VEC_FN_GE static inline union vec -vec_ge (const union vec a, const union vec b) -{ - return (union vec) { .gcc.i = a.gcc.f >= b.gcc.f }; + vec_ge(const union vec a, const union vec b) { + return (union vec) { .gcc.i = a.gcc.f >= b.gcc.f }; } #endif #endif @@ -291,9 +266,8 @@ vec_ge (const union vec a, const union vec b) #ifndef VEC_FN_IGE #define VEC_FN_IGE static inline union vec -vec_ige (const union vec a, const union vec b) -{ - return (union vec) { .gcc.i = a.gcc.i >= b.gcc.i }; + vec_ige(const union vec a, const union vec b) { + return (union vec) { .gcc.i = a.gcc.i >= b.gcc.i }; } #endif #endif @@ -303,9 +277,8 @@ vec_ige (const union vec a, const union vec b) #ifndef VEC_FN_UGE #define VEC_FN_UGE static inline union vec -vec_uge (const union vec a, const union vec b) -{ - return (union vec) { .gcc.i = a.gcc.u >= b.gcc.u }; + vec_uge(const union vec a, const union vec b) { + return (union vec) { .gcc.i = a.gcc.u >= b.gcc.u }; } #endif #endif diff --git a/client/deps/vec/vec/private/generic.h b/client/deps/vec/vec/private/generic.h index ec2e8bb21..a4cbc41a1 100644 --- a/client/deps/vec/vec/private/generic.h +++ b/client/deps/vec/vec/private/generic.h @@ -2,9 +2,8 @@ #ifndef VEC_FN_ #define VEC_FN_ static inline union vec -vec (const float x, const float y, const float z, const float w) -{ - return (union vec) { .x = x, .y = y, .z = z, .w = w }; + vec(const float x, const float y, const float z, const float w) { + return (union vec) { .x = x, .y = y, .z = z, .w = w }; } #endif @@ -12,9 +11,8 @@ vec (const float x, const float y, const float z, const float w) #ifndef VEC_FN_I #define VEC_FN_I static inline union vec -vec_i (const int32_t x, const int32_t y, const int32_t z, const int32_t w) -{ - return (union vec) { .xi = x, .yi = y, .zi = z, .wi = w }; + vec_i(const int32_t x, const int32_t y, const int32_t z, const int32_t w) { + return (union vec) { .xi = x, .yi = y, .zi = z, .wi = w }; } #endif @@ -22,9 +20,8 @@ vec_i (const int32_t x, const int32_t y, const int32_t z, const int32_t w) #ifndef VEC_FN_U #define VEC_FN_U static inline union vec -vec_u (const uint32_t x, const uint32_t y, const uint32_t z, const uint32_t w) -{ - return (union vec) { .xu = x, .yu = y, .zu = z, .wu = w }; + vec_u(const uint32_t x, const uint32_t y, const uint32_t z, const uint32_t w) { + return (union vec) { .xu = x, .yu = y, .zu = z, .wu = w }; } #endif @@ -32,9 +29,8 @@ vec_u (const uint32_t x, const uint32_t y, const uint32_t z, const uint32_t w) #ifndef VEC_FN_1 #define VEC_FN_1 static inline union vec -vec_1 (const float val) -{ - return vec(val, val, val, val); + vec_1(const float val) { + return vec(val, val, val, val); } #endif @@ -42,9 +38,8 @@ vec_1 (const float val) #ifndef VEC_FN_I1 #define VEC_FN_I1 static inline union vec -vec_i1 (const int32_t val) -{ - return vec_i(val, val, val, val); + vec_i1(const int32_t val) { + return vec_i(val, val, val, val); } #endif @@ -52,9 +47,8 @@ vec_i1 (const int32_t val) #ifndef VEC_FN_U1 #define VEC_FN_U1 static inline union vec -vec_u1 (const uint32_t val) -{ - return vec_u(val, val, val, val); + vec_u1(const uint32_t val) { + return vec_u(val, val, val, val); } #endif @@ -62,9 +56,8 @@ vec_u1 (const uint32_t val) #ifndef VEC_FN_ZERO #define VEC_FN_ZERO static inline union vec -vec_zero (void) -{ - return vec_1(0.0f); + vec_zero(void) { + return vec_1(0.0f); } #endif @@ -72,9 +65,8 @@ vec_zero (void) #ifndef VEC_FN_IZERO #define VEC_FN_IZERO static inline union vec -vec_izero (void) -{ - return vec_i1(0); + vec_izero(void) { + return vec_i1(0); } #endif @@ -82,9 +74,8 @@ vec_izero (void) #ifndef VEC_FN_UZERO #define VEC_FN_UZERO static inline union vec -vec_uzero (void) -{ - return vec_u1(0U); + vec_uzero(void) { + return vec_u1(0U); } #endif @@ -92,9 +83,8 @@ vec_uzero (void) #ifndef VEC_FN_TO_INT #define VEC_FN_TO_INT static inline union vec -vec_to_int (const union vec v) -{ - return (union vec) { .xi = v.x, .yi = v.y, .zi = v.z, .wi = v.w }; + vec_to_int(const union vec v) { + return (union vec) { .xi = v.x, .yi = v.y, .zi = v.z, .wi = v.w }; } #endif @@ -102,9 +92,8 @@ vec_to_int (const union vec v) #ifndef VEC_FN_TO_FLOAT #define VEC_FN_TO_FLOAT static inline union vec -vec_to_float (const union vec v) -{ - return (union vec) { .x = v.xi, .y = v.yi, .z = v.zi, .w = v.wi }; + vec_to_float(const union vec v) { + return (union vec) { .x = v.xi, .y = v.yi, .z = v.zi, .w = v.wi }; } #endif @@ -112,14 +101,13 @@ vec_to_float (const union vec v) #ifndef VEC_FN_ADD #define VEC_FN_ADD static inline union vec -vec_add (const union vec a, const union vec b) -{ - return (union vec) { - .x = a.x + b.x, - .y = a.y + b.y, - .z = a.z + b.z, - .w = a.w + b.w, - }; + vec_add(const union vec a, const union vec b) { + return (union vec) { + .x = a.x + b.x, + .y = a.y + b.y, + .z = a.z + b.z, + .w = a.w + b.w, + }; } #endif @@ -127,14 +115,13 @@ vec_add (const union vec a, const union vec b) #ifndef VEC_FN_IADD #define VEC_FN_IADD static inline union vec -vec_iadd (const union vec a, const union vec b) -{ - return (union vec) { - .xi = a.xi + b.xi, - .yi = a.yi + b.yi, - .zi = a.zi + b.zi, - .wi = a.wi + b.wi, - }; + vec_iadd(const union vec a, const union vec b) { + return (union vec) { + .xi = a.xi + b.xi, + .yi = a.yi + b.yi, + .zi = a.zi + b.zi, + .wi = a.wi + b.wi, + }; } #endif @@ -142,14 +129,13 @@ vec_iadd (const union vec a, const union vec b) #ifndef VEC_FN_UADD #define VEC_FN_UADD static inline union vec -vec_uadd (const union vec a, const union vec b) -{ - return (union vec) { - .xu = a.xu + b.xu, - .yu = a.yu + b.yu, - .zu = a.zu + b.zu, - .wu = a.wu + b.wu, - }; + vec_uadd(const union vec a, const union vec b) { + return (union vec) { + .xu = a.xu + b.xu, + .yu = a.yu + b.yu, + .zu = a.zu + b.zu, + .wu = a.wu + b.wu, + }; } #endif @@ -157,14 +143,13 @@ vec_uadd (const union vec a, const union vec b) #ifndef VEC_FN_SUB #define VEC_FN_SUB static inline union vec -vec_sub (const union vec a, const union vec b) -{ - return (union vec) { - .x = a.x - b.x, - .y = a.y - b.y, - .z = a.z - b.z, - .w = a.w - b.w, - }; + vec_sub(const union vec a, const union vec b) { + return (union vec) { + .x = a.x - b.x, + .y = a.y - b.y, + .z = a.z - b.z, + .w = a.w - b.w, + }; } #endif @@ -172,14 +157,13 @@ vec_sub (const union vec a, const union vec b) #ifndef VEC_FN_ISUB #define VEC_FN_ISUB static inline union vec -vec_isub (const union vec a, const union vec b) -{ - return (union vec) { - .xi = a.xi - b.xi, - .yi = a.yi - b.yi, - .zi = a.zi - b.zi, - .wi = a.wi - b.wi, - }; + vec_isub(const union vec a, const union vec b) { + return (union vec) { + .xi = a.xi - b.xi, + .yi = a.yi - b.yi, + .zi = a.zi - b.zi, + .wi = a.wi - b.wi, + }; } #endif @@ -187,14 +171,13 @@ vec_isub (const union vec a, const union vec b) #ifndef VEC_FN_USUB #define VEC_FN_USUB static inline union vec -vec_usub (const union vec a, const union vec b) -{ - return (union vec) { - .xu = a.xu - b.xu, - .yu = a.yu - b.yu, - .zu = a.zu - b.zu, - .wu = a.wu - b.wu, - }; + vec_usub(const union vec a, const union vec b) { + return (union vec) { + .xu = a.xu - b.xu, + .yu = a.yu - b.yu, + .zu = a.zu - b.zu, + .wu = a.wu - b.wu, + }; } #endif @@ -202,14 +185,13 @@ vec_usub (const union vec a, const union vec b) #ifndef VEC_FN_MUL #define VEC_FN_MUL static inline union vec -vec_mul (const union vec a, const union vec b) -{ - return (union vec) { - .x = a.x * b.x, - .y = a.y * b.y, - .z = a.z * b.z, - .w = a.w * b.w, - }; + vec_mul(const union vec a, const union vec b) { + return (union vec) { + .x = a.x * b.x, + .y = a.y * b.y, + .z = a.z * b.z, + .w = a.w * b.w, + }; } #endif @@ -217,14 +199,13 @@ vec_mul (const union vec a, const union vec b) #ifndef VEC_FN_DIV #define VEC_FN_DIV static inline union vec -vec_div (const union vec a, const union vec b) -{ - return (union vec) { - .x = a.x / b.x, - .y = a.y / b.y, - .z = a.z / b.z, - .w = a.w / b.w, - }; + vec_div(const union vec a, const union vec b) { + return (union vec) { + .x = a.x / b.x, + .y = a.y / b.y, + .z = a.z / b.z, + .w = a.w / b.w, + }; } #endif @@ -232,14 +213,13 @@ vec_div (const union vec a, const union vec b) #ifndef VEC_FN_AND #define VEC_FN_AND static inline union vec -vec_and (const union vec a, const union vec b) -{ - return (union vec) { - .xu = a.xu & b.xu, - .yu = a.yu & b.yu, - .zu = a.zu & b.zu, - .wu = a.wu & b.wu, - }; + vec_and(const union vec a, const union vec b) { + return (union vec) { + .xu = a.xu & b.xu, + .yu = a.yu & b.yu, + .zu = a.zu & b.zu, + .wu = a.wu & b.wu, + }; } #endif @@ -247,14 +227,13 @@ vec_and (const union vec a, const union vec b) #ifndef VEC_FN_OR #define VEC_FN_OR static inline union vec -vec_or (const union vec a, const union vec b) -{ - return (union vec) { - .xu = a.xu | b.xu, - .yu = a.yu | b.yu, - .zu = a.zu | b.zu, - .wu = a.wu | b.wu, - }; + vec_or(const union vec a, const union vec b) { + return (union vec) { + .xu = a.xu | b.xu, + .yu = a.yu | b.yu, + .zu = a.zu | b.zu, + .wu = a.wu | b.wu, + }; } #endif @@ -262,14 +241,13 @@ vec_or (const union vec a, const union vec b) #ifndef VEC_FN_XOR #define VEC_FN_XOR static inline union vec -vec_xor (const union vec a, const union vec b) -{ - return (union vec) { - .xu = a.xu ^ b.xu, - .yu = a.yu ^ b.yu, - .zu = a.zu ^ b.zu, - .wu = a.wu ^ b.wu, - }; + vec_xor(const union vec a, const union vec b) { + return (union vec) { + .xu = a.xu ^ b.xu, + .yu = a.yu ^ b.yu, + .zu = a.zu ^ b.zu, + .wu = a.wu ^ b.wu, + }; } #endif @@ -277,14 +255,13 @@ vec_xor (const union vec a, const union vec b) #ifndef VEC_FN_NOT #define VEC_FN_NOT static inline union vec -vec_not (const union vec v) -{ - return (union vec) { - .xu = ~v.xu, - .yu = ~v.yu, - .zu = ~v.zu, - .wu = ~v.wu, - }; + vec_not(const union vec v) { + return (union vec) { + .xu = ~v.xu, + .yu = ~v.yu, + .zu = ~v.zu, + .wu = ~v.wu, + }; } #endif @@ -292,14 +269,13 @@ vec_not (const union vec v) #ifndef VEC_FN_EQ #define VEC_FN_EQ static inline union vec -vec_eq (const union vec a, const union vec b) -{ - return (union vec) { - .xi = a.x == b.x ? -1 : 0, - .yi = a.y == b.y ? -1 : 0, - .zi = a.z == b.z ? -1 : 0, - .wi = a.w == b.w ? -1 : 0, - }; + vec_eq(const union vec a, const union vec b) { + return (union vec) { + .xi = a.x == b.x ? -1 : 0, + .yi = a.y == b.y ? -1 : 0, + .zi = a.z == b.z ? -1 : 0, + .wi = a.w == b.w ? -1 : 0, + }; } #endif @@ -307,14 +283,13 @@ vec_eq (const union vec a, const union vec b) #ifndef VEC_FN_IEQ #define VEC_FN_IEQ static inline union vec -vec_ieq (const union vec a, const union vec b) -{ - return (union vec) { - .xi = a.xi == b.xi ? -1 : 0, - .yi = a.yi == b.yi ? -1 : 0, - .zi = a.zi == b.zi ? -1 : 0, - .wi = a.wi == b.wi ? -1 : 0, - }; + vec_ieq(const union vec a, const union vec b) { + return (union vec) { + .xi = a.xi == b.xi ? -1 : 0, + .yi = a.yi == b.yi ? -1 : 0, + .zi = a.zi == b.zi ? -1 : 0, + .wi = a.wi == b.wi ? -1 : 0, + }; } #endif @@ -322,14 +297,13 @@ vec_ieq (const union vec a, const union vec b) #ifndef VEC_FN_UEQ #define VEC_FN_UEQ static inline union vec -vec_ueq (const union vec a, const union vec b) -{ - return (union vec) { - .xi = a.xu == b.xu ? -1 : 0, - .yi = a.yu == b.yu ? -1 : 0, - .zi = a.zu == b.zu ? -1 : 0, - .wi = a.wu == b.wu ? -1 : 0, - }; + vec_ueq(const union vec a, const union vec b) { + return (union vec) { + .xi = a.xu == b.xu ? -1 : 0, + .yi = a.yu == b.yu ? -1 : 0, + .zi = a.zu == b.zu ? -1 : 0, + .wi = a.wu == b.wu ? -1 : 0, + }; } #endif @@ -337,14 +311,13 @@ vec_ueq (const union vec a, const union vec b) #ifndef VEC_FN_LT #define VEC_FN_LT static inline union vec -vec_lt (const union vec a, const union vec b) -{ - return (union vec) { - .xi = a.x < b.x ? -1 : 0, - .yi = a.y < b.y ? -1 : 0, - .zi = a.z < b.z ? -1 : 0, - .wi = a.w < b.w ? -1 : 0, - }; + vec_lt(const union vec a, const union vec b) { + return (union vec) { + .xi = a.x < b.x ? -1 : 0, + .yi = a.y < b.y ? -1 : 0, + .zi = a.z < b.z ? -1 : 0, + .wi = a.w < b.w ? -1 : 0, + }; } #endif @@ -352,14 +325,13 @@ vec_lt (const union vec a, const union vec b) #ifndef VEC_FN_ILT #define VEC_FN_ILT static inline union vec -vec_ilt (const union vec a, const union vec b) -{ - return (union vec) { - .xi = a.xi < b.xi ? -1 : 0, - .yi = a.yi < b.yi ? -1 : 0, - .zi = a.zi < b.zi ? -1 : 0, - .wi = a.wi < b.wi ? -1 : 0, - }; + vec_ilt(const union vec a, const union vec b) { + return (union vec) { + .xi = a.xi < b.xi ? -1 : 0, + .yi = a.yi < b.yi ? -1 : 0, + .zi = a.zi < b.zi ? -1 : 0, + .wi = a.wi < b.wi ? -1 : 0, + }; } #endif @@ -367,14 +339,13 @@ vec_ilt (const union vec a, const union vec b) #ifndef VEC_FN_ULT #define VEC_FN_ULT static inline union vec -vec_ult (const union vec a, const union vec b) -{ - return (union vec) { - .xi = a.xu < b.xu ? -1 : 0, - .yi = a.yu < b.yu ? -1 : 0, - .zi = a.zu < b.zu ? -1 : 0, - .wi = a.wu < b.wu ? -1 : 0, - }; + vec_ult(const union vec a, const union vec b) { + return (union vec) { + .xi = a.xu < b.xu ? -1 : 0, + .yi = a.yu < b.yu ? -1 : 0, + .zi = a.zu < b.zu ? -1 : 0, + .wi = a.wu < b.wu ? -1 : 0, + }; } #endif @@ -382,14 +353,13 @@ vec_ult (const union vec a, const union vec b) #ifndef VEC_FN_LE #define VEC_FN_LE static inline union vec -vec_le (const union vec a, const union vec b) -{ - return (union vec) { - .xi = a.x <= b.x ? -1 : 0, - .yi = a.y <= b.y ? -1 : 0, - .zi = a.z <= b.z ? -1 : 0, - .wi = a.w <= b.w ? -1 : 0, - }; + vec_le(const union vec a, const union vec b) { + return (union vec) { + .xi = a.x <= b.x ? -1 : 0, + .yi = a.y <= b.y ? -1 : 0, + .zi = a.z <= b.z ? -1 : 0, + .wi = a.w <= b.w ? -1 : 0, + }; } #endif @@ -397,14 +367,13 @@ vec_le (const union vec a, const union vec b) #ifndef VEC_FN_ILE #define VEC_FN_ILE static inline union vec -vec_ile (const union vec a, const union vec b) -{ - return (union vec) { - .xi = a.xi <= b.xi ? -1 : 0, - .yi = a.yi <= b.yi ? -1 : 0, - .zi = a.zi <= b.zi ? -1 : 0, - .wi = a.wi <= b.wi ? -1 : 0, - }; + vec_ile(const union vec a, const union vec b) { + return (union vec) { + .xi = a.xi <= b.xi ? -1 : 0, + .yi = a.yi <= b.yi ? -1 : 0, + .zi = a.zi <= b.zi ? -1 : 0, + .wi = a.wi <= b.wi ? -1 : 0, + }; } #endif @@ -412,14 +381,13 @@ vec_ile (const union vec a, const union vec b) #ifndef VEC_FN_ULE #define VEC_FN_ULE static inline union vec -vec_ule (const union vec a, const union vec b) -{ - return (union vec) { - .xi = a.xu <= b.xu ? -1 : 0, - .yi = a.yu <= b.yu ? -1 : 0, - .zi = a.zu <= b.zu ? -1 : 0, - .wi = a.wu <= b.wu ? -1 : 0, - }; + vec_ule(const union vec a, const union vec b) { + return (union vec) { + .xi = a.xu <= b.xu ? -1 : 0, + .yi = a.yu <= b.yu ? -1 : 0, + .zi = a.zu <= b.zu ? -1 : 0, + .wi = a.wu <= b.wu ? -1 : 0, + }; } #endif @@ -427,14 +395,13 @@ vec_ule (const union vec a, const union vec b) #ifndef VEC_FN_GT #define VEC_FN_GT static inline union vec -vec_gt (const union vec a, const union vec b) -{ - return (union vec) { - .xi = a.x > b.x ? -1 : 0, - .yi = a.y > b.y ? -1 : 0, - .zi = a.z > b.z ? -1 : 0, - .wi = a.w > b.w ? -1 : 0, - }; + vec_gt(const union vec a, const union vec b) { + return (union vec) { + .xi = a.x > b.x ? -1 : 0, + .yi = a.y > b.y ? -1 : 0, + .zi = a.z > b.z ? -1 : 0, + .wi = a.w > b.w ? -1 : 0, + }; } #endif @@ -442,14 +409,13 @@ vec_gt (const union vec a, const union vec b) #ifndef VEC_FN_IGT #define VEC_FN_IGT static inline union vec -vec_igt (const union vec a, const union vec b) -{ - return (union vec) { - .xi = a.xi > b.xi ? -1 : 0, - .yi = a.yi > b.yi ? -1 : 0, - .zi = a.zi > b.zi ? -1 : 0, - .wi = a.wi > b.wi ? -1 : 0, - }; + vec_igt(const union vec a, const union vec b) { + return (union vec) { + .xi = a.xi > b.xi ? -1 : 0, + .yi = a.yi > b.yi ? -1 : 0, + .zi = a.zi > b.zi ? -1 : 0, + .wi = a.wi > b.wi ? -1 : 0, + }; } #endif @@ -457,14 +423,13 @@ vec_igt (const union vec a, const union vec b) #ifndef VEC_FN_UGT #define VEC_FN_UGT static inline union vec -vec_ugt (const union vec a, const union vec b) -{ - return (union vec) { - .xi = a.xu > b.xu ? -1 : 0, - .yi = a.yu > b.yu ? -1 : 0, - .zi = a.zu > b.zu ? -1 : 0, - .wi = a.wu > b.wu ? -1 : 0, - }; + vec_ugt(const union vec a, const union vec b) { + return (union vec) { + .xi = a.xu > b.xu ? -1 : 0, + .yi = a.yu > b.yu ? -1 : 0, + .zi = a.zu > b.zu ? -1 : 0, + .wi = a.wu > b.wu ? -1 : 0, + }; } #endif @@ -472,14 +437,13 @@ vec_ugt (const union vec a, const union vec b) #ifndef VEC_FN_GE #define VEC_FN_GE static inline union vec -vec_ge (const union vec a, const union vec b) -{ - return (union vec) { - .xi = a.x >= b.x ? -1 : 0, - .yi = a.y >= b.y ? -1 : 0, - .zi = a.z >= b.z ? -1 : 0, - .wi = a.w >= b.w ? -1 : 0, - }; + vec_ge(const union vec a, const union vec b) { + return (union vec) { + .xi = a.x >= b.x ? -1 : 0, + .yi = a.y >= b.y ? -1 : 0, + .zi = a.z >= b.z ? -1 : 0, + .wi = a.w >= b.w ? -1 : 0, + }; } #endif @@ -487,14 +451,13 @@ vec_ge (const union vec a, const union vec b) #ifndef VEC_FN_IGE #define VEC_FN_IGE static inline union vec -vec_ige (const union vec a, const union vec b) -{ - return (union vec) { - .xi = a.xi >= b.xi ? -1 : 0, - .yi = a.yi >= b.yi ? -1 : 0, - .zi = a.zi >= b.zi ? -1 : 0, - .wi = a.wi >= b.wi ? -1 : 0, - }; + vec_ige(const union vec a, const union vec b) { + return (union vec) { + .xi = a.xi >= b.xi ? -1 : 0, + .yi = a.yi >= b.yi ? -1 : 0, + .zi = a.zi >= b.zi ? -1 : 0, + .wi = a.wi >= b.wi ? -1 : 0, + }; } #endif @@ -502,14 +465,13 @@ vec_ige (const union vec a, const union vec b) #ifndef VEC_FN_UGE #define VEC_FN_UGE static inline union vec -vec_uge (const union vec a, const union vec b) -{ - return (union vec) { - .xi = a.xu >= b.xu ? -1 : 0, - .yi = a.yu >= b.yu ? -1 : 0, - .zi = a.zu >= b.zu ? -1 : 0, - .wi = a.wu >= b.wu ? -1 : 0, - }; + vec_uge(const union vec a, const union vec b) { + return (union vec) { + .xi = a.xu >= b.xu ? -1 : 0, + .yi = a.yu >= b.yu ? -1 : 0, + .zi = a.zu >= b.zu ? -1 : 0, + .wi = a.wu >= b.wu ? -1 : 0, + }; } #endif @@ -517,9 +479,8 @@ vec_uge (const union vec a, const union vec b) #ifndef VEC_FN_DOT #define VEC_FN_DOT static inline float -vec_dot (const union vec a, const union vec b) -{ - return a.x * b.x + a.y * b.y + a.z * b.z; +vec_dot(const union vec a, const union vec b) { + return a.x * b.x + a.y * b.y + a.z * b.z; } #endif @@ -527,13 +488,12 @@ vec_dot (const union vec a, const union vec b) #ifndef VEC_FN_CROSS #define VEC_FN_CROSS static inline union vec -vec_cross (const union vec a, const union vec b) -{ - return (union vec) { - .x = a.y * b.z - a.z * b.y, - .y = a.z * b.x - a.x * b.z, - .z = a.x * b.y - a.y * b.x, - .w = 0.0f, - }; + vec_cross(const union vec a, const union vec b) { + return (union vec) { + .x = a.y * b.z - a.z * b.y, + .y = a.z * b.x - a.x * b.z, + .z = a.x * b.y - a.y * b.x, + .w = 0.0f, + }; } #endif diff --git a/client/deps/vec/vec/private/neon_asm.h b/client/deps/vec/vec/private/neon_asm.h index 8dbb02c10..a4414bc42 100644 --- a/client/deps/vec/vec/private/neon_asm.h +++ b/client/deps/vec/vec/private/neon_asm.h @@ -2,34 +2,33 @@ #ifndef VEC_FN_DIV #define VEC_FN_DIV static inline union vec -vec_div (const union vec a, const union vec b) -{ + vec_div(const union vec a, const union vec b) { #ifdef __aarch64__ - float32x4_t ret; + float32x4_t ret; - __asm__ ( - "fdiv %0.4s,%1.4s,%2.4s \n\t" + __asm__( + "fdiv %0.4s,%1.4s,%2.4s \n\t" - : "=&w" (ret) // Outputs: ret=v0 - : "w" (a.neon.f), "w" (b.neon.f) // Inputs: a=v1, b=v2 - ); + : "=&w"(ret) // Outputs: ret=v0 + : "w"(a.neon.f), "w"(b.neon.f) // Inputs: a=v1, b=v2 + ); #else - float32x4_t ret, tmp; + float32x4_t ret, tmp; - __asm__ ( - "vrecpeq.f32 %q0,%q3 \n\t" - "vrecpsq.f32 %q1,%q3,%q0 \n\t" - "vmulq.f32 %q0,%q1,%q0 \n\t" - "vrecpsq.f32 %q1,%q3,%q0 \n\t" - "vmulq.f32 %q0,%q1,%q0 \n\t" - "vmulq.f32 %q0,%q2,%q0 \n\t" + __asm__( + "vrecpeq.f32 %q0,%q3 \n\t" + "vrecpsq.f32 %q1,%q3,%q0 \n\t" + "vmulq.f32 %q0,%q1,%q0 \n\t" + "vrecpsq.f32 %q1,%q3,%q0 \n\t" + "vmulq.f32 %q0,%q1,%q0 \n\t" + "vmulq.f32 %q0,%q2,%q0 \n\t" - : "=&w" (ret), "=&w" (tmp) // Outputs: ret=q0, tmp=q1 - : "w" (a.neon.f), "w" (b.neon.f) // Inputs: a=q2, b=q3 - ); + : "=&w"(ret), "=&w"(tmp) // Outputs: ret=q0, tmp=q1 + : "w"(a.neon.f), "w"(b.neon.f) // Inputs: a=q2, b=q3 + ); #endif - return (union vec) { .neon.f = ret }; + return (union vec) { .neon.f = ret }; } #endif @@ -37,54 +36,53 @@ vec_div (const union vec a, const union vec b) #ifndef VEC_FN_CROSS #define VEC_FN_CROSS static inline union vec -vec_cross (const union vec a, const union vec b) -{ - // Make read/write copies of the inputs: - float32x4_t atmp = a.neon.f, btmp = b.neon.f; + vec_cross(const union vec a, const union vec b) { + // Make read/write copies of the inputs: + float32x4_t atmp = a.neon.f, btmp = b.neon.f; #ifdef __aarch64__ - float32x4_t ret, t1, t2; + float32x4_t ret, t1, t2; - __asm__ ( - "zip1 %0.4s,%3.4s,%4.4s \n\t" // v0 := a0 b0 a1 b1 - "zip2 %1.4s,%3.4s,%4.4s \n\t" // v1 := a2 b2 a3 b3 - "trn1 %2.4s,%3.4s,%4.4s \n\t" // v2 := a0 b0 a2 b2 - "trn2 %3.4s,%3.4s,%4.4s \n\t" // v3 := a1 b1 a3 b3 - "ext %0.16b,%0.16b,%0.16b,#8 \n\t" // v0 := a1 b1 a0 b0 - "ext %2.16b,%2.16b,%2.16b,#8 \n\t" // v2 := a2 b2 a0 b0 - "trn2 %4.4s,%0.4s,%1.4s \n\t" // v4 := b1 b2 b0 b3 = byzxw - "trn1 %0.4s,%0.4s,%1.4s \n\t" // v0 := a1 a2 a0 a3 = ayzxw - "uzp1 %1.4s,%2.4s,%3.4s \n\t" // v1 := a2 a0 a1 a3 = azxyw - "uzp2 %2.4s,%2.4s,%3.4s \n\t" // v2 := b2 b0 b1 b3 = bzxyw + __asm__( + "zip1 %0.4s,%3.4s,%4.4s \n\t" // v0 := a0 b0 a1 b1 + "zip2 %1.4s,%3.4s,%4.4s \n\t" // v1 := a2 b2 a3 b3 + "trn1 %2.4s,%3.4s,%4.4s \n\t" // v2 := a0 b0 a2 b2 + "trn2 %3.4s,%3.4s,%4.4s \n\t" // v3 := a1 b1 a3 b3 + "ext %0.16b,%0.16b,%0.16b,#8 \n\t" // v0 := a1 b1 a0 b0 + "ext %2.16b,%2.16b,%2.16b,#8 \n\t" // v2 := a2 b2 a0 b0 + "trn2 %4.4s,%0.4s,%1.4s \n\t" // v4 := b1 b2 b0 b3 = byzxw + "trn1 %0.4s,%0.4s,%1.4s \n\t" // v0 := a1 a2 a0 a3 = ayzxw + "uzp1 %1.4s,%2.4s,%3.4s \n\t" // v1 := a2 a0 a1 a3 = azxyw + "uzp2 %2.4s,%2.4s,%3.4s \n\t" // v2 := b2 b0 b1 b3 = bzxyw - "fmul %0.4s,%0.4s,%2.4s \n\t" // v0 := ayzxw * bzxyw - "fmls %0.4s,%1.4s,%4.4s \n\t" // v0 := ayzxw * bzxyw - azxyw * byzxw + "fmul %0.4s,%0.4s,%2.4s \n\t" // v0 := ayzxw * bzxyw + "fmls %0.4s,%1.4s,%4.4s \n\t" // v0 := ayzxw * bzxyw - azxyw * byzxw - : "=&w" (ret), "=&w" (t1), "=&w" (t2), // Outputs: ret=v0, t1=v1, t2=v2 - "+w" (atmp), "+w" (btmp) // Outputs (reused inputs): a=v3, b=v4 - ); + : "=&w"(ret), "=&w"(t1), "=&w"(t2), // Outputs: ret=v0, t1=v1, t2=v2 + "+w"(atmp), "+w"(btmp) // Outputs (reused inputs): a=v3, b=v4 + ); #else - float32x4_t ret, tmp; + float32x4_t ret, tmp; - __asm__ ( - "vext.8 %q0,%q2,%q2,#4 \n\t" // q0 := ayzwx - "vext.8 %q1,%q3,%q3,#4 \n\t" // q1 := byzwx - "vrev64.32 %f0,%f0 \n\t" // q0 := ayzxw - "vrev64.32 %f1,%f1 \n\t" // q1 := byzxw + __asm__( + "vext.8 %q0,%q2,%q2,#4 \n\t" // q0 := ayzwx + "vext.8 %q1,%q3,%q3,#4 \n\t" // q1 := byzwx + "vrev64.32 %f0,%f0 \n\t" // q0 := ayzxw + "vrev64.32 %f1,%f1 \n\t" // q1 := byzxw - "vtrn.32 %e2,%f2 \n\t" // q2 := axzyw - "vtrn.32 %e3,%f3 \n\t" // q3 := bxzyw - "vrev64.32 %e2,%e2 \n\t" // q2 := azxyw - "vrev64.32 %e3,%e3 \n\t" // q3 := bzxyw + "vtrn.32 %e2,%f2 \n\t" // q2 := axzyw + "vtrn.32 %e3,%f3 \n\t" // q3 := bxzyw + "vrev64.32 %e2,%e2 \n\t" // q2 := azxyw + "vrev64.32 %e3,%e3 \n\t" // q3 := bzxyw - "vmulq.f32 %q0,%q0,%q3 \n\t" // q0 := ayzxw * bzxyw - "vmlsq.f32 %q0,%q2,%q1 \n\t" // q0 := ayzxw * bzxyw - azxyw * byzxw + "vmulq.f32 %q0,%q0,%q3 \n\t" // q0 := ayzxw * bzxyw + "vmlsq.f32 %q0,%q2,%q1 \n\t" // q0 := ayzxw * bzxyw - azxyw * byzxw - : "=&w" (ret), "=&w" (tmp), // Outputs: ret=q0, tmp=q1 - "+w" (atmp), "+w" (btmp) // Outputs (reused inputs): a=q2, b=q3 - ); + : "=&w"(ret), "=&w"(tmp), // Outputs: ret=q0, tmp=q1 + "+w"(atmp), "+w"(btmp) // Outputs (reused inputs): a=q2, b=q3 + ); #endif - return (union vec) { .neon.f = ret }; + return (union vec) { .neon.f = ret }; } #endif diff --git a/client/deps/vec/vec/private/neon_intrin.h b/client/deps/vec/vec/private/neon_intrin.h index 6b07054a2..607c90042 100644 --- a/client/deps/vec/vec/private/neon_intrin.h +++ b/client/deps/vec/vec/private/neon_intrin.h @@ -2,15 +2,14 @@ #ifndef VEC_FN_ #define VEC_FN_ static inline union vec -vec (const float x, const float y, const float z, const float w) -{ - union { - float i[2]; - uint64_t u; - } lo = { { x, y } } - , hi = { { z, w } }; + vec(const float x, const float y, const float z, const float w) { + union { + float i[2]; + uint64_t u; + } lo = { { x, y } } + , hi = { { z, w } }; - return (union vec) { .neon.f = vcombine_f32(vcreate_f32(lo.u), vcreate_f32(hi.u)) }; + return (union vec) { .neon.f = vcombine_f32(vcreate_f32(lo.u), vcreate_f32(hi.u)) }; } #endif @@ -18,15 +17,14 @@ vec (const float x, const float y, const float z, const float w) #ifndef VEC_FN_I #define VEC_FN_I static inline union vec -vec_i (const int32_t x, const int32_t y, const int32_t z, const int32_t w) -{ - union { - int32_t i[2]; - uint64_t u; - } lo = { { x, y } } - , hi = { { z, w } }; + vec_i(const int32_t x, const int32_t y, const int32_t z, const int32_t w) { + union { + int32_t i[2]; + uint64_t u; + } lo = { { x, y } } + , hi = { { z, w } }; - return (union vec) { .neon.i = vcombine_s32(vcreate_s32(lo.u), vcreate_s32(hi.u)) }; + return (union vec) { .neon.i = vcombine_s32(vcreate_s32(lo.u), vcreate_s32(hi.u)) }; } #endif @@ -34,15 +32,14 @@ vec_i (const int32_t x, const int32_t y, const int32_t z, const int32_t w) #ifndef VEC_FN_U #define VEC_FN_U static inline union vec -vec_u (const uint32_t x, const uint32_t y, const uint32_t z, const uint32_t w) -{ - union { - uint32_t i[2]; - uint64_t u; - } lo = { { x, y } } - , hi = { { z, w } }; + vec_u(const uint32_t x, const uint32_t y, const uint32_t z, const uint32_t w) { + union { + uint32_t i[2]; + uint64_t u; + } lo = { { x, y } } + , hi = { { z, w } }; - return (union vec) { .neon.u = vcombine_u32(vcreate_u32(lo.u), vcreate_u32(hi.u)) }; + return (union vec) { .neon.u = vcombine_u32(vcreate_u32(lo.u), vcreate_u32(hi.u)) }; } #endif @@ -50,9 +47,8 @@ vec_u (const uint32_t x, const uint32_t y, const uint32_t z, const uint32_t w) #ifndef VEC_FN_1 #define VEC_FN_1 static inline union vec -vec_1 (const float val) -{ - return (union vec) { .neon.f = vdupq_n_f32(val) }; + vec_1(const float val) { + return (union vec) { .neon.f = vdupq_n_f32(val) }; } #endif @@ -60,9 +56,8 @@ vec_1 (const float val) #ifndef VEC_FN_I1 #define VEC_FN_I1 static inline union vec -vec_i1 (const int32_t val) -{ - return (union vec) { .neon.i = vdupq_n_s32(val) }; + vec_i1(const int32_t val) { + return (union vec) { .neon.i = vdupq_n_s32(val) }; } #endif @@ -70,9 +65,8 @@ vec_i1 (const int32_t val) #ifndef VEC_FN_U1 #define VEC_FN_U1 static inline union vec -vec_u1 (const uint32_t val) -{ - return (union vec) { .neon.u = vdupq_n_u32(val) }; + vec_u1(const uint32_t val) { + return (union vec) { .neon.u = vdupq_n_u32(val) }; } #endif @@ -80,9 +74,8 @@ vec_u1 (const uint32_t val) #ifndef VEC_FN_ZERO #define VEC_FN_ZERO static inline union vec -vec_zero (void) -{ - return vec_1(0.0f); + vec_zero(void) { + return vec_1(0.0f); } #endif @@ -90,9 +83,8 @@ vec_zero (void) #ifndef VEC_FN_IZERO #define VEC_FN_IZERO static inline union vec -vec_izero (void) -{ - return vec_i1(0); + vec_izero(void) { + return vec_i1(0); } #endif @@ -100,9 +92,8 @@ vec_izero (void) #ifndef VEC_FN_UZERO #define VEC_FN_UZERO static inline union vec -vec_uzero (void) -{ - return vec_u1(0U); + vec_uzero(void) { + return vec_u1(0U); } #endif @@ -110,9 +101,8 @@ vec_uzero (void) #ifndef VEC_FN_TO_INT #define VEC_FN_TO_INT static inline union vec -vec_to_int (const union vec v) -{ - return (union vec) { .neon.i = vcvtq_s32_f32(v.neon.f) }; + vec_to_int(const union vec v) { + return (union vec) { .neon.i = vcvtq_s32_f32(v.neon.f) }; } #endif @@ -120,9 +110,8 @@ vec_to_int (const union vec v) #ifndef VEC_FN_TO_FLOAT #define VEC_FN_TO_FLOAT static inline union vec -vec_to_float (const union vec v) -{ - return (union vec) { .neon.f = vcvtq_f32_s32(v.neon.i) }; + vec_to_float(const union vec v) { + return (union vec) { .neon.f = vcvtq_f32_s32(v.neon.i) }; } #endif @@ -130,9 +119,8 @@ vec_to_float (const union vec v) #ifndef VEC_FN_ADD #define VEC_FN_ADD static inline union vec -vec_add (const union vec a, const union vec b) -{ - return (union vec) { .neon.f = vaddq_f32(a.neon.f, b.neon.f) }; + vec_add(const union vec a, const union vec b) { + return (union vec) { .neon.f = vaddq_f32(a.neon.f, b.neon.f) }; } #endif @@ -140,9 +128,8 @@ vec_add (const union vec a, const union vec b) #ifndef VEC_FN_IADD #define VEC_FN_IADD static inline union vec -vec_iadd (const union vec a, const union vec b) -{ - return (union vec) { .neon.i = vaddq_s32(a.neon.i, b.neon.i) }; + vec_iadd(const union vec a, const union vec b) { + return (union vec) { .neon.i = vaddq_s32(a.neon.i, b.neon.i) }; } #endif @@ -150,9 +137,8 @@ vec_iadd (const union vec a, const union vec b) #ifndef VEC_FN_UADD #define VEC_FN_UADD static inline union vec -vec_uadd (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vaddq_u32(a.neon.u, b.neon.u) }; + vec_uadd(const union vec a, const union vec b) { + return (union vec) { .neon.u = vaddq_u32(a.neon.u, b.neon.u) }; } #endif @@ -160,9 +146,8 @@ vec_uadd (const union vec a, const union vec b) #ifndef VEC_FN_SUB #define VEC_FN_SUB static inline union vec -vec_sub (const union vec a, const union vec b) -{ - return (union vec) { .neon.f = vsubq_f32(a.neon.f, b.neon.f) }; + vec_sub(const union vec a, const union vec b) { + return (union vec) { .neon.f = vsubq_f32(a.neon.f, b.neon.f) }; } #endif @@ -170,9 +155,8 @@ vec_sub (const union vec a, const union vec b) #ifndef VEC_FN_ISUB #define VEC_FN_ISUB static inline union vec -vec_isub (const union vec a, const union vec b) -{ - return (union vec) { .neon.i = vsubq_s32(a.neon.i, b.neon.i) }; + vec_isub(const union vec a, const union vec b) { + return (union vec) { .neon.i = vsubq_s32(a.neon.i, b.neon.i) }; } #endif @@ -180,9 +164,8 @@ vec_isub (const union vec a, const union vec b) #ifndef VEC_FN_USUB #define VEC_FN_USUB static inline union vec -vec_usub (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vsubq_u32(a.neon.u, b.neon.u) }; + vec_usub(const union vec a, const union vec b) { + return (union vec) { .neon.u = vsubq_u32(a.neon.u, b.neon.u) }; } #endif @@ -190,9 +173,8 @@ vec_usub (const union vec a, const union vec b) #ifndef VEC_FN_MUL #define VEC_FN_MUL static inline union vec -vec_mul (const union vec a, const union vec b) -{ - return (union vec) { .neon.f = vmulq_f32(a.neon.f, b.neon.f) }; + vec_mul(const union vec a, const union vec b) { + return (union vec) { .neon.f = vmulq_f32(a.neon.f, b.neon.f) }; } #endif @@ -200,17 +182,16 @@ vec_mul (const union vec a, const union vec b) #ifndef VEC_FN_DIV #define VEC_FN_DIV static inline union vec -vec_div (const union vec a, const union vec b) -{ - // Estimate reciprocal of b: - float32x4_t recp = vrecpeq_f32(b.neon.f); + vec_div(const union vec a, const union vec b) { + // Estimate reciprocal of b: + float32x4_t recp = vrecpeq_f32(b.neon.f); - // Refine the estimate using Newton-Raphson: - recp = vmulq_f32(vrecpsq_f32(b.neon.f, recp), recp); - recp = vmulq_f32(vrecpsq_f32(b.neon.f, recp), recp); + // Refine the estimate using Newton-Raphson: + recp = vmulq_f32(vrecpsq_f32(b.neon.f, recp), recp); + recp = vmulq_f32(vrecpsq_f32(b.neon.f, recp), recp); - // Multiply by the reciprocal to approximate a / b: - return (union vec) { .neon.f = vmulq_f32(a.neon.f, recp) }; + // Multiply by the reciprocal to approximate a / b: + return (union vec) { .neon.f = vmulq_f32(a.neon.f, recp) }; } #endif @@ -218,9 +199,8 @@ vec_div (const union vec a, const union vec b) #ifndef VEC_FN_AND #define VEC_FN_AND static inline union vec -vec_and (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vandq_u32(a.neon.u, b.neon.u) }; + vec_and(const union vec a, const union vec b) { + return (union vec) { .neon.u = vandq_u32(a.neon.u, b.neon.u) }; } #endif @@ -228,9 +208,8 @@ vec_and (const union vec a, const union vec b) #ifndef VEC_FN_OR #define VEC_FN_OR static inline union vec -vec_or (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vorrq_u32(a.neon.u, b.neon.u) }; + vec_or(const union vec a, const union vec b) { + return (union vec) { .neon.u = vorrq_u32(a.neon.u, b.neon.u) }; } #endif @@ -238,9 +217,8 @@ vec_or (const union vec a, const union vec b) #ifndef VEC_FN_XOR #define VEC_FN_XOR static inline union vec -vec_xor (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = veorq_u32(a.neon.u, b.neon.u) }; + vec_xor(const union vec a, const union vec b) { + return (union vec) { .neon.u = veorq_u32(a.neon.u, b.neon.u) }; } #endif @@ -248,9 +226,8 @@ vec_xor (const union vec a, const union vec b) #ifndef VEC_FN_NOT #define VEC_FN_NOT static inline union vec -vec_not (const union vec v) -{ - return (union vec) { .neon.u = vmvnq_u32(v.neon.u) }; + vec_not(const union vec v) { + return (union vec) { .neon.u = vmvnq_u32(v.neon.u) }; } #endif @@ -258,9 +235,8 @@ vec_not (const union vec v) #ifndef VEC_FN_EQ #define VEC_FN_EQ static inline union vec -vec_eq (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vceqq_f32(a.neon.f, b.neon.f) }; + vec_eq(const union vec a, const union vec b) { + return (union vec) { .neon.u = vceqq_f32(a.neon.f, b.neon.f) }; } #endif @@ -268,9 +244,8 @@ vec_eq (const union vec a, const union vec b) #ifndef VEC_FN_IEQ #define VEC_FN_IEQ static inline union vec -vec_ieq (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vceqq_s32(a.neon.i, b.neon.i) }; + vec_ieq(const union vec a, const union vec b) { + return (union vec) { .neon.u = vceqq_s32(a.neon.i, b.neon.i) }; } #endif @@ -278,9 +253,8 @@ vec_ieq (const union vec a, const union vec b) #ifndef VEC_FN_UEQ #define VEC_FN_UEQ static inline union vec -vec_ueq (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vceqq_u32(a.neon.u, b.neon.u) }; + vec_ueq(const union vec a, const union vec b) { + return (union vec) { .neon.u = vceqq_u32(a.neon.u, b.neon.u) }; } #endif @@ -288,9 +262,8 @@ vec_ueq (const union vec a, const union vec b) #ifndef VEC_FN_LT #define VEC_FN_LT static inline union vec -vec_lt (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vcltq_f32(a.neon.f, b.neon.f) }; + vec_lt(const union vec a, const union vec b) { + return (union vec) { .neon.u = vcltq_f32(a.neon.f, b.neon.f) }; } #endif @@ -298,9 +271,8 @@ vec_lt (const union vec a, const union vec b) #ifndef VEC_FN_ILT #define VEC_FN_ILT static inline union vec -vec_ilt (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vcltq_s32(a.neon.i, b.neon.i) }; + vec_ilt(const union vec a, const union vec b) { + return (union vec) { .neon.u = vcltq_s32(a.neon.i, b.neon.i) }; } #endif @@ -308,9 +280,8 @@ vec_ilt (const union vec a, const union vec b) #ifndef VEC_FN_ULT #define VEC_FN_ULT static inline union vec -vec_ult (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vcltq_u32(a.neon.u, b.neon.u) }; + vec_ult(const union vec a, const union vec b) { + return (union vec) { .neon.u = vcltq_u32(a.neon.u, b.neon.u) }; } #endif @@ -318,9 +289,8 @@ vec_ult (const union vec a, const union vec b) #ifndef VEC_FN_LE #define VEC_FN_LE static inline union vec -vec_le (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vcleq_f32(a.neon.f, b.neon.f) }; + vec_le(const union vec a, const union vec b) { + return (union vec) { .neon.u = vcleq_f32(a.neon.f, b.neon.f) }; } #endif @@ -328,9 +298,8 @@ vec_le (const union vec a, const union vec b) #ifndef VEC_FN_ILE #define VEC_FN_ILE static inline union vec -vec_ile (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vcleq_s32(a.neon.i, b.neon.i) }; + vec_ile(const union vec a, const union vec b) { + return (union vec) { .neon.u = vcleq_s32(a.neon.i, b.neon.i) }; } #endif @@ -338,9 +307,8 @@ vec_ile (const union vec a, const union vec b) #ifndef VEC_FN_ULE #define VEC_FN_ULE static inline union vec -vec_ule (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vcleq_u32(a.neon.u, b.neon.u) }; + vec_ule(const union vec a, const union vec b) { + return (union vec) { .neon.u = vcleq_u32(a.neon.u, b.neon.u) }; } #endif @@ -348,9 +316,8 @@ vec_ule (const union vec a, const union vec b) #ifndef VEC_FN_GT #define VEC_FN_GT static inline union vec -vec_gt (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vcgtq_f32(a.neon.f, b.neon.f) }; + vec_gt(const union vec a, const union vec b) { + return (union vec) { .neon.u = vcgtq_f32(a.neon.f, b.neon.f) }; } #endif @@ -358,9 +325,8 @@ vec_gt (const union vec a, const union vec b) #ifndef VEC_FN_IGT #define VEC_FN_IGT static inline union vec -vec_igt (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vcgtq_s32(a.neon.i, b.neon.i) }; + vec_igt(const union vec a, const union vec b) { + return (union vec) { .neon.u = vcgtq_s32(a.neon.i, b.neon.i) }; } #endif @@ -368,9 +334,8 @@ vec_igt (const union vec a, const union vec b) #ifndef VEC_FN_UGT #define VEC_FN_UGT static inline union vec -vec_ugt (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vcgtq_u32(a.neon.u, b.neon.u) }; + vec_ugt(const union vec a, const union vec b) { + return (union vec) { .neon.u = vcgtq_u32(a.neon.u, b.neon.u) }; } #endif @@ -378,9 +343,8 @@ vec_ugt (const union vec a, const union vec b) #ifndef VEC_FN_GE #define VEC_FN_GE static inline union vec -vec_ge (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vcgeq_f32(a.neon.f, b.neon.f) }; + vec_ge(const union vec a, const union vec b) { + return (union vec) { .neon.u = vcgeq_f32(a.neon.f, b.neon.f) }; } #endif @@ -388,9 +352,8 @@ vec_ge (const union vec a, const union vec b) #ifndef VEC_FN_IGE #define VEC_FN_IGE static inline union vec -vec_ige (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vcgeq_s32(a.neon.i, b.neon.i) }; + vec_ige(const union vec a, const union vec b) { + return (union vec) { .neon.u = vcgeq_s32(a.neon.i, b.neon.i) }; } #endif @@ -398,9 +361,8 @@ vec_ige (const union vec a, const union vec b) #ifndef VEC_FN_UGE #define VEC_FN_UGE static inline union vec -vec_uge (const union vec a, const union vec b) -{ - return (union vec) { .neon.u = vcgeq_u32(a.neon.u, b.neon.u) }; + vec_uge(const union vec a, const union vec b) { + return (union vec) { .neon.u = vcgeq_u32(a.neon.u, b.neon.u) }; } #endif @@ -408,12 +370,11 @@ vec_uge (const union vec a, const union vec b) #ifndef VEC_FN_DOT #define VEC_FN_DOT static inline float -vec_dot (const union vec a, const union vec b) -{ - const float32x4_t mul = vmulq_f32(a.neon.f, b.neon.f); - return vgetq_lane_f32(mul, 0) - + vgetq_lane_f32(mul, 1) - + vgetq_lane_f32(mul, 2); +vec_dot(const union vec a, const union vec b) { + const float32x4_t mul = vmulq_f32(a.neon.f, b.neon.f); + return vgetq_lane_f32(mul, 0) + + vgetq_lane_f32(mul, 1) + + vgetq_lane_f32(mul, 2); } #endif @@ -421,20 +382,19 @@ vec_dot (const union vec a, const union vec b) #ifndef VEC_FN_CROSS #define VEC_FN_CROSS static inline union vec -vec_cross (const union vec a, const union vec b) -{ - const float32x4_t ayzwx = (float32x4_t) vextq_u32((uint32x4_t) a.neon.f, (uint32x4_t) a.neon.f, 1); - const float32x4_t byzwx = (float32x4_t) vextq_u32((uint32x4_t) b.neon.f, (uint32x4_t) b.neon.f, 1); + vec_cross(const union vec a, const union vec b) { + const float32x4_t ayzwx = (float32x4_t) vextq_u32((uint32x4_t) a.neon.f, (uint32x4_t) a.neon.f, 1); + const float32x4_t byzwx = (float32x4_t) vextq_u32((uint32x4_t) b.neon.f, (uint32x4_t) b.neon.f, 1); - const float32x4_t ayzxw = vcombine_f32(vget_low_f32(ayzwx), vrev64_f32(vget_high_f32(ayzwx))); - const float32x4_t byzxw = vcombine_f32(vget_low_f32(byzwx), vrev64_f32(vget_high_f32(byzwx))); + const float32x4_t ayzxw = vcombine_f32(vget_low_f32(ayzwx), vrev64_f32(vget_high_f32(ayzwx))); + const float32x4_t byzxw = vcombine_f32(vget_low_f32(byzwx), vrev64_f32(vget_high_f32(byzwx))); - const float32x2x2_t azxwy_pair = vtrn_f32(vget_high_f32(a.neon.f), vget_low_f32(a.neon.f)); - const float32x2x2_t bzxwy_pair = vtrn_f32(vget_high_f32(b.neon.f), vget_low_f32(b.neon.f)); + const float32x2x2_t azxwy_pair = vtrn_f32(vget_high_f32(a.neon.f), vget_low_f32(a.neon.f)); + const float32x2x2_t bzxwy_pair = vtrn_f32(vget_high_f32(b.neon.f), vget_low_f32(b.neon.f)); - const float32x4_t azxyw = vcombine_f32(azxwy_pair.val[0], vrev64_f32(azxwy_pair.val[1])); - const float32x4_t bzxyw = vcombine_f32(bzxwy_pair.val[0], vrev64_f32(bzxwy_pair.val[1])); + const float32x4_t azxyw = vcombine_f32(azxwy_pair.val[0], vrev64_f32(azxwy_pair.val[1])); + const float32x4_t bzxyw = vcombine_f32(bzxwy_pair.val[0], vrev64_f32(bzxwy_pair.val[1])); - return (union vec) { .neon.f = vmlsq_f32(vmulq_f32(ayzxw, bzxyw), byzxw, azxyw) }; + return (union vec) { .neon.f = vmlsq_f32(vmulq_f32(ayzxw, bzxyw), byzxw, azxyw) }; } #endif diff --git a/client/deps/vec/vec/private/sse2.h b/client/deps/vec/vec/private/sse2.h index c3814875f..50bb04813 100644 --- a/client/deps/vec/vec/private/sse2.h +++ b/client/deps/vec/vec/private/sse2.h @@ -2,9 +2,8 @@ #ifndef VEC_FN_ #define VEC_FN_ static inline union vec -vec (const float x, const float y, const float z, const float w) -{ - return (union vec) { .sse.f = _mm_setr_ps(x, y, z, w) }; + vec(const float x, const float y, const float z, const float w) { + return (union vec) { .sse.f = _mm_setr_ps(x, y, z, w) }; } #endif @@ -12,9 +11,8 @@ vec (const float x, const float y, const float z, const float w) #ifndef VEC_FN_I #define VEC_FN_I static inline union vec -vec_i (const int32_t x, const int32_t y, const int32_t z, const int32_t w) -{ - return (union vec) { .sse.i = _mm_setr_epi32(x, y, z, w) }; + vec_i(const int32_t x, const int32_t y, const int32_t z, const int32_t w) { + return (union vec) { .sse.i = _mm_setr_epi32(x, y, z, w) }; } #endif @@ -22,9 +20,8 @@ vec_i (const int32_t x, const int32_t y, const int32_t z, const int32_t w) #ifndef VEC_FN_U #define VEC_FN_U static inline union vec -vec_u (const uint32_t x, const uint32_t y, const uint32_t z, const uint32_t w) -{ - return vec_i((int32_t) x, (int32_t) y, (int32_t) z, (int32_t) w); + vec_u(const uint32_t x, const uint32_t y, const uint32_t z, const uint32_t w) { + return vec_i((int32_t) x, (int32_t) y, (int32_t) z, (int32_t) w); } #endif @@ -32,9 +29,8 @@ vec_u (const uint32_t x, const uint32_t y, const uint32_t z, const uint32_t w) #ifndef VEC_FN_1 #define VEC_FN_1 static inline union vec -vec_1 (const float val) -{ - return (union vec) { .sse.f = _mm_set1_ps(val) }; + vec_1(const float val) { + return (union vec) { .sse.f = _mm_set1_ps(val) }; } #endif @@ -42,9 +38,8 @@ vec_1 (const float val) #ifndef VEC_FN_I1 #define VEC_FN_I1 static inline union vec -vec_i1 (const int32_t val) -{ - return (union vec) { .sse.i = _mm_set1_epi32(val) }; + vec_i1(const int32_t val) { + return (union vec) { .sse.i = _mm_set1_epi32(val) }; } #endif @@ -52,9 +47,8 @@ vec_i1 (const int32_t val) #ifndef VEC_FN_U1 #define VEC_FN_U1 static inline union vec -vec_u1 (const uint32_t val) -{ - return vec_i1((int32_t) val); + vec_u1(const uint32_t val) { + return vec_i1((int32_t) val); } #endif @@ -62,9 +56,8 @@ vec_u1 (const uint32_t val) #ifndef VEC_FN_ZERO #define VEC_FN_ZERO static inline union vec -vec_zero (void) -{ - return (union vec) { .sse.f = _mm_setzero_ps() }; + vec_zero(void) { + return (union vec) { .sse.f = _mm_setzero_ps() }; } #endif @@ -72,9 +65,8 @@ vec_zero (void) #ifndef VEC_FN_IZERO #define VEC_FN_IZERO static inline union vec -vec_izero (void) -{ - return (union vec) { .sse.i = _mm_setzero_si128() }; + vec_izero(void) { + return (union vec) { .sse.i = _mm_setzero_si128() }; } #endif @@ -82,9 +74,8 @@ vec_izero (void) #ifndef VEC_FN_UZERO #define VEC_FN_UZERO static inline union vec -vec_uzero (void) -{ - return vec_izero(); + vec_uzero(void) { + return vec_izero(); } #endif @@ -92,9 +83,8 @@ vec_uzero (void) #ifndef VEC_FN_TO_INT #define VEC_FN_TO_INT static inline union vec -vec_to_int (const union vec v) -{ - return (union vec) { .sse.i = _mm_cvttps_epi32(v.sse.f) }; + vec_to_int(const union vec v) { + return (union vec) { .sse.i = _mm_cvttps_epi32(v.sse.f) }; } #endif @@ -102,9 +92,8 @@ vec_to_int (const union vec v) #ifndef VEC_FN_TO_FLOAT #define VEC_FN_TO_FLOAT static inline union vec -vec_to_float (const union vec v) -{ - return (union vec) { .sse.f = _mm_cvtepi32_ps(v.sse.i) }; + vec_to_float(const union vec v) { + return (union vec) { .sse.f = _mm_cvtepi32_ps(v.sse.i) }; } #endif @@ -112,9 +101,8 @@ vec_to_float (const union vec v) #ifndef VEC_FN_ADD #define VEC_FN_ADD static inline union vec -vec_add (const union vec a, const union vec b) -{ - return (union vec) { .sse.f = _mm_add_ps(a.sse.f, b.sse.f) }; + vec_add(const union vec a, const union vec b) { + return (union vec) { .sse.f = _mm_add_ps(a.sse.f, b.sse.f) }; } #endif @@ -122,9 +110,8 @@ vec_add (const union vec a, const union vec b) #ifndef VEC_FN_IADD #define VEC_FN_IADD static inline union vec -vec_iadd (const union vec a, const union vec b) -{ - return (union vec) { .sse.i = _mm_add_epi32(a.sse.i, b.sse.i) }; + vec_iadd(const union vec a, const union vec b) { + return (union vec) { .sse.i = _mm_add_epi32(a.sse.i, b.sse.i) }; } #endif @@ -132,9 +119,8 @@ vec_iadd (const union vec a, const union vec b) #ifndef VEC_FN_UADD #define VEC_FN_UADD static inline union vec -vec_uadd (const union vec a, const union vec b) -{ - return vec_iadd(a, b); + vec_uadd(const union vec a, const union vec b) { + return vec_iadd(a, b); } #endif @@ -142,9 +128,8 @@ vec_uadd (const union vec a, const union vec b) #ifndef VEC_FN_SUB #define VEC_FN_SUB static inline union vec -vec_sub (const union vec a, const union vec b) -{ - return (union vec) { .sse.f = _mm_sub_ps(a.sse.f, b.sse.f) }; + vec_sub(const union vec a, const union vec b) { + return (union vec) { .sse.f = _mm_sub_ps(a.sse.f, b.sse.f) }; } #endif @@ -152,9 +137,8 @@ vec_sub (const union vec a, const union vec b) #ifndef VEC_FN_ISUB #define VEC_FN_ISUB static inline union vec -vec_isub (const union vec a, const union vec b) -{ - return (union vec) { .sse.i = _mm_sub_epi32(a.sse.i, b.sse.i) }; + vec_isub(const union vec a, const union vec b) { + return (union vec) { .sse.i = _mm_sub_epi32(a.sse.i, b.sse.i) }; } #endif @@ -162,9 +146,8 @@ vec_isub (const union vec a, const union vec b) #ifndef VEC_FN_USUB #define VEC_FN_USUB static inline union vec -vec_usub (const union vec a, const union vec b) -{ - return vec_isub(a, b); + vec_usub(const union vec a, const union vec b) { + return vec_isub(a, b); } #endif @@ -172,9 +155,8 @@ vec_usub (const union vec a, const union vec b) #ifndef VEC_FN_MUL #define VEC_FN_MUL static inline union vec -vec_mul (const union vec a, const union vec b) -{ - return (union vec) { .sse.f = _mm_mul_ps(a.sse.f, b.sse.f) }; + vec_mul(const union vec a, const union vec b) { + return (union vec) { .sse.f = _mm_mul_ps(a.sse.f, b.sse.f) }; } #endif @@ -182,9 +164,8 @@ vec_mul (const union vec a, const union vec b) #ifndef VEC_FN_DIV #define VEC_FN_DIV static inline union vec -vec_div (const union vec a, const union vec b) -{ - return (union vec) { .sse.f = _mm_div_ps(a.sse.f, b.sse.f) }; + vec_div(const union vec a, const union vec b) { + return (union vec) { .sse.f = _mm_div_ps(a.sse.f, b.sse.f) }; } #endif @@ -192,9 +173,8 @@ vec_div (const union vec a, const union vec b) #ifndef VEC_FN_AND #define VEC_FN_AND static inline union vec -vec_and (const union vec a, const union vec b) -{ - return (union vec) { .sse.u = _mm_and_si128(a.sse.u, b.sse.u) }; + vec_and(const union vec a, const union vec b) { + return (union vec) { .sse.u = _mm_and_si128(a.sse.u, b.sse.u) }; } #endif @@ -202,9 +182,8 @@ vec_and (const union vec a, const union vec b) #ifndef VEC_FN_OR #define VEC_FN_OR static inline union vec -vec_or (const union vec a, const union vec b) -{ - return (union vec) { .sse.u = _mm_or_si128(a.sse.u, b.sse.u) }; + vec_or(const union vec a, const union vec b) { + return (union vec) { .sse.u = _mm_or_si128(a.sse.u, b.sse.u) }; } #endif @@ -212,9 +191,8 @@ vec_or (const union vec a, const union vec b) #ifndef VEC_FN_XOR #define VEC_FN_XOR static inline union vec -vec_xor (const union vec a, const union vec b) -{ - return (union vec) { .sse.u = _mm_xor_si128(a.sse.u, b.sse.u) }; + vec_xor(const union vec a, const union vec b) { + return (union vec) { .sse.u = _mm_xor_si128(a.sse.u, b.sse.u) }; } #endif @@ -222,11 +200,10 @@ vec_xor (const union vec a, const union vec b) #ifndef VEC_FN_NOT #define VEC_FN_NOT static inline union vec -vec_not (const union vec v) -{ - const __m128i allset = _mm_set1_epi32(INT32_C(0xFFFFFFFF)); + vec_not(const union vec v) { + const __m128i allset = _mm_set1_epi32(INT32_C(0xFFFFFFFF)); - return (union vec) { .sse.u = _mm_xor_si128(v.sse.u, allset) }; + return (union vec) { .sse.u = _mm_xor_si128(v.sse.u, allset) }; } #endif @@ -234,9 +211,8 @@ vec_not (const union vec v) #ifndef VEC_FN_EQ #define VEC_FN_EQ static inline union vec -vec_eq (const union vec a, const union vec b) -{ - return (union vec) { .sse.f = _mm_cmpeq_ps(a.sse.f, b.sse.f) }; + vec_eq(const union vec a, const union vec b) { + return (union vec) { .sse.f = _mm_cmpeq_ps(a.sse.f, b.sse.f) }; } #endif @@ -244,9 +220,8 @@ vec_eq (const union vec a, const union vec b) #ifndef VEC_FN_IEQ #define VEC_FN_IEQ static inline union vec -vec_ieq (const union vec a, const union vec b) -{ - return (union vec) { .sse.i = _mm_cmpeq_epi32(a.sse.i, b.sse.i) }; + vec_ieq(const union vec a, const union vec b) { + return (union vec) { .sse.i = _mm_cmpeq_epi32(a.sse.i, b.sse.i) }; } #endif @@ -254,9 +229,8 @@ vec_ieq (const union vec a, const union vec b) #ifndef VEC_FN_UEQ #define VEC_FN_UEQ static inline union vec -vec_ueq (const union vec a, const union vec b) -{ - return (union vec) { .sse.u = _mm_cmpeq_epi32(a.sse.u, b.sse.u) }; + vec_ueq(const union vec a, const union vec b) { + return (union vec) { .sse.u = _mm_cmpeq_epi32(a.sse.u, b.sse.u) }; } #endif @@ -264,9 +238,8 @@ vec_ueq (const union vec a, const union vec b) #ifndef VEC_FN_LT #define VEC_FN_LT static inline union vec -vec_lt (const union vec a, const union vec b) -{ - return (union vec) { .sse.f = _mm_cmplt_ps(a.sse.f, b.sse.f) }; + vec_lt(const union vec a, const union vec b) { + return (union vec) { .sse.f = _mm_cmplt_ps(a.sse.f, b.sse.f) }; } #endif @@ -274,9 +247,8 @@ vec_lt (const union vec a, const union vec b) #ifndef VEC_FN_ILT #define VEC_FN_ILT static inline union vec -vec_ilt (const union vec a, const union vec b) -{ - return (union vec) { .sse.i = _mm_cmplt_epi32(a.sse.i, b.sse.i) }; + vec_ilt(const union vec a, const union vec b) { + return (union vec) { .sse.i = _mm_cmplt_epi32(a.sse.i, b.sse.i) }; } #endif @@ -284,13 +256,14 @@ vec_ilt (const union vec a, const union vec b) #ifndef VEC_FN_ULT #define VEC_FN_ULT static inline union vec -vec_ult (const union vec a, const union vec b) -{ - const __m128i bias = _mm_set1_epi32(INT32_C(0x80000000)); + vec_ult(const union vec a, const union vec b) { + const __m128i bias = _mm_set1_epi32(INT32_C(0x80000000)); - return (union vec) { .sse.i = _mm_cmplt_epi32( - _mm_sub_epi32(a.sse.i, bias), - _mm_sub_epi32(b.sse.i, bias)) }; + return (union vec) { + .sse.i = _mm_cmplt_epi32( + _mm_sub_epi32(a.sse.i, bias), + _mm_sub_epi32(b.sse.i, bias)) + }; } #endif @@ -298,9 +271,8 @@ vec_ult (const union vec a, const union vec b) #ifndef VEC_FN_LE #define VEC_FN_LE static inline union vec -vec_le (const union vec a, const union vec b) -{ - return (union vec) { .sse.f = _mm_cmple_ps(a.sse.f, b.sse.f) }; + vec_le(const union vec a, const union vec b) { + return (union vec) { .sse.f = _mm_cmple_ps(a.sse.f, b.sse.f) }; } #endif @@ -308,11 +280,12 @@ vec_le (const union vec a, const union vec b) #ifndef VEC_FN_ILE #define VEC_FN_ILE static inline union vec -vec_ile (const union vec a, const union vec b) -{ - return (union vec) { .sse.i = _mm_or_si128( - _mm_cmplt_epi32(a.sse.i, b.sse.i), - _mm_cmpeq_epi32(a.sse.i, b.sse.i)) }; + vec_ile(const union vec a, const union vec b) { + return (union vec) { + .sse.i = _mm_or_si128( + _mm_cmplt_epi32(a.sse.i, b.sse.i), + _mm_cmpeq_epi32(a.sse.i, b.sse.i)) + }; } #endif @@ -320,9 +293,8 @@ vec_ile (const union vec a, const union vec b) #ifndef VEC_FN_ULE #define VEC_FN_ULE static inline union vec -vec_ule (const union vec a, const union vec b) -{ - return vec_or(vec_ult(a, b), vec_ueq(a, b)); + vec_ule(const union vec a, const union vec b) { + return vec_or(vec_ult(a, b), vec_ueq(a, b)); } #endif @@ -330,9 +302,8 @@ vec_ule (const union vec a, const union vec b) #ifndef VEC_FN_GT #define VEC_FN_GT static inline union vec -vec_gt (const union vec a, const union vec b) -{ - return (union vec) { .sse.f = _mm_cmpgt_ps(a.sse.f, b.sse.f) }; + vec_gt(const union vec a, const union vec b) { + return (union vec) { .sse.f = _mm_cmpgt_ps(a.sse.f, b.sse.f) }; } #endif @@ -340,9 +311,8 @@ vec_gt (const union vec a, const union vec b) #ifndef VEC_FN_IGT #define VEC_FN_IGT static inline union vec -vec_igt (const union vec a, const union vec b) -{ - return (union vec) { .sse.i = _mm_cmpgt_epi32(a.sse.i, b.sse.i) }; + vec_igt(const union vec a, const union vec b) { + return (union vec) { .sse.i = _mm_cmpgt_epi32(a.sse.i, b.sse.i) }; } #endif @@ -350,13 +320,14 @@ vec_igt (const union vec a, const union vec b) #ifndef VEC_FN_UGT #define VEC_FN_UGT static inline union vec -vec_ugt (const union vec a, const union vec b) -{ - const __m128i bias = _mm_set1_epi32(INT32_C(0x80000000)); + vec_ugt(const union vec a, const union vec b) { + const __m128i bias = _mm_set1_epi32(INT32_C(0x80000000)); - return (union vec) { .sse.i = _mm_cmpgt_epi32( - _mm_sub_epi32(a.sse.i, bias), - _mm_sub_epi32(b.sse.i, bias)) }; + return (union vec) { + .sse.i = _mm_cmpgt_epi32( + _mm_sub_epi32(a.sse.i, bias), + _mm_sub_epi32(b.sse.i, bias)) + }; } #endif @@ -364,9 +335,8 @@ vec_ugt (const union vec a, const union vec b) #ifndef VEC_FN_GE #define VEC_FN_GE static inline union vec -vec_ge (const union vec a, const union vec b) -{ - return (union vec) { .sse.f = _mm_cmpge_ps(a.sse.f, b.sse.f) }; + vec_ge(const union vec a, const union vec b) { + return (union vec) { .sse.f = _mm_cmpge_ps(a.sse.f, b.sse.f) }; } #endif @@ -374,11 +344,12 @@ vec_ge (const union vec a, const union vec b) #ifndef VEC_FN_IGE #define VEC_FN_IGE static inline union vec -vec_ige (const union vec a, const union vec b) -{ - return (union vec) { .sse.i = _mm_or_si128( - _mm_cmpgt_epi32(a.sse.i, b.sse.i), - _mm_cmpeq_epi32(a.sse.i, b.sse.i)) }; + vec_ige(const union vec a, const union vec b) { + return (union vec) { + .sse.i = _mm_or_si128( + _mm_cmpgt_epi32(a.sse.i, b.sse.i), + _mm_cmpeq_epi32(a.sse.i, b.sse.i)) + }; } #endif @@ -386,9 +357,8 @@ vec_ige (const union vec a, const union vec b) #ifndef VEC_FN_UGE #define VEC_FN_UGE static inline union vec -vec_uge (const union vec a, const union vec b) -{ - return vec_or(vec_ugt(a, b), vec_ueq(a, b)); + vec_uge(const union vec a, const union vec b) { + return vec_or(vec_ugt(a, b), vec_ueq(a, b)); } #endif @@ -396,15 +366,14 @@ vec_uge (const union vec a, const union vec b) #ifndef VEC_FN_DOT #define VEC_FN_DOT static inline float -vec_dot (const union vec a, const union vec b) -{ - const __m128 mulx = _mm_mul_ps(a.sse.f, b.sse.f); - const __m128 muly = _mm_shuffle_ps(mulx, mulx, _MM_SHUFFLE(0, 0, 0, 1)); - const __m128 mulz = _mm_shuffle_ps(mulx, mulx, _MM_SHUFFLE(0, 0, 0, 2)); - const __m128 sum = _mm_add_ps(mulx, _mm_add_ps(muly, mulz)); +vec_dot(const union vec a, const union vec b) { + const __m128 mulx = _mm_mul_ps(a.sse.f, b.sse.f); + const __m128 muly = _mm_shuffle_ps(mulx, mulx, _MM_SHUFFLE(0, 0, 0, 1)); + const __m128 mulz = _mm_shuffle_ps(mulx, mulx, _MM_SHUFFLE(0, 0, 0, 2)); + const __m128 sum = _mm_add_ps(mulx, _mm_add_ps(muly, mulz)); - // Extract first element: - return ((union vec) { .xi = _mm_cvtsi128_si32(_mm_castps_si128(sum)) }).x; + // Extract first element: + return ((union vec) { .xi = _mm_cvtsi128_si32(_mm_castps_si128(sum)) }).x; } #endif @@ -412,22 +381,21 @@ vec_dot (const union vec a, const union vec b) #ifndef VEC_FN_CROSS #define VEC_FN_CROSS static inline union vec -vec_cross (const union vec a, const union vec b) -{ - // Shuffle a: - const __m128 ayzx = _mm_shuffle_ps(a.sse.f, a.sse.f, _MM_SHUFFLE(0, 0, 2, 1)); - const __m128 azxy = _mm_shuffle_ps(a.sse.f, a.sse.f, _MM_SHUFFLE(0, 1, 0, 2)); + vec_cross(const union vec a, const union vec b) { + // Shuffle a: + const __m128 ayzx = _mm_shuffle_ps(a.sse.f, a.sse.f, _MM_SHUFFLE(0, 0, 2, 1)); + const __m128 azxy = _mm_shuffle_ps(a.sse.f, a.sse.f, _MM_SHUFFLE(0, 1, 0, 2)); - // Shuffle b: - const __m128 byzx = _mm_shuffle_ps(b.sse.f, b.sse.f, _MM_SHUFFLE(0, 0, 2, 1)); - const __m128 bzxy = _mm_shuffle_ps(b.sse.f, b.sse.f, _MM_SHUFFLE(0, 1, 0, 2)); + // Shuffle b: + const __m128 byzx = _mm_shuffle_ps(b.sse.f, b.sse.f, _MM_SHUFFLE(0, 0, 2, 1)); + const __m128 bzxy = _mm_shuffle_ps(b.sse.f, b.sse.f, _MM_SHUFFLE(0, 1, 0, 2)); - // (ay * bz), (az * bx), (ax * by), (ax * bx): - const __m128 mul1 = _mm_mul_ps(ayzx, bzxy); + // (ay * bz), (az * bx), (ax * by), (ax * bx): + const __m128 mul1 = _mm_mul_ps(ayzx, bzxy); - // (az * by), (ax * bz), (ay * bx), (ax * bx): - const __m128 mul2 = _mm_mul_ps(azxy, byzx); + // (az * by), (ax * bz), (ay * bx), (ax * bx): + const __m128 mul2 = _mm_mul_ps(azxy, byzx); - return (union vec) { .sse.f = _mm_sub_ps(mul1, mul2) }; + return (union vec) { .sse.f = _mm_sub_ps(mul1, mul2) }; } #endif diff --git a/client/deps/vec/vec/private/sse41.h b/client/deps/vec/vec/private/sse41.h index 797596f79..196e042e0 100644 --- a/client/deps/vec/vec/private/sse41.h +++ b/client/deps/vec/vec/private/sse41.h @@ -2,11 +2,10 @@ #ifndef VEC_FN_DOT #define VEC_FN_DOT static inline float -vec_dot (const union vec a, const union vec b) -{ - const __m128 dot = _mm_dp_ps(a.sse.f, b.sse.f, 0x7F); +vec_dot(const union vec a, const union vec b) { + const __m128 dot = _mm_dp_ps(a.sse.f, b.sse.f, 0x7F); - // Extract first element: - return ((union vec) { .xi = _mm_cvtsi128_si32(_mm_castps_si128(dot)) }).x; + // Extract first element: + return ((union vec) { .xi = _mm_cvtsi128_si32(_mm_castps_si128(dot)) }).x; } #endif diff --git a/client/deps/vec/vec/vec.h b/client/deps/vec/vec/vec.h index 34b85c04a..e0dd0e39b 100644 --- a/client/deps/vec/vec/vec.h +++ b/client/deps/vec/vec/vec.h @@ -4,106 +4,106 @@ // GCC-style vector extensions work with Clang >= 3 or GCC >= 4.0: #if !defined(VEC_SUPPRESS_GCC) - #if __GNUC__ >= 4 || __clang_major__ >= 3 - #define VEC_GCC - #endif +#if __GNUC__ >= 4 || __clang_major__ >= 3 +#define VEC_GCC +#endif #endif // For testing purposes, allow the user to bypass any platform-specific support // and to use only the generic functions: #if !defined(VEC_SUPPRESS_HW) - // Check for SSE support: - #if defined(__SSE2__) - #define VEC_SSE2 - #include - #endif +// Check for SSE support: +#if defined(__SSE2__) +#define VEC_SSE2 +#include +#endif - // Check for SSE4 support: - #if defined(__SSE4_1__) - #define VEC_SSE41 - #include - #endif +// Check for SSE4 support: +#if defined(__SSE4_1__) +#define VEC_SSE41 +#include +#endif - // Check for ARM NEON support: - #if defined(__ARM_NEON__) || defined(__ARM_NEON) - #define VEC_NEON - #include +// Check for ARM NEON support: +#if defined(__ARM_NEON__) || defined(__ARM_NEON) +#define VEC_NEON +#include - // GCC and Clang support inline assembly: - #if defined(__GNUC__) || defined(__clang_major__) - #define VEC_NEON_ASM - #endif - #endif +// GCC and Clang support inline assembly: +#if defined(__GNUC__) || defined(__clang_major__) +#define VEC_NEON_ASM +#endif +#endif #endif // Define architecture-independent vector types. // This syntax is valid for GCC and LLVM/Clang: #if defined(VEC_GCC) -typedef float vec4f __attribute__ ((vector_size (16), aligned (16))); -typedef int32_t vec4i __attribute__ ((vector_size (16), aligned (16))); -typedef uint32_t vec4u __attribute__ ((vector_size (16), aligned (16))); +typedef float vec4f __attribute__((vector_size(16), aligned(16))); +typedef int32_t vec4i __attribute__((vector_size(16), aligned(16))); +typedef uint32_t vec4u __attribute__((vector_size(16), aligned(16))); #endif // Union to represent a 4x32-bit (128-bit) vector in various ways: union vec { - // Named member representation in float form, assuming a 3D vector: - struct { - float x; - float y; - float z; - float w; - }; + // Named member representation in float form, assuming a 3D vector: + struct { + float x; + float y; + float z; + float w; + }; - // Named member representation in signed integer form: - struct { - int32_t xi; - int32_t yi; - int32_t zi; - int32_t wi; - }; + // Named member representation in signed integer form: + struct { + int32_t xi; + int32_t yi; + int32_t zi; + int32_t wi; + }; - // Named member representation in unsigned integer form: - struct { - uint32_t xu; - uint32_t yu; - uint32_t zu; - uint32_t wu; - }; + // Named member representation in unsigned integer form: + struct { + uint32_t xu; + uint32_t yu; + uint32_t zu; + uint32_t wu; + }; - // Representation as array of separate elements: - union { - float f[4]; - int32_t i[4]; - uint32_t u[4]; - } elem; + // Representation as array of separate elements: + union { + float f[4]; + int32_t i[4]; + uint32_t u[4]; + } elem; - // Representation as GCC-style vector extensions: + // Representation as GCC-style vector extensions: #if defined(VEC_GCC) - union { - vec4f f; - vec4i i; - vec4u u; - } gcc; + union { + vec4f f; + vec4i i; + vec4u u; + } gcc; #endif - // SSE representation: + // SSE representation: #if defined(VEC_SSE2) - union { - __m128 f; - __m128i i; - __m128i u; - } sse; + union { + __m128 f; + __m128i i; + __m128i u; + } sse; #endif - // NEON representation: + // NEON representation: #if defined(VEC_NEON) - union { - float32x4_t f; - int32x4_t i; - uint32x4_t u; - } neon; + union { + float32x4_t f; + int32x4_t i; + uint32x4_t u; + } neon; #endif }; @@ -124,23 +124,23 @@ union vec { // are available. #if defined(VEC_SSE41) - #include "private/sse41.h" +#include "private/sse41.h" #endif #if defined(VEC_SSE2) - #include "private/sse2.h" +#include "private/sse2.h" #endif #if defined(VEC_NEON_ASM) - #include "private/neon_asm.h" +#include "private/neon_asm.h" #endif #if defined(VEC_NEON) - #include "private/neon_intrin.h" +#include "private/neon_intrin.h" #endif #if defined(VEC_GCC) - #include "private/gcc.h" +#include "private/gcc.h" #endif #include "private/generic.h" diff --git a/client/pyscripts/mfulc_counterfeit_recovery.py b/client/pyscripts/mfulc_counterfeit_recovery.py index 0feec6623..9db03b4d1 100755 --- a/client/pyscripts/mfulc_counterfeit_recovery.py +++ b/client/pyscripts/mfulc_counterfeit_recovery.py @@ -13,6 +13,7 @@ import subprocess import argparse import random import sys +import re import threading import time import queue @@ -33,9 +34,19 @@ if sys.version_info < required_version: tools = { "mfulc_des_brute": find_tool("mfulc_des_brute"), + "mfulc_des_brute_cuda": find_tool("mfulc_des_brute_cuda"), } +def extract_full_key(output: str) -> Optional[str]: + """Extract a 32-hex-digit full key from brute tool output.""" + pattern = r"Full\s+key(?:\s*\(hex\))?\s*:\s*([0-9A-Fa-f]{32})" + match = re.search(pattern, output) + if match: + return match.group(1).upper() + return None + + class CrackEffect: """ A class to create a visual effect of cracking blocks of data. @@ -221,68 +232,99 @@ class CrackEffect: scramble_thread.join() -def collect(num_challenges: int, p, debug: bool) -> Optional[dict]: - """ - Collect challenges from the card and check if it is vulnerable. +def try_unlock(num_challenges: int, erndb: str, erndarndb: str, p) -> bool: + """Try to unlock the card by using the provided reader response Args: - num_challenges (int): Number of challenges to collect. - p: Proxmark3 instance. - debug (bool): Enable debug mode. + num_challenges (int): Number of challenge reads to attempt. + erndb (str): Card challenge to look for. + erndarndb (str): Reader response to use. + p: Proxmark3 instance used to issue raw commands and read responses. Returns: - Optional[dict]: Collected challenges data or None if the card is not vulnerable. + bool: + Success """ - # Sanity check: make sure an Ultralight C is on the Proxmark - p.console("hf 14a info") - if "MIFARE Ultralight C" not in p.grabbed_output: - print("[-] Error: \033[1;31mUltralight C not placed on Proxmark\033[0m") - return - else: - print("[+] Ultralight C detected. Keep stable on Proxmark during the attack.") + challenges_collected = 0 + next_progress = 10 - # Sanity check: ensure card is unlocked and lock bytes do not prevent key overwrite - p.console("hf 14a raw -sc 3028") - hex_bytes = p.grabbed_output.split() - if len(hex_bytes) < 16: - print("[-] Error: \033[1;31mCard not unlocked. Run relay attack in UNLOCK mode first.\033[0m") - return - data_bytes = [bytes.fromhex(b) for b in hex_bytes[1:17]] - # Byte 0 of page 42: 0x30 minimum - minimum_auth_page = ord(data_bytes[8]) - if minimum_auth_page < 48: - print("[-] Error: \033[1;31mCard not unlocked. Run relay attack in UNLOCK mode first.\033[0m") - return - # First bit of byte 1 in page 40: lock key - is_locked_key = ((ord(data_bytes[1]) & 0x80) >> 7) == 1 - if is_locked_key: - print("[-] Error: \033[1;31mCard is not vulnerable (see READ mode in relay app)\033[0m") - return + print("[=] Waiting for the provided challenge to appear...") + while challenges_collected < max(1, num_challenges): + p.console("hf 14a raw -sck 1A00") + challenge = p.grabbed_output.split() + if (len(challenge) > 8) and (challenge[1] == "AF"): + hex_challenge = "".join(challenge[2:10]).upper() + # print(hex_challenge, erndb) + challenges_collected += 1 + progress = challenges_collected * 100 // max(1, num_challenges) + if progress >= next_progress: + print(f"[=] Progress: {min(progress, 100)}%") + next_progress += 10 + if hex_challenge == erndb: + p.console(f"hf 14a raw -ck AF{erndarndb}") + response = p.grabbed_output.split() + if (len(response) > 8) and (response[1] == "00"): + print("[+] Unlock successful!") + # Rewrite AUTH0 + p.console("hf 14a raw -c a2 2a 30000000") + response = p.grabbed_output.split() + if response[1] == "0A": + print("[+] AUTH0 reset successful!") + return True + else: + print("[-] AUTH0 reset failed") + print(response) + return False + else: + print("[-] Unlock failed") + p.console("hf 14a reader --drop", capture=False) + return False + p.console("hf 14a reader --drop", capture=False) + print("[-] Provided challenge not found, try again") + return False - print("[+] All sanity checks \033[1;32mpassed\033[0m. Checking if card is vulnerable.\033[?25l") +def collect_100(num_challenges: int, p, early_stop: bool) -> tuple[int, dict]: + """Collect challenges and track the most frequent nonce occurrence. + + Args: + num_challenges (int): Number of challenge reads to attempt. + p: Proxmark3 instance used to issue raw commands and read responses. + early_stop (bool): Stop as soon as a repeated challenge is detected. + + Returns: + tuple[int, dict]: + - max_occurrence: Highest number of times any single challenge appeared. + - challenges: Collected challenge map including "challenge_100", set to the + most frequent challenge seen during collection. + """ # Collect challenges (100) challenges_collected = 0 - challenges_100 = set() + occurrences = {} + max_occurrence = 1 challenges = {} - collision = False - while challenges_collected < num_challenges: + while challenges_collected < max(1, num_challenges): p.console("hf 14a raw -sc 1A00") challenge = p.grabbed_output.split() if (len(challenge) > 8) and (challenge[1] == "AF"): hex_challenge = "".join(challenge[2:10]) - if hex_challenge in challenges_100: - collision = True + if challenges_collected == 0: challenges["challenge_100"] = hex_challenge - break + if hex_challenge in occurrences: + occurrences[hex_challenge] += 1 + if occurrences[hex_challenge] > max_occurrence: + max_occurrence = occurrences[hex_challenge] + challenges["challenge_100"] = hex_challenge + if early_stop: + break else: - challenges_100.add(hex_challenge) + occurrences[hex_challenge] = 1 challenges_collected += 1 print("\n[+] 100 collection complete") print(f"\r[+] Challenges collected: \033[96m{challenges_collected}\033[0m") - if collision: + if max_occurrence > 1: print("[+] Status: \033[1;31mVulnerable\033[0m\033[?25h") else: experimental_chals_subset_size = 600 @@ -292,6 +334,75 @@ def collect(num_challenges: int, p, debug: bool) -> Optional[dict]: precision = max(1, -int(math.floor(math.log10(probability_no_collision))) + 1) print("[+] Status: \033[1;32mNot vulnerable\033[0m" f" (false negative probability: {probability_no_collision*100:.{precision-1}f}%)\033[?25h") + return max_occurrence, challenges + + +def get_ulc_uid(p) -> Optional[str]: + """Check whether the card on the reader is a MIFARE Ultralight C. + + Args: + p: Proxmark3 instance. + + Returns: + tuple[bool, Optional[str]]: + - True and normalized UID (uppercase hex, no spaces) when detected. + - False and None otherwise. + """ + # Sanity check: make sure an Ultralight C is on the Proxmark + p.console("hf 14a info") + info = p.grabbed_output + if "MIFARE Ultralight C" not in info: + print("[-] Error: \033[1;31mUltralight C not placed on Proxmark\033[0m") + return None + else: + print("[+] Ultralight C detected. Keep stable on Proxmark during the operations.") + uid_match = re.search(r"UID:\s*([0-9A-Fa-f ]+)", info) + uid = "".join(uid_match.group(1).split()).upper() if uid_match else None + return uid + + +def collect(num_challenges: int, p, debug: bool, force: bool = False, erndarndb: Optional[str] = None) -> Optional[dict]: + """ + Collect challenges from the card and check if it is vulnerable. + + Args: + num_challenges (int): Number of challenges to collect. + p: Proxmark3 instance. + debug (bool): Enable debug mode. + force (bool): Force the attack even if the card does not appear vulnerable (dangerous!). + + Returns: + Optional[dict]: Collected challenges data or None if the card is not vulnerable. + """ + + uid = get_ulc_uid(p) + if uid is None: + return + + # Sanity check: ensure card is unlocked and lock bytes do not prevent key overwrite + p.console("hf 14a raw -sc 3028") + hex_bytes = p.grabbed_output.split() + if len(hex_bytes) < 16: + print("[-] Error: \033[1;31mCard not unlocked. See --get_frequent_chal and --unlock.\033[0m") + return + data_bytes = [bytes.fromhex(b) for b in hex_bytes[1:17]] + # First bit of byte 1 in page 40: lock key + is_locked_key = ((ord(data_bytes[1]) & 0x80) >> 7) == 1 + if is_locked_key: + print("[-] Error: \033[1;31mCard OTP prevents key overwrite." + " Card is not vulnerable (see READ mode in relay app)" + " unless it's a Giantec (see tearing OTP)\033[0m") + return + # Byte 0 of page 42: 0x30 minimum + minimum_auth_page = ord(data_bytes[8]) + if minimum_auth_page < 48: + print("[-] Error: \033[1;31mCard not unlocked. See --get_frequent_chal and --unlock.\033[0m") + return + + print("[+] All sanity checks \033[1;32mpassed\033[0m. Checking if card is vulnerable.\033[?25l") + + max_occurrence, challenges = collect_100(num_challenges, p, early_stop=True) + if max_occurrence <= 1 and not force: return # The card is vulnerable, proceed with attack @@ -389,15 +500,54 @@ def main(): parser.add_argument('-d', '--debug', action='store_true', help='Enable debug mode') parser.add_argument('-j', '--json', help='Path to JSON file to load or save collected challenges') parser.add_argument('-o', '--offline', action='store_true', help='Use offline mode with pre-collected challenges') + parser.add_argument('--cuda', action='store_true', + help='Use CUDA implementation') + parser.add_argument('--force', action='store_true', + help='Force the attack even if the card does not appear vulnerable (dangerous!)') + parser.add_argument('--get_frequent_chal', action='store_true', + help='Collect a "gold" challenge to perform an unlock, and quit afterwards') + parser.add_argument('--unlock', help='Unlock a card with a "gold" challenge/response pair', + type=str, metavar='ERndB,ERndARndB\'') args = parser.parse_args() debug = args.debug num_challenges = args.challenges offline = args.offline + use_cuda = args.cuda + force = args.force + get_frequent_chal = args.get_frequent_chal + erndb, erndarndb = args.unlock.split(',') if args.unlock else (None, None) + brute_tool = tools["mfulc_des_brute_cuda"] if use_cuda else tools["mfulc_des_brute"] + + if get_frequent_chal and (offline or args.json or force or use_cuda): + print("[-] Error: --get_frequent_chal can only be combined with --challenges") + return + + if (erndb or erndarndb) and offline: + print("[-] Error: --unlock can'n be combined with --offline") + return + + if get_frequent_chal: + import pm3 + p = pm3.pm3() + uid = get_ulc_uid(p) + if uid is None: + return + max_occurrence, challenges = collect_100(num_challenges, p, early_stop=False) + print(f"[+] Most frequent challenge: \033[1;34m{challenges['challenge_100']}\033[0m" + f" (occurrences: {max_occurrence}/{num_challenges})") + print("[+] Get the corresponding reader response with") + print(f"[+] \033[1;33mhf mfu sim -t 13 -u {uid} --1a1 {challenges['challenge_100']}\033[0m") + return if not offline: import pm3 p = pm3.pm3() - challenges = collect(num_challenges, p, debug) + if erndb and erndarndb: + erndb = erndb.upper() + erndarndb = erndarndb.upper() + if not try_unlock(num_challenges, erndb, erndarndb, p): + return + challenges = collect(num_challenges, p, debug, force, erndarndb) if challenges is None: return if args.json: @@ -435,13 +585,14 @@ def main(): 2: challenges["challenge_100"]} for key_segment_idx in [1, 0, 3, 2]: ciphertext = ciphertexts[key_segment_idx] - cmd = [tools["mfulc_des_brute"], + cmd = [brute_tool, "-c", f"{challenges['challenge_0']}", f"{ciphertext}", "".join(key_segment_values.values()), - str(key_segment_idx+1), - str(args.threads)] + str(key_segment_idx+1)] + if not use_cuda: + cmd.append(str(args.threads)) if debug: crack_effect.print_above("[=] CMD:" + ' '.join(cmd)) start_time = time.time() @@ -461,19 +612,20 @@ def main(): for line in result.stdout.split('\n'): if "LFSR detection" in line: crack_effect.print_above(f"[+] {line}") - if "No matching key was found" in result.stdout: + if "No matching key was found" in result.stdout or "RESULT: KEY NOT FOUND" in result.stdout: key_found = False crack_effect.stop_event.set() crack_effect.erase_key() print(f"\n\n\n[-] Error: {result.stdout}") break - if "Full key (hex): " not in result.stdout: + full_key = extract_full_key(result.stdout) + if full_key is None: key_found = False crack_effect.stop_event.set() crack_effect.erase_key() print(f"\n\n\n[-] Error: {result}") break - key_segment_values[key_segment_idx] = result.stdout.split("Full key (hex): ")[1][(8*key_segment_idx):][:8] + key_segment_values[key_segment_idx] = full_key[(8*key_segment_idx):][:8] if debug: crack_effect.print_above(f"[+] Found key segment: {key_segment_values[key_segment_idx]}") key_found = True diff --git a/client/pyscripts/pm3_help2json.py b/client/pyscripts/pm3_help2json.py index b7612d7cc..aa4f6b991 100755 --- a/client/pyscripts/pm3_help2json.py +++ b/client/pyscripts/pm3_help2json.py @@ -133,7 +133,7 @@ def build_metadata(extra_data, command_data): logging.info('Building metadata...') metadata = { 'extracted_by': get_version(), - 'extracted_on': datetime.datetime.utcnow().replace(microsecond=0).isoformat(), + 'extracted_on': datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0).isoformat(), 'commands_extracted': len(command_data) } for key, value in metadata.items(): diff --git a/client/resources/felica_ic_code_list.json b/client/resources/felica/felica_ic_code_list.json similarity index 100% rename from client/resources/felica_ic_code_list.json rename to client/resources/felica/felica_ic_code_list.json diff --git a/client/resources/felica_system_code_list.json b/client/resources/felica/felica_system_code_list.json similarity index 97% rename from client/resources/felica_system_code_list.json rename to client/resources/felica/felica_system_code_list.json index 6f274a75f..ed5102764 100644 --- a/client/resources/felica_system_code_list.json +++ b/client/resources/felica/felica_system_code_list.json @@ -696,6 +696,13 @@ "type": "transit", "description": "Used on Kartu Multi Trip Commet transit card" }, + { + "code": "90E3", + "name": "Dhaka Mass Transit", + "region": "Bangladesh", + "type": "transit", + "description": "Used by DMTCL MRT Pass transit card" + }, { "code": "9105", "name": "Starbucks Touch", @@ -717,6 +724,13 @@ "type": "transit", "description": "Used on Kartu Multi Trip Jelajah transit card" }, + { + "code": "93EC", + "name": "NTASU", + "region": "Japan", + "type": "transit", + "description": "Used by NTASU transit card" + }, { "code": "9450", "name": "HCMC", @@ -731,6 +745,13 @@ "type": "transit", "description": "Used by kinoca regional transit card (Wakayama Bus)" }, + { + "code": "957A", + "name": "FeliCa Secure ID", + "region": "Global", + "type": "general", + "description": "Used by FeliCa Secure ID credentials" + }, { "code": "FE00", "name": "FeliCa Networks Common Area", diff --git a/client/src/cmdflashmemspiffs.c b/client/src/cmdflashmemspiffs.c index e2d5417ff..62a85f246 100644 --- a/client/src/cmdflashmemspiffs.c +++ b/client/src/cmdflashmemspiffs.c @@ -467,7 +467,7 @@ static int CmdFlashMemSpiFFSWipe(const char *Cmd) { CLIParserInit(&ctx, "mem spiffs wipe", _RED_("* * * Warning * * *") " \n" _CYAN_("This command wipes all files on the device SPIFFS file system"), - "mem spiffs wipe"); + "mem spiffs wipe"); void *argtable[] = { arg_param_begin, diff --git a/client/src/cmdhf14a.c b/client/src/cmdhf14a.c index d5076205d..712cfd6a4 100644 --- a/client/src/cmdhf14a.c +++ b/client/src/cmdhf14a.c @@ -3025,7 +3025,7 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { int16_t fsci = card.ats[1] & 0x0f; PrintAndLogEx(INFO, " ..." _YELLOW_("%02X") "............ T0 TA1 is%s present, TB1 is%s present, " - "TC1 is%s present, FSCI is %d (FSC = %d)", + "TC1 is%s present, FSCI is %d (FSC = %d)", card.ats[1], (ta1 ? "" : _RED_(" NOT")), (tb1 ? "" : _RED_(" NOT")), @@ -3047,7 +3047,7 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { if (strlen(ds) != 0) ds[strlen(ds) - 2] = '\0'; if (strlen(dr) != 0) dr[strlen(dr) - 2] = '\0'; PrintAndLogEx(INFO, " ......" _YELLOW_("%02X") "......... TA1 different divisors are%s supported, " - "DR: [%s], DS: [%s]", + "DR: [%s], DS: [%s]", card.ats[pos], ((card.ats[pos] & 0x80) ? _RED_(" NOT") : ""), dr, diff --git a/client/src/cmdhfcalypso.c b/client/src/cmdhfcalypso.c index f45e9429e..fa02c78ff 100644 --- a/client/src/cmdhfcalypso.c +++ b/client/src/cmdhfcalypso.c @@ -57,30 +57,34 @@ #define CALYPSO_MAX_ENCODED_SFI 0x1F #define CALYPSO_HCE_TOKEN_LEN 2 #define CALYPSO_DUMP_FILENAME_MAX_SERIALS 8 -#define CALYPSO_MAX_EF_LIST_LIDS 128 -#define CALYPSO_MAX_LID_CANDIDATES 384 #define CALYPSO_GET_DATA_NAME_WIDTH 22 -#define CALYPSO_HEX_ENTRY_INLINE_MAX 32 #define CALYPSO_HEX_ENTRY_BREAK 32 #define CALYPSO_PROBE_FORM_NAME_WIDTH 10 #define CALYPSO_PROBE_SELECT_WIDTH 56 #define CALYPSO_PROBE_RESPONSE_HEX_WIDTH 81 +#define CALYPSO_DUMP_HEX_ENTRY_BREAK 48 #define CALYPSO_MANUFACTURERS_RESOURCE "calypso/manufacturers" #define CALYPSO_IC_FAMILIES_RESOURCE "calypso/ic_families" #define CALYPSO_OPERATORS_RESOURCE "calypso/operators" #define CALYPSO_NODES_RESOURCE "calypso/nodes" #define CALYPSO_DUMP_PATH_MAX 2 +#define CALYPSO_DUMP_NODE_PATH_MAX 8 // https://docs.keyple.org/keyple-card-calypso-cpp-lib/2.2.5.6/_cmd_card_select_file_8cpp_source.html -#define CALYPSO_SELECT_FIRST_EF_P1 0x02 -#define CALYPSO_SELECT_FIRST_EF_P2 0x00 -#define CALYPSO_SELECT_NEXT_EF_P1 0x02 -#define CALYPSO_SELECT_NEXT_EF_P2 0x02 #define CALYPSO_SELECT_CURRENT_DF_P1 0x09 #define CALYPSO_SELECT_CURRENT_DF_P2 0x00 -// Most existing public code uses P1=00 for LID selection, and on many cards it exposes more files. +// ISO-style path selection: data is one or more big-endian file IDs. +#define CALYPSO_SELECT_PATH_P1 0x08 +#define CALYPSO_SELECT_PATH_P2 0x00 #define CALYPSO_SELECT_FILE_ID_P1 0x00 #define CALYPSO_SELECT_FILE_ID_P2 0x00 +#define CALYPSO_DUMP_SOURCE_EFLIST 0x01 +#define CALYPSO_DUMP_SOURCE_KNOWN 0x02 +#define CALYPSO_DUMP_SOURCE_SELECTED 0x08 +#define CALYPSO_DUMP_SOURCE_BRUTE 0x10 +#define CALYPSO_DUMP_CANDIDATE_MAX 1600 + +static const uint8_t calypso_mf_aid[] = {0x33, 0x4D, 0x54, 0x52, 0x2E, 0x49, 0x43, 0x41}; // "3MTR.ICA" typedef struct { bool has_df_name; @@ -144,25 +148,13 @@ typedef struct { typedef struct { bool found; - const char *source; - const char *aid_hex; const char *vendor; const char *name; - const char *country; - const char *description; - const char *type; bool prefix; bool generic; size_t aid_len; } calypso_aid_match_t; -typedef struct { - json_t *root; - calypso_aid_match_t selected_match; - calypso_aid_match_t df_name_match; - const calypso_aid_match_t *best; -} calypso_aid_attribution_t; - typedef struct { const char *path; json_t *root; @@ -176,22 +168,11 @@ typedef struct { size_t path_len; } calypso_file_ref_t; -typedef enum { - CALYPSO_FILE_SOURCE_KNOWN = 0x01, - CALYPSO_FILE_SOURCE_EF_LIST = 0x02, -} calypso_file_source_t; - typedef struct { - calypso_file_ref_t ref; - uint8_t source; - char name_storage[16]; -} calypso_file_candidate_t; - -typedef struct { - uint16_t lids[CALYPSO_MAX_EF_LIST_LIDS]; - size_t count; - bool truncated; -} calypso_ef_list_t; + uint8_t data[APDU_RES_LEN]; + size_t len; + uint16_t sw; +} calypso_raw_response_t; typedef struct { uint16_t tag; @@ -199,15 +180,10 @@ typedef struct { bool tlv; } calypso_get_data_probe_t; -typedef struct { - uint8_t aid[CALYPSO_MAX_AID_LEN]; - size_t aid_len; -} calypso_app_identity_t; - typedef struct { size_t serial_count; uint8_t serials[CALYPSO_DUMP_FILENAME_MAX_SERIALS][CALYPSO_SERIAL_LEN]; -} calypso_dump_context_t; +} calypso_dump_filename_context_t; typedef struct { uint8_t p1; @@ -227,6 +203,63 @@ typedef struct { uint16_t le; } calypso_probe_select_le_t; +typedef struct { + uint16_t lid; + uint8_t sources; +} calypso_dump_lid_candidate_t; + +typedef struct { + calypso_dump_lid_candidate_t items[CALYPSO_DUMP_CANDIDATE_MAX]; + size_t count; +} calypso_dump_candidate_list_t; + +typedef struct { + uint16_t path[CALYPSO_DUMP_NODE_PATH_MAX]; + size_t path_len; + size_t depth; + bool from_root; + bool is_mf; + bool default_selection; + bool has_lid; + uint16_t lid; + bool has_seed_lid; + uint16_t seed_lid; +} calypso_dump_walk_context_t; + +typedef struct { + calypso_select_result_t selected; + bool default_selection; + uint8_t select_aid[CALYPSO_MAX_AID_LEN]; + size_t select_aid_len; + bool has_select_lid; + uint16_t select_lid; + calypso_raw_response_t select_fci; + calypso_raw_response_t select_fcp; + calypso_raw_response_t select_current_fcp; + calypso_raw_response_t get_data_fci; + calypso_raw_response_t get_data_fcp; + bool has_lid; + uint16_t lid; + uint8_t sources; +} calypso_dump_node_t; + +typedef struct { + uint8_t serial[CALYPSO_SERIAL_LEN]; + calypso_dump_node_t *nodes; + size_t node_count; + size_t node_capacity; +} calypso_dump_profile_t; + +typedef struct { + calypso_dump_profile_t items[CALYPSO_DUMP_FILENAME_MAX_SERIALS]; + size_t count; +} calypso_dump_profile_list_t; + +typedef struct { + json_t *nodes; + const calypso_dump_profile_t *profile; +} calypso_dump_json_context_t; + static calypso_resource_t calypso_manufacturers_resource = {CALYPSO_MANUFACTURERS_RESOURCE, NULL, false}; static calypso_resource_t calypso_ic_families_resource = {CALYPSO_IC_FAMILIES_RESOURCE, NULL, false}; static calypso_resource_t calypso_operators_resource = {CALYPSO_OPERATORS_RESOURCE, NULL, false}; @@ -236,18 +269,32 @@ static const char *calypso_json_lookup_name(calypso_resource_t *resource, uint32 static void calypso_set_selected_result(bool is_implicitly_selected, const uint8_t *aid, size_t aid_len, bool has_df_lid, uint16_t df_lid, const calypso_rf_info_t *rf, const uint8_t *fci_data, size_t fci_len, uint16_t sw, const calypso_fci_t *fci, calypso_select_result_t *selected); static bool calypso_fcp_default_lid(const calypso_fcp_t *fcp, uint16_t *lid); static bool calypso_get_current_ef_lid(bool verbose, uint16_t *lid); +static bool calypso_get_current_file_lid(bool verbose, uint16_t *lid); static bool calypso_read_sw_has_data(uint16_t sw, size_t read_len); static int calypso_get_data_object(uint16_t tag, uint8_t *out, size_t out_len, size_t *read_len, uint16_t *sw); static void calypso_print_hex_entry(const char *label, const uint8_t *data, size_t data_len, const char *ansi_color); static void calypso_reselect_exact_df_name(const calypso_select_result_t *selected, bool verbose); static void calypso_print_rf_info(const calypso_rf_info_t *rf); +static int calypso_exchange_apdu(sAPDU_t apdu, bool include_le, uint16_t le, uint8_t *out, size_t out_len, size_t *read_len, uint16_t *sw); +static int calypso_dump_reselect_base(const calypso_select_result_t *selected, const calypso_dump_walk_context_t *ctx, bool verbose); +static bool calypso_lid_is_valid(uint16_t lid); +static bool calypso_fcp_lid(const uint8_t *fcp, size_t fcp_len, uint16_t *lid); +static bool calypso_fcp_lid_with_hint(const uint8_t *fcp, size_t fcp_len, bool have_hint, uint16_t hint, uint16_t *lid); +static void calypso_dump_node_copy_raw(uint8_t *dst, size_t *dst_len, const uint8_t *src, size_t src_len, size_t dst_size); +static void calypso_dump_node_set_select_response(calypso_dump_node_t *node, const uint8_t *data, size_t data_len, uint16_t sw); +static void calypso_raw_response_set(calypso_raw_response_t *dst, const uint8_t *src, size_t src_len, uint16_t sw); +static size_t calypso_dump_node_aid(const calypso_dump_node_t *node, const uint8_t **aid); +static bool calypso_dump_node_first_fcp(const calypso_dump_node_t *node, const uint8_t **fcp, size_t *fcp_len); +static bool calypso_dump_node_known_lid(const calypso_dump_node_t *node, uint16_t *lid); +static void calypso_dump_node_init_from_selected(calypso_dump_node_t *node, const calypso_select_result_t *selected); +static void calypso_dump_apply_fci_identity(calypso_dump_node_t *node); +static void calypso_dump_apply_profile_node(calypso_dump_node_t *node, const calypso_dump_profile_t *profile); static int CmdHelp(const char *Cmd); // https://docs.keypop.org/keypop-calypso-card-cpp-api/latest-stable/namespacekeypop_1_1calypso_1_1card.html#aa274077fbdeafe85dfe208791490462f // https://gnupg.org/ftp/specs/OpenPGP-smart-card-application-2.0.pdf static const calypso_get_data_probe_t calypso_get_data_probes[] = { - {0x004F, "Current DF AID", true}, {0x0062, "FCP For Current File", true}, {0x006F, "FCI For Current DF", true}, {0x00C0, "EF List", true}, @@ -613,7 +660,7 @@ static bool calypso_json_parse_hex_uint(json_t *value, uint32_t max, uint32_t *o return false; } - while (isspace((unsigned char)*text)) { + while (isspace((unsigned char) * text)) { text++; } @@ -624,7 +671,7 @@ static bool calypso_json_parse_hex_uint(json_t *value, uint32_t max, uint32_t *o return false; } - while (isspace((unsigned char)*end)) { + while (isspace((unsigned char) * end)) { end++; } @@ -748,9 +795,8 @@ static int calypso_aid_specificity(bool prefix, bool generic, size_t aid_len) { return 2000 + (int)aid_len; } -static void calypso_find_aid_match(json_t *root, const uint8_t *aid, size_t aid_len, const char *source, bool fci_aid, calypso_aid_match_t *match) { +static void calypso_find_aid_match(json_t *root, const uint8_t *aid, size_t aid_len, bool fci_aid, calypso_aid_match_t *match) { memset(match, 0, sizeof(*match)); - match->source = source; if (root == NULL || aid == NULL || aid_len == 0) { return; @@ -785,12 +831,8 @@ static void calypso_find_aid_match(json_t *root, const uint8_t *aid, size_t aid_ } match->found = true; - match->aid_hex = calypso_json_string_get(data, "AID"); match->vendor = calypso_json_string_get(data, "Vendor"); match->name = calypso_json_string_get(data, "Name"); - match->country = calypso_json_string_get(data, "Country"); - match->description = calypso_json_string_get(data, "Description"); - match->type = calypso_json_string_get(data, "Type"); match->prefix = prefix; match->generic = generic; match->aid_len = (size_t)entry_aid_len; @@ -816,89 +858,13 @@ static const calypso_aid_match_t *calypso_best_aid_match(const calypso_aid_match return selected; } -static void calypso_aid_attribution_init(const calypso_select_result_t *selected, bool verbose, calypso_aid_attribution_t *attribution) { - memset(attribution, 0, sizeof(*attribution)); - - attribution->root = AIDSearchInit(verbose); - if (attribution->root == NULL) { - return; - } - - calypso_find_aid_match(attribution->root, selected->requested_aid, selected->requested_aid_len, selected->default_selection ? "default selection AID" : "selected AID", false, &attribution->selected_match); - if (selected->parsed.has_df_name) { - calypso_find_aid_match(attribution->root, selected->parsed.df_name, selected->parsed.df_name_len, "DF name", true, &attribution->df_name_match); - } - - attribution->best = calypso_best_aid_match(&attribution->selected_match, &attribution->df_name_match); -} - -static void calypso_aid_attribution_free(calypso_aid_attribution_t *attribution) { - if (attribution->root != NULL) { - AIDSearchFree(attribution->root); - } - - memset(attribution, 0, sizeof(*attribution)); -} - -static bool calypso_aid_match_same(const calypso_aid_match_t *a, const calypso_aid_match_t *b) { - if (a == NULL || b == NULL || a->found == false || b->found == false || a->aid_hex == NULL || b->aid_hex == NULL) { - return false; - } - - return strcmp(a->aid_hex, b->aid_hex) == 0; -} - -static void calypso_print_aid_match_line(const char *label, const calypso_aid_match_t *match) { - if (match == NULL || match->found == false) { - return; - } - - PrintAndLogEx(SUCCESS, "%s : " _YELLOW_("%s") "%s | %s | %s", - label, - match->aid_hex ? match->aid_hex : "", - match->prefix ? " (prefix)" : (match->generic ? " (generic)" : ""), - match->vendor ? match->vendor : "", - match->name ? match->name : ""); -} - -static const char *calypso_nonempty(const char *value) { - return value != NULL && value[0] != '\0' ? value : NULL; -} - -static void calypso_print_aid_attribution_details(const calypso_aid_attribution_t *attribution, bool verbose) { - if (attribution == NULL || attribution->root == NULL) { - return; - } - - const calypso_aid_match_t *best = attribution->best; - - if (verbose && best != NULL && best->found) { - PrintAndLogEx(SUCCESS, " AID source : " _YELLOW_("%s") "%s", best->source, best->prefix ? " (prefix)" : (best->generic ? " (generic)" : "")); - if (best->type) { - PrintAndLogEx(SUCCESS, " AID type : " _YELLOW_("%s"), best->type); - } - if (best->country) { - PrintAndLogEx(SUCCESS, " AID country : " _YELLOW_("%s"), best->country); - } - if (best->description) { - PrintAndLogEx(SUCCESS, " AID description : " _YELLOW_("%s"), best->description); - } - } - - if (verbose && attribution->selected_match.found && attribution->df_name_match.found && calypso_aid_match_same(&attribution->selected_match, &attribution->df_name_match) == false) { - PrintAndLogEx(INFO, " AID attribution : " _YELLOW_("%s match preferred"), best->source); - calypso_print_aid_match_line(" Selected AID ref", &attribution->selected_match); - calypso_print_aid_match_line(" DF name ref ", &attribution->df_name_match); - } -} - static bool calypso_df_name_matches_known_aid(json_t *root, const calypso_select_result_t *selected) { if (selected->parsed.has_df_name == false) { return false; } calypso_aid_match_t df_name_match; - calypso_find_aid_match(root, selected->parsed.df_name, selected->parsed.df_name_len, "DF name", true, &df_name_match); + calypso_find_aid_match(root, selected->parsed.df_name, selected->parsed.df_name_len, true, &df_name_match); return df_name_match.found; } @@ -907,9 +873,9 @@ static int calypso_select_attribution_score(json_t *root, const calypso_select_r calypso_aid_match_t df_name_match; memset(&df_name_match, 0, sizeof(df_name_match)); - calypso_find_aid_match(root, selected->requested_aid, selected->requested_aid_len, "selected AID", false, &selected_match); + calypso_find_aid_match(root, selected->requested_aid, selected->requested_aid_len, false, &selected_match); if (selected->parsed.has_df_name) { - calypso_find_aid_match(root, selected->parsed.df_name, selected->parsed.df_name_len, "DF name", true, &df_name_match); + calypso_find_aid_match(root, selected->parsed.df_name, selected->parsed.df_name_len, true, &df_name_match); } const calypso_aid_match_t *best = calypso_best_aid_match(&selected_match, &df_name_match); @@ -925,13 +891,20 @@ static int calypso_select_aid(const uint8_t *aid, size_t aid_len, bool verbose, bool has_df_lid = false; uint16_t df_lid = 0; - int res = Iso7816Select(CC_CONTACTLESS, false, true, (uint8_t *)aid, aid_len, select_response, sizeof(select_response), &select_response_len, &select_sw); + sAPDU_t apdu = {0x00, ISO7816_SELECT_FILE, 0x04, 0x00, (uint8_t)aid_len, (uint8_t *)aid}; + int res = calypso_exchange_apdu(apdu, true, 0, select_response, sizeof(select_response), &select_response_len, &select_sw); if (res != PM3_SUCCESS) { if (verbose) { PrintAndLogEx(DEBUG, "Select AID %s failed: %d", sprint_hex_inrow(aid, aid_len), res); } return res; } + if (select_sw == 0 && select_response_len == 0) { + if (verbose) { + PrintAndLogEx(DEBUG, "Select AID %s returned an empty RF/APDU response", sprint_hex_inrow(aid, aid_len)); + } + return PM3_EAPDU_FAIL; + } if (select_sw != ISO7816_OK && select_sw != 0x6283) { if (verbose) { @@ -948,7 +921,7 @@ static int calypso_select_aid(const uint8_t *aid, size_t aid_len, bool verbose, return PM3_SUCCESS; } - has_df_lid = calypso_get_current_ef_lid(verbose, &df_lid); + has_df_lid = calypso_get_current_file_lid(verbose, &df_lid); calypso_set_selected_result(false, aid, aid_len, has_df_lid, df_lid, rf, select_response, select_response_len, select_sw, &fci, selected); @@ -1121,13 +1094,26 @@ static void calypso_print_hex_ascii_line(const char *label, const uint8_t *data, } } -static void calypso_print_aid_match_summary(const calypso_aid_match_t *match) { - if (match == NULL || match->found == false) { +static const char *calypso_nonempty(const char *value) { + return value != NULL && value[0] != '\0' ? value : NULL; +} + +static void calypso_print_aid_info(const calypso_select_result_t *selected, bool verbose) { + json_t *root = AIDSearchInit(verbose); + if (root == NULL) { return; } - const char *vendor = calypso_nonempty(match->vendor); - const char *name = calypso_nonempty(match->name); + calypso_aid_match_t selected_match = {0}; + calypso_aid_match_t df_name_match = {0}; + calypso_find_aid_match(root, selected->requested_aid, selected->requested_aid_len, false, &selected_match); + if (selected->parsed.has_df_name) { + calypso_find_aid_match(root, selected->parsed.df_name, selected->parsed.df_name_len, true, &df_name_match); + } + + const calypso_aid_match_t *match = calypso_best_aid_match(&selected_match, &df_name_match); + const char *name = match != NULL ? calypso_nonempty(match->name) : NULL; + const char *vendor = match != NULL ? calypso_nonempty(match->vendor) : NULL; if (name != NULL && vendor != NULL) { PrintAndLogEx(SUCCESS, " AID info : " _YELLOW_("%s") " (" _YELLOW_("%s") ")", name, vendor); } else if (name != NULL) { @@ -1135,6 +1121,8 @@ static void calypso_print_aid_match_summary(const calypso_aid_match_t *match) { } else if (vendor != NULL) { PrintAndLogEx(SUCCESS, " AID info : " _YELLOW_("%s"), vendor); } + + AIDSearchFree(root); } static uint8_t calypso_icc_check_value(const uint8_t *data, size_t len) { @@ -1333,7 +1321,7 @@ static bool calypso_get_current_ef_lid(bool verbose, uint16_t *lid) { calypso_fcp_t fcp = {0}; if (calypso_read_sw_has_data(sw, response_len) && calypso_parse_fcp(response, response_len, &fcp)) { - return calypso_fcp_default_lid(&fcp, lid); + return calypso_fcp_lid(response, response_len, lid) || calypso_fcp_default_lid(&fcp, lid); } if (verbose) { PrintAndLogEx(DEBUG, "GET DATA 0062 did not return Calypso FCP (%04X - %s)", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xFF)); @@ -1366,6 +1354,75 @@ static int calypso_select_current_df_with_file_id_fallback(uint8_t *response, si return calypso_select_current_df(true, response, response_max, response_len, sw); } +static int calypso_select_current_file_fcp(bool verbose, uint8_t *out, size_t out_len, size_t *read_len, uint16_t *sw, uint16_t *lid, bool *has_lid) { + if (read_len == NULL || sw == NULL) { + return PM3_EINVARG; + } + + *read_len = 0; + *sw = 0; + if (has_lid != NULL) { + *has_lid = false; + } + if (lid != NULL) { + *lid = 0; + } + + uint8_t response[APDU_RES_LEN] = {0}; + size_t response_len = 0; + uint16_t response_sw = 0; + int res = calypso_select_current_df_with_file_id_fallback(response, sizeof(response), &response_len, &response_sw); + *sw = response_sw; + if (res != PM3_SUCCESS) { + return res; + } + if (calypso_select_sw_has_file(response_sw) == false) { + return PM3_SUCCESS; + } + + calypso_fcp_t fcp = {0}; + if (calypso_parse_fcp(response, response_len, &fcp) == false) { + if (verbose) { + PrintAndLogEx(DEBUG, "Current DF SELECT did not return Calypso FCP (%04X - %s)", response_sw, GetAPDUCodeDescription(response_sw >> 8, response_sw & 0xFF)); + } + return PM3_SUCCESS; + } + + *read_len = MIN(response_len, out_len); + if (out != NULL && *read_len > 0) { + memcpy(out, response, *read_len); + } + if (has_lid != NULL && lid != NULL) { + *has_lid = calypso_fcp_lid(response, response_len, lid) || calypso_fcp_default_lid(&fcp, lid); + } + return PM3_SUCCESS; +} + +static bool calypso_get_current_file_lid(bool verbose, uint16_t *lid) { + if (lid == NULL) { + return false; + } + + if (calypso_get_current_ef_lid(verbose, lid)) { + return true; + } + + size_t fcp_len = 0; + uint16_t sw = 0; + bool has_lid = false; + int res = calypso_select_current_file_fcp(verbose, NULL, 0, &fcp_len, &sw, lid, &has_lid); + if (res != PM3_SUCCESS) { + if (verbose) { + PrintAndLogEx(DEBUG, "Current DF SELECT exchange failed while reading LID: %d", res); + } + return false; + } + if (verbose && has_lid == false && calypso_select_sw_has_file(sw) == false) { + PrintAndLogEx(DEBUG, "Current DF SELECT did not select a file while reading LID (%04X - %s)", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xFF)); + } + return has_lid; +} + static int calypso_probe_current_df(const calypso_rf_info_t *rf, bool verbose, calypso_select_result_t *selected, bool *matched, bool *default_df_selected) { *matched = false; if (default_df_selected != NULL) { @@ -1409,7 +1466,7 @@ static int calypso_probe_current_df(const calypso_rf_info_t *rf, bool verbose, c } else { calypso_fcp_t fcp = {0}; if (calypso_parse_fcp(select_response, select_response_len, &fcp)) { - has_df_lid = calypso_fcp_default_lid(&fcp, &df_lid); + has_df_lid = calypso_fcp_lid(select_response, select_response_len, &df_lid) || calypso_fcp_default_lid(&fcp, &df_lid); } if (verbose) { PrintAndLogEx(DEBUG, "Current DF SELECT did not return Calypso FCI (%04X - %s)", select_response_sw, GetAPDUCodeDescription(select_response_sw >> 8, select_response_sw & 0xFF)); @@ -1440,7 +1497,7 @@ static int calypso_probe_current_df(const calypso_rf_info_t *rf, bool verbose, c } uint16_t get_data_lid = 0; - if (calypso_get_current_ef_lid(verbose, &get_data_lid)) { + if (calypso_get_current_file_lid(verbose, &get_data_lid)) { has_df_lid = true; df_lid = get_data_lid; } @@ -1479,20 +1536,60 @@ static int calypso_select_file_id_with_p1_fallback(uint16_t file_id, uint8_t *re (uint8_t)(file_id >> 8), (uint8_t)(file_id & 0xFF), }; - sAPDU_t apdu = {0x00, ISO7816_SELECT_FILE, CALYPSO_SELECT_FILE_ID_P1, CALYPSO_SELECT_FILE_ID_P2, sizeof(file_id_data), file_id_data}; + sAPDU_t apdu = {0x00, ISO7816_SELECT_FILE, CALYPSO_SELECT_CURRENT_DF_P1, CALYPSO_SELECT_CURRENT_DF_P2, sizeof(file_id_data), file_id_data}; int res = calypso_exchange_apdu_with_cla_fallback(apdu, true, 0, response, response_max, response_len, sw); if (res != PM3_SUCCESS || calypso_select_sw_has_file(*sw)) { return res; } - // Prefer ISO-style file-id selection, but retry the Calypso current-DF LID form when rejected. + // Prefer modern Calypso relative-path LID selection, then retry ISO-style file-id lookup. *response_len = 0; *sw = 0; - apdu.P1 = CALYPSO_SELECT_CURRENT_DF_P1; - apdu.P2 = CALYPSO_SELECT_CURRENT_DF_P2; + apdu.P1 = CALYPSO_SELECT_FILE_ID_P1; + apdu.P2 = CALYPSO_SELECT_FILE_ID_P2; return calypso_exchange_apdu_with_cla_fallback(apdu, true, 0, response, response_max, response_len, sw); } +static int calypso_select_file_path(const uint16_t *path, size_t path_len, uint8_t *response, size_t response_max, size_t *response_len, uint16_t *sw) { + if (path == NULL || path_len == 0 || path_len > (UINT8_MAX / 2)) { + return PM3_EINVARG; + } + + uint8_t path_data[CALYPSO_DUMP_NODE_PATH_MAX * 2 + 2] = {0}; + if (path_len * 2 > sizeof(path_data)) { + return PM3_EINVARG; + } + + for (size_t i = 0; i < path_len; i++) { + path_data[i * 2] = (uint8_t)(path[i] >> 8); + path_data[i * 2 + 1] = (uint8_t)(path[i] & 0xFF); + } + + sAPDU_t apdu = { + 0x00, + ISO7816_SELECT_FILE, + CALYPSO_SELECT_PATH_P1, + CALYPSO_SELECT_PATH_P2, + (uint8_t)(path_len * 2), + path_data + }; + return calypso_exchange_apdu_with_cla_fallback(apdu, true, 0, response, response_max, response_len, sw); +} + +static int calypso_select_file_path_then_id_fallback(const uint16_t *path, size_t path_len, uint16_t file_id, uint8_t *response, size_t response_max, size_t *response_len, uint16_t *sw) { + if (path != NULL && path_len > 0) { + int res = calypso_select_file_path(path, path_len, response, response_max, response_len, sw); + if (res != PM3_SUCCESS || calypso_select_sw_has_file(*sw)) { + return res; + } + + *response_len = 0; + *sw = 0; + } + + return calypso_select_file_id_with_p1_fallback(file_id, response, response_max, response_len, sw); +} + static int calypso_select_file_by_id(uint16_t file_id, uint16_t *sw) { uint8_t response[APDU_RES_LEN] = {0}; size_t response_len = 0; @@ -1568,7 +1665,6 @@ static bool calypso_should_try_master_file_icc(const calypso_select_result_t *se } static bool calypso_read_icc_from_master_file(const calypso_select_result_t *selected, bool verbose, uint8_t *icc, size_t icc_len, size_t *read_len, uint16_t *sw) { - static const uint8_t calypso_mf_aid[] = {0x33, 0x4D, 0x54, 0x52, 0x2E, 0x49, 0x43, 0x41}; const uint8_t *fci_serial = selected->parsed.has_serial ? selected->parsed.serial : NULL; calypso_select_result_t mf = {0}; bool matched = false; @@ -1636,7 +1732,7 @@ static int calypso_read_ticketing_environment(uint8_t *env, size_t env_len, size return calypso_read_ticketing_environment_file(env, env_len, read_len, sw); } -static void calypso_dump_context_add_serial(calypso_dump_context_t *ctx, const calypso_select_result_t *selected) { +static void calypso_dump_filename_add_serial(calypso_dump_filename_context_t *ctx, const calypso_select_result_t *selected) { if (ctx == NULL || selected == NULL || selected->parsed.has_serial == false) { return; } @@ -1655,7 +1751,7 @@ static void calypso_dump_context_add_serial(calypso_dump_context_t *ctx, const c ctx->serial_count++; } -static void calypso_dump_default_filename(const calypso_select_result_t *selected, const calypso_dump_context_t *ctx, char *filename, size_t filename_len) { +static void calypso_dump_default_filename(const calypso_select_result_t *selected, const calypso_dump_filename_context_t *ctx, char *filename, size_t filename_len) { bool hce_filename = selected != NULL && selected->parsed.has_serial && calypso_serial_is_hce(selected->parsed.serial); if (ctx != NULL && ctx->serial_count > 0) { @@ -1709,122 +1805,12 @@ static void calypso_json_set_hex(json_t *obj, const char *key, const uint8_t *da json_object_set_new(obj, key, json_string(sprint_hex_inrow(data, data_len))); } -static void calypso_json_set_sw(json_t *obj, const char *key, uint16_t sw) { +static void calypso_json_set_lid(json_t *obj, const char *key, uint16_t lid) { char hex[5] = {0}; - snprintf(hex, sizeof(hex), "%04X", sw); + snprintf(hex, sizeof(hex), "%04X", lid); json_object_set_new(obj, key, json_string(hex)); } -static void calypso_json_add_record(json_t *records, uint8_t record, const uint8_t *data, size_t data_len) { - json_t *entry = json_object(); - json_object_set_new(entry, "record", json_integer(record)); - calypso_json_set_hex(entry, "data", data, data_len); - json_array_append_new(records, entry); -} - -static void calypso_json_add_select(json_t *root, const calypso_select_result_t *selected) { - json_object_set_new(root, "type", json_string("calypso")); - calypso_json_set_sw(root, "selectStatus", selected->sw); - calypso_json_set_hex(root, "selectAid", selected->requested_aid, selected->requested_aid_len); - if (selected->fci_len > 0) { - calypso_json_set_hex(root, "fci", selected->fci, selected->fci_len); - } - if (selected->parsed.has_df_name) { - calypso_json_set_hex(root, "fciDfName", selected->parsed.df_name, selected->parsed.df_name_len); - } - if (selected->parsed.has_serial) { - calypso_json_set_hex(root, "serial", selected->parsed.serial, sizeof(selected->parsed.serial)); - } - if (selected->parsed.has_startup) { - calypso_json_set_hex(root, "startupInfo", selected->parsed.startup, sizeof(selected->parsed.startup)); - } -} - -static void calypso_json_add_get_data(json_t *entries, const calypso_get_data_probe_t *probe, const uint8_t *data, size_t data_len) { - char tag[5] = {0}; - snprintf(tag, sizeof(tag), "%04X", probe->tag); - - json_t *entry = json_object(); - json_object_set_new(entry, "tag", json_string(tag)); - json_object_set_new(entry, "name", json_string(probe->name)); - calypso_json_set_hex(entry, "data", data, data_len); - json_array_append_new(entries, entry); -} - -static void calypso_ef_list_add_lid(calypso_ef_list_t *ef_list, uint16_t lid) { - if (ef_list == NULL) { - return; - } - - for (size_t i = 0; i < ef_list->count; i++) { - if (ef_list->lids[i] == lid) { - return; - } - } - - if (ef_list->count >= ARRAYLEN(ef_list->lids)) { - ef_list->truncated = true; - return; - } - - ef_list->lids[ef_list->count++] = lid; -} - -static void calypso_parse_ef_list_entries(const uint8_t *data, size_t data_len, calypso_ef_list_t *ef_list) { - const unsigned char *p = data; - size_t left = data_len; - - while (left > 0) { - struct tlv entry = {0}; - if (tlv_parse_tl(&p, &left, &entry) == false || entry.len > left) { - return; - } - - if (entry.tag == 0xC1 && entry.len >= 2) { - uint16_t lid = ((uint16_t)p[0] << 8) | p[1]; - calypso_ef_list_add_lid(ef_list, lid); - } - - p += entry.len; - left -= entry.len; - } -} - -static void calypso_parse_ef_list_object(const uint8_t *data, size_t data_len, calypso_ef_list_t *ef_list) { - const unsigned char *p = data; - size_t left = data_len; - - while (left > 0) { - struct tlv tlv = {0}; - if (tlv_parse_tl(&p, &left, &tlv) == false || tlv.len > left) { - return; - } - - if (tlv.tag == 0xC0) { - calypso_parse_ef_list_entries(p, tlv.len, ef_list); - } else if (tlv.tag == 0xC1 && tlv.len >= 2) { - uint16_t lid = ((uint16_t)p[0] << 8) | p[1]; - calypso_ef_list_add_lid(ef_list, lid); - } - - p += tlv.len; - left -= tlv.len; - } -} - -static bool calypso_ef_list_contains_lid(const calypso_ef_list_t *ef_list, uint16_t lid) { - if (ef_list == NULL) { - return false; - } - - for (size_t i = 0; i < ef_list->count; i++) { - if (ef_list->lids[i] == lid) { - return true; - } - } - return false; -} - static void calypso_print_get_data_object(const calypso_get_data_probe_t *probe, const uint8_t *data, size_t data_len) { char label[64] = {0}; snprintf(label, sizeof(label), " %04X %-*s : ", probe->tag, CALYPSO_GET_DATA_NAME_WIDTH, probe->name); @@ -1869,249 +1855,6 @@ static void calypso_print_info_data_objects(void) { } } -static size_t calypso_probe_get_data_objects(json_t *entries, bool print_results, bool verbose, calypso_ef_list_t *ef_list) { - size_t found = 0; - - if (print_results || verbose) { - PrintAndLogEx(INFO, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Get Data") " ------------------------------"); - } - - for (size_t i = 0; i < ARRAYLEN(calypso_get_data_probes); i++) { - const calypso_get_data_probe_t *probe = &calypso_get_data_probes[i]; - uint8_t response[APDU_RES_LEN] = {0}; - size_t response_len = 0; - uint16_t sw = 0; - int res = calypso_get_data_object(probe->tag, response, sizeof(response), &response_len, &sw); - - if (res != PM3_SUCCESS) { - if (verbose) { - PrintAndLogEx(INFO, " %04X %-*s : exchange failed (%d)", probe->tag, CALYPSO_GET_DATA_NAME_WIDTH, probe->name, res); - } - continue; - } - - if (sw == ISO7816_INS_NOT_SUPPORTED) { - if (verbose) { - PrintAndLogEx(INFO, " %04X %-*s : " _YELLOW_("%04X") " - %s", probe->tag, CALYPSO_GET_DATA_NAME_WIDTH, probe->name, sw, GetAPDUCodeDescription(sw >> 8, sw & 0xFF)); - } - break; - } - - if (calypso_read_sw_has_data(sw, response_len)) { - if (print_results || verbose) { - calypso_print_get_data_object(probe, response, response_len); - if (verbose && probe->tlv) { - TLVPrintFromBuffer(response, (int)response_len); - } - } - if (entries != NULL) { - calypso_json_add_get_data(entries, probe, response, response_len); - } - if (probe->tag == 0x00C0) { - calypso_parse_ef_list_object(response, response_len, ef_list); - } - found++; - continue; - } - - if (verbose) { - PrintAndLogEx(INFO, " %04X %-*s : " _YELLOW_("%04X") " - %s", probe->tag, CALYPSO_GET_DATA_NAME_WIDTH, probe->name, sw, GetAPDUCodeDescription(sw >> 8, sw & 0xFF)); - } - } - - return found; -} - -static const char *calypso_file_name_for_sfi(uint8_t sfi) { - json_t *root = calypso_json_resource_root(&calypso_nodes_resource); - if (root == NULL) { - return NULL; - } - - size_t index; - json_t *entry; - json_array_foreach(root, index, entry) { - calypso_file_ref_t file = {0}; - if (calypso_json_file_ref_parse(entry, &file) && file.sfi == sfi) { - return file.name; - } - } - return NULL; -} - -static void calypso_file_path_string(const calypso_file_ref_t *file, char *out, size_t out_len) { - if (out_len == 0) { - return; - } - - size_t pos = 0; - for (size_t i = 0; i < file->path_len; i++) { - int written = snprintf(out + pos, out_len - pos, "%s%04X", i == 0 ? "" : ":", file->path[i]); - if (written < 0 || (size_t)written >= out_len - pos) { - break; - } - pos += (size_t)written; - } -} - -static uint16_t calypso_file_ref_leaf_lid(const calypso_file_ref_t *file) { - if (file == NULL || file->path_len == 0) { - return 0; - } - return file->path[file->path_len - 1]; -} - -static bool calypso_file_ref_path_equals(const calypso_file_ref_t *file, const uint16_t *path, size_t path_len) { - if (file == NULL || path == NULL || file->path_len != path_len) { - return false; - } - return memcmp(file->path, path, path_len * sizeof(path[0])) == 0; -} - -static bool calypso_lid_is_known(uint16_t lid) { - json_t *root = calypso_json_resource_root(&calypso_nodes_resource); - if (root == NULL) { - return false; - } - - size_t index; - json_t *entry; - json_array_foreach(root, index, entry) { - calypso_file_ref_t file = {0}; - if (calypso_json_file_ref_parse(entry, &file) && calypso_file_ref_leaf_lid(&file) == lid) { - return true; - } - } - return false; -} - -static bool calypso_lid_seen(const uint16_t *lids, size_t count, uint16_t lid) { - for (size_t i = 0; i < count; i++) { - if (lids[i] == lid) { - return true; - } - } - return false; -} - -static calypso_file_candidate_t *calypso_find_file_candidate_by_path(calypso_file_candidate_t *candidates, size_t count, const uint16_t *path, size_t path_len) { - for (size_t i = 0; i < count; i++) { - if (calypso_file_ref_path_equals(&candidates[i].ref, path, path_len)) { - return &candidates[i]; - } - } - return NULL; -} - -static bool calypso_add_file_candidate(calypso_file_candidate_t *candidates, size_t capacity, size_t *count, const char *name, const uint16_t *path, size_t path_len, uint8_t source) { - if (candidates == NULL || count == NULL || path == NULL || path_len == 0 || path_len > CALYPSO_DUMP_PATH_MAX) { - return false; - } - - calypso_file_candidate_t *existing = calypso_find_file_candidate_by_path(candidates, *count, path, path_len); - if (existing != NULL) { - existing->source |= source; - return true; - } - - if (*count >= capacity) { - return false; - } - - calypso_file_candidate_t *candidate = &candidates[*count]; - memset(candidate, 0, sizeof(*candidate)); - if (name == NULL) { - snprintf(candidate->name_storage, sizeof(candidate->name_storage), "EF_%04X", path[path_len - 1]); - candidate->ref.name = candidate->name_storage; - } else { - candidate->ref.name = name; - } - candidate->ref.sfi = -1; - memcpy(candidate->ref.path, path, path_len * sizeof(path[0])); - candidate->ref.path_len = path_len; - candidate->source = source; - (*count)++; - return true; -} - -static size_t calypso_infer_lid_path(uint16_t lid, uint16_t *path) { - if (path == NULL) { - return 0; - } - - uint16_t parent = lid & 0xFF00; - uint8_t high = (uint8_t)(lid >> 8); - if (parent != 0x0000 && high != 0x2F && high != 0x3F) { - path[0] = parent; - path[1] = lid; - return 2; - } - - path[0] = lid; - return 1; -} - -static size_t calypso_build_lid_file_candidates(const calypso_ef_list_t *ef_list, calypso_file_candidate_t *candidates, size_t capacity) { - size_t count = 0; - - json_t *root = calypso_json_resource_root(&calypso_nodes_resource); - if (root != NULL) { - size_t index; - json_t *entry; - json_array_foreach(root, index, entry) { - calypso_file_ref_t file = {0}; - if (calypso_json_file_ref_parse(entry, &file) == false) { - continue; - } - - uint8_t source = CALYPSO_FILE_SOURCE_KNOWN; - if (calypso_ef_list_contains_lid(ef_list, calypso_file_ref_leaf_lid(&file))) { - source |= CALYPSO_FILE_SOURCE_EF_LIST; - } - calypso_add_file_candidate(candidates, capacity, &count, file.name, file.path, file.path_len, source); - } - } - - if (ef_list == NULL) { - return count; - } - - for (size_t i = 0; i < ef_list->count; i++) { - uint16_t lid = ef_list->lids[i]; - if (calypso_lid_is_known(lid)) { - continue; - } - - uint16_t inferred_path[CALYPSO_DUMP_PATH_MAX] = {0}; - size_t inferred_path_len = calypso_infer_lid_path(lid, inferred_path); - calypso_add_file_candidate(candidates, capacity, &count, NULL, inferred_path, inferred_path_len, CALYPSO_FILE_SOURCE_EF_LIST); - - uint16_t direct_path[CALYPSO_DUMP_PATH_MAX] = {lid}; - if (inferred_path_len != 1 || inferred_path[0] != lid) { - calypso_add_file_candidate(candidates, capacity, &count, NULL, direct_path, 1, CALYPSO_FILE_SOURCE_EF_LIST); - } - } - - return count; -} - -static int calypso_read_binary_sfi(uint8_t sfi, uint8_t *out, size_t out_len, size_t *read_len, uint16_t *sw) { - uint8_t response[APDU_RES_LEN] = {0}; - size_t response_len = 0; - sAPDU_t apdu = {0x00, CALYPSO_READ_BINARY, (uint8_t)(0x80 | sfi), 0x00, 0, NULL}; - int res = calypso_exchange_apdu_with_cla_fallback(apdu, true, 0, response, sizeof(response), &response_len, sw); - - if (res != PM3_SUCCESS || calypso_read_sw_has_data(*sw, response_len) == false) { - *read_len = 0; - return res; - } - - *read_len = MIN(response_len, out_len); - memcpy(out, response, *read_len); - return PM3_SUCCESS; -} - static int calypso_read_current_binary(uint8_t *out, size_t out_len, size_t *read_len, uint16_t *sw) { uint8_t response[APDU_RES_LEN] = {0}; size_t response_len = 0; @@ -2128,67 +1871,25 @@ static int calypso_read_current_binary(uint8_t *out, size_t out_len, size_t *rea return PM3_SUCCESS; } -static int calypso_select_file_element(uint16_t file_id, uint8_t *fcp, size_t fcp_len, size_t *read_len, uint16_t *sw) { - uint8_t response[APDU_RES_LEN] = {0}; - size_t response_len = 0; - int res = calypso_select_file_id_with_p1_fallback(file_id, response, sizeof(response), &response_len, sw); - - *read_len = MIN(response_len, fcp_len); - memcpy(fcp, response, *read_len); - return res; -} - -static int calypso_select_file_path(const calypso_file_ref_t *file, uint8_t *fcp, size_t fcp_len, size_t *read_len, uint16_t *sw) { - uint8_t response[APDU_RES_LEN] = {0}; - size_t response_len = 0; - uint16_t current_df_sw = 0; - calypso_select_current_df_with_file_id_fallback(response, sizeof(response), &response_len, ¤t_df_sw); - - size_t last_len = 0; - uint16_t last_sw = 0; - int res = PM3_SUCCESS; - for (size_t i = 0; i < file->path_len; i++) { - last_len = 0; - last_sw = 0; - res = calypso_select_file_element(file->path[i], fcp, fcp_len, &last_len, &last_sw); - if (res != PM3_SUCCESS || calypso_select_sw_has_file(last_sw) == false) { - break; - } - } - - if (res == PM3_SUCCESS && calypso_select_sw_has_file(last_sw)) { - *read_len = last_len; - *sw = last_sw; - return PM3_SUCCESS; - } - - if (res != PM3_SUCCESS) { - *read_len = 0; - *sw = last_sw; - return res; - } - - *read_len = 0; - *sw = last_sw; - return PM3_SUCCESS; -} - -static void calypso_print_hex_entry(const char *label, const uint8_t *data, size_t data_len, const char *ansi_color) { +static void calypso_print_hex_entry_wrapped(const char *label, const uint8_t *data, size_t data_len, const char *ansi_color, size_t break_len) { if (label == NULL || data == NULL || data_len == 0) { return; } + if (break_len == 0) { + break_len = CALYPSO_HEX_ENTRY_BREAK; + } if (ansi_color == NULL) { ansi_color = ""; } const char *suffix = ansi_color[0] == '\0' ? "" : AEND; - if (data_len <= CALYPSO_HEX_ENTRY_INLINE_MAX) { + if (data_len <= break_len) { PrintAndLogEx(SUCCESS, "%s%s%s%s", label, ansi_color, sprint_hex(data, data_len), suffix); return; } - size_t first_len = MIN(data_len, CALYPSO_HEX_ENTRY_BREAK); + size_t first_len = MIN(data_len, break_len); PrintAndLogEx(SUCCESS, "%s%s%s%s", label, ansi_color, sprint_hex(data, first_len), suffix); char prefix[128] = {0}; @@ -2199,251 +1900,30 @@ static void calypso_print_hex_entry(const char *label, const uint8_t *data, size } memcpy_filter_ansi(visible_label, label, label_len, true); visible_label[sizeof(visible_label) - 1] = '\0'; - size_t label_width = strlen(visible_label); + size_t visible_len = strlen(visible_label); + size_t decoration_len = 0; + char *last_pipe = strrchr(visible_label, '|'); + if (last_pipe != NULL) { + decoration_len = (size_t)(last_pipe - visible_label) + 1; + while (visible_label[decoration_len] == ' ') { + decoration_len++; + } + } size_t color_len = strlen(ansi_color); if (color_len >= sizeof(prefix)) { color_len = sizeof(prefix) - 1; } - size_t spaces = MIN(label_width, sizeof(prefix) - color_len - 1); - memset(prefix, ' ', spaces); - memcpy(prefix + spaces, ansi_color, color_len); - print_hex_noascii_break_ex(data + first_len, data_len - first_len, CALYPSO_HEX_ENTRY_BREAK, prefix, ' ', suffix); + visible_len = MIN(visible_len, sizeof(prefix) - color_len - 1); + decoration_len = MIN(decoration_len, visible_len); + memcpy(prefix, visible_label, decoration_len); + memset(prefix + decoration_len, ' ', visible_len - decoration_len); + size_t pos = visible_len; + memcpy(prefix + pos, ansi_color, color_len); + print_hex_noascii_break_ex(data + first_len, data_len - first_len, break_len, prefix, ' ', suffix); } -static void calypso_dump_print_record_entry(long long record, const uint8_t *data, size_t data_len) { - char label[64] = {0}; - snprintf(label, sizeof(label), " record " _GREEN_("%03lld") " : ", record); - calypso_print_hex_entry(label, data, data_len, ANSI_GREEN); -} - -static bool calypso_dump_print_record(uint8_t record, const uint8_t *data, size_t data_len, json_t *records, bool print_record) { - if (data_len == 0) { - return false; - } - - if (print_record) { - calypso_dump_print_record_entry(record, data, data_len); - } - if (records != NULL) { - calypso_json_add_record(records, record, data, data_len); - } - return true; -} - -static void calypso_dump_print_json_records(json_t *records) { - if (records == NULL) { - return; - } - - size_t index = 0; - json_t *entry = NULL; - json_array_foreach(records, index, entry) { - json_t *record_value = json_object_get(entry, "record"); - json_t *data_value = json_object_get(entry, "data"); - if (json_is_integer(record_value) == false || json_is_string(data_value) == false) { - continue; - } - const char *hex = json_string_value(data_value); - size_t hex_len = strlen(hex); - if ((hex_len & 1) || hex_len / 2 > APDU_RES_LEN) { - continue; - } - - uint8_t data[APDU_RES_LEN] = {0}; - size_t data_len = 0; - if (hexstr_to_byte_array(hex, data, &data_len) == false) { - continue; - } - calypso_dump_print_record_entry((long long)json_integer_value(record_value), data, data_len); - } -} - -static bool calypso_dump_read_records(bool sfi_mode, uint8_t sfi, json_t *records, bool print_records, bool verbose, size_t *record_count, int *first_error) { - bool found = false; - - for (uint16_t record = 1; record <= 0xFF; record++) { - uint8_t data[APDU_RES_LEN] = {0}; - size_t data_len = 0; - uint16_t sw = 0; - int res = sfi_mode ? - calypso_read_sfi_record(sfi, (uint8_t)record, 0, data, sizeof(data), &data_len, &sw) : - calypso_read_current_record((uint8_t)record, 0, data, sizeof(data), &data_len, &sw); - if (res == PM3_SUCCESS && calypso_read_sw_has_data(sw, data_len) == false && calypso_read_sw_is_unavailable(sw) == false) { - data_len = 0; - sw = 0; - res = sfi_mode ? - calypso_read_sfi_record(sfi, (uint8_t)record, CALYPSO_LEGACY_RECORD_LEN, data, sizeof(data), &data_len, &sw) : - calypso_read_current_record((uint8_t)record, CALYPSO_LEGACY_RECORD_LEN, data, sizeof(data), &data_len, &sw); - } - - if (res != PM3_SUCCESS) { - if (first_error != NULL && *first_error == PM3_SUCCESS) { - *first_error = res; - } - return found; - } - - if (calypso_read_sw_has_data(sw, data_len)) { - if (data_len == 0) { - if (verbose) { - PrintAndLogEx(INFO, " record %03u stopped (empty response)", record); - } - return found; - } - found |= calypso_dump_print_record((uint8_t)record, data, data_len, records, print_records); - (*record_count)++; - continue; - } - - if (calypso_read_sw_is_eof(sw) || calypso_read_sw_is_unavailable(sw)) { - if (verbose && found == false && sw != 0) { - PrintAndLogEx(INFO, " records unavailable (%04X - %s)", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xFF)); - } - return found; - } - - if (verbose) { - PrintAndLogEx(INFO, " record %03u stopped (%04X - %s)", record, sw, GetAPDUCodeDescription(sw >> 8, sw & 0xFF)); - } - return found; - } - - return found; -} - -static bool calypso_dump_sfi(uint8_t sfi, json_t *sfi_files, bool verbose, size_t *file_count, size_t *record_count, int *first_error) { - uint8_t binary[APDU_RES_LEN] = {0}; - size_t binary_len = 0; - uint16_t binary_sw = 0; - int res = calypso_read_binary_sfi(sfi, binary, sizeof(binary), &binary_len, &binary_sw); - if (res != PM3_SUCCESS) { - if (first_error != NULL && *first_error == PM3_SUCCESS) { - *first_error = res; - } - return false; - } - - json_t *file = json_object(); - json_t *records = json_array(); - json_object_set_new(file, "sfi", json_integer(sfi)); - const char *name = calypso_file_name_for_sfi(sfi); - if (name != NULL) { - json_object_set_new(file, "name", json_string(name)); - } - - bool has_binary = calypso_read_sw_has_data(binary_sw, binary_len) && binary_len > 0; - bool has_records = false; - if (has_binary) { - calypso_json_set_hex(file, "binary", binary, binary_len); - } - - has_records = calypso_dump_read_records(true, sfi, records, false, false, record_count, first_error); - if (json_array_size(records) > 0) { - json_object_set_new(file, "records", records); - } else { - json_decref(records); - } - - if (has_binary == false && has_records == false) { - if (verbose && binary_sw != 0 && calypso_read_sw_is_unavailable(binary_sw) == false) { - PrintAndLogEx(INFO, " SFI %02X unavailable (%04X - %s)", sfi, binary_sw, GetAPDUCodeDescription(binary_sw >> 8, binary_sw & 0xFF)); - } - json_decref(file); - return false; - } - - PrintAndLogEx(INFO, ""); - if (name != NULL) { - PrintAndLogEx(INFO, "--- " _CYAN_("SFI %02X") " (%s) ----------------------------", sfi, name); - } else { - PrintAndLogEx(INFO, "--- " _CYAN_("SFI %02X") " -----------------------------------", sfi); - } - if (has_binary) { - calypso_print_hex_entry(" binary : ", binary, binary_len, ANSI_GREEN); - } - json_t *records_to_print = json_object_get(file, "records"); - calypso_dump_print_json_records(records_to_print); - if (has_records == false && verbose) { - calypso_dump_read_records(true, sfi, NULL, false, verbose, record_count, first_error); - } - - json_array_append_new(sfi_files, file); - (*file_count)++; - return true; -} - -static bool calypso_dump_file_path(const calypso_file_ref_t *ref, uint8_t source, json_t *files, bool verbose, size_t *file_count, size_t *record_count, int *first_error) { - uint8_t fcp[APDU_RES_LEN] = {0}; - size_t fcp_len = 0; - uint16_t select_sw = 0; - int res = calypso_select_file_path(ref, fcp, sizeof(fcp), &fcp_len, &select_sw); - if (res != PM3_SUCCESS) { - if (first_error != NULL && *first_error == PM3_SUCCESS) { - *first_error = res; - } - return false; - } - - if (calypso_select_sw_has_file(select_sw) == false) { - if (verbose && calypso_read_sw_is_unavailable(select_sw) == false) { - char path[16] = {0}; - calypso_file_path_string(ref, path, sizeof(path)); - PrintAndLogEx(INFO, " File %s unavailable (%04X - %s)", path, select_sw, GetAPDUCodeDescription(select_sw >> 8, select_sw & 0xFF)); - } - return false; - } - - uint8_t binary[APDU_RES_LEN] = {0}; - size_t binary_len = 0; - uint16_t binary_sw = 0; - res = calypso_read_current_binary(binary, sizeof(binary), &binary_len, &binary_sw); - if (res != PM3_SUCCESS) { - if (first_error != NULL && *first_error == PM3_SUCCESS) { - *first_error = res; - } - return false; - } - - json_t *file = json_object(); - json_t *records = json_array(); - char path[16] = {0}; - calypso_file_path_string(ref, path, sizeof(path)); - json_object_set_new(file, "name", json_string(ref->name)); - json_object_set_new(file, "path", json_string(path)); - if (fcp_len > 0) { - calypso_json_set_hex(file, "fcp", fcp, fcp_len); - } - if (calypso_read_sw_has_data(binary_sw, binary_len) && binary_len > 0) { - calypso_json_set_hex(file, "binary", binary, binary_len); - } - - PrintAndLogEx(INFO, ""); - if ((source & CALYPSO_FILE_SOURCE_KNOWN) && (source & CALYPSO_FILE_SOURCE_EF_LIST)) { - PrintAndLogEx(INFO, "--- " _CYAN_("%s") " (%s) (known, ef list) --------------------", ref->name, path); - } else if (source & CALYPSO_FILE_SOURCE_EF_LIST) { - PrintAndLogEx(INFO, "--- " _CYAN_("%s") " (%s) (" _YELLOW_("ef list") ") --------------------", ref->name, path); - } else { - PrintAndLogEx(INFO, "--- " _CYAN_("%s") " (%s) (known) --------------------", ref->name, path); - } - if (fcp_len > 0) { - calypso_print_hex_entry(" fcp : ", fcp, fcp_len, ANSI_YELLOW); - } - if (calypso_read_sw_has_data(binary_sw, binary_len) && binary_len > 0) { - calypso_print_hex_entry(" binary : ", binary, binary_len, ANSI_GREEN); - } else if (verbose && binary_sw != 0 && calypso_read_sw_is_unavailable(binary_sw) == false) { - PrintAndLogEx(INFO, " binary unavailable (%04X - %s)", binary_sw, GetAPDUCodeDescription(binary_sw >> 8, binary_sw & 0xFF)); - } - - calypso_dump_read_records(false, 0, records, true, verbose, record_count, first_error); - if (json_array_size(records) > 0) { - json_object_set_new(file, "records", records); - } else { - json_decref(records); - } - - json_array_append_new(files, file); - (*file_count)++; - return true; +static void calypso_print_hex_entry(const char *label, const uint8_t *data, size_t data_len, const char *ansi_color) { + calypso_print_hex_entry_wrapped(label, data, data_len, ansi_color, CALYPSO_HEX_ENTRY_BREAK); } static void calypso_reselect_exact_df_name(const calypso_select_result_t *selected, bool verbose) { @@ -2650,13 +2130,11 @@ static void calypso_print_rf_info(const calypso_rf_info_t *rf) { } } -static void calypso_print_select_info(const calypso_select_result_t *selected, bool verbose) { - calypso_aid_attribution_t attribution; - calypso_aid_attribution_init(selected, verbose, &attribution); - const calypso_aid_match_t *aid_line_match = attribution.best != NULL && attribution.best->found ? attribution.best : NULL; - - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Calypso Info") " ----------------------------"); +static void calypso_print_select_info_ex(const calypso_select_result_t *selected, bool verbose, bool header) { + if (header) { + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Calypso Info") " ----------------------------"); + } if (selected->requested_aid_len > 0) { calypso_print_hex_ascii_line(selected->default_selection ? " Default AID : " : " Selected AID : ", selected->requested_aid, selected->requested_aid_len); } @@ -2671,11 +2149,9 @@ static void calypso_print_select_info(const calypso_select_result_t *selected, b if (selected->parsed.has_df_name && selected->default_selection == false) { calypso_print_hex_ascii_line(" DF Name : ", selected->parsed.df_name, selected->parsed.df_name_len); } - calypso_print_aid_match_summary(aid_line_match); - calypso_print_aid_attribution_details(&attribution, verbose); + calypso_print_aid_info(selected, verbose); if (calypso_selected_has_fci_info(selected) == false) { - calypso_aid_attribution_free(&attribution); return; } @@ -2690,155 +2166,1998 @@ static void calypso_print_select_info(const calypso_select_result_t *selected, b } calypso_print_startup(selected->parsed.startup); - - if (verbose) { - PrintAndLogEx(INFO, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("FCI") " -------------------------------------"); - PrintAndLogEx(SUCCESS, " FCI raw : " _YELLOW_("%s"), sprint_hex(selected->fci, selected->fci_len)); - TLVPrintFromBuffer((uint8_t *)selected->fci, (int)selected->fci_len); - } - - calypso_aid_attribution_free(&attribution); } -static void calypso_select_identity(const calypso_select_result_t *selected, calypso_app_identity_t *identity) { - memset(identity, 0, sizeof(*identity)); - - const uint8_t *aid = selected->requested_aid; - size_t aid_len = selected->requested_aid_len; - if (selected->parsed.has_df_name && selected->parsed.df_name_len > 0) { - aid = selected->parsed.df_name; - aid_len = selected->parsed.df_name_len; - } - - identity->aid_len = MIN(aid_len, sizeof(identity->aid)); - memcpy(identity->aid, aid, identity->aid_len); +static void calypso_print_select_info(const calypso_select_result_t *selected, bool verbose) { + calypso_print_select_info_ex(selected, verbose, true); } -static bool calypso_dump_identity_seen(const calypso_app_identity_t *seen, size_t seen_count, const calypso_select_result_t *selected) { - calypso_app_identity_t identity = {0}; - calypso_select_identity(selected, &identity); +static bool calypso_dump_candidate_add(calypso_dump_candidate_list_t *list, uint16_t lid, uint8_t source) { + // LID 0000 is a special SELECT target, not a real file candidate. + if (lid == 0x0000) { + return true; + } - for (size_t i = 0; i < seen_count; i++) { - if (seen[i].aid_len == identity.aid_len && memcmp(seen[i].aid, identity.aid, identity.aid_len) == 0) { + for (size_t i = 0; i < list->count; i++) { + if (list->items[i].lid == lid) { + if ((list->items[i].sources & CALYPSO_DUMP_SOURCE_BRUTE) == 0) { + list->items[i].sources |= source; + } return true; } } + if (list->count >= ARRAYLEN(list->items)) { + return false; + } + + list->items[list->count].lid = lid; + list->items[list->count].sources = source; + list->count++; + return true; +} + +static size_t calypso_dump_walk_effective_path(const calypso_dump_walk_context_t *ctx, uint16_t *path, size_t path_max) { + if (ctx == NULL || path == NULL || path_max == 0) { + return 0; + } + + size_t path_len = MIN(ctx->path_len, path_max); + if (path_len > 0) { + memcpy(path, ctx->path, path_len * sizeof(path[0])); + if (ctx->has_lid) { + path[path_len - 1] = ctx->lid; + } + return path_len; + } + + if (ctx->from_root == false && ctx->is_mf == false && ctx->has_lid) { + path[0] = ctx->lid; + return 1; + } + + return 0; +} + +static size_t calypso_dump_walk_lid_path(const calypso_dump_walk_context_t *ctx, uint16_t lid, uint16_t *path, size_t path_max) { + if (path == NULL || path_max == 0) { + return 0; + } + + size_t path_len = calypso_dump_walk_effective_path(ctx, path, path_max); + if (path_len > 0 && path[path_len - 1] == lid) { + return path_len; + } + if (path_len >= path_max) { + return 0; + } + + path[path_len++] = lid; + return path_len; +} + +static void calypso_dump_profile_list_free(calypso_dump_profile_list_t *list) { + if (list == NULL) { + return; + } + + for (size_t i = 0; i < list->count; i++) { + free(list->items[i].nodes); + } + memset(list, 0, sizeof(*list)); +} + +static bool calypso_empty_response_lost(size_t read_len, uint16_t sw) { + return sw == 0 && read_len == 0; +} + +static int calypso_dump_reselect_exact_df_name_checked(const calypso_select_result_t *selected, bool verbose) { + if (selected->parsed.has_df_name == false || selected->parsed.df_name_len == 0) { + return PM3_SUCCESS; + } + + calypso_select_result_t exact = {0}; + bool matched = false; + calypso_rf_info_t rf = selected->rf; + int res = calypso_select_aid(selected->parsed.df_name, selected->parsed.df_name_len, verbose, &rf, &exact, &matched); + if (res != PM3_SUCCESS) { + return res; + } + if (matched == false) { + if (verbose) { + PrintAndLogEx(DEBUG, "Unable to reselect exact Calypso DF name %s before node probe", sprint_hex_inrow(selected->parsed.df_name, selected->parsed.df_name_len)); + } + return PM3_EOPABORTED; + } + return PM3_SUCCESS; +} + +static int calypso_dump_select_lid(const calypso_dump_walk_context_t *ctx, uint16_t lid, uint8_t *response, size_t response_max, size_t *response_len, uint16_t *sw) { + uint16_t path[CALYPSO_DUMP_NODE_PATH_MAX + 1] = {0}; + size_t path_len = calypso_dump_walk_lid_path(ctx, lid, path, ARRAYLEN(path)); + return calypso_select_file_path_then_id_fallback(path, path_len, lid, response, response_max, response_len, sw); +} + +static bool calypso_dump_result_lost(int res) { + return res == PM3_ETIMEOUT || res == PM3_ECARDEXCHANGE || res == PM3_ERFTRANS; +} + +static bool calypso_dump_exchange_lost(int res, size_t read_len, uint16_t sw) { + return calypso_dump_result_lost(res) || (res == PM3_SUCCESS && calypso_empty_response_lost(read_len, sw)); +} + +static int calypso_dump_repoll_context(const calypso_select_result_t *selected, const calypso_dump_walk_context_t *ctx, bool verbose) { + calypso_rf_info_t rf = selected->rf; + PrintAndLogEx(WARNING, "Card connection lost; re-polling and resuming"); + DropField(); + int res = calypso_connect_contactless(verbose, &rf); + if (res != PM3_SUCCESS) { + return res; + } + return calypso_dump_reselect_base(selected, ctx, verbose); +} + +static int calypso_dump_repoll_file(const calypso_select_result_t *selected, const calypso_dump_walk_context_t *ctx, uint16_t lid, bool verbose) { + int res = calypso_dump_repoll_context(selected, ctx, verbose); + if (res != PM3_SUCCESS) { + return res; + } + + uint8_t response[APDU_RES_LEN] = {0}; + size_t response_len = 0; + uint16_t sw = 0; + res = calypso_dump_select_lid(ctx, lid, response, sizeof(response), &response_len, &sw); + if (calypso_dump_exchange_lost(res, response_len, sw)) { + return PM3_ETIMEOUT; + } + if (res != PM3_SUCCESS) { + return res; + } + return calypso_select_sw_has_file(sw) ? PM3_SUCCESS : PM3_EOPABORTED; +} + +typedef enum { + CALYPSO_DUMP_RESUME_CONTEXT, + CALYPSO_DUMP_RESUME_FILE, +} calypso_dump_resume_scope_t; + +typedef struct { + const calypso_select_result_t *selected; + const calypso_dump_walk_context_t *ctx; + bool verbose; + calypso_dump_resume_scope_t scope; + uint16_t lid; +} calypso_dump_resume_t; + +typedef int (*calypso_dump_command_fn_t)(void *arg, size_t *read_len, uint16_t *sw); + +static int calypso_dump_resume_restore(const calypso_dump_resume_t *resume) { + return resume->scope == CALYPSO_DUMP_RESUME_FILE ? + calypso_dump_repoll_file(resume->selected, resume->ctx, resume->lid, resume->verbose) : + calypso_dump_repoll_context(resume->selected, resume->ctx, resume->verbose); +} + +static int calypso_dump_command_with_resume(const calypso_dump_resume_t *resume, calypso_dump_command_fn_t command, void *arg, size_t *read_len, uint16_t *sw) { + int res = PM3_SUCCESS; + for (uint8_t attempt = 0; attempt < 4; attempt++) { + *read_len = 0; + *sw = 0; + res = command(arg, read_len, sw); + if (calypso_dump_exchange_lost(res, *read_len, *sw) == false || attempt == 3) { + break; + } + res = calypso_dump_resume_restore(resume); + if (res != PM3_SUCCESS && calypso_dump_result_lost(res) == false) { + return res; + } + } + return calypso_dump_exchange_lost(res, *read_len, *sw) ? PM3_ETIMEOUT : res; +} + +typedef struct { + uint8_t *out; + size_t out_len; +} calypso_dump_buffer_args_t; + +typedef struct { + uint16_t tag; + calypso_dump_buffer_args_t buffer; +} calypso_dump_get_data_args_t; + +static int calypso_dump_send_get_data(void *arg, size_t *read_len, uint16_t *sw) { + calypso_dump_get_data_args_t *cmd = arg; + return calypso_get_data_object(cmd->tag, cmd->buffer.out, cmd->buffer.out_len, read_len, sw); +} + +typedef struct { + bool verbose; + uint8_t *out; + size_t out_len; +} calypso_dump_current_fcp_args_t; + +static int calypso_dump_send_current_fcp(void *arg, size_t *read_len, uint16_t *sw) { + calypso_dump_current_fcp_args_t *cmd = arg; + return calypso_select_current_file_fcp(cmd->verbose, cmd->out, cmd->out_len, read_len, sw, NULL, NULL); +} + +typedef struct { + const calypso_dump_walk_context_t *ctx; + uint16_t lid; + uint8_t *out; + size_t out_len; +} calypso_dump_select_lid_args_t; + +static int calypso_dump_send_select_lid(void *arg, size_t *read_len, uint16_t *sw) { + calypso_dump_select_lid_args_t *cmd = arg; + return calypso_dump_select_lid(cmd->ctx, cmd->lid, cmd->out, cmd->out_len, read_len, sw); +} + +typedef struct { + uint8_t record; + uint16_t le; + uint8_t *out; + size_t out_len; +} calypso_dump_read_record_args_t; + +static int calypso_dump_send_read_binary(void *arg, size_t *read_len, uint16_t *sw) { + calypso_dump_buffer_args_t *cmd = arg; + return calypso_read_current_binary(cmd->out, cmd->out_len, read_len, sw); +} + +static int calypso_dump_send_read_record(void *arg, size_t *read_len, uint16_t *sw) { + calypso_dump_read_record_args_t *cmd = arg; + return calypso_read_current_record(cmd->record, cmd->le, cmd->out, cmd->out_len, read_len, sw); +} + +static bool calypso_tlv_read_len(const uint8_t *data, size_t data_len, size_t *pos, size_t *len); + +static void calypso_dump_add_c0_candidates(calypso_dump_candidate_list_t *candidates, const uint8_t *data, size_t data_len) { + if (candidates == NULL || data == NULL || data_len == 0) { + return; + } + + size_t pos = 0; + size_t end = data_len; + if (data[0] == 0xC0) { + pos = 1; + size_t len = 0; + if (calypso_tlv_read_len(data, data_len, &pos, &len) == false || pos + len > data_len) { + return; + } + end = pos + len; + } + + while (pos < end) { + uint8_t tag = data[pos++]; + size_t len = 0; + if (calypso_tlv_read_len(data, end, &pos, &len) == false) { + return; + } + if (pos + len > end) { + return; + } + if (tag != 0xC1 || len < 2) { + pos += len; + continue; + } + + uint16_t lid = ((uint16_t)data[pos] << 8) | data[pos + 1]; + if (calypso_dump_candidate_add(candidates, lid, CALYPSO_DUMP_SOURCE_EFLIST) == false) { + return; + } + pos += len; + } +} + +static bool calypso_dump_infer_parent_from_c0(const calypso_dump_candidate_list_t *candidates, uint16_t *parent) { + bool have_parent = false; + uint16_t inferred_parent = 0; + + for (size_t i = 0; i < candidates->count; i++) { + if ((candidates->items[i].sources & CALYPSO_DUMP_SOURCE_EFLIST) == 0) { + continue; + } + + uint16_t candidate_parent = candidates->items[i].lid & 0xFF00; + if (candidate_parent == 0x0000) { + return false; + } + if (have_parent == false) { + inferred_parent = candidate_parent; + have_parent = true; + continue; + } + if (candidate_parent != inferred_parent) { + return false; + } + } + + if (have_parent == false) { + return false; + } + *parent = inferred_parent; + return true; +} + +static bool calypso_dump_add_known_candidates(calypso_dump_candidate_list_t *candidates, const calypso_dump_walk_context_t *ctx, bool have_inferred_parent, uint16_t inferred_parent) { + uint16_t path[CALYPSO_DUMP_NODE_PATH_MAX] = {0}; + size_t path_len = ctx->path_len; + + if (path_len > 0) { + memcpy(path, ctx->path, path_len * sizeof(path[0])); + if (ctx->has_lid) { + path[path_len - 1] = ctx->lid; + } + } else if (ctx->depth == 0 && ctx->from_root == false && ctx->is_mf == false) { + if (ctx->has_lid) { + path[0] = ctx->lid; + path_len = 1; + } else if (have_inferred_parent) { + path[0] = inferred_parent; + path_len = 1; + } else { + path_len = 0; + } + } else if (ctx->depth == 0) { + path_len = 0; + } else if (ctx->from_root == false && ctx->is_mf == false) { + if (ctx->has_lid) { + path[0] = ctx->lid; + path_len = 1; + } else if (have_inferred_parent) { + path[0] = inferred_parent; + path_len = 1; + } else { + return true; + } + } + + json_t *root = calypso_json_resource_root(&calypso_nodes_resource); + if (root == NULL) { + return true; + } + + size_t index; + json_t *entry; + json_array_foreach(root, index, entry) { + calypso_file_ref_t file = {0}; + if (calypso_json_file_ref_parse(entry, &file) == false || path_len >= file.path_len) { + continue; + } + + bool prefix_match = true; + for (size_t j = 0; j < path_len; j++) { + if (path[j] != file.path[j]) { + prefix_match = false; + break; + } + } + if (prefix_match == false) { + continue; + } + + if (calypso_dump_candidate_add(candidates, file.path[path_len], CALYPSO_DUMP_SOURCE_KNOWN) == false) { + return false; + } + } + return true; +} + +static bool calypso_dump_walk_is_root(const calypso_dump_walk_context_t *ctx) { + return ctx != NULL && ctx->depth == 0; +} + +static bool calypso_dump_walk_is_current_lid(const calypso_dump_walk_context_t *ctx, uint16_t lid) { + if (ctx == NULL) { + return false; + } + if (ctx->has_lid && ctx->lid == lid) { + return true; + } + if (ctx->path_len > 0 && ctx->path[ctx->path_len - 1] == lid) { + return true; + } + return ctx->from_root && lid == 0x3F00; +} + +static void calypso_dump_brute_status_clear(bool *visible) { + if (visible != NULL && *visible) { + PrintAndLogEx(INPLACE, "%80s\r", ""); + *visible = false; + } +} + +static void calypso_dump_brute_status_update(const calypso_dump_lid_candidate_t *candidate, bool *visible, uint16_t *last_lid) { + if (candidate == NULL || (candidate->sources & CALYPSO_DUMP_SOURCE_BRUTE) == 0) { + calypso_dump_brute_status_clear(visible); + return; + } + + uint16_t range_start = candidate->lid & 0xFF00; + uint16_t range_end = range_start | 0x00FF; + if ((candidate->lid & 0x00FF) == 0x00) { + range_start = 0x0000; + range_end = 0xFF00; + } + if (visible != NULL && last_lid != NULL && *visible && *last_lid == candidate->lid) { + return; + } + + PrintAndLogEx(INPLACE, "Bruteforcing range " _YELLOW_("%04X-%04X") " (" _YELLOW_("%04X") ")" _CLR_, range_start, range_end, candidate->lid); + if (visible != NULL) { + *visible = true; + } + if (last_lid != NULL) { + *last_lid = candidate->lid; + } +} + +static bool calypso_dump_walk_lid_base(const calypso_dump_walk_context_t *ctx, bool have_inferred_parent, uint16_t inferred_parent, uint16_t *base) { + if (ctx->has_lid) { + *base = ctx->lid & 0xFF00; + return true; + } + if (ctx->path_len > 0) { + *base = ctx->path[ctx->path_len - 1] & 0xFF00; + return true; + } + if (have_inferred_parent) { + *base = inferred_parent & 0xFF00; + return *base != 0x0000; + } + return false; +} + +static bool calypso_dump_add_brute_ef_range(calypso_dump_candidate_list_t *candidates, uint16_t base) { + for (uint32_t low = 1; low <= 0xFF; low++) { + uint16_t lid = base | (uint16_t)low; + if (calypso_dump_candidate_add(candidates, lid, CALYPSO_DUMP_SOURCE_BRUTE) == false) { + return false; + } + } + return true; +} + +static bool calypso_dump_add_root_brute_candidates(calypso_dump_candidate_list_t *candidates) { + if (calypso_dump_add_brute_ef_range(candidates, 0x0000) == false || + calypso_dump_add_brute_ef_range(candidates, 0x2F00) == false || + calypso_dump_add_brute_ef_range(candidates, 0x3F00) == false) { + return false; + } + + for (uint32_t high = 0; high <= 0xFF; high++) { + uint16_t base = (uint16_t)(high << 8); + if (calypso_dump_candidate_add(candidates, base, CALYPSO_DUMP_SOURCE_BRUTE) == false) { + return false; + } + } + return true; +} + +static bool calypso_dump_add_brute_file_candidates(calypso_dump_candidate_list_t *candidates, const calypso_dump_walk_context_t *ctx, bool have_inferred_parent, uint16_t inferred_parent) { + if (calypso_dump_walk_is_root(ctx) && calypso_dump_add_root_brute_candidates(candidates) == false) { + return false; + } + + uint16_t base = 0; + if (calypso_dump_walk_lid_base(ctx, have_inferred_parent, inferred_parent, &base) == false) { + return true; + } + return calypso_dump_add_brute_ef_range(candidates, base); +} + +static int calypso_dump_reselect_base(const calypso_select_result_t *selected, const calypso_dump_walk_context_t *ctx, bool verbose) { + int res = PM3_SUCCESS; + if (ctx->from_root == false) { + res = calypso_dump_reselect_exact_df_name_checked(selected, verbose); + if (res != PM3_SUCCESS) { + return res; + } + } + + if (ctx->from_root) { + uint8_t response[APDU_RES_LEN] = {0}; + size_t response_len = 0; + uint16_t sw = 0; + const uint16_t mf_path[] = {0x3F00}; + res = calypso_select_file_path_then_id_fallback(mf_path, ARRAYLEN(mf_path), 0x3F00, response, sizeof(response), &response_len, &sw); + if (res == PM3_SUCCESS && calypso_empty_response_lost(response_len, sw)) { + return PM3_ETIMEOUT; + } + if (res != PM3_SUCCESS || calypso_select_sw_has_file(sw) == false) { + if (verbose) { + PrintAndLogEx(INFO, " SELECT 3F00 failed (%04X - %s)", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xFF)); + } + return res == PM3_SUCCESS ? PM3_EOPABORTED : res; + } + } + + for (size_t i = 0; i < ctx->path_len; i++) { + uint8_t response[APDU_RES_LEN] = {0}; + size_t response_len = 0; + uint16_t sw = 0; + res = calypso_select_file_path_then_id_fallback(ctx->path, i + 1, ctx->path[i], response, sizeof(response), &response_len, &sw); + if (res == PM3_SUCCESS && calypso_empty_response_lost(response_len, sw)) { + return PM3_ETIMEOUT; + } + if (res != PM3_SUCCESS || calypso_select_sw_has_file(sw) == false) { + if (verbose) { + PrintAndLogEx(INFO, " SELECT %04X failed while restoring context (%04X - %s)", ctx->path[i], sw, GetAPDUCodeDescription(sw >> 8, sw & 0xFF)); + } + return res == PM3_SUCCESS ? PM3_EOPABORTED : res; + } + } + + return PM3_SUCCESS; +} + +static bool calypso_tlv_read_len(const uint8_t *data, size_t data_len, size_t *pos, size_t *len) { + if (data == NULL || pos == NULL || len == NULL || *pos >= data_len) { + return false; + } + + uint8_t first = data[(*pos)++]; + if ((first & 0x80) == 0) { + *len = first; + return true; + } + + size_t len_len = first & 0x7F; + if (len_len == 0 || len_len > sizeof(size_t) || *pos + len_len > data_len) { + return false; + } + + size_t parsed = 0; + for (size_t i = 0; i < len_len; i++) { + parsed = (parsed << 8) | data[(*pos)++]; + } + + *len = parsed; + return true; +} + +static bool calypso_fcp_value(const uint8_t *fcp, size_t fcp_len, const uint8_t **value, size_t *value_len) { + if (fcp == NULL || value == NULL || value_len == NULL || fcp_len < 2) { + return false; + } + + if (fcp[0] != 0x85) { + *value = fcp; + *value_len = fcp_len; + return true; + } + + size_t pos = 1; + size_t len = 0; + if (calypso_tlv_read_len(fcp, fcp_len, &pos, &len) == false) { + return false; + } + + if (pos + len > fcp_len) { + return false; + } + + *value = fcp + pos; + *value_len = len; + return true; +} + +static int calypso_fcp_file_type(const uint8_t *fcp, size_t fcp_len) { + const uint8_t *value = NULL; + size_t value_len = 0; + if (calypso_fcp_value(fcp, fcp_len, &value, &value_len) == false || value_len < 2) { + return -1; + } + + return value[1]; +} + +static bool calypso_fcp_is_df(const uint8_t *fcp, size_t fcp_len) { + return calypso_fcp_file_type(fcp, fcp_len) == 0x02; +} + +static bool calypso_fcp_is_ef(const uint8_t *fcp, size_t fcp_len) { + return calypso_fcp_file_type(fcp, fcp_len) == 0x04; +} + +static bool calypso_select_fcp_lid_matches(uint16_t candidate, uint16_t target_lid, bool *have_specific_lid) { + if (candidate == target_lid) { + return true; + } + if (calypso_lid_is_valid(candidate)) { + *have_specific_lid = true; + } + return false; +} + +static bool calypso_select_fcp_matches_lid(const uint8_t *fcp, size_t fcp_len, uint16_t target_lid) { + const uint8_t *value = NULL; + size_t value_len = 0; + if (calypso_fcp_value(fcp, fcp_len, &value, &value_len) == false || value_len < 2) { + return true; + } + + bool have_specific_lid = false; + uint16_t tail = ((uint16_t)value[value_len - 2] << 8) | value[value_len - 1]; + if (calypso_select_fcp_lid_matches(tail, target_lid, &have_specific_lid)) { + return true; + } + + if (value_len >= 3) { + uint16_t shifted = ((uint16_t)value[value_len - 3] << 8) | value[value_len - 2]; + if (calypso_select_fcp_lid_matches(shifted, target_lid, &have_specific_lid)) { + return true; + } + } + + return have_specific_lid == false; +} + +static bool calypso_preferred_fcp(const uint8_t *select_fcp, size_t select_fcp_len, const uint8_t *get_data_fcp, size_t get_data_fcp_len, const uint8_t **fcp, size_t *fcp_len) { + calypso_fcp_t parsed = {0}; + if (select_fcp != NULL && select_fcp_len > 0 && calypso_parse_fcp(select_fcp, select_fcp_len, &parsed)) { + *fcp = select_fcp; + *fcp_len = select_fcp_len; + return true; + } + + if (get_data_fcp != NULL && get_data_fcp_len > 0 && calypso_parse_fcp(get_data_fcp, get_data_fcp_len, &parsed)) { + *fcp = get_data_fcp; + *fcp_len = get_data_fcp_len; + return true; + } + + *fcp = NULL; + *fcp_len = 0; + return false; +} + +static bool calypso_lid_is_valid(uint16_t lid) { + return lid != 0x0000 && lid != 0xFFFF; +} + +static bool calypso_fcp_lid_matches(uint16_t candidate, bool have_hint, uint16_t hint, uint16_t *lid) { + if (calypso_lid_is_valid(candidate) == false) { + return false; + } + if (have_hint && candidate != hint) { + return false; + } + *lid = candidate; + return true; +} + +static bool calypso_fcp_lid_with_hint(const uint8_t *fcp, size_t fcp_len, bool have_hint, uint16_t hint, uint16_t *lid) { + const uint8_t *value = NULL; + size_t value_len = 0; + if (lid == NULL || calypso_fcp_value(fcp, fcp_len, &value, &value_len) == false || value_len < 2) { + return false; + } + + uint16_t tail = ((uint16_t)value[value_len - 2] << 8) | value[value_len - 1]; + uint16_t before_trailer = 0; + bool have_before_trailer = value_len >= 3 && value[value_len - 1] == 0x00; + if (have_before_trailer) { + before_trailer = ((uint16_t)value[value_len - 3] << 8) | value[value_len - 2]; + } + + if (calypso_fcp_lid_matches(tail, have_hint, hint, lid)) { + return true; + } + if (have_before_trailer && calypso_fcp_lid_matches(before_trailer, have_hint, hint, lid)) { + return true; + } + + if (have_hint) { + return false; + } + + // Calypso FCP commonly stores LID before a trailing byte, but some selected + // application DFs expose it in the final two bytes. Prefer the pre-trailer + // pair when it looks like a normal app/file LID; otherwise use the tail. + if (have_before_trailer && calypso_lid_is_valid(before_trailer) && (before_trailer & 0xFF00) != 0x0000) { + *lid = before_trailer; + return true; + } + if (calypso_lid_is_valid(tail)) { + *lid = tail; + return true; + } + if (have_before_trailer && calypso_lid_is_valid(before_trailer)) { + *lid = before_trailer; + return true; + } + return false; } -static void calypso_dump_identity_add(calypso_app_identity_t *seen, size_t seen_capacity, size_t *seen_count, const calypso_select_result_t *selected) { - if (*seen_count >= seen_capacity) { +static bool calypso_fcp_lid(const uint8_t *fcp, size_t fcp_len, uint16_t *lid) { + return calypso_fcp_lid_with_hint(fcp, fcp_len, false, 0, lid); +} + +static void calypso_dump_prefix(size_t parent_depth, const char *suffix, char *out, size_t out_len) { + if (out_len == 0) { return; } - calypso_select_identity(selected, &seen[*seen_count]); - (*seen_count)++; + size_t pos = 0; + int written = snprintf(out, out_len, " "); + if (written < 0 || (size_t)written >= out_len) { + return; + } + pos = (size_t)written; + + for (size_t i = 0; i < parent_depth && pos < out_len; i++) { + written = snprintf(out + pos, out_len - pos, "| "); + if (written < 0 || (size_t)written >= out_len - pos) { + return; + } + pos += (size_t)written; + } + + if (pos < out_len) { + snprintf(out + pos, out_len - pos, "%s", suffix); + } } -static int calypso_dump_selected_df(const calypso_select_result_t *selected, json_t *dfs, bool verbose, size_t *total_sfi_file_count, size_t *total_lid_file_count, size_t *total_record_count) { - calypso_print_select_info(selected, verbose); +static void calypso_dump_branch_prefix(size_t parent_depth, char *out, size_t out_len) { + calypso_dump_prefix(parent_depth, "|-- ", out, out_len); +} - calypso_reselect_exact_df_name(selected, verbose); +static void calypso_dump_detail_prefix(size_t parent_depth, char *out, size_t out_len) { + calypso_dump_prefix(parent_depth, "| ", out, out_len); +} - json_t *app = json_object(); - json_t *sfi_files = json_array(); - json_t *lid_files = json_array(); - calypso_json_add_select(app, selected); +static bool calypso_data_is_fci(const uint8_t *data, size_t data_len) { + calypso_fci_t fci = {0}; + return data != NULL && data_len > 0 && calypso_parse_fci(data, data_len, &fci); +} - json_t *get_data = json_array(); - calypso_ef_list_t ef_list = {0}; - if (calypso_probe_get_data_objects(get_data, true, verbose, &ef_list) > 0) { - json_object_set_new(app, "dataObjects", get_data); +static bool calypso_data_is_fcp(const uint8_t *data, size_t data_len) { + calypso_fcp_t fcp = {0}; + return data != NULL && data_len > 0 && calypso_parse_fcp(data, data_len, &fcp); +} + +static void calypso_dump_print_inline_data(const char *prefix, const char *label, const uint8_t *data, size_t data_len) { + if (data == NULL || data_len == 0) { + return; + } + + char full_label[160] = {0}; + snprintf(full_label, sizeof(full_label), "%s%s", prefix != NULL ? prefix : "", label); + calypso_print_hex_entry_wrapped(full_label, data, data_len, ANSI_YELLOW, CALYPSO_DUMP_HEX_ENTRY_BREAK); +} + +static void calypso_dump_print_inline_response(const char *prefix, const char *label, const uint8_t *data, size_t data_len, uint16_t sw, bool verbose) { + if (data_len > 0) { + calypso_dump_print_inline_data(prefix, label, data, data_len); + } else if (verbose && sw != 0 && calypso_read_sw_is_unavailable(sw) == false) { + PrintAndLogEx(INFO, "%s%sunavailable (%04X - %s)", prefix != NULL ? prefix : "", label, sw, GetAPDUCodeDescription(sw >> 8, sw & 0xFF)); + } +} + +static void calypso_dump_print_inline_file_data(const char *prefix, bool is_df, const calypso_dump_node_t *node, bool verbose) { + if (node == NULL) { + return; + } + + if (is_df) { + calypso_dump_print_inline_response(prefix, "SEL FCI: ", node->select_fci.data, node->select_fci.len, node->select_fci.sw, verbose); + calypso_dump_print_inline_response(prefix, "GET FCI: ", node->get_data_fci.data, node->get_data_fci.len, node->get_data_fci.sw, verbose); + } + calypso_dump_print_inline_response(prefix, "SEL FCP: ", node->select_fcp.data, node->select_fcp.len, is_df ? 0 : node->select_fcp.sw, verbose); + calypso_dump_print_inline_response(prefix, "GET FCP: ", node->get_data_fcp.data, node->get_data_fcp.len, node->get_data_fcp.sw, verbose); + if (is_df) { + calypso_dump_print_inline_response(prefix, "CUR FCP: ", node->select_current_fcp.data, node->select_current_fcp.len, node->select_current_fcp.sw, verbose); + } +} + +static const char *calypso_ef_type_name(uint8_t ef_type, char *fallback, size_t fallback_len) { + switch (ef_type) { + case 0x01: + return "binary"; + case 0x02: + return "linear"; + case 0x04: + return "cyclic"; + case 0x08: + case 0x09: + return "counter"; + default: + snprintf(fallback, fallback_len, "type %02X", ef_type); + return fallback; + } +} + +static void calypso_dump_print_root(const calypso_dump_walk_context_t *root, const calypso_dump_node_t *node) { + char root_lid[8] = {0}; + if (root->from_root) { + snprintf(root_lid, sizeof(root_lid), "3F00"); + } else if (root->has_lid) { + snprintf(root_lid, sizeof(root_lid), "%04X", root->lid); } else { - json_decref(get_data); + snprintf(root_lid, sizeof(root_lid), "AID"); } - // Some cards misbehaved on further commands after GET DATA unless the DF was reselected. - calypso_reselect_exact_df_name(selected, verbose); - json_object_set_new(app, "filesBySFI", sfi_files); - json_object_set_new(app, "filesByLID", lid_files); + const uint8_t *aid = NULL; + size_t aid_len = calypso_dump_node_aid(node, &aid); - size_t sfi_file_count = 0; - size_t lid_file_count = 0; - size_t record_count = 0; - int first_error = PM3_SUCCESS; + const char *root_type = root->is_mf ? "MF" : "DF"; + if (aid != NULL && aid_len > 0) { + PrintAndLogEx(INFO, "%s " _GREEN_("%s") " (AID " _YELLOW_("%s") "%s)", root_type, root_lid, sprint_hex_inrow(aid, aid_len), node != NULL && node->default_selection ? ", default" : ""); + } else { + PrintAndLogEx(INFO, "%s " _GREEN_("%s"), root_type, root_lid); + } +} - PrintAndLogEx(INFO, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("SFI Sweep") " -------------------------------"); - // Calypso EF SFIs are 1..30, but the APDU field encodes five bits; probe 31 too for diagnostics. - for (uint8_t sfi = 1; sfi <= CALYPSO_MAX_ENCODED_SFI; sfi++) { +static void calypso_dump_add_fcp_sfi(json_t *node, const uint8_t *fcp, size_t fcp_len) { + calypso_fcp_t parsed = {0}; + if (node == NULL || fcp == NULL || fcp_len == 0 || calypso_parse_fcp(fcp, fcp_len, &parsed) == false) { + return; + } + + json_object_set_new(node, "sfi", json_integer(parsed.sfi)); +} + +static void calypso_json_object_add_record(json_t *records, uint8_t record, const uint8_t *data, size_t data_len) { + char key[3] = {0}; + snprintf(key, sizeof(key), "%02X", record); + json_object_set_new(records, key, json_string(sprint_hex_inrow(data, data_len))); +} + +static void calypso_json_set_dump_sources(json_t *node, uint8_t sources) { + json_t *source_array = json_array(); + if (sources & CALYPSO_DUMP_SOURCE_EFLIST) { + json_array_append_new(source_array, json_string("eflist")); + } + if (sources & CALYPSO_DUMP_SOURCE_BRUTE) { + json_array_append_new(source_array, json_string("brute")); + } + if (sources & CALYPSO_DUMP_SOURCE_KNOWN) { + json_array_append_new(source_array, json_string("known")); + } + if (sources & CALYPSO_DUMP_SOURCE_SELECTED) { + json_array_append_new(source_array, json_string("selected")); + } + json_object_set_new(node, "sources", source_array); +} + +static bool calypso_dump_parent_lid(const calypso_dump_walk_context_t *ctx, uint16_t *parent_lid) { + if (ctx == NULL || parent_lid == NULL) { + return false; + } + + if (ctx->depth == 0 && (ctx->from_root || ctx->is_mf)) { + *parent_lid = 0x3F00; + return true; + } + if (ctx->has_lid) { + *parent_lid = ctx->lid; + return true; + } + if (ctx->path_len > 0) { + *parent_lid = ctx->path[ctx->path_len - 1]; + return true; + } + return false; +} + +static void calypso_dump_set_parent(json_t *node, bool have_parent, uint16_t parent_lid) { + if (node == NULL) { + return; + } + + if (have_parent) { + calypso_json_set_lid(node, "parent", parent_lid); + } else { + json_object_set_new(node, "parent", json_null()); + } +} + +static void calypso_dump_add_response_fields(json_t *json_node, const calypso_dump_node_t *dump_node, bool is_df) { + if (json_node == NULL || dump_node == NULL) { + return; + } + + if (is_df) { + if (dump_node->select_fci.len > 0) { + calypso_json_set_hex(json_node, "selectFci", dump_node->select_fci.data, dump_node->select_fci.len); + } + if (dump_node->get_data_fci.len > 0) { + calypso_json_set_hex(json_node, "getFci", dump_node->get_data_fci.data, dump_node->get_data_fci.len); + } + } + if (dump_node->get_data_fcp.len > 0) { + calypso_json_set_hex(json_node, "getFcp", dump_node->get_data_fcp.data, dump_node->get_data_fcp.len); + } + if (dump_node->select_fcp.len > 0) { + calypso_json_set_hex(json_node, "selectFcp", dump_node->select_fcp.data, dump_node->select_fcp.len); + } + if (dump_node->select_current_fcp.len > 0) { + calypso_json_set_hex(json_node, "selectCurrentFcp", dump_node->select_current_fcp.data, dump_node->select_current_fcp.len); + } +} + +static json_t *calypso_dump_add_file_json(calypso_dump_json_context_t *dump, const calypso_dump_walk_context_t *ctx, const calypso_dump_node_t *dump_node, bool is_df, bool is_root) { + if (dump == NULL || dump->nodes == NULL || ctx == NULL) { + return NULL; + } + + const uint8_t *aid = NULL; + size_t aid_len = is_df ? calypso_dump_node_aid(dump_node, &aid) : 0; + + const uint8_t *fcp = NULL; + size_t fcp_len = 0; + bool have_fcp = calypso_dump_node_first_fcp(dump_node, &fcp, &fcp_len); + + uint16_t lid = 0; + bool have_lid = calypso_dump_node_known_lid(dump_node, &lid); + if (is_root && (ctx->from_root || ctx->is_mf)) { + have_lid = true; + lid = 0x3F00; + } + + json_t *node = json_object(); + json_object_set_new(node, "kind", json_string(is_root && ctx->is_mf ? "mf" : (is_df ? "df" : "ef"))); + if (is_df) { + json_object_set_new(node, "default", json_boolean(dump_node != NULL ? dump_node->default_selection : (is_root && ctx->default_selection))); + } + if (aid_len > 0) { + calypso_json_set_hex(node, "aid", aid, aid_len); + } + if (have_lid) { + calypso_json_set_lid(node, "lid", lid); + } + if (is_root) { + calypso_dump_set_parent(node, false, 0); + } else { + uint16_t parent_lid = 0; + calypso_dump_set_parent(node, calypso_dump_parent_lid(ctx, &parent_lid), parent_lid); + } + if (have_fcp && is_df == false) { + calypso_dump_add_fcp_sfi(node, fcp, fcp_len); + } + if (is_root == false) { + calypso_json_set_dump_sources(node, dump_node != NULL ? dump_node->sources : 0); + } + calypso_dump_add_response_fields(node, dump_node, is_df); + + json_array_append_new(dump->nodes, node); + return node; +} + +static int calypso_dump_read_ef(const calypso_select_result_t *selected, const calypso_dump_walk_context_t *ctx, uint16_t lid, json_t *node, bool verbose) { + char detail_prefix[96] = {0}; + calypso_dump_detail_prefix(ctx->depth, detail_prefix, sizeof(detail_prefix)); + calypso_dump_resume_t resume = {selected, ctx, verbose, CALYPSO_DUMP_RESUME_FILE, lid}; + + uint8_t binary[APDU_RES_LEN] = {0}; + size_t binary_len = 0; + uint16_t binary_sw = 0; + calypso_dump_buffer_args_t binary_cmd = {binary, sizeof(binary)}; + int res = calypso_dump_command_with_resume(&resume, calypso_dump_send_read_binary, &binary_cmd, &binary_len, &binary_sw); + if (res != PM3_SUCCESS) { + return res; + } + if (calypso_read_sw_has_data(binary_sw, binary_len)) { + calypso_json_set_hex(node, "data", binary, binary_len); + char label[160] = {0}; + snprintf(label, sizeof(label), "%sbinary: ", detail_prefix); + calypso_print_hex_entry_wrapped(label, binary, binary_len, ANSI_GREEN, CALYPSO_DUMP_HEX_ENTRY_BREAK); + } else if (verbose && calypso_read_sw_is_unavailable(binary_sw) == false) { + PrintAndLogEx(INFO, "%sbinary: %04X - %s", detail_prefix, binary_sw, GetAPDUCodeDescription(binary_sw >> 8, binary_sw & 0xFF)); + } + + json_t *records = json_object(); + bool found = false; + for (uint16_t record = 1; record <= 0xFF; record++) { + uint8_t data[APDU_RES_LEN] = {0}; + size_t data_len = 0; + uint16_t sw = 0; + calypso_dump_read_record_args_t record_cmd = {(uint8_t)record, 0, data, sizeof(data)}; + res = calypso_dump_command_with_resume(&resume, calypso_dump_send_read_record, &record_cmd, &data_len, &sw); + if (res != PM3_SUCCESS) { + json_decref(records); + return res; + } + if (calypso_read_sw_has_data(sw, data_len) == false && calypso_read_sw_is_unavailable(sw) == false) { + data_len = 0; + sw = 0; + record_cmd.le = CALYPSO_LEGACY_RECORD_LEN; + res = calypso_dump_command_with_resume(&resume, calypso_dump_send_read_record, &record_cmd, &data_len, &sw); + if (res != PM3_SUCCESS) { + json_decref(records); + return res; + } + } + + if (calypso_read_sw_has_data(sw, data_len)) { + if (data_len > 0) { + char label[160] = {0}; + snprintf(label, sizeof(label), "%srec " _GREEN_("%03u") ": ", detail_prefix, record); + calypso_print_hex_entry_wrapped(label, data, data_len, ANSI_GREEN, CALYPSO_DUMP_HEX_ENTRY_BREAK); + calypso_json_object_add_record(records, (uint8_t)record, data, data_len); + found = true; + } + continue; + } + + if (calypso_read_sw_is_eof(sw) || calypso_read_sw_is_unavailable(sw)) { + if (verbose && found == false && sw != 0) { + PrintAndLogEx(INFO, "%srecords : unavailable (%04X - %s)", detail_prefix, sw, GetAPDUCodeDescription(sw >> 8, sw & 0xFF)); + } + break; + } + + if (verbose) { + PrintAndLogEx(INFO, "%srec %03u: stopped (%04X - %s)", detail_prefix, record, sw, GetAPDUCodeDescription(sw >> 8, sw & 0xFF)); + } + break; + } + + if (json_object_size(records) > 0) { + json_object_set_new(node, "records", records); + } else { + json_decref(records); + } + return PM3_SUCCESS; +} + +static void calypso_dump_print_node(const calypso_dump_walk_context_t *ctx, const calypso_dump_node_t *node, bool is_df, bool verbose) { + char prefix[96] = {0}; + calypso_dump_branch_prefix(ctx->depth, prefix, sizeof(prefix)); + + uint16_t lid = 0; + calypso_dump_node_known_lid(node, &lid); + + char aid_details[CALYPSO_MAX_AID_LEN * 3 + 32] = {0}; + if (is_df) { + const uint8_t *aid = NULL; + size_t aid_len = calypso_dump_node_aid(node, &aid); + if (aid != NULL && aid_len > 0) { + snprintf(aid_details, sizeof(aid_details), " (AID " _YELLOW_("%s") "%s)", sprint_hex_inrow(aid, aid_len), node != NULL && node->default_selection ? ", default" : ""); + } + } + + char fcp_details[96] = {0}; + const uint8_t *fcp = NULL; + size_t fcp_len = 0; + bool have_fcp = calypso_dump_node_first_fcp(node, &fcp, &fcp_len); + if (have_fcp) { + calypso_fcp_t parsed = {0}; + if (calypso_parse_fcp(fcp, fcp_len, &parsed)) { + if (is_df == false && parsed.file_type == 0x04) { + char type_fallback[16] = {0}; + const char *type = calypso_ef_type_name(parsed.ef_type, type_fallback, sizeof(type_fallback)); + int record_pad = (int)(strlen(type) < 8 ? 8 - strlen(type) : 1); + snprintf(fcp_details, sizeof(fcp_details), " (SFI " _YELLOW_("%02X") ", %s,%*srecords %3u, size %3u)", + parsed.sfi, + type, + record_pad, + "", + parsed.num_records, + parsed.record_size); + } + } + } + + const char *source = ""; + uint8_t sources = node != NULL ? node->sources : 0; + if (sources & CALYPSO_DUMP_SOURCE_BRUTE) { + source = " (brute)"; + } else if (sources & CALYPSO_DUMP_SOURCE_KNOWN) { + source = " (known)"; + } else if (sources & CALYPSO_DUMP_SOURCE_EFLIST) { + source = " (eflist)"; + } + + PrintAndLogEx(INFO, "%s%s " _GREEN_("%04X") "%s%s%s", + prefix, + is_df ? "DF" : "EF", + lid, + aid_details, + fcp_details, + source); +} + +static int calypso_dump_process_context(const calypso_select_result_t *selected, const calypso_dump_walk_context_t *base_ctx, uint16_t max_depth, bool brute, bool verbose, calypso_dump_json_context_t *dump) { + calypso_dump_walk_context_t ctx = *base_ctx; + calypso_dump_resume_t context_resume = {selected, &ctx, verbose, CALYPSO_DUMP_RESUME_CONTEXT, 0}; + bool restore_base_needed = false; + bool brute_status_visible = false; + uint16_t brute_status_last_lid = 0; + int res = calypso_dump_reselect_base(selected, &ctx, verbose); + if (calypso_dump_result_lost(res)) { + res = calypso_dump_resume_restore(&context_resume); + } + if (res != PM3_SUCCESS) { + return res; + } + bool have_lid_hint = false; + uint16_t lid_hint = 0; + if (ctx.path_len > 0) { + have_lid_hint = true; + lid_hint = ctx.path[ctx.path_len - 1]; + } else if (ctx.from_root) { + have_lid_hint = true; + lid_hint = 0x3F00; + } else if (ctx.has_lid) { + have_lid_hint = true; + lid_hint = ctx.lid; + } + ctx.has_lid = false; + ctx.lid = 0; + + uint8_t baseline_fcp[APDU_RES_LEN] = {0}; + size_t baseline_fcp_len = 0; + uint16_t baseline_fcp_sw = 0; + calypso_dump_get_data_args_t get_baseline_fcp = {0x0062, {baseline_fcp, sizeof(baseline_fcp)}}; + res = calypso_dump_command_with_resume(&context_resume, calypso_dump_send_get_data, &get_baseline_fcp, &baseline_fcp_len, &baseline_fcp_sw); + if (res != PM3_SUCCESS) { + return res; + } + bool have_baseline_get_fcp = calypso_read_sw_has_data(baseline_fcp_sw, baseline_fcp_len); + + uint8_t baseline_cur_fcp[APDU_RES_LEN] = {0}; + size_t baseline_cur_fcp_len = 0; + uint16_t baseline_cur_fcp_sw = 0; + calypso_dump_current_fcp_args_t get_baseline_cur_fcp = {verbose, baseline_cur_fcp, sizeof(baseline_cur_fcp)}; + res = calypso_dump_command_with_resume(&context_resume, calypso_dump_send_current_fcp, &get_baseline_cur_fcp, &baseline_cur_fcp_len, &baseline_cur_fcp_sw); + if (res != PM3_SUCCESS) { + return res; + } + bool have_baseline_cur_fcp = baseline_cur_fcp_len > 0; + + const uint8_t *baseline_node_fcp = have_baseline_cur_fcp ? baseline_cur_fcp : baseline_fcp; + size_t baseline_node_fcp_len = have_baseline_cur_fcp ? baseline_cur_fcp_len : baseline_fcp_len; + bool have_baseline_fcp = have_baseline_get_fcp || have_baseline_cur_fcp; + + uint16_t baseline_lid = 0; + if (have_baseline_fcp && calypso_fcp_lid_with_hint(baseline_node_fcp, baseline_node_fcp_len, have_lid_hint, lid_hint, &baseline_lid)) { + ctx.has_lid = true; + ctx.lid = baseline_lid; + } + + if (ctx.depth == 0 || ctx.is_mf) { + calypso_dump_node_t root_raw = {0}; + bool selected_is_root = ctx.from_root == false || (selected->has_df_lid && selected->df_lid == 0x3F00); + if (selected_is_root) { + calypso_dump_node_init_from_selected(&root_raw, selected); + } + root_raw.default_selection = selected_is_root && ctx.default_selection; + root_raw.sources = CALYPSO_DUMP_SOURCE_SELECTED; + if (ctx.from_root || ctx.is_mf || ctx.has_lid) { + root_raw.has_select_lid = true; + root_raw.select_lid = (ctx.from_root || ctx.is_mf) ? 0x3F00 : ctx.lid; + root_raw.has_lid = true; + root_raw.lid = root_raw.select_lid; + } + if (have_baseline_get_fcp) { + calypso_raw_response_set(&root_raw.get_data_fcp, baseline_fcp, baseline_fcp_len, baseline_fcp_sw); + } + if (have_baseline_cur_fcp) { + calypso_raw_response_set(&root_raw.select_current_fcp, baseline_cur_fcp, baseline_cur_fcp_len, baseline_cur_fcp_sw); + } + + char detail_prefix[96] = {0}; + calypso_dump_detail_prefix(0, detail_prefix, sizeof(detail_prefix)); + calypso_dump_print_root(&ctx, &root_raw); + calypso_dump_print_inline_file_data(detail_prefix, true, &root_raw, verbose); + calypso_dump_add_file_json(dump, &ctx, &root_raw, true, true); + } + + calypso_dump_candidate_list_t candidates = {0}; + calypso_dump_candidate_list_t c0_candidates = {0}; + uint8_t ef_list[APDU_RES_LEN] = {0}; + size_t ef_list_len = 0; + uint16_t ef_list_sw = 0; + calypso_dump_get_data_args_t get_ef_list = {0x00C0, {ef_list, sizeof(ef_list)}}; + res = calypso_dump_command_with_resume(&context_resume, calypso_dump_send_get_data, &get_ef_list, &ef_list_len, &ef_list_sw); + if (res != PM3_SUCCESS) { + goto done; + } + bool have_ef_list = calypso_read_sw_has_data(ef_list_sw, ef_list_len); + if (have_ef_list) { + calypso_dump_add_c0_candidates(&c0_candidates, ef_list, ef_list_len); + } + uint16_t inferred_parent = 0; + bool have_inferred_parent = ctx.is_mf == false && ctx.from_root == false && ctx.path_len == 0 && + calypso_dump_infer_parent_from_c0(&c0_candidates, &inferred_parent); + if (brute && calypso_dump_add_brute_file_candidates(&candidates, &ctx, have_inferred_parent, inferred_parent) == false) { + return PM3_EMALLOC; + } + if (calypso_dump_add_known_candidates(&candidates, &ctx, have_inferred_parent, inferred_parent) == false) { + return PM3_EMALLOC; + } + if (ctx.has_seed_lid && (ctx.has_lid == false || ctx.seed_lid != ctx.lid) && + calypso_dump_candidate_add(&candidates, ctx.seed_lid, CALYPSO_DUMP_SOURCE_SELECTED) == false) { + return PM3_EMALLOC; + } + for (size_t i = 0; i < c0_candidates.count; i++) { + if (calypso_dump_candidate_add(&candidates, c0_candidates.items[i].lid, CALYPSO_DUMP_SOURCE_EFLIST) == false) { + return PM3_EMALLOC; + } + } + + if (verbose) { + PrintAndLogEx(DEBUG, "Dump context has %zu candidates", candidates.count); + if (have_ef_list) { + PrintAndLogEx(DEBUG, "Dump context EF List %s", sprint_hex(ef_list, ef_list_len)); + } else { + PrintAndLogEx(DEBUG, "Dump context EF List unavailable (%04X - %s)", ef_list_sw, GetAPDUCodeDescription(ef_list_sw >> 8, ef_list_sw & 0xFF)); + } + } + + for (size_t i = 0; i < candidates.count; i++) { if (kbd_enter_pressed()) { + calypso_dump_brute_status_clear(&brute_status_visible); PrintAndLogEx(WARNING, "Aborted by user"); - first_error = PM3_EOPABORTED; - break; + res = PM3_EOPABORTED; + goto done; } - calypso_dump_sfi(sfi, sfi_files, verbose, &sfi_file_count, &record_count, &first_error); - if (first_error != PM3_SUCCESS) { - break; + + const calypso_dump_lid_candidate_t *candidate = &candidates.items[i]; + calypso_dump_brute_status_update(candidate, &brute_status_visible, &brute_status_last_lid); + + uint16_t lid = candidate->lid; + if (calypso_dump_walk_is_current_lid(&ctx, lid)) { + continue; } - } - - if (first_error == PM3_SUCCESS) { - calypso_reselect_exact_df_name(selected, verbose); - PrintAndLogEx(INFO, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Search known/discovered file LID paths") " --"); - - calypso_file_candidate_t candidates[CALYPSO_MAX_LID_CANDIDATES] = {0}; - size_t candidate_count = calypso_build_lid_file_candidates(&ef_list, candidates, ARRAYLEN(candidates)); - uint16_t dumped_lids[CALYPSO_MAX_LID_CANDIDATES] = {0}; - size_t dumped_lid_count = 0; - for (size_t i = 0; i < candidate_count; i++) { - if (kbd_enter_pressed()) { - PrintAndLogEx(WARNING, "Aborted by user"); - first_error = PM3_EOPABORTED; - break; + if (restore_base_needed) { + res = calypso_dump_reselect_base(selected, &ctx, verbose); + if (calypso_dump_result_lost(res)) { + calypso_dump_brute_status_clear(&brute_status_visible); + res = calypso_dump_resume_restore(&context_resume); } - uint16_t leaf_lid = calypso_file_ref_leaf_lid(&candidates[i].ref); - if ((candidates[i].source & CALYPSO_FILE_SOURCE_EF_LIST) && calypso_lid_seen(dumped_lids, dumped_lid_count, leaf_lid)) { - continue; + if (res != PM3_SUCCESS) { + goto done; } - calypso_reselect_exact_df_name(selected, verbose); - if (calypso_dump_file_path(&candidates[i].ref, candidates[i].source, lid_files, verbose, &lid_file_count, &record_count, &first_error)) { - if (dumped_lid_count < ARRAYLEN(dumped_lids) && calypso_lid_seen(dumped_lids, dumped_lid_count, leaf_lid) == false) { - dumped_lids[dumped_lid_count++] = leaf_lid; + restore_base_needed = false; + } + + uint8_t select_response[APDU_RES_LEN] = {0}; + size_t select_len = 0; + uint16_t select_sw = 0; + calypso_dump_select_lid_args_t select_cmd = {&ctx, lid, select_response, sizeof(select_response)}; + res = calypso_dump_command_with_resume(&context_resume, calypso_dump_send_select_lid, &select_cmd, &select_len, &select_sw); + if (res != PM3_SUCCESS) { + goto done; + } + if (select_sw == 0x6A82) { + continue; + } + if (calypso_select_sw_has_file(select_sw) == false) { + if (verbose && calypso_read_sw_is_unavailable(select_sw) == false) { + calypso_dump_brute_status_clear(&brute_status_visible); + PrintAndLogEx(INFO, " %*s%04X unavailable (%04X - %s)", (int)(ctx.depth * 2), "", lid, select_sw, GetAPDUCodeDescription(select_sw >> 8, select_sw & 0xFF)); + } + continue; + } + + restore_base_needed = true; + calypso_dump_resume_t file_resume = {selected, &ctx, verbose, CALYPSO_DUMP_RESUME_FILE, lid}; + + uint8_t df_fci[APDU_RES_LEN] = {0}; + size_t df_fci_len = 0; + bool have_df_fci = false; + uint16_t df_fci_sw = 0; + + bool select_is_fci = calypso_data_is_fci(select_response, select_len); + bool select_is_fcp = calypso_data_is_fcp(select_response, select_len); + bool is_df = select_is_fci || (select_is_fcp && calypso_fcp_is_df(select_response, select_len)); + bool is_ef = select_is_fcp && calypso_fcp_is_ef(select_response, select_len); + // Some HCE Calypso cards default unknown LID selection to another file. + // Guard DF recursion against endlessly walking that fallback response. + if (select_is_fcp && is_df && calypso_select_fcp_matches_lid(select_response, select_len, lid) == false) { + continue; + } + + bool tried_df_fci = false; + if (is_df || select_is_fcp == false) { + tried_df_fci = true; + calypso_dump_get_data_args_t get_fci = {0x006F, {df_fci, sizeof(df_fci)}}; + res = calypso_dump_command_with_resume(&file_resume, calypso_dump_send_get_data, &get_fci, &df_fci_len, &df_fci_sw); + if (res != PM3_SUCCESS) { + goto done; + } + have_df_fci = calypso_read_sw_has_data(df_fci_sw, df_fci_len); + if (have_df_fci) { + is_df = true; + } + } + + uint8_t fcp[APDU_RES_LEN] = {0}; + size_t fcp_len = 0; + uint16_t fcp_sw = 0; + calypso_dump_get_data_args_t get_fcp = {0x0062, {fcp, sizeof(fcp)}}; + res = calypso_dump_command_with_resume(&file_resume, calypso_dump_send_get_data, &get_fcp, &fcp_len, &fcp_sw); + if (res != PM3_SUCCESS) { + goto done; + } + bool have_fcp = calypso_read_sw_has_data(fcp_sw, fcp_len); + + const uint8_t *node_fcp = NULL; + size_t node_fcp_len = 0; + bool have_node_fcp = calypso_preferred_fcp(select_is_fcp ? select_response : NULL, select_is_fcp ? select_len : 0, have_fcp ? fcp : NULL, have_fcp ? fcp_len : 0, &node_fcp, &node_fcp_len); + if (have_node_fcp) { + is_df = is_df || calypso_fcp_is_df(node_fcp, node_fcp_len); + is_ef = is_ef || calypso_fcp_is_ef(node_fcp, node_fcp_len); + } + + if (is_df && tried_df_fci == false) { + tried_df_fci = true; + calypso_dump_get_data_args_t get_fci = {0x006F, {df_fci, sizeof(df_fci)}}; + res = calypso_dump_command_with_resume(&file_resume, calypso_dump_send_get_data, &get_fci, &df_fci_len, &df_fci_sw); + if (res != PM3_SUCCESS) { + goto done; + } + have_df_fci = calypso_read_sw_has_data(df_fci_sw, df_fci_len); + } + + uint8_t current_df_fcp[APDU_RES_LEN] = {0}; + size_t current_df_fcp_len = 0; + uint16_t current_df_fcp_sw = 0; + bool have_current_df_fcp = false; + if (is_df) { + calypso_dump_current_fcp_args_t get_current_fcp = {verbose, current_df_fcp, sizeof(current_df_fcp)}; + res = calypso_dump_command_with_resume(&file_resume, calypso_dump_send_current_fcp, &get_current_fcp, ¤t_df_fcp_len, ¤t_df_fcp_sw); + if (res != PM3_SUCCESS) { + goto done; + } + have_current_df_fcp = current_df_fcp_len > 0; + if (have_node_fcp == false && have_current_df_fcp && calypso_data_is_fcp(current_df_fcp, current_df_fcp_len)) { + node_fcp = current_df_fcp; + node_fcp_len = current_df_fcp_len; + have_node_fcp = true; + is_df = calypso_fcp_is_df(node_fcp, node_fcp_len); + is_ef = calypso_fcp_is_ef(node_fcp, node_fcp_len); + } + } + + if (have_node_fcp == false) { + restore_base_needed = true; + continue; + } + + if (is_df == false && is_ef == false) { + continue; + } + + uint16_t node_lid = 0; + bool have_node_lid = calypso_fcp_lid_with_hint(node_fcp, node_fcp_len, true, lid, &node_lid); + + calypso_dump_node_t raw_node = {0}; + raw_node.sources = candidate->sources; + raw_node.has_select_lid = true; + raw_node.select_lid = lid; + raw_node.has_lid = true; + raw_node.lid = have_node_lid ? node_lid : lid; + calypso_dump_node_set_select_response(&raw_node, select_response, select_len, select_sw); + if (tried_df_fci) { + calypso_raw_response_set(&raw_node.get_data_fci, df_fci, have_df_fci ? df_fci_len : 0, df_fci_sw); + } + calypso_raw_response_set(&raw_node.get_data_fcp, fcp, have_fcp ? fcp_len : 0, fcp_sw); + if (is_df) { + calypso_raw_response_set(&raw_node.select_current_fcp, current_df_fcp, have_current_df_fcp ? current_df_fcp_len : 0, current_df_fcp_sw); + } + if (is_df) { + calypso_dump_apply_fci_identity(&raw_node); + calypso_dump_apply_profile_node(&raw_node, dump != NULL ? dump->profile : NULL); + calypso_dump_apply_fci_identity(&raw_node); + } + calypso_dump_brute_status_clear(&brute_status_visible); + calypso_dump_print_node(&ctx, &raw_node, is_df, verbose); + char detail_prefix[96] = {0}; + calypso_dump_detail_prefix(ctx.depth, detail_prefix, sizeof(detail_prefix)); + calypso_dump_print_inline_file_data(detail_prefix, is_df, &raw_node, verbose); + json_t *json_node = calypso_dump_add_file_json(dump, &ctx, &raw_node, is_df, false); + + if (is_df) { + uint16_t child_lid = have_node_lid ? node_lid : lid; + if (ctx.depth + 1 < max_depth && ctx.path_len < CALYPSO_DUMP_NODE_PATH_MAX && + calypso_dump_walk_is_current_lid(&ctx, child_lid) == false) { + calypso_dump_walk_context_t child = ctx; + child.path[child.path_len++] = lid; + child.depth = ctx.depth + 1; + child.is_mf = false; + child.default_selection = false; + child.has_lid = have_node_lid; + child.lid = have_node_lid ? node_lid : 0; + child.has_seed_lid = false; + child.seed_lid = 0; + res = calypso_dump_process_context(selected, &child, max_depth, brute, verbose, dump); + if (res != PM3_SUCCESS) { + goto done; } } - if (first_error != PM3_SUCCESS) { - break; + } else { + res = calypso_dump_read_ef(selected, &ctx, lid, json_node, verbose); + if (res != PM3_SUCCESS) { + goto done; } } } - json_object_set_new(app, "sfiFileCount", json_integer(sfi_file_count)); - json_object_set_new(app, "lidFileCount", json_integer(lid_file_count)); - json_object_set_new(app, "recordCount", json_integer(record_count)); - json_array_append_new(dfs, app); - - *total_sfi_file_count += sfi_file_count; - *total_lid_file_count += lid_file_count; - *total_record_count += record_count; - return first_error; + res = PM3_SUCCESS; +done: + calypso_dump_brute_status_clear(&brute_status_visible); + return res; } -static int calypso_dump_all_declared_dfs(json_t *dfs, calypso_rf_info_t *rf, bool verbose, calypso_select_result_t *first_selected, bool *have_first_selected, calypso_dump_context_t *dump_ctx, size_t *df_count, size_t *total_sfi_file_count, size_t *total_lid_file_count, size_t *total_record_count) { +static int calypso_dump_select_root_mode(const calypso_select_result_t *selected, bool verbose, bool *from_root) { + *from_root = false; + + calypso_dump_walk_context_t aid_ctx = {0}; + uint8_t response[APDU_RES_LEN] = {0}; + size_t response_len = 0; + uint16_t sw = 0; + int res = calypso_dump_select_lid(&aid_ctx, 0x3F00, response, sizeof(response), &response_len, &sw); + if (res != PM3_SUCCESS) { + return res; + } + + if (calypso_select_sw_has_file(sw)) { + uint16_t current_lid = 0; + bool has_current_lid = false; + size_t current_fcp_len = 0; + uint16_t current_fcp_sw = 0; + res = calypso_select_current_file_fcp(verbose, NULL, 0, ¤t_fcp_len, ¤t_fcp_sw, ¤t_lid, &has_current_lid); + if (res != PM3_SUCCESS) { + return res; + } + if ((has_current_lid && calypso_lid_is_valid(current_lid)) || + (calypso_get_current_ef_lid(verbose, ¤t_lid) && calypso_lid_is_valid(current_lid))) { + *from_root = current_lid == 0x3F00; + return PM3_SUCCESS; + } + } + + if (verbose && sw != 0x6A82 && calypso_read_sw_is_unavailable(sw) == false) { + PrintAndLogEx(INFO, " SELECT 3F00 unavailable for root reset (%04X - %s)", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xFF)); + } + + // If MF is not reachable, reset to the selected AID and discover that DF as the root. + return calypso_dump_reselect_base(selected, &aid_ctx, verbose); +} + +static int calypso_dump_selected_df(const calypso_select_result_t *selected, uint16_t max_depth, bool brute, bool verbose, bool default_selection, calypso_dump_json_context_t *dump) { + calypso_print_select_info_ex(selected, verbose, false); + + uint16_t selected_lid = 0; + bool have_selected_lid = false; + uint8_t selected_fcp[APDU_RES_LEN] = {0}; + size_t selected_fcp_len = 0; + uint16_t selected_fcp_sw = 0; + int res = calypso_get_data_object(0x0062, selected_fcp, sizeof(selected_fcp), &selected_fcp_len, &selected_fcp_sw); + if (res != PM3_SUCCESS) { + return res; + } + bool have_selected_fcp = calypso_read_sw_has_data(selected_fcp_sw, selected_fcp_len); + if (have_selected_fcp) { + if (calypso_fcp_lid(selected_fcp, selected_fcp_len, &selected_lid)) { + have_selected_lid = true; + } + } + if (have_selected_lid == false) { + size_t selected_cur_fcp_len = 0; + uint16_t selected_cur_fcp_sw = 0; + bool has_current_lid = false; + res = calypso_select_current_file_fcp(verbose, NULL, 0, &selected_cur_fcp_len, &selected_cur_fcp_sw, &selected_lid, &has_current_lid); + if (res != PM3_SUCCESS) { + return res; + } + have_selected_lid = has_current_lid; + } + bool from_root = false; + res = calypso_dump_select_root_mode(selected, verbose, &from_root); + if (res != PM3_SUCCESS) { + return res; + } + + calypso_dump_walk_context_t root = {0}; + root.from_root = from_root; + root.is_mf = from_root || (have_selected_lid && selected_lid == 0x3F00); + root.default_selection = default_selection; + root.has_lid = have_selected_lid; + root.lid = have_selected_lid ? selected_lid : 0; + if (from_root && have_selected_lid) { + root.has_seed_lid = true; + root.seed_lid = selected_lid; + } + return calypso_dump_process_context(selected, &root, max_depth, brute, verbose, dump); +} + +static int calypso_dump_reactivate(calypso_rf_info_t *rf, bool verbose) { + DropField(); + return calypso_connect_contactless(verbose, rf); +} + +static void calypso_dump_node_copy_raw(uint8_t *dst, size_t *dst_len, const uint8_t *src, size_t src_len, size_t dst_size) { + if (dst == NULL || dst_len == NULL || src == NULL || src_len == 0 || dst_size == 0) { + return; + } + + src_len = MIN(src_len, dst_size); + memcpy(dst, src, src_len); + *dst_len = src_len; +} + +static void calypso_raw_response_set(calypso_raw_response_t *dst, const uint8_t *src, size_t src_len, uint16_t sw) { + if (dst == NULL) { + return; + } + + dst->sw = sw; + dst->len = 0; + calypso_dump_node_copy_raw(dst->data, &dst->len, src, src_len, sizeof(dst->data)); +} + +static void calypso_dump_node_set_select_response(calypso_dump_node_t *node, const uint8_t *data, size_t data_len, uint16_t sw) { + if (node == NULL) { + return; + } + + if (data == NULL || data_len == 0) { + return; + } + + if (calypso_data_is_fcp(data, data_len)) { + calypso_raw_response_set(&node->select_fcp, data, data_len, sw); + } else if (calypso_data_is_fci(data, data_len)) { + calypso_raw_response_set(&node->select_fci, data, data_len, sw); + } +} + +static size_t calypso_dump_node_aid(const calypso_dump_node_t *node, const uint8_t **aid) { + if (aid == NULL) { + return 0; + } + *aid = NULL; + if (node != NULL && node->select_aid_len > 0) { + *aid = node->select_aid; + return node->select_aid_len; + } + return 0; +} + +static bool calypso_dump_node_first_fcp(const calypso_dump_node_t *node, const uint8_t **fcp, size_t *fcp_len) { + if (node == NULL || fcp == NULL || fcp_len == NULL) { + return false; + } + const calypso_raw_response_t *views[] = {&node->select_current_fcp, &node->select_fcp, &node->get_data_fcp}; + for (size_t i = 0; i < ARRAYLEN(views); i++) { + if (views[i]->len > 0) { + *fcp = views[i]->data; + *fcp_len = views[i]->len; + return true; + } + } + return false; +} + +static bool calypso_dump_fcp_lid_pair(const uint8_t *fcp, size_t fcp_len, size_t trailing_bytes, uint16_t *lid) { + const uint8_t *value = NULL; + size_t value_len = 0; + if (lid == NULL || calypso_fcp_value(fcp, fcp_len, &value, &value_len) == false || value_len < trailing_bytes + 2) { + return false; + } + + size_t pos = value_len - trailing_bytes - 2; + uint16_t candidate = ((uint16_t)value[pos] << 8) | value[pos + 1]; + if (calypso_lid_is_valid(candidate) == false) { + return false; + } + *lid = candidate; + return true; +} + +static bool calypso_dump_node_lid_pair(const calypso_dump_node_t *node, bool shifted, uint16_t *lid) { + const uint8_t *fcp = NULL; + size_t fcp_len = 0; + if (calypso_dump_node_first_fcp(node, &fcp, &fcp_len) == false) { + return false; + } + return calypso_dump_fcp_lid_pair(fcp, fcp_len, shifted ? 1 : 0, lid); +} + +static bool calypso_fci_df_name(const uint8_t *fci_data, size_t fci_len, uint8_t *aid, size_t *aid_len) { + if (fci_data == NULL || fci_len == 0 || aid == NULL || aid_len == NULL) { + return false; + } + + struct tlvdb *tlv = tlvdb_parse_multi(fci_data, fci_len); + if (tlv == NULL) { + return false; + } + + calypso_fci_t fci = {0}; + bool found = calypso_tlv_get_df_name(tlv, &fci); + tlvdb_free(tlv); + if (found == false) { + return false; + } + + memcpy(aid, fci.df_name, fci.df_name_len); + *aid_len = fci.df_name_len; + return true; +} + +static void calypso_dump_apply_fci_identity(calypso_dump_node_t *node) { + if (node == NULL || node->select_aid_len > 0) { + return; + } + + if (node->select_fci.len > 0 && + calypso_fci_df_name(node->select_fci.data, node->select_fci.len, node->select_aid, &node->select_aid_len)) { + return; + } + if (node->get_data_fci.len > 0) { + calypso_fci_df_name(node->get_data_fci.data, node->get_data_fci.len, node->select_aid, &node->select_aid_len); + } +} + +static const calypso_dump_node_t *calypso_dump_profile_unique_lid_node(const calypso_dump_profile_t *profile, const calypso_dump_node_t *node) { + uint16_t node_lid = 0; + if (profile == NULL || node == NULL || calypso_dump_node_known_lid(node, &node_lid) == false) { + return NULL; + } + + const calypso_dump_node_t *match = NULL; + for (size_t i = 0; i < profile->node_count; i++) { + uint16_t profile_lid = 0; + if (calypso_dump_node_known_lid(&profile->nodes[i], &profile_lid) == false || profile_lid != node_lid) { + continue; + } + if (match != NULL) { + return NULL; + } + match = &profile->nodes[i]; + } + + return match; +} + +static void calypso_raw_response_copy_missing(calypso_raw_response_t *dst, const calypso_raw_response_t *src) { + if (dst == NULL || src == NULL || dst->len > 0 || src->len == 0) { + return; + } + + calypso_raw_response_set(dst, src->data, src->len, src->sw); +} + +static void calypso_dump_apply_profile_node(calypso_dump_node_t *node, const calypso_dump_profile_t *profile) { + const calypso_dump_node_t *match = calypso_dump_profile_unique_lid_node(profile, node); + if (match == NULL) { + return; + } + + if (node->select_aid_len == 0) { + calypso_dump_node_copy_raw(node->select_aid, &node->select_aid_len, match->select_aid, match->select_aid_len, sizeof(node->select_aid)); + } + if (node->has_select_lid == false && match->has_select_lid) { + node->has_select_lid = true; + node->select_lid = match->select_lid; + } + if (node->has_lid == false && match->has_lid) { + node->has_lid = true; + node->lid = match->lid; + } + node->default_selection = node->default_selection || match->default_selection; + + calypso_raw_response_copy_missing(&node->select_fci, &match->select_fci); + calypso_raw_response_copy_missing(&node->select_fcp, &match->select_fcp); + calypso_raw_response_copy_missing(&node->select_current_fcp, &match->select_current_fcp); + calypso_raw_response_copy_missing(&node->get_data_fci, &match->get_data_fci); + calypso_raw_response_copy_missing(&node->get_data_fcp, &match->get_data_fcp); +} + +static bool calypso_dump_node_serial(const calypso_dump_node_t *node, uint8_t *serial) { + if (node == NULL || serial == NULL) { + return false; + } + + if (node->selected.parsed.has_serial) { + memcpy(serial, node->selected.parsed.serial, CALYPSO_SERIAL_LEN); + return true; + } + + return false; +} + +static bool calypso_dump_profile_has_node_aid(const calypso_dump_profile_t *profile, const calypso_dump_node_t *node) { + if (profile == NULL || node == NULL) { + return false; + } + + const uint8_t *aid = NULL; + size_t aid_len = calypso_dump_node_aid(node, &aid); + if (aid == NULL || aid_len == 0) { + return false; + } + + for (size_t i = 0; i < profile->node_count; i++) { + const uint8_t *seen_aid = NULL; + size_t seen_aid_len = calypso_dump_node_aid(&profile->nodes[i], &seen_aid); + if (seen_aid != NULL && seen_aid_len == aid_len && memcmp(seen_aid, aid, aid_len) == 0) { + return true; + } + } + return false; +} + +static calypso_dump_profile_t *calypso_dump_profile_list_get_or_add(calypso_dump_profile_list_t *profiles, const uint8_t *serial) { + if (profiles == NULL || serial == NULL) { + return NULL; + } + for (size_t i = 0; i < profiles->count; i++) { + if (memcmp(profiles->items[i].serial, serial, CALYPSO_SERIAL_LEN) == 0) { + return &profiles->items[i]; + } + } + if (profiles->count >= ARRAYLEN(profiles->items)) { + return NULL; + } + calypso_dump_profile_t *profile = &profiles->items[profiles->count++]; + memset(profile, 0, sizeof(*profile)); + memcpy(profile->serial, serial, CALYPSO_SERIAL_LEN); + return profile; +} + +static void calypso_dump_node_init_from_selected(calypso_dump_node_t *node, const calypso_select_result_t *selected) { + memset(node, 0, sizeof(*node)); + node->selected = *selected; + node->default_selection = selected->default_selection; + + const uint8_t *aid = NULL; + size_t aid_len = 0; + if (selected->parsed.has_df_name && selected->parsed.df_name_len > 0) { + aid = selected->parsed.df_name; + aid_len = calypso_aid_len_without_trailing_zeroes(selected->parsed.df_name, selected->parsed.df_name_len); + } else if (selected->requested_aid_len > 0) { + aid = selected->requested_aid; + aid_len = selected->requested_aid_len; + } + calypso_dump_node_copy_raw(node->select_aid, &node->select_aid_len, aid, aid_len, sizeof(node->select_aid)); + + calypso_dump_node_set_select_response(node, selected->fci, selected->fci_len, selected->sw); + + if (selected->has_df_lid) { + node->has_select_lid = true; + node->select_lid = selected->df_lid; + node->has_lid = true; + node->lid = selected->df_lid; + } +} + +static int calypso_dump_record_preprobe(calypso_dump_profile_list_t *profiles, const calypso_select_result_t *selected, bool verbose) { + if (profiles == NULL || selected == NULL) { + return PM3_EINVARG; + } + + calypso_dump_node_t node = {0}; + calypso_dump_node_init_from_selected(&node, selected); + + uint8_t fcp[APDU_RES_LEN] = {0}; + size_t fcp_len = 0; + uint16_t fcp_sw = 0; + int res = calypso_get_data_object(0x0062, fcp, sizeof(fcp), &fcp_len, &fcp_sw); + if (res != PM3_SUCCESS) { + return res; + } + if (calypso_read_sw_has_data(fcp_sw, fcp_len)) { + calypso_raw_response_set(&node.get_data_fcp, fcp, fcp_len, fcp_sw); + } + + uint8_t current_fcp[APDU_RES_LEN] = {0}; + size_t current_fcp_len = 0; + uint16_t current_fcp_sw = 0; + uint16_t current_lid = 0; + bool has_current_lid = false; + res = calypso_select_current_file_fcp(verbose, current_fcp, sizeof(current_fcp), ¤t_fcp_len, ¤t_fcp_sw, ¤t_lid, &has_current_lid); + if (res != PM3_SUCCESS) { + return res; + } + if (current_fcp_len > 0) { + calypso_raw_response_set(&node.select_current_fcp, current_fcp, current_fcp_len, current_fcp_sw); + } + if (has_current_lid) { + node.has_lid = true; + node.lid = current_lid; + } + + uint8_t serial[CALYPSO_SERIAL_LEN] = {0}; + bool serial_found = calypso_dump_node_serial(&node, serial); + if (serial_found == false) { + return PM3_SUCCESS; + } + + calypso_dump_profile_t *profile = calypso_dump_profile_list_get_or_add(profiles, serial); + if (profile == NULL) { + return PM3_EMALLOC; + } + + if (calypso_dump_profile_has_node_aid(profile, &node)) { + return PM3_SUCCESS; + } + if (profile->node_count >= profile->node_capacity) { + size_t new_capacity = profile->node_capacity == 0 ? 8 : profile->node_capacity * 2; + calypso_dump_node_t *nodes = realloc(profile->nodes, new_capacity * sizeof(*nodes)); + if (nodes == NULL) { + return PM3_EMALLOC; + } + profile->nodes = nodes; + profile->node_capacity = new_capacity; + } + profile->nodes[profile->node_count++] = node; + return PM3_SUCCESS; +} + +static bool calypso_dump_profile_default_selected(const calypso_dump_profile_t *profile) { + for (size_t i = 0; profile != NULL && i < profile->node_count; i++) { + if (profile->nodes[i].default_selection) { + return true; + } + } + return false; +} + +static int calypso_dump_reselect_for_walk(const calypso_select_result_t *selected, calypso_rf_info_t *rf, bool verbose, bool keep_field, calypso_select_result_t *walk_selected) { + if (selected == NULL || rf == NULL || walk_selected == NULL) { + return PM3_EINVARG; + } + + int res = PM3_SUCCESS; + if (keep_field == false) { + res = calypso_dump_reactivate(rf, verbose); + if (res != PM3_SUCCESS) { + return res; + } + } + + *walk_selected = *selected; + walk_selected->rf = *rf; + + if (selected->default_selection) { + return PM3_SUCCESS; + } + + const uint8_t *aid = selected->parsed.has_df_name ? selected->parsed.df_name : selected->requested_aid; + size_t aid_len = selected->parsed.has_df_name ? selected->parsed.df_name_len : selected->requested_aid_len; + if (aid == NULL || aid_len == 0) { + return PM3_SUCCESS; + } + + bool matched = false; + res = calypso_select_aid(aid, aid_len, verbose, rf, walk_selected, &matched); + if (res != PM3_SUCCESS || matched) { + return res; + } + + bool requested_same = selected->requested_aid_len == aid_len && + memcmp(aid, selected->requested_aid, aid_len) == 0; + if (selected->requested_aid_len > 0 && requested_same == false) { + res = calypso_select_aid(selected->requested_aid, selected->requested_aid_len, verbose, rf, walk_selected, &matched); + if (res != PM3_SUCCESS || matched) { + return res; + } + } + + return PM3_ETIMEOUT; +} + +static bool calypso_dump_node_known_lid(const calypso_dump_node_t *node, uint16_t *lid) { + if (node == NULL || lid == NULL) { + return false; + } + + if (node->has_select_lid && calypso_lid_is_valid(node->select_lid)) { + *lid = node->select_lid; + return true; + } + if (node->has_lid && calypso_lid_is_valid(node->lid)) { + *lid = node->lid; + return true; + } + return calypso_dump_node_lid_pair(node, false, lid) || + calypso_dump_node_lid_pair(node, true, lid); +} + +static const calypso_dump_node_t *calypso_dump_select_root_node(const calypso_dump_profile_t *profile) { + if (profile == NULL || profile->node_count == 0) { + return NULL; + } + + for (size_t i = 0; i < profile->node_count; i++) { + uint16_t lid = 0; + if (calypso_dump_node_known_lid(&profile->nodes[i], &lid) && lid == 0x3F00) { + return &profile->nodes[i]; + } + } + + for (size_t i = 0; i < profile->node_count; i++) { + uint16_t lid = 0; + if (calypso_dump_node_known_lid(&profile->nodes[i], &lid)) { + continue; + } + const uint8_t *aid = NULL; + size_t aid_len = calypso_dump_node_aid(&profile->nodes[i], &aid); + if (aid != NULL && aid_len >= sizeof(calypso_mf_aid) && memcmp(aid, calypso_mf_aid, sizeof(calypso_mf_aid)) == 0) { + return &profile->nodes[i]; + } + } + + for (size_t i = 0; i < profile->node_count; i++) { + const uint8_t *aid = NULL; + size_t aid_len = calypso_dump_node_aid(&profile->nodes[i], &aid); + if (aid_len > 0 || profile->nodes[i].default_selection) { + return &profile->nodes[i]; + } + } + + return &profile->nodes[0]; +} + +static void calypso_dump_print_profile_map(const calypso_dump_profile_list_t *profiles) { + if (profiles == NULL || profiles->count == 0) { + return; + } + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Calypso dump Profile Map") " ----------------"); + for (size_t i = 0; i < profiles->count; i++) { + const calypso_dump_profile_t *profile = &profiles->items[i]; + PrintAndLogEx(INFO, "Serial " _GREEN_("%s") ":", sprint_hex_inrow(profile->serial, CALYPSO_SERIAL_LEN)); + for (size_t j = 0; j < profile->node_count; j++) { + const calypso_dump_node_t *node = &profile->nodes[j]; + const uint8_t *aid = NULL; + size_t aid_len = calypso_dump_node_aid(node, &aid); + uint16_t lid = 0; + bool have_lid = calypso_dump_node_known_lid(node, &lid); + char lid_text[8] = "unknown"; + if (have_lid) { + snprintf(lid_text, sizeof(lid_text), "%04X", lid); + } + if (aid_len > 0) { + PrintAndLogEx(INFO, " " _YELLOW_("%s") " (LID " _GREEN_("%s") "%s)", sprint_hex_inrow(aid, aid_len), lid_text, node->default_selection ? ", default" : ""); + } else { + PrintAndLogEx(INFO, " " _YELLOW_("AID unknown") " (LID " _GREEN_("%s") "%s)", lid_text, node->default_selection ? ", default" : ""); + } + } + } +} + +static int calypso_dump_scan_applications(calypso_rf_info_t *rf, bool verbose, calypso_dump_profile_list_t *profiles, size_t *profile_count) { + if (rf == NULL || profiles == NULL || profile_count == NULL) { + return PM3_EINVARG; + } + + *profile_count = 0; + json_t *root = AIDSearchInit(verbose); if (root == NULL) { return PM3_EFILE; } - size_t seen_capacity = json_array_size(root); - calypso_app_identity_t *seen = calloc(seen_capacity == 0 ? 1 : seen_capacity, sizeof(*seen)); - if (seen == NULL) { - AIDSearchFree(root); - return PM3_EMALLOC; - } - size_t seen_count = 0; int first_error = PM3_SUCCESS; - bool reactivate_before_next_probe = false; + bool implicit_matched = false; - for (size_t scan_aid_len = CALYPSO_MIN_AID_LEN; scan_aid_len <= CALYPSO_MAX_AID_LEN && first_error == PM3_SUCCESS; scan_aid_len++) { + calypso_select_result_t implicit_selected = {0}; + bool default_df_selected = false; + first_error = calypso_probe_current_df(rf, verbose, &implicit_selected, &implicit_matched, &default_df_selected); + if (first_error == PM3_SUCCESS && implicit_matched) { + first_error = calypso_dump_record_preprobe(profiles, &implicit_selected, verbose); + } else if (first_error == PM3_SUCCESS && default_df_selected) { + calypso_fci_t empty_fci = {0}; + uint8_t empty_data = 0; + calypso_set_selected_result(true, NULL, 0, false, 0, rf, &empty_data, 0, 0, &empty_fci, &implicit_selected); + first_error = calypso_dump_record_preprobe(profiles, &implicit_selected, verbose); + } + if (first_error != PM3_SUCCESS) { + AIDSearchFree(root); + return first_error; + } + + for (int scan_pass = 0; scan_pass < 3 && first_error == PM3_SUCCESS; scan_pass++) { for (size_t elmindx = 0; elmindx < json_array_size(root); elmindx++) { json_t *data = AIDSearchGetElm(root, elmindx); if (data == NULL || calypso_json_string_is(data, "Protocol", "cna_calypso") == false) { @@ -2851,7 +4170,11 @@ static int calypso_dump_all_declared_dfs(json_t *dfs, calypso_rf_info_t *rf, boo continue; } - if ((size_t)aid_len != scan_aid_len) { + bool prefix = calypso_aid_is_prefix(aid, (size_t)aid_len); + bool generic = calypso_aid_is_generic(aid, (size_t)aid_len); + if ((scan_pass == 0 && prefix == false) || + (scan_pass == 1 && (prefix || generic == false)) || + (scan_pass == 2 && (prefix || generic))) { continue; } @@ -2859,19 +4182,6 @@ static int calypso_dump_all_declared_dfs(json_t *dfs, calypso_rf_info_t *rf, boo continue; } - if (reactivate_before_next_probe) { - if (verbose) { - PrintAndLogEx(DEBUG, "Reactivating ISO14443-4 target before probing next Calypso DF"); - } - DropField(); - int res = calypso_connect_contactless(verbose, rf); - if (res != PM3_SUCCESS) { - first_error = res; - break; - } - reactivate_before_next_probe = false; - } - calypso_select_result_t selected = {0}; bool matched = false; int res = calypso_select_aid(aid, (size_t)aid_len, verbose, rf, &selected, &matched); @@ -2882,75 +4192,94 @@ static int calypso_dump_all_declared_dfs(json_t *dfs, calypso_rf_info_t *rf, boo if (matched == false) { continue; } - if (calypso_dump_identity_seen(seen, seen_count, &selected)) { - if (verbose) { - calypso_app_identity_t identity = {0}; - calypso_select_identity(&selected, &identity); - PrintAndLogEx(DEBUG, "Skipping duplicate Calypso DF %s", sprint_hex_inrow(identity.aid, identity.aid_len)); - } - continue; - } - calypso_dump_identity_add(seen, seen_capacity, &seen_count, &selected); - if (*have_first_selected == false) { - *first_selected = selected; - *have_first_selected = true; - } - (*df_count)++; - calypso_dump_context_add_serial(dump_ctx, &selected); - - first_error = calypso_dump_selected_df(&selected, dfs, verbose, total_sfi_file_count, total_lid_file_count, total_record_count); + first_error = calypso_dump_record_preprobe(profiles, &selected, verbose); if (first_error != PM3_SUCCESS) { break; } - // HCE implementations may stop responding after sustained access; refresh before the next DF probe. - reactivate_before_next_probe = true; } } - free(seen); + if (first_error == PM3_SUCCESS) { + calypso_dump_print_profile_map(profiles); + } + + *profile_count = profiles->count; + AIDSearchFree(root); return first_error; } +static int calypso_dump_profile(calypso_dump_profile_t *dump_profile, calypso_rf_info_t *rf, uint16_t max_depth, bool brute, bool verbose, bool keep_field, json_t *profiles_json, calypso_dump_filename_context_t *filename_ctx, calypso_select_result_t *first_selected, bool *have_first_selected) { + if (dump_profile == NULL || rf == NULL || profiles_json == NULL) { + return PM3_EINVARG; + } + + const calypso_dump_node_t *root_node = calypso_dump_select_root_node(dump_profile); + if (root_node == NULL) { + return PM3_EOPABORTED; + } + bool root_default_selection = root_node->default_selection; + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Calypso dump Profile %s") " ----------", sprint_hex_inrow(dump_profile->serial, CALYPSO_SERIAL_LEN)); + + calypso_select_result_t walk_selected = {0}; + int res = calypso_dump_reselect_for_walk(&root_node->selected, rf, verbose, keep_field, &walk_selected); + if (res != PM3_SUCCESS) { + return res; + } + + if (*have_first_selected == false) { + *first_selected = walk_selected; + *have_first_selected = true; + } + calypso_dump_filename_add_serial(filename_ctx, &walk_selected); + + json_t *profile = json_object(); + calypso_json_set_hex(profile, "serial", dump_profile->serial, sizeof(dump_profile->serial)); + json_t *nodes = json_array(); + json_object_set_new(profile, "nodes", nodes); + + calypso_dump_json_context_t dump = { + .nodes = nodes, + .profile = dump_profile, + }; + res = calypso_dump_selected_df(&walk_selected, max_depth, brute, verbose, root_default_selection, &dump); + + json_array_append_new(profiles_json, profile); + return res; +} + static int CmdHFCalypsoDump(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf calypso dump", - "Dump readable files and records from Calypso DFs", + "Dump Calypso nodes by first scanning available application profiles", "hf calypso dump\n" - "hf calypso dump --aid 315449432E494341\n" + "hf calypso dump --brute\n" "hf calypso dump -f my-calypso-dump\n" "hf calypso dump --ns -v"); void *argtable[] = { arg_param_begin, - arg_str0(NULL, "aid", "", "Calypso application AID or AID prefix (5..16 bytes)"), arg_str0("f", "file", "", "Specify a filename for JSON dump file"), + arg_lit0(NULL, "brute", "bruteforce LID candidates"), arg_lit0(NULL, "ns", "no save to file"), arg_lit0("v", "verbose", "verbose output"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); - uint8_t user_aid[CALYPSO_MAX_AID_LEN] = {0}; - int user_aid_len = 0; - int parse_res = CLIParamHexToBuf(arg_get_str(ctx, 1), user_aid, sizeof(user_aid), &user_aid_len); - char filename[FILE_PATH_SIZE] = {0}; int fnlen = 0; - CLIParamStrToBuf(arg_get_str(ctx, 2), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + bool brute = arg_get_lit(ctx, 2); bool no_save = arg_get_lit(ctx, 3); bool verbose = arg_get_lit(ctx, 4); CLIParserFree(ctx); - if (parse_res != PM3_SUCCESS) { - return PM3_EINVARG; - } - if (user_aid_len > 0 && (user_aid_len < 5 || user_aid_len > CALYPSO_MAX_AID_LEN)) { - PrintAndLogEx(ERR, "AID length must be 5..16 bytes, got %d", user_aid_len); - return PM3_EINVARG; - } + uint16_t max_depth = 4; calypso_rf_info_t rf = {0}; int res = calypso_connect_contactless(verbose, &rf); @@ -2961,76 +4290,52 @@ static int CmdHFCalypsoDump(const char *Cmd) { } calypso_print_rf_info(&rf); - json_t *root = json_object(); - json_t *dfs = json_array(); - json_object_set_new(root, "type", json_string("calypso-dump")); - json_object_set_new(root, "dfs", dfs); - - size_t df_count = 0; - size_t sfi_file_count = 0; - size_t lid_file_count = 0; - size_t record_count = 0; - int first_error = PM3_SUCCESS; - calypso_select_result_t first_selected = {0}; - bool have_first_selected = false; - calypso_dump_context_t dump_ctx = {0}; - - if (user_aid_len > 0) { - calypso_select_result_t selected = {0}; - bool matched = false; - res = calypso_select_aid(user_aid, (size_t)user_aid_len, verbose, &rf, &selected, &matched); - if (res != PM3_SUCCESS) { - DropField(); - json_decref(root); - PrintAndLogEx(WARNING, "No ISO14443-4 Calypso application selected"); - return res; - } - - if (matched == false) { - DropField(); - json_decref(root); - PrintAndLogEx(WARNING, "No Calypso application found"); - return PM3_EOPABORTED; - } - - first_selected = selected; - have_first_selected = true; - df_count = 1; - calypso_dump_context_add_serial(&dump_ctx, &selected); - first_error = calypso_dump_selected_df(&selected, dfs, verbose, &sfi_file_count, &lid_file_count, &record_count); - } else { - first_error = calypso_dump_all_declared_dfs(dfs, &rf, verbose, &first_selected, &have_first_selected, &dump_ctx, &df_count, &sfi_file_count, &lid_file_count, &record_count); - if (first_error != PM3_SUCCESS && df_count == 0) { - DropField(); - json_decref(root); - return first_error; - } - if (first_error == PM3_SUCCESS && df_count == 0) { - DropField(); - json_decref(root); - PrintAndLogEx(WARNING, "No Calypso application found"); - return PM3_EOPABORTED; - } + calypso_dump_profile_list_t dump_profiles = {0}; + size_t profile_count = 0; + int first_error = calypso_dump_scan_applications(&rf, verbose, &dump_profiles, &profile_count); + if (first_error != PM3_SUCCESS) { + calypso_dump_profile_list_free(&dump_profiles); + DropField(); + return first_error; } - json_object_set_new(root, "dfCount", json_integer(df_count)); - json_object_set_new(root, "sfiFileCount", json_integer(sfi_file_count)); - json_object_set_new(root, "lidFileCount", json_integer(lid_file_count)); - json_object_set_new(root, "recordCount", json_integer(record_count)); + if (profile_count == 0) { + calypso_dump_profile_list_free(&dump_profiles); + DropField(); + PrintAndLogEx(WARNING, "No serial-bearing Calypso profile found"); + return PM3_EOPABORTED; + } + + json_t *root = json_object(); + json_t *profiles = json_array(); + json_object_set_new(root, "type", json_string("calypso-dump")); + json_object_set_new(root, "profiles", profiles); + + calypso_select_result_t first_selected = {0}; + bool have_first_selected = false; + calypso_dump_filename_context_t filename_ctx = {0}; + size_t dumped_profiles = 0; + + for (size_t i = 0; i < dump_profiles.count; i++) { + bool keep_field = dump_profiles.count == 1 && calypso_dump_profile_default_selected(&dump_profiles.items[i]) == false; + first_error = calypso_dump_profile(&dump_profiles.items[i], &rf, max_depth, brute, verbose, keep_field, profiles, &filename_ctx, &first_selected, &have_first_selected); + if (first_error != PM3_SUCCESS) { + break; + } + dumped_profiles++; + } DropField(); PrintAndLogEx(INFO, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Calypso Dump Summary") " --------------------"); - PrintAndLogEx(SUCCESS, " DFs : " _GREEN_("%zu"), df_count); - PrintAndLogEx(SUCCESS, " SFI files : " _GREEN_("%zu"), sfi_file_count); - PrintAndLogEx(SUCCESS, " LID files : " _GREEN_("%zu"), lid_file_count); - PrintAndLogEx(SUCCESS, " Records : " _GREEN_("%zu"), record_count); + PrintAndLogEx(INFO, "--- " _CYAN_("Calypso dump Summary") " --------------------"); + PrintAndLogEx(SUCCESS, " Profiles scanned : " _GREEN_("%zu"), profile_count); + PrintAndLogEx(SUCCESS, " Profiles dumped : " _GREEN_("%zu"), dumped_profiles); if (no_save == false) { if (fnlen == 0) { if (have_first_selected) { - calypso_dump_default_filename(&first_selected, &dump_ctx, filename, sizeof(filename)); + calypso_dump_default_filename(&first_selected, &filename_ctx, filename, sizeof(filename)); } else { snprintf(filename, sizeof(filename), "hf-calypso-dump"); } @@ -3042,6 +4347,7 @@ static int CmdHFCalypsoDump(const char *Cmd) { } json_decref(root); + calypso_dump_profile_list_free(&dump_profiles); PrintAndLogEx(NORMAL, ""); return first_error; } @@ -3406,7 +4712,7 @@ static int CmdHFCalypsoInfo(const char *Cmd) { static command_t CommandTable[] = { {"help", CmdHelp, AlwaysAvailable, "This help"}, {"info", CmdHFCalypsoInfo, IfPm3Iso14443, "Tag information"}, - {"dump", CmdHFCalypsoDump, IfPm3Iso14443, "Dump readable files and records"}, + {"dump", CmdHFCalypsoDump, IfPm3Iso14443, "Dump nodes after application profile scan"}, {"probecmdcompat", CmdHFCalypsoProbe, IfPm3Iso14443, "Probe SELECT command compatibility"}, {"list", CmdHFCalypsoList, AlwaysAvailable, "List Calypso history"}, {NULL, NULL, NULL, NULL} diff --git a/client/src/cmdhffelica.c b/client/src/cmdhffelica.c index f2860b0b7..0f01acf29 100644 --- a/client/src/cmdhffelica.c +++ b/client/src/cmdhffelica.c @@ -70,8 +70,8 @@ #define FELICA_SYSTEM_CODE_FELICA_LITE 0x88B4U #define FELICA_POLL_REQUEST_NO_DATA 0x00U #define FELICA_POLL_REQUEST_SYSTEM_CODE 0x01U -#define FELICA_SYSTEM_LIST_JSON "felica_system_code_list" -#define FELICA_IC_CODE_LIST_JSON "felica_ic_code_list" +#define FELICA_SYSTEM_LIST_JSON "felica/felica_system_code_list" +#define FELICA_IC_CODE_LIST_JSON "felica/felica_ic_code_list" #define FELICA_SERVICE_ATTRIBUTE_UNAUTH_READ (0b000001) #define FELICA_SERVICE_ATTRIBUTE_READ_ONLY (0b000010) @@ -350,10 +350,10 @@ static void print_status_flag1_interpretation(void) { PrintAndLogEx(INFO, "----+--------------------------------------------------------------------------------------------------------------------"); PrintAndLogEx(INFO, " 00 | Indicates the successful completion of a command."); PrintAndLogEx(INFO, " FF | If an error occurs during the processing of a command that includes no list in the command packet, \n" - " | or if an error occurs independently of any list, the card returns a response by setting FFh to Status Flag1."); + " | or if an error occurs independently of any list, the card returns a response by setting FFh to Status Flag1."); PrintAndLogEx(INFO, " XX | If an error occurs while processing a command that includes Service Code List or Block List \n" - " | in the command packet, the card returns a response by setting a number in the list to Status Flag1,\n" - " | indicating the location of the error."); + " | in the command packet, the card returns a response by setting a number in the list to Status Flag1,\n" + " | indicating the location of the error."); PrintAndLogEx(INFO, "----+--------------------------------------------------------------------------------------------------------------------"); } @@ -362,28 +362,28 @@ static void print_status_flag2_interpration(void) { PrintAndLogEx(INFO, "----+--------------------------------------------------------------------------------------------------------------------"); PrintAndLogEx(INFO, " 00 | Indicates the successful completion of a command."); PrintAndLogEx(INFO, " 01 | The calculated result is either less than zero when the purse data is decremented, or exceeds 4\n" - " | Bytes when the purse data is incremented."); + " | Bytes when the purse data is incremented."); PrintAndLogEx(INFO, " 02 | The specified data exceeds the value of cashback data at cashback of purse."); PrintAndLogEx(INFO, " 70 | Memory error (fatal error)."); PrintAndLogEx(INFO, " 71 | The number of memory rewrites exceeds the upper limit (this is only a warning; data writing is performed as normal).\n" - " | The maximum number of rewrites can differ, depending on the product being used.\n" - " | In addition, Status Flag1 is either 00h or FFh depending on the product being used."); + " | The maximum number of rewrites can differ, depending on the product being used.\n" + " | In addition, Status Flag1 is either 00h or FFh depending on the product being used."); PrintAndLogEx(INFO, " A1 | Illegal Number of Service| Number of Service or Number of Node specified by the command \n" - " | falls outside the range of the prescribed value."); + " | falls outside the range of the prescribed value."); PrintAndLogEx(INFO, " A2 | Illegal command packet (specified Number of Block) : Number of Block specified by the \n" - " | command falls outside the range of the prescribed values for the product."); + " | command falls outside the range of the prescribed values for the product."); PrintAndLogEx(INFO, " A3 | Illegal Block List (specified order of Service) : Service Code List Order specified by \n" - " | Block List Element falls outside the Number of Service specified by the command \n" - " | (or the Number of Service specified at the times of mutual authentication)."); + " | Block List Element falls outside the Number of Service specified by the command \n" + " | (or the Number of Service specified at the times of mutual authentication)."); PrintAndLogEx(INFO, " A4 | Illegal Service type : Area Attribute specified by the command or Service Attribute of Service Code is incorrect."); PrintAndLogEx(INFO, " A5 | Access is not allowed : Area or Service specified by the command cannot be accessed.\n" - " | The parameter specified by the command does not satisfy the conditions for success."); + " | The parameter specified by the command does not satisfy the conditions for success."); PrintAndLogEx(INFO, " A6 | Illegal Service Code List : Target to be accessed, identified by Service Code List Order, specified by Block\n" - " | List Element does not exist. Or, Node specified by Node Code List does not exist."); + " | List Element does not exist. Or, Node specified by Node Code List does not exist."); PrintAndLogEx(INFO, " A7 | Illegal Block List (Access Mode) : Access Mode specified by Block List Element is incorrect."); PrintAndLogEx(INFO, " A8 | Illegal Block Number Block Number (access to the specified data is inhibited) :\n" - " | specified by Block List Element exceeds the number of Blocks assigned to Service."); + " | specified by Block List Element exceeds the number of Blocks assigned to Service."); PrintAndLogEx(INFO, " A9 | Data write failure : This is the error that occurs in issuance commands."); PrintAndLogEx(INFO, " AA | Key-change failure : Key change failed."); PrintAndLogEx(INFO, " AB | Illegal Package Parity or illegal Package MAC : This is the error that occurs in issuance commands."); @@ -391,7 +391,7 @@ static void print_status_flag2_interpration(void) { PrintAndLogEx(INFO, " AD | Service exists already : This is the error that occurs in issuance commands."); PrintAndLogEx(INFO, " AE | Illegal System Code : This is the error that occurs in issuance commands."); PrintAndLogEx(INFO, " AF | Too many simultaneous cyclic write operations : Number of simultaneous write Blocks\n" - " | specified by the command to Cyclic Service exceeds the number of Blocks assigned to Service."); + " | specified by the command to Cyclic Service exceeds the number of Blocks assigned to Service."); PrintAndLogEx(INFO, " C0 | Illegal Package Identifier : This is the error that occurs in issuance commands."); PrintAndLogEx(INFO, " C1 | Discrepancy of parameters inside and outside Package : This is the error that occurs in issuance commands."); PrintAndLogEx(INFO, " C2 | Command is disabled already : This is the error that occurs in issuance commands."); @@ -415,16 +415,16 @@ static void print_number_of_service_constraints(void) { static void print_number_of_block_constraints(void) { PrintAndLogEx(INFO, " - Number of Block: shall be less than or equal to the maximum number of Blocks that can be read simultaneously.\n" - " The maximum number of Blocks that can be read simultaneously can differ, depending on the product being used.\n" - " Use as default 01"); + " The maximum number of Blocks that can be read simultaneously can differ, depending on the product being used.\n" + " Use as default 01"); } static void print_service_code_list_constraints(void) { PrintAndLogEx(INFO, " - Service Code List: For Service Code List, only Service Code existing in the product shall be specified:"); PrintAndLogEx(INFO, " - Even when Service Code exists in the product, Service Code not referenced from Block List shall not \n" - " be specified to Service Code List."); + " be specified to Service Code List."); PrintAndLogEx(INFO, " - For existence or nonexistence of Service in a product, please check using the Request Service \n" - " (or Request Service v2) command."); + " (or Request Service v2) command."); } /* diff --git a/client/src/cmdhfgallagher.c b/client/src/cmdhfgallagher.c index 4cacbbc8a..08ffbec17 100644 --- a/client/src/cmdhfgallagher.c +++ b/client/src/cmdhfgallagher.c @@ -381,7 +381,7 @@ static int hfgal_create_creds_app(DesfireContext_t *ctx, uint8_t *site_key, uint // UID is required for key diversification if (ctx->uidlen == 0) { PM3_RET_ERR(PM3_EINVARG, "UID is required for key diversification. " - "Please fetch it before calling `hfgal_create_creds_app`"); + "Please fetch it before calling `hfgal_create_creds_app`"); } // Create application @@ -871,11 +871,11 @@ static int hfgal_read_desfire_card(uint32_t aid, uint8_t *site_key, bool verbose PM3_RET_IF_ERR_MAYBE_MSG(res, !quiet, "Failed reading card application credentials"); PrintAndLogEx(SUCCESS, "Gallagher (AID %06X) - region: " _GREEN_("%c") " ( " _GREEN_("%u") " )" - ", facility: " _GREEN_("%u") - ", card number: " _GREEN_("%u") - ", issue level: " _GREEN_("%u"), + ", facility: " _GREEN_("%u") + ", card number: " _GREEN_("%u") + ", issue level: " _GREEN_("%u"), current_aid, - 'A' + creds.region_code, + 'A' + creds.region_code, creds.region_code, creds.facility_code, creds.card_number, @@ -1696,10 +1696,10 @@ static int CmdGallagherDecode(const char *cmd) { gallagher_decode_creds(data_buf, &creds); PrintAndLogEx(SUCCESS, "Gallagher - region: " _GREEN_("%c") " ( " _GREEN_("%u") " )" - ", facility: " _GREEN_("%u") - ", card number: " _GREEN_("%u") - ", issue level: " _GREEN_("%u"), - 'A' + creds.region_code, + ", facility: " _GREEN_("%u") + ", card number: " _GREEN_("%u") + ", issue level: " _GREEN_("%u"), + 'A' + creds.region_code, creds.region_code, creds.facility_code, creds.card_number, diff --git a/client/src/cmdhflegic.c b/client/src/cmdhflegic.c index 5caf36c4f..f1539cceb 100644 --- a/client/src/cmdhflegic.c +++ b/client/src/cmdhflegic.c @@ -352,7 +352,7 @@ static int decode_and_print_memory(uint16_t card_size, const uint8_t *input_buff // for printing the complete segment we need at least wrc + wrp_len + remain_seg_payload_len bytes if ((i + wrc + wrp_len + remain_seg_payload_len) > card_size) { PrintAndLogEx(FAILED, "Cannot read segment body, because the input buffer is too small. " - "Please check that the data is correct and properly aligned. "); + "Please check that the data is correct and properly aligned. "); return_value = PM3_EOUTOFBOUND; goto out; } @@ -436,7 +436,7 @@ static int decode_and_print_memory(uint16_t card_size, const uint8_t *input_buff // for printing the complete segment we need at least wrc + wrp_len + remain_seg_payload_len bytes if ((i + wrc + wrp_len + remain_seg_payload_len) > card_size) { PrintAndLogEx(FAILED, "Cannot read segment body, because the input buffer is too small. " - "Please check that the data is correct and properly aligned. "); + "Please check that the data is correct and properly aligned. "); return_value = PM3_EOUTOFBOUND; goto out; } @@ -607,7 +607,7 @@ static int CmdLegicSim(const char *Cmd) { "If a file is supplied, it is loaded into emulator memory first.", "hf legic sim --22\n" "hf legic sim -f myfile.bin --1024\n" - ); + ); void *argtable[] = { arg_param_begin, diff --git a/client/src/cmdhflist.c b/client/src/cmdhflist.c index e64eb9ee7..d02c2e16b 100644 --- a/client/src/cmdhflist.c +++ b/client/src/cmdhflist.c @@ -33,6 +33,7 @@ #include "cmdhfcalypso.h" #include "mifare/mifaredefault.h" // mifare consts #include "cmdhfseos.h" +#include "iso7816/apduinfo.h" enum MifareAuthSeq { masNone, @@ -1034,24 +1035,48 @@ static bool annotateCalypsoApdu(char *exp, size_t size, const uint8_t *apdu, siz return false; } - uint8_t ins = apdu[1]; - uint8_t p1 = apdu[2]; - uint8_t p2 = apdu[3]; + uint8_t decoded_data[1024] = {0}; + APDU_t decoded = {0}; + bool decoded_ok = false; + if (apdu_len <= sizeof(decoded_data)) { + memcpy(decoded_data, apdu, apdu_len); + decoded_ok = APDUDecode(decoded_data, (int)apdu_len, &decoded) == 0; + if (decoded_ok == false && apdu_len > 2) { + decoded_ok = APDUDecode(decoded_data, (int)(apdu_len - 2), &decoded) == 0; + } + } + + uint8_t ins = decoded_ok ? decoded.ins : apdu[1]; + uint8_t p1 = decoded_ok ? decoded.p1 : apdu[2]; + uint8_t p2 = decoded_ok ? decoded.p2 : apdu[3]; switch (ins) { case CALYPSO_SELECT: { - if (p1 == 0x04) { + if (decoded_ok && (p1 == 0x00 || p1 == 0x08 || p1 == 0x09)) { + char ref[64] = "current DF"; // Select for empty LID implies current DF + if (decoded.lc == 2) { + uint16_t fid = (decoded.data[0] << 8) | decoded.data[1]; + if (fid == 0x3F00) { + snprintf(ref, sizeof(ref), "MF"); + } else if (fid != 0x0000) { + snprintf(ref, sizeof(ref), p1 == 0x08 ? "path=%04X" : "lid=%04X", fid); + } + } else if (decoded.lc > 0) { + snprintf(ref, sizeof(ref), p1 == 0x08 ? "path=%s" : "data=%s", sprint_hex_inrow(decoded.data, decoded.lc)); + } + snprintf(exp, size, "SELECT FILE (%s)", ref); + } else if (p1 == 0x04) { const char *mode = (p2 == 0x02 || p2 == 0x0E) ? "next" : "first"; - const char *fci = (p2 == 0x0C || p2 == 0x0E) ? "none" : "return"; - snprintf(exp, size, "SELECT APPLICATION (mode=%s, fci=%s)", mode, fci); + const char *fci = (p2 == 0x0C || p2 == 0x0E) ? "N" : "Y"; + if (decoded_ok && decoded.lc > 0) { + snprintf(exp, size, "SELECT APP (aid=%s, mode=%s, fci=%s)", sprint_hex_inrow(decoded.data, decoded.lc), mode, fci); + } else { + snprintf(exp, size, "SELECT APP (mode=%s, fci=%s)", mode, fci); + } } else if (p1 == 0x02 && (p2 == 0x00 || p2 == 0x02)) { - snprintf(exp, size, "SELECT FILE"); - } else if (p1 == 0x09 && p2 == 0x00) { - snprintf(exp, size, "SELECT FILE (current DF)"); - } else if (p1 == 0x00) { - snprintf(exp, size, "SELECT FILE (by file id)"); - } else if (p1 == 0x08) { - snprintf(exp, size, "SELECT FILE (by path)"); + snprintf(exp, size, p2 == 0x02 ? "SELECT FILE (next EF)" : "SELECT FILE (first EF)"); + } else if (p1 == 0x03) { + snprintf(exp, size, "SELECT FILE (parent DF)"); } else { snprintf(exp, size, "SELECT"); } diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index 33bb4dc0f..7411426eb 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -5050,7 +5050,7 @@ void printKeyTableEx(size_t sectorscnt, sector_t *e_sector, uint8_t start_sector _YELLOW_("H") ":Hardnested / " _YELLOW_("C") ":statiCnested / " _YELLOW_("A") ":keyA " - " )" + " )" ); if (sectorscnt == 18) { PrintAndLogEx(INFO, "( " _MAGENTA_("*") " ) These sectors used for signature. Lays outside of user memory"); diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index ab643e2bc..4d03185c4 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -9234,7 +9234,7 @@ static int CmdHF14ADesVerifyCert(const char *Cmd) { arg_str0(NULL, "fid", "", "Certificate file ID (1 byte)"), // 15 arg_lit0(NULL, "no-auth", "Read certificate file without authentication"), // 16 arg_strn(NULL, "ca", "", 0, MFDES_VERIFYCERT_MAX_CAS, - "CA input, or `skip` to skip certificate signature validation. Repeat --ca for multiple entries"), // 17 + "CA input, or `skip` to skip certificate signature validation. Repeat --ca for multiple entries"), // 17 arg_str0(NULL, "keyaid", "", "Key application ID (default: cert app)"), // 18 arg_str0(NULL, "keyisoid", "", "Key application ISO DF ID (2 bytes)"), // 19 arg_str0(NULL, "keydfname", "", "Key application DF name (default: cert app)"), // 20 diff --git a/client/src/cmdhfmfsen.c b/client/src/cmdhfmfsen.c index 34f959f44..bc4f8c39e 100644 --- a/client/src/cmdhfmfsen.c +++ b/client/src/cmdhfmfsen.c @@ -1236,7 +1236,7 @@ static uint32_t fm11_count_candidate_seed_matches_vec(const fm11_keylist_t *list uint32_t i = 0; for (; i + 4 <= list->count; i += 4) { const union vec probe = VEC_U(list->data[i].seed, list->data[i + 1].seed, - list->data[i + 2].seed, list->data[i + 3].seed); + list->data[i + 2].seed, list->data[i + 3].seed); const union vec eq = vec_ueq(probe, target); matches += eq.elem.u[0] != 0; matches += eq.elem.u[1] != 0; @@ -1289,7 +1289,7 @@ static int fm11_filter_candidates_by_seed(fm11_keylist_t *list, uint32_t nt, uin uint32_t i = 0; for (; i + 4 <= list->count; i += 4) { const union vec probe = VEC_U(list->data[i].seed, list->data[i + 1].seed, - list->data[i + 2].seed, list->data[i + 3].seed); + list->data[i + 2].seed, list->data[i + 3].seed); const union vec eq = vec_ueq(probe, target); if (eq.elem.u[0] != 0) { filtered.data[filtered.count++] = list->data[i]; @@ -1401,30 +1401,38 @@ static int fm11_intersect_pair(uint32_t nt_a, fm11_keylist_t *a, uint32_t nt_b, fm11_keylist_t fb = {0}; for (uint32_t i = 0; i < a->count; i++) { if (((i & 0x3FF) == 0) && kbd_enter_pressed()) { - free(bset_a); free(bset_b); - fm11_keylist_free(&fa); fm11_keylist_free(&fb); + free(bset_a); + free(bset_b); + fm11_keylist_free(&fa); + fm11_keylist_free(&fb); return PM3_EOPABORTED; } if (BSET_TEST(bset_b, a->data[i].seed)) { int res = fm11_keylist_push_seeded(&fa, a->data[i].key, a->data[i].seed); if (res != PM3_SUCCESS) { - free(bset_a); free(bset_b); - fm11_keylist_free(&fa); fm11_keylist_free(&fb); + free(bset_a); + free(bset_b); + fm11_keylist_free(&fa); + fm11_keylist_free(&fb); return res; } } } for (uint32_t i = 0; i < b->count; i++) { if (((i & 0x3FF) == 0) && kbd_enter_pressed()) { - free(bset_a); free(bset_b); - fm11_keylist_free(&fa); fm11_keylist_free(&fb); + free(bset_a); + free(bset_b); + fm11_keylist_free(&fa); + fm11_keylist_free(&fb); return PM3_EOPABORTED; } if (BSET_TEST(bset_a, b->data[i].seed)) { int res = fm11_keylist_push_seeded(&fb, b->data[i].key, b->data[i].seed); if (res != PM3_SUCCESS) { - free(bset_a); free(bset_b); - fm11_keylist_free(&fa); fm11_keylist_free(&fb); + free(bset_a); + free(bset_b); + fm11_keylist_free(&fa); + fm11_keylist_free(&fb); return res; } } @@ -1462,8 +1470,8 @@ typedef struct { } fm11_seed_bucket_t; static int fm11_build_seed_buckets(fm11_keylist_t *a, fm11_keylist_t *b, - fm11_seed_bucket_t **buckets_out, - uint32_t *bucket_count_out) { + fm11_seed_bucket_t **buckets_out, + uint32_t *bucket_count_out) { uint32_t *count_a = calloc(UINT16_MAX + 1, sizeof(uint32_t)); uint32_t *count_b = calloc(UINT16_MAX + 1, sizeof(uint32_t)); if (count_a == NULL || count_b == NULL) { @@ -1763,7 +1771,7 @@ static void fm11_probe_queue_push(fm11_probe_queue_t *q, uint8_t sec, uint8_t kt return; } } - q->entries[q->count++] = (fm11_probe_entry_t){.sec = sec, .key_type = kt, .key = key}; + q->entries[q->count++] = (fm11_probe_entry_t) {.sec = sec, .key_type = kt, .key = key}; } static uint32_t fm11_accept_found_key_global( @@ -1891,9 +1899,9 @@ static uint32_t fm11_promote_singletons(const iso14a_fm11rf08s_nonces_with_data_ } static uint32_t fm11_propagate_exact_reused_keys(fm11_keylist_t candidates[FM11RF08S_SECTORS][2], - uint64_t keys_found[FM11RF08S_SECTORS][2], - bool found_key[FM11RF08S_SECTORS][2], - bool promote_inferred) { + uint64_t keys_found[FM11RF08S_SECTORS][2], + bool found_key[FM11RF08S_SECTORS][2], + bool promote_inferred) { uint32_t propagated = 0; if (promote_inferred == false) { return 0; @@ -3121,7 +3129,7 @@ int CmdHF14AMfSEN(const char *Cmd) { fm11_keylist_free(&priority); } - priority = (fm11_keylist_t){0}; + priority = (fm11_keylist_t) {0}; retval = fm11_build_global_priority_keys(candidates, duplicate_prefix, &priority); if (retval != PM3_SUCCESS) { fm11_keylist_free(&priority); @@ -3256,7 +3264,7 @@ int CmdHF14AMfSEN(const char *Cmd) { snprintf(activity, sizeof(activity), "sec %03u key %c - checking %u candidates", real_sec, kt ? 'B' : 'A', candidates[sec][kt].count); fm11_sen_progress(nonce_count, activity, candidates[sec][kt].count, - (candidates[sec][kt].count / 2 / FM11RF08S_FCHK_KEYS_PER_SECOND) + 1); + (candidates[sec][kt].count / 2 / FM11RF08S_FCHK_KEYS_PER_SECOND) + 1); uint64_t key = 0; int res = fm11_verify_candidates(real_sec, kt, &candidates[sec][kt], &key); if (res == PM3_SUCCESS) { diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c index 2b91a1813..45690507e 100644 --- a/client/src/cmdhfmfu.c +++ b/client/src/cmdhfmfu.c @@ -38,6 +38,9 @@ #include "preferences.h" // setDeviceDebugLevel #include "crc16.h" #include "crypto/originality.h" +#include "util.h" +#include +#include #define MAX_UL_BLOCKS 0x0F #define MAX_ULC_BLOCKS 0x2F @@ -4882,6 +4885,631 @@ out: return PM3_SUCCESS; } +//DESBRUTE Translation: C2Pwn + +typedef enum { + MFULC_DESBRUTE_LFSR_UNDEF = 0, + MFULC_DESBRUTE_LFSR_ULCG = 1, + MFULC_DESBRUTE_LFSR_MFC = 2, +} mfulc_desbrute_lfsr_t; + +typedef struct { + uint32_t start; + uint32_t end; + int key_mode; + bool candidate_in_k1; + int var_offset; + uint8_t init_ciphertext[8]; + uint8_t prev_ciphertext[8]; + uint8_t ciphertext[8]; + uint64_t init_ip_block; + uint64_t prev_ciphertext_be; + uint64_t ciphertext_ip_block; + uint8_t base_key[16]; + uint64_t fixed_sk[16]; + uint64_t cand_sk_base[16]; + uint64_t cand_sk_contrib[28 * 16]; + mfulc_desbrute_lfsr_t lfsr_type; + bool is_reader_mode; + int thread_id; +} mfulc_desbrute_thread_args_t; + +typedef struct { + volatile bool found; + volatile bool aborted; + uint32_t found_idx; + uint8_t found_key[16]; +} mfulc_desbrute_shared_t; + +typedef struct { + mfulc_desbrute_thread_args_t args; + mfulc_desbrute_shared_t *shared; + volatile uint32_t progress; + volatile bool done; +} mfulc_desbrute_worker_args_t; + +static uint64_t mfulc_desbrute_be64(const uint8_t *b) { + return ((uint64_t)b[0] << 56) | ((uint64_t)b[1] << 48) | + ((uint64_t)b[2] << 40) | ((uint64_t)b[3] << 32) | + ((uint64_t)b[4] << 24) | ((uint64_t)b[5] << 16) | + ((uint64_t)b[6] << 8) | (uint64_t)b[7]; +} + +static const uint8_t MFULC_DES_PC1[56] = { + 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, + 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, + 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, + 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 +}; + +static const uint8_t MFULC_DES_PC2[48] = { + 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, + 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, + 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, + 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 +}; + +static const uint8_t MFULC_DES_SHIFTS[16] = { + 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 +}; + +static const uint8_t MFULC_DES_IP[64] = { + 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, + 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, + 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, + 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 +}; + +static const uint8_t MFULC_DES_FP[64] = { + 40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, + 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, + 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, + 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25 +}; + +static const uint32_t MFULC_DES_SP[512] = { + 0x00808200, 0x00000000, 0x00008000, 0x00808202, 0x00808002, 0x00008202, 0x00000002, 0x00008000, 0x00000200, 0x00808200, 0x00808202, 0x00000200, 0x00800202, 0x00808002, 0x00800000, 0x00000002, 0x00000202, 0x00800200, 0x00800200, 0x00008200, 0x00008200, 0x00808000, 0x00808000, 0x00800202, 0x00008002, 0x00800002, 0x00800002, 0x00008002, 0x00000000, 0x00000202, 0x00008202, 0x00800000, 0x00008000, 0x00808202, 0x00000002, 0x00808000, 0x00808200, 0x00800000, 0x00800000, 0x00000200, 0x00808002, 0x00008000, 0x00008200, 0x00800002, 0x00000200, 0x00000002, 0x00800202, 0x00008202, 0x00808202, 0x00008002, 0x00808000, 0x00800202, 0x00800002, 0x00000202, 0x00008202, 0x00808200, 0x00000202, 0x00800200, 0x00800200, 0x00000000, 0x00008002, 0x00008200, 0x00000000, 0x00808002, + 0x40084010, 0x40004000, 0x00004000, 0x00084010, 0x00080000, 0x00000010, 0x40080010, 0x40004010, 0x40000010, 0x40084010, 0x40084000, 0x40000000, 0x40004000, 0x00080000, 0x00000010, 0x40080010, 0x00084000, 0x00080010, 0x40004010, 0x00000000, 0x40000000, 0x00004000, 0x00084010, 0x40080000, 0x00080010, 0x40000010, 0x00000000, 0x00084000, 0x00004010, 0x40084000, 0x40080000, 0x00004010, 0x00000000, 0x00084010, 0x40080010, 0x00080000, 0x40004010, 0x40080000, 0x40084000, 0x00004000, 0x40080000, 0x40004000, 0x00000010, 0x40084010, 0x00084010, 0x00000010, 0x00004000, 0x40000000, 0x00004010, 0x40084000, 0x00080000, 0x40000010, 0x00080010, 0x40004010, 0x40000010, 0x00080010, 0x00084000, 0x00000000, 0x40004000, 0x00004010, 0x40000000, 0x40080010, 0x40084010, 0x00084000, + 0x00000104, 0x04010100, 0x00000000, 0x04010004, 0x04000100, 0x00000000, 0x00010104, 0x04000100, 0x00010004, 0x04000004, 0x04000004, 0x00010000, 0x04010104, 0x00010004, 0x04010000, 0x00000104, 0x04000000, 0x00000004, 0x04010100, 0x00000100, 0x00010100, 0x04010000, 0x04010004, 0x00010104, 0x04000104, 0x00010100, 0x00010000, 0x04000104, 0x00000004, 0x04010104, 0x00000100, 0x04000000, 0x04010100, 0x04000000, 0x00010004, 0x00000104, 0x00010000, 0x04010100, 0x04000100, 0x00000000, 0x00000100, 0x00010004, 0x04010104, 0x04000100, 0x04000004, 0x00000100, 0x00000000, 0x04010004, 0x04000104, 0x00010000, 0x04000000, 0x04010104, 0x00000004, 0x00010104, 0x00010100, 0x04000004, 0x04010000, 0x04000104, 0x00000104, 0x04010000, 0x00010104, 0x00000004, 0x04010004, 0x00010100, + 0x80401000, 0x80001040, 0x80001040, 0x00000040, 0x00401040, 0x80400040, 0x80400000, 0x80001000, 0x00000000, 0x00401000, 0x00401000, 0x80401040, 0x80000040, 0x00000000, 0x00400040, 0x80400000, 0x80000000, 0x00001000, 0x00400000, 0x80401000, 0x00000040, 0x00400000, 0x80001000, 0x00001040, 0x80400040, 0x80000000, 0x00001040, 0x00400040, 0x00001000, 0x00401040, 0x80401040, 0x80000040, 0x00400040, 0x80400000, 0x00401000, 0x80401040, 0x80000040, 0x00000000, 0x00000000, 0x00401000, 0x00001040, 0x00400040, 0x80400040, 0x80000000, 0x80401000, 0x80001040, 0x80001040, 0x00000040, 0x80401040, 0x80000040, 0x80000000, 0x00001000, 0x80400000, 0x80001000, 0x00401040, 0x80400040, 0x80001000, 0x00001040, 0x00400000, 0x80401000, 0x00000040, 0x00400000, 0x00001000, 0x00401040, + 0x00000080, 0x01040080, 0x01040000, 0x21000080, 0x00040000, 0x00000080, 0x20000000, 0x01040000, 0x20040080, 0x00040000, 0x01000080, 0x20040080, 0x21000080, 0x21040000, 0x00040080, 0x20000000, 0x01000000, 0x20040000, 0x20040000, 0x00000000, 0x20000080, 0x21040080, 0x21040080, 0x01000080, 0x21040000, 0x20000080, 0x00000000, 0x21000000, 0x01040080, 0x01000000, 0x21000000, 0x00040080, 0x00040000, 0x21000080, 0x00000080, 0x01000000, 0x20000000, 0x01040000, 0x21000080, 0x20040080, 0x01000080, 0x20000000, 0x21040000, 0x01040080, 0x20040080, 0x00000080, 0x01000000, 0x21040000, 0x21040080, 0x00040080, 0x21000000, 0x21040080, 0x01040000, 0x00000000, 0x20040000, 0x21000000, 0x00040080, 0x01000080, 0x20000080, 0x00040000, 0x00000000, 0x20040000, 0x01040080, 0x20000080, + 0x10000008, 0x10200000, 0x00002000, 0x10202008, 0x10200000, 0x00000008, 0x10202008, 0x00200000, 0x10002000, 0x00202008, 0x00200000, 0x10000008, 0x00200008, 0x10002000, 0x10000000, 0x00002008, 0x00000000, 0x00200008, 0x10002008, 0x00002000, 0x00202000, 0x10002008, 0x00000008, 0x10200008, 0x10200008, 0x00000000, 0x00202008, 0x10202000, 0x00002008, 0x00202000, 0x10202000, 0x10000000, 0x10002000, 0x00000008, 0x10200008, 0x00202000, 0x10202008, 0x00200000, 0x00002008, 0x10000008, 0x00200000, 0x10002000, 0x10000000, 0x00002008, 0x10000008, 0x10202008, 0x00202000, 0x10200000, 0x00202008, 0x10202000, 0x00000000, 0x10200008, 0x00000008, 0x00002000, 0x10200000, 0x00202008, 0x00002000, 0x00200008, 0x10002008, 0x00000000, 0x10202000, 0x10000000, 0x00200008, 0x10002008, + 0x00100000, 0x02100001, 0x02000401, 0x00000000, 0x00000400, 0x02000401, 0x00100401, 0x02100400, 0x02100401, 0x00100000, 0x00000000, 0x02000001, 0x00000001, 0x02000000, 0x02100001, 0x00000401, 0x02000400, 0x00100401, 0x00100001, 0x02000400, 0x02000001, 0x02100000, 0x02100400, 0x00100001, 0x02100000, 0x00000400, 0x00000401, 0x02100401, 0x00100400, 0x00000001, 0x02000000, 0x00100400, 0x02000000, 0x00100400, 0x00100000, 0x02000401, 0x02000401, 0x02100001, 0x02100001, 0x00000001, 0x00100001, 0x02000000, 0x02000400, 0x00100000, 0x02100400, 0x00000401, 0x00100401, 0x02100400, 0x00000401, 0x02000001, 0x02100401, 0x02100000, 0x00100400, 0x00000000, 0x00000001, 0x02100401, 0x00000000, 0x00100401, 0x02100000, 0x00000400, 0x02000001, 0x02000400, 0x00000400, 0x00100001, + 0x08000820, 0x00000800, 0x00020000, 0x08020820, 0x08000000, 0x08000820, 0x00000020, 0x08000000, 0x00020020, 0x08020000, 0x08020820, 0x00020800, 0x08020800, 0x00020820, 0x00000800, 0x00000020, 0x08020000, 0x08000020, 0x08000800, 0x00000820, 0x00020800, 0x00020020, 0x08020020, 0x08020800, 0x00000820, 0x00000000, 0x00000000, 0x08020020, 0x08000020, 0x08000800, 0x00020820, 0x00020000, 0x00020820, 0x00020000, 0x08020800, 0x00000800, 0x00000020, 0x08020020, 0x00000800, 0x00020820, 0x08000800, 0x00000020, 0x08000020, 0x08020000, 0x08020020, 0x08000000, 0x00020000, 0x08000820, 0x00000000, 0x08020820, 0x00020020, 0x08000020, 0x08020000, 0x08000800, 0x08000820, 0x00000000, 0x08020820, 0x00020800, 0x00020800, 0x00000820, 0x00000820, 0x00020020, 0x08000000, 0x08020800 +}; + +static uint64_t mfulc_desbrute_perm(uint64_t src, int src_bits, const uint8_t *tbl, int n) { + uint64_t dst = 0; + for (int i = 0; i < n; i++) { + int sb = tbl[i] - 1; + dst |= ((src >> (src_bits - 1 - sb)) & 1ULL) << (n - 1 - i); + } + return dst; +} + +static void mfulc_desbrute_keyschedule(uint64_t key64, uint64_t sk[16]) { + uint64_t key56 = mfulc_desbrute_perm(key64, 64, MFULC_DES_PC1, 56); + uint32_t c = (uint32_t)(key56 >> 28) & 0x0FFFFFFF; + uint32_t d = (uint32_t)key56 & 0x0FFFFFFF; + + for (int i = 0; i < 16; i++) { + int s = MFULC_DES_SHIFTS[i]; + c = ((c << s) | (c >> (28 - s))) & 0x0FFFFFFF; + d = ((d << s) | (d >> (28 - s))) & 0x0FFFFFFF; + sk[i] = mfulc_desbrute_perm(((uint64_t)c << 28) | d, 56, MFULC_DES_PC2, 48); + } +} + +static uint32_t mfulc_desbrute_f(uint32_t r, uint64_t k) { + uint32_t r0 = ((r & 1u) << 5) | ((r >> 27) & 0x1Fu); + uint32_t r1 = (r >> 23) & 0x3Fu; + uint32_t r2 = (r >> 19) & 0x3Fu; + uint32_t r3 = (r >> 15) & 0x3Fu; + uint32_t r4 = (r >> 11) & 0x3Fu; + uint32_t r5 = (r >> 7) & 0x3Fu; + uint32_t r6 = (r >> 3) & 0x3Fu; + uint32_t r7 = ((r & 0x1Fu) << 1) | ((r >> 31) & 1u); + + r0 ^= (uint32_t)((k >> 42) & 0x3Fu); + r1 ^= (uint32_t)((k >> 36) & 0x3Fu); + r2 ^= (uint32_t)((k >> 30) & 0x3Fu); + r3 ^= (uint32_t)((k >> 24) & 0x3Fu); + r4 ^= (uint32_t)((k >> 18) & 0x3Fu); + r5 ^= (uint32_t)((k >> 12) & 0x3Fu); + r6 ^= (uint32_t)((k >> 6) & 0x3Fu); + r7 ^= (uint32_t)(k & 0x3Fu); + + return MFULC_DES_SP[r0] ^ MFULC_DES_SP[64 + r1] ^ MFULC_DES_SP[128 + r2] ^ MFULC_DES_SP[192 + r3] ^ + MFULC_DES_SP[256 + r4] ^ MFULC_DES_SP[320 + r5] ^ MFULC_DES_SP[384 + r6] ^ MFULC_DES_SP[448 + r7]; +} + +static uint64_t mfulc_desbrute_des_rounds(uint64_t ip_block, const uint64_t sk[16], bool decrypt) { + uint32_t l = (uint32_t)(ip_block >> 32); + uint32_t r = (uint32_t)ip_block; + + for (int i = 0; i < 16; i++) { + uint64_t k = decrypt ? sk[15 - i] : sk[i]; + uint32_t nr = l ^ mfulc_desbrute_f(r, k); + l = r; + r = nr; + } + return ((uint64_t)r << 32) | l; +} + +static uint64_t mfulc_desbrute_des(uint64_t block, const uint64_t sk[16], bool decrypt) { + uint64_t t = mfulc_desbrute_perm(block, 64, MFULC_DES_IP, 64); + t = mfulc_desbrute_des_rounds(t, sk, decrypt); + return mfulc_desbrute_perm(t, 64, MFULC_DES_FP, 64); +} + +static uint64_t mfulc_desbrute_tdea2_dec_ip(uint64_t ip_block, const uint64_t k1_sk[16], const uint64_t k2_sk[16]) { + uint64_t t = mfulc_desbrute_des_rounds(ip_block, k1_sk, true); + t = mfulc_desbrute_des_rounds(t, k2_sk, false); + t = mfulc_desbrute_des_rounds(t, k1_sk, true); + return mfulc_desbrute_perm(t, 64, MFULC_DES_FP, 64); +} + +static void mfulc_desbrute_format_duration(uint64_t seconds, char *buf, size_t buflen) { + unsigned int h = (unsigned int)(seconds / 3600); + unsigned int m = (unsigned int)((seconds / 60) % 60); + unsigned int s = (unsigned int)(seconds % 60); + + if (h > 99) { + snprintf(buf, buflen, ">99h"); + } else if (h > 0) { + snprintf(buf, buflen, "%02u:%02u:%02u", h, m, s); + } else { + snprintf(buf, buflen, "%02u:%02u", m, s); + } +} + +static void mfulc_desbrute_progress_bar(double pct, char *buf, size_t buflen) { + const int width = 28; + int filled = (int)((pct / 100.0) * width); + + if (filled < 0) filled = 0; + if (filled > width) filled = width; + if (buflen < (size_t)width + 3) { + if (buflen > 0) buf[0] = '\0'; + return; + } + + buf[0] = '['; + for (int i = 0; i < width; i++) { + buf[i + 1] = i < filled ? '#' : '.'; + } + buf[width + 1] = ']'; + buf[width + 2] = '\0'; +} + +static const char *mfulc_desbrute_progress_color(double pct) { + if (pct >= 90.0) { + return "\x1b[32m"; + } + if (pct >= 50.0) { + return "\x1b[33m"; + } + return "\x1b[36m"; +} + +static void mfulc_desbrute_compute_sk_tables(const uint8_t base_half[8], int var_offset, uint64_t sk_base[16], uint64_t sk_contrib[28 * 16]) { + uint8_t half[8] = {0}; + + memcpy(half, base_half, sizeof(half)); + half[var_offset] = 0; + half[var_offset + 1] = 0; + half[var_offset + 2] = 0; + half[var_offset + 3] = 0; + mfulc_desbrute_keyschedule(mfulc_desbrute_be64(half), sk_base); + + for (int bit = 0; bit < 28; bit++) { + uint8_t tmp[8] = {0}; + int byte_in_half = bit / 7; + int bit_in_byte = bit % 7; + uint64_t bit_sk[16] = {0}; + + tmp[var_offset + byte_in_half] = (uint8_t)(1u << (bit_in_byte + 1)); + mfulc_desbrute_keyschedule(mfulc_desbrute_be64(tmp), bit_sk); + + for (int round = 0; round < 16; round++) { + sk_contrib[(bit * 16) + round] = bit_sk[round]; + } + } +} + +static void mfulc_desbrute_make_candidate_sk(const mfulc_desbrute_thread_args_t *args, uint32_t idx, uint64_t cand_sk[16]) { + memcpy(cand_sk, args->cand_sk_base, sizeof(args->cand_sk_base)); + + for (int bit = 0; bit < 28; bit++) { + if ((idx >> bit) & 1u) { + const uint64_t *contrib = &args->cand_sk_contrib[bit * 16]; + for (int round = 0; round < 16; round++) { + cand_sk[round] ^= contrib[round]; + } + } + } +} + +static void mfulc_desbrute_update_candidate_sk(const mfulc_desbrute_thread_args_t *args, uint32_t old_idx, uint32_t new_idx, uint64_t cand_sk[16]) { + uint32_t changed = old_idx ^ new_idx; + + while (changed != 0) { + int bit = __builtin_ctz(changed); + const uint64_t *contrib = &args->cand_sk_contrib[bit * 16]; + + for (int round = 0; round < 16; round++) { + cand_sk[round] ^= contrib[round]; + } + changed &= changed - 1; + } +} + +static bool mfulc_desbrute_valid_lfsr_ulcg(uint64_t x64) { + x64 = BSWAP_64(x64); + uint16_t x16 = x64 >> 48; + x16 = (uint16_t)(x16 << 15 | ((x16 >> 1) ^ ((x16 >> 3 ^ x16 >> 4 ^ x16 >> 6) & 1))); + if (x16 != ((x64 >> 32) & 0xFFFF)) return false; + x16 = (uint16_t)(x16 << 15 | ((x16 >> 1) ^ ((x16 >> 3 ^ x16 >> 4 ^ x16 >> 6) & 1))); + if (x16 != ((x64 >> 16) & 0xFFFF)) return false; + x16 = (uint16_t)(x16 << 15 | ((x16 >> 1) ^ ((x16 >> 3 ^ x16 >> 4 ^ x16 >> 6) & 1))); + return x16 == (x64 & 0xFFFF); +} + +static bool mfulc_desbrute_valid_lfsr_mfc(uint64_t x64) { + x64 = BSWAP_64(x64); + uint16_t x16 = x64 & 0xFFFF; + for (int i = 0; i < 16; i++) x16 = (uint16_t)(x16 >> 1 | (x16 ^ x16 >> 2 ^ x16 >> 3 ^ x16 >> 5) << 15); + if (x16 != ((x64 >> 16) & 0xFFFF)) return false; + for (int i = 0; i < 16; i++) x16 = (uint16_t)(x16 >> 1 | (x16 ^ x16 >> 2 ^ x16 >> 3 ^ x16 >> 5) << 15); + if (x16 != ((x64 >> 32) & 0xFFFF)) return false; + for (int i = 0; i < 16; i++) x16 = (uint16_t)(x16 >> 1 | (x16 ^ x16 >> 2 ^ x16 >> 3 ^ x16 >> 5) << 15); + return x16 == ((x64 >> 48) & 0xFFFF); +} + +static bool mfulc_desbrute_valid_lfsr(uint64_t x64, mfulc_desbrute_lfsr_t lfsr_type) { + switch (lfsr_type) { + case MFULC_DESBRUTE_LFSR_ULCG: + return mfulc_desbrute_valid_lfsr_ulcg(x64); + case MFULC_DESBRUTE_LFSR_MFC: + return mfulc_desbrute_valid_lfsr_mfc(x64); + case MFULC_DESBRUTE_LFSR_UNDEF: + default: + return false; + } +} + +static mfulc_desbrute_lfsr_t mfulc_desbrute_detect_lfsr_type(const uint8_t init_ciphertext[8]) { + uint64_t zero_sk[16] = {0}; + uint64_t x_be; + + mfulc_desbrute_keyschedule(0, zero_sk); + x_be = mfulc_desbrute_des(mfulc_desbrute_be64(init_ciphertext), zero_sk, true); + uint64_t x = BSWAP_64(x_be); + if (mfulc_desbrute_valid_lfsr_ulcg(x)) { + return MFULC_DESBRUTE_LFSR_ULCG; + } + if (mfulc_desbrute_valid_lfsr_mfc(x)) { + return MFULC_DESBRUTE_LFSR_MFC; + } + return MFULC_DESBRUTE_LFSR_UNDEF; +} + +static void mfulc_desbrute_fill_candidate(uint8_t key[16], const uint8_t base_key[16], int key_mode, uint32_t idx) { + memcpy(key, base_key, 16); + int seg_offset = key_mode * 4; + key[seg_offset] = (uint8_t)(((idx) & 0x7F) << 1); + key[seg_offset + 1] = (uint8_t)(((idx >> 7) & 0x7F) << 1); + key[seg_offset + 2] = (uint8_t)(((idx >> 14) & 0x7F) << 1); + key[seg_offset + 3] = (uint8_t)(((idx >> 21) & 0x7F) << 1); +} + +static void mfulc_desbrute_candidate_batch(uint32_t start, uint32_t idx[4]) { + union vec lanes = vec_uadd(vec_u1(start), vec_u(0, 1, 2, 3)); + for (int i = 0; i < 4; i++) { + idx[i] = lanes.elem.u[i]; + } +} + +static bool mfulc_desbrute_test_candidate_sk(const mfulc_desbrute_thread_args_t *args, const uint64_t cand_sk[16]) { + uint64_t out_be; + const uint64_t *k1_sk; + const uint64_t *k2_sk; + + k1_sk = args->candidate_in_k1 ? cand_sk : args->fixed_sk; + k2_sk = args->candidate_in_k1 ? args->fixed_sk : cand_sk; + out_be = mfulc_desbrute_tdea2_dec_ip(args->ciphertext_ip_block, k1_sk, k2_sk); + + bool match = false; + if (args->is_reader_mode) { + uint64_t init_be = mfulc_desbrute_tdea2_dec_ip(args->init_ip_block, k1_sk, k2_sk); + uint64_t rotated_init_be = (init_be << 8) | (init_be >> 56); + + match = (out_be ^ args->prev_ciphertext_be) == rotated_init_be; + } else { + match = mfulc_desbrute_valid_lfsr(BSWAP_64(out_be), args->lfsr_type); + } + return match; +} + +static void *mfulc_desbrute_worker(void *arg) { + mfulc_desbrute_worker_args_t *ctx = arg; + + uint32_t candidate[4] = {0}; + uint32_t last_candidate = 0; + uint64_t cand_sk[16] = {0}; + bool have_candidate_sk = false; + + ctx->progress = ctx->args.start; + for (uint32_t idx = ctx->args.start; idx < ctx->args.end; idx += 4) { + if (ctx->shared->found || ctx->shared->aborted) { + break; + } + if ((idx & 0x3FF) == 0) { + ctx->progress = idx; + } + if (ctx->args.thread_id == 0 && ((idx & 0x3FFFF) == 0) && kbd_enter_pressed()) { + ctx->shared->aborted = true; + break; + } + + mfulc_desbrute_candidate_batch(idx, candidate); + for (int lane = 0; lane < 4; lane++) { + if (candidate[lane] >= ctx->args.end) { + break; + } + + if (have_candidate_sk) { + mfulc_desbrute_update_candidate_sk(&ctx->args, last_candidate, candidate[lane], cand_sk); + } else { + mfulc_desbrute_make_candidate_sk(&ctx->args, candidate[lane], cand_sk); + have_candidate_sk = true; + } + last_candidate = candidate[lane]; + + if (mfulc_desbrute_test_candidate_sk(&ctx->args, cand_sk)) { + ctx->shared->found_idx = candidate[lane]; + mfulc_desbrute_fill_candidate(ctx->shared->found_key, ctx->args.base_key, ctx->args.key_mode, candidate[lane]); + ctx->progress = candidate[lane] + 1; + ctx->shared->found = true; + ctx->done = true; + return NULL; + } + } + } + ctx->progress = ctx->shared->found || ctx->shared->aborted ? ctx->progress : ctx->args.end; + ctx->done = true; + return NULL; +} + +static int CmdHF14AMfUCDesBrute(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfu desbrute", + "Recover one 4-byte segment of a MIFARE Ultralight-C 2TDEA key from known authentication ciphertexts.", + "hf mfu desbrute --counterfeit --null F35C740106ECED87 --target E9E0DC67B35919FC --key 00000000000000000000000000000000 --segment 2\n" + "hf mfu desbrute --counterfeit --null 49C1603621CCAA72 --target 8122262EF5FA8DEB --key 48444C4A4044524200000000544E5846 --segment 3\n" + "hf mfu desbrute --reader --erndb EC9C5CF763244367 --cryptogram 2283BFE8DEBE1780922327794D0706EF --key 48444C4A4044524200000000544E5846 --segment 3"); + + void *argtable[] = { + arg_param_begin, + arg_lit0("c", "counterfeit", "Counterfeit nonce mode: --null and --target are ERndB blocks"), + arg_lit0("r", "reader", "Reader nonce mode: --erndb and --cryptogram are sniffed authentication blocks"), + arg_str0(NULL, "null", "", "Null-key ERndB, 8 hex bytes"), + arg_str0(NULL, "target", "", "Target-key ERndB, 8 hex bytes"), + arg_str0(NULL, "erndb", "", "Reader mode ERndB, 8 hex bytes"), + arg_str0(NULL, "cryptogram", "", "Reader mode ERndA|ERndB', 16 hex bytes"), + arg_str1("k", "key", "", "Base 3DES key, 16 hex bytes"), + arg_int1("s", "segment", "<1..4>", "4-byte key segment to brute force"), + arg_int0("t", "threads", "", "Worker threads (default: all logical CPUs)"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + + bool counterfeit_mode = arg_get_lit(ctx, 1); + bool reader_mode = arg_get_lit(ctx, 2); + uint8_t init_ciphertext[8] = {0}; + uint8_t ciphertext[8] = {0}; + uint8_t prev_ciphertext[8] = {0}; + uint8_t tmp_blocks[16] = {0}; + uint8_t base_key[16] = {0}; + int init_len = 0; + int ciphertext_len = 0; + int tmp_len = 0; + int key_len = 0; + + if (counterfeit_mode) { + CLIGetHexWithReturn(ctx, 3, init_ciphertext, &init_len); + CLIGetHexWithReturn(ctx, 4, ciphertext, &ciphertext_len); + } + if (reader_mode) { + CLIGetHexWithReturn(ctx, 5, init_ciphertext, &init_len); + CLIGetHexWithReturn(ctx, 6, tmp_blocks, &tmp_len); + memcpy(prev_ciphertext, tmp_blocks, 8); + memcpy(ciphertext, tmp_blocks + 8, 8); + } + CLIGetHexWithReturn(ctx, 7, base_key, &key_len); + int segment = arg_get_int_def(ctx, 8, 0); + int threads = arg_get_int_def(ctx, 9, num_CPUs()); + CLIParserFree(ctx); + + if (counterfeit_mode == reader_mode) { + PrintAndLogEx(WARNING, "Select exactly one mode: --counterfeit or --reader"); + return PM3_EINVARG; + } + if (init_len != 8 || key_len != 16 || (counterfeit_mode && ciphertext_len != 8) || (reader_mode && tmp_len != 16)) { + PrintAndLogEx(WARNING, "Invalid input length. Blocks are 8 bytes, reader cryptogram is 16 bytes, key is 16 bytes"); + return PM3_EINVARG; + } + if (segment < 1 || segment > 4) { + PrintAndLogEx(WARNING, "Segment must be 1..4"); + return PM3_EINVARG; + } + if (threads < 1) { + threads = 1; + } + int max_threads = num_CPUs(); + if (threads > max_threads) { + PrintAndLogEx(INFO, "Capping threads at available CPU count (%d)", max_threads); + threads = max_threads; + } + + mfulc_desbrute_lfsr_t lfsr_type = MFULC_DESBRUTE_LFSR_UNDEF; + if (counterfeit_mode) { + lfsr_type = mfulc_desbrute_detect_lfsr_type(init_ciphertext); + if (lfsr_type == MFULC_DESBRUTE_LFSR_UNDEF) { + PrintAndLogEx(WARNING, "LFSR detection failed"); + return PM3_ESOFT; + } + PrintAndLogEx(INFO, "LFSR detection: %s", lfsr_type == MFULC_DESBRUTE_LFSR_ULCG ? "ULCG" : "MFC (USCUID-UL/FJ8010)"); + } + + pthread_t *tids = calloc(threads, sizeof(pthread_t)); + mfulc_desbrute_worker_args_t *worker_args = calloc(threads, sizeof(*worker_args)); + if (tids == NULL || worker_args == NULL) { + free(tids); + free(worker_args); + return PM3_EMALLOC; + } + + mfulc_desbrute_shared_t shared = {0}; + uint64_t start_ms = msclock(); + uint32_t total = 1UL << 28; + uint32_t chunk = total / (uint32_t)threads; + uint32_t remainder = total % (uint32_t)threads; + uint32_t current = 0; + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("MFU DESBRUTE")); + PrintAndLogEx(INFO, "Mode....... " _YELLOW_("%s"), counterfeit_mode ? "counterfeit nonce" : "reader nonce"); + PrintAndLogEx(INFO, "Segment.... " _YELLOW_("%d") " (key bytes " _YELLOW_("%d..%d") ")", segment, (segment - 1) * 4, ((segment - 1) * 4) + 3); + PrintAndLogEx(INFO, "Keyspace... " _YELLOW_("2^28") " = " _YELLOW_("%" PRIu32) " candidates", total); + PrintAndLogEx(INFO, "Threads.... " _YELLOW_("%d") " / " _YELLOW_("%d") " logical CPUs", threads, max_threads); + PrintAndLogEx(INFO, "Base key... " _GREEN_("%s"), sprint_hex_inrow(base_key, sizeof(base_key))); + if (counterfeit_mode) { + PrintAndLogEx(INFO, "Null ERndB. " _GREEN_("%s"), sprint_hex_inrow(init_ciphertext, sizeof(init_ciphertext))); + PrintAndLogEx(INFO, "Target..... " _GREEN_("%s"), sprint_hex_inrow(ciphertext, sizeof(ciphertext))); + PrintAndLogEx(INFO, "LFSR....... " _YELLOW_("%s"), lfsr_type == MFULC_DESBRUTE_LFSR_ULCG ? "ULCG" : "MFC (USCUID-UL/FJ8010)"); + } else { + PrintAndLogEx(INFO, "ERndB...... " _GREEN_("%s"), sprint_hex_inrow(init_ciphertext, sizeof(init_ciphertext))); + PrintAndLogEx(INFO, "ERndA|B'... " _GREEN_("%s"), sprint_hex_inrow(tmp_blocks, sizeof(tmp_blocks))); + } + PrintAndLogEx(INFO, "Engine..... " _CYAN_("DES SP table + subkey contribution tables + vec candidate lanes")); + PrintAndLogEx(INFO, "Abort...... " _YELLOW_("press Enter")); + PrintAndLogEx(NORMAL, ""); + + for (int i = 0; i < threads; i++) { + mfulc_desbrute_worker_args_t *wa = &worker_args[i]; + + wa->args.start = current; + wa->args.end = current + chunk + (i == threads - 1 ? remainder : 0); + wa->progress = wa->args.start; + wa->done = false; + wa->args.key_mode = segment - 1; + wa->args.candidate_in_k1 = wa->args.key_mode < 2; + wa->args.var_offset = wa->args.candidate_in_k1 ? ((wa->args.key_mode % 2) * 4) : (((wa->args.key_mode - 2) % 2) * 4); + wa->args.lfsr_type = lfsr_type; + wa->args.is_reader_mode = reader_mode; + wa->args.thread_id = i; + memcpy(wa->args.init_ciphertext, init_ciphertext, sizeof(init_ciphertext)); + memcpy(wa->args.prev_ciphertext, prev_ciphertext, sizeof(prev_ciphertext)); + memcpy(wa->args.ciphertext, ciphertext, sizeof(ciphertext)); + memcpy(wa->args.base_key, base_key, sizeof(base_key)); + wa->args.init_ip_block = mfulc_desbrute_perm(mfulc_desbrute_be64(init_ciphertext), 64, MFULC_DES_IP, 64); + wa->args.prev_ciphertext_be = mfulc_desbrute_be64(prev_ciphertext); + wa->args.ciphertext_ip_block = mfulc_desbrute_perm(mfulc_desbrute_be64(ciphertext), 64, MFULC_DES_IP, 64); + mfulc_desbrute_keyschedule( + mfulc_desbrute_be64(wa->args.candidate_in_k1 ? base_key + 8 : base_key), + wa->args.fixed_sk + ); + mfulc_desbrute_compute_sk_tables( + wa->args.candidate_in_k1 ? base_key : base_key + 8, + wa->args.var_offset, + wa->args.cand_sk_base, + wa->args.cand_sk_contrib + ); + wa->shared = &shared; + current = wa->args.end; + + if (pthread_create(&tids[i], NULL, mfulc_desbrute_worker, wa) != 0) { + shared.aborted = true; + threads = i; + PrintAndLogEx(WARNING, "Failed creating worker thread"); + break; + } + } + + while (true) { + uint64_t checked = 0; + bool all_done = true; + + for (int i = 0; i < threads; i++) { + uint32_t p = worker_args[i].progress; + if (p < worker_args[i].args.start) { + p = worker_args[i].args.start; + } + if (p > worker_args[i].args.end) { + p = worker_args[i].args.end; + } + checked += (uint64_t)(p - worker_args[i].args.start); + if (worker_args[i].done == false) { + all_done = false; + } + } + + uint64_t elapsed_now_ms = msclock() - start_ms; + double elapsed_s = elapsed_now_ms > 0 ? elapsed_now_ms / 1000.0 : 0.001; + double speed = checked / elapsed_s; + double pct = ((double)checked * 100.0) / (double)total; + uint64_t eta_s = 0; + char eta[16] = {0}; + char elapsed[16] = {0}; + char bar[32] = {0}; + + if (pct > 100.0) pct = 100.0; + if (speed > 0.0 && checked < total) { + eta_s = (uint64_t)(((double)total - (double)checked) / speed); + } + mfulc_desbrute_format_duration(eta_s, eta, sizeof(eta)); + mfulc_desbrute_format_duration(elapsed_now_ms / 1000, elapsed, sizeof(elapsed)); + mfulc_desbrute_progress_bar(pct, bar, sizeof(bar)); + + PrintAndLogEx(INPLACE, "%s%s" AEND " " _YELLOW_("%6.2f%%") " checked " _CYAN_("%" PRIu64) "/" _CYAN_("%" PRIu32) " " _GREEN_("%.0f keys/s") " elapsed " _YELLOW_("%s") " ETA " _YELLOW_("%s"), + mfulc_desbrute_progress_color(pct), bar, pct, checked, total, speed, elapsed, eta); + + if (all_done || shared.found || shared.aborted) { + break; + } + if (kbd_enter_pressed()) { + shared.aborted = true; + break; + } + msleep(250); + } + PrintAndLogEx(NORMAL, ""); + + for (int i = 0; i < threads; i++) { + pthread_join(tids[i], NULL); + } + + uint64_t elapsed_ms = msclock() - start_ms; + free(tids); + free(worker_args); + + if (shared.aborted) { + PrintAndLogEx(WARNING, "Aborted"); + return PM3_EOPABORTED; + } + if (shared.found) { + PrintAndLogEx(SUCCESS, "Found key index: " _YELLOW_("%" PRIu32), shared.found_idx); + PrintAndLogEx(SUCCESS, "Full key: " _GREEN_("%s"), sprint_hex_inrow(shared.found_key, sizeof(shared.found_key))); + PrintAndLogEx(INFO, "Time spent " _YELLOW_("%.1fs"), elapsed_ms / 1000.0); + return PM3_SUCCESS; + } + + PrintAndLogEx(WARNING, "Key segment not found"); + PrintAndLogEx(INFO, "Time spent " _YELLOW_("%.1fs"), elapsed_ms / 1000.0); + return PM3_ESOFT; +} + /** A test function to validate that the polarssl-function works the same was as the openssl-implementation. @@ -5935,7 +6563,7 @@ static int CmdHF14AMfuEv1CounterTearoff(const char *Cmd) { clearCommandBuffer(); PacketResponseNG resp; - SendCommandNG(CMD_HF_MFU_COUNTER_TEAROFF, (uint8_t *)&payload, sizeof(payload)); + SendCommandNG(CMD_HF_MFU_COUNTER_TEAROFF, (uint8_t*)&payload, sizeof(payload)); if (WaitForResponseTimeout(CMD_HF_MFU_COUNTER_TEAROFF, &resp, 2000) == false) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(WARNING, "\nTear off command failed"); @@ -6057,7 +6685,7 @@ static int CmdHF14AMfuEv1CounterTearoff(const char *Cmd) { clearCommandBuffer(); PacketResponseNG resp; - SendCommandNG(CMD_HF_MFU_COUNTER_TEAROFF, (uint8_t *)&payload, sizeof(payload)); + SendCommandNG(CMD_HF_MFU_COUNTER_TEAROFF, (uint8_t*)&payload, sizeof(payload)); if (WaitForResponseTimeout(CMD_HF_MFU_COUNTER_TEAROFF, &resp, 2000) == false) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(WARNING, "\nTear off command failed"); @@ -6146,7 +6774,7 @@ static int CmdHF14AMfuEv1CounterTearoff(const char *Cmd) { clearCommandBuffer(); PacketResponseNG resp; - SendCommandNG(CMD_HF_MFU_COUNTER_TEAROFF, (uint8_t *)&payload, sizeof(payload)); + SendCommandNG(CMD_HF_MFU_COUNTER_TEAROFF, (uint8_t*)&payload, sizeof(payload)); if (WaitForResponseTimeout(CMD_HF_MFU_COUNTER_TEAROFF, &resp, 2000) == false) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(WARNING, "\nTear off command failed"); @@ -6168,7 +6796,7 @@ static int CmdHF14AMfuEv1CounterTearoff(const char *Cmd) { memcpy(payload.value, (uint8_t[]) {0x00, 0x00, 0x00}, sizeof(payload.value)); clearCommandBuffer(); - SendCommandNG(CMD_HF_MFU_COUNTER_TEAROFF, (uint8_t *)&payload, sizeof(payload)); + SendCommandNG(CMD_HF_MFU_COUNTER_TEAROFF, (uint8_t*)&payload, sizeof(payload)); if (WaitForResponseTimeout(CMD_HF_MFU_COUNTER_TEAROFF, &resp, 2000) == false) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(WARNING, "\nTear off command failed"); @@ -7302,6 +7930,7 @@ static command_t CommandTable[] = { {"-----------", CmdHelp, IfPm3Iso14443a, "----------------------- " _CYAN_("operations") " -----------------------"}, {"cauth", CmdHF14AMfUCAuth, IfPm3Iso14443a, "Ultralight-C - Authentication"}, {"cchk", CmdHF14AMfUCAuthChk, IfPm3Iso14443a, "Ultralight-C - Authentication dictionary check"}, + {"desbrute", CmdHF14AMfUCDesBrute, AlwaysAvailable, "Ultralight-C - 3DES key segment brute force"}, {"aesauth", CmdHF14AMfUAESAuth, IfPm3Iso14443a, "Ultralight-AES - Authentication"}, {"aeschk", CmdHF14AMfUAESAuthChk, IfPm3Iso14443a, "Ultralight-AES - Authentication dictionary check"}, {"setkey", CmdHF14AMfUSetKey, IfPm3Iso14443a, "Ultralight C/AES - Set 3DES/AES keys"}, diff --git a/client/src/cmdhfntag424.c b/client/src/cmdhfntag424.c index 92639f864..97108a741 100644 --- a/client/src/cmdhfntag424.c +++ b/client/src/cmdhfntag424.c @@ -723,8 +723,8 @@ static int ntag424_authenticate_ev2_first(uint8_t keyno, uint8_t *key, ntag424_s if (memcmp(response.rnd_a, &rnd_a_clear[1], 15) != 0 || response.rnd_a[15] != rnd_a_clear[0]) { PrintAndLogEx(ERR, "Incorrect response from card\n" - "expected: %s\n" - "got: %s" + "expected: %s\n" + "got: %s" , sprint_hex(rnd_a_clear, 16), sprint_hex(response.rnd_a, 16)); return PM3_ESOFT; diff --git a/client/src/cmdhfsecc.c b/client/src/cmdhfsecc.c index ae1ebda62..c08ed687f 100644 --- a/client/src/cmdhfsecc.c +++ b/client/src/cmdhfsecc.c @@ -476,11 +476,11 @@ static int CmdHFHIDConfigSim(const char *Cmd) { strncpy(uid_str, sprint_hex_inrow(uid, uidlen), sizeof(uid_str) - 1); uid_str[sizeof(uid_str) - 1] = '\0'; PrintAndLogEx(INFO, "HID Config Card sim:" - " UID " _YELLOW_("%s") - " AID " _YELLOW_("%s") - " ATS len " _YELLOW_("%d") - " APDU overrides " _YELLOW_("%u") - " default resp " _YELLOW_("%s"), + " UID " _YELLOW_("%s") + " AID " _YELLOW_("%s") + " ATS len " _YELLOW_("%d") + " APDU overrides " _YELLOW_("%u") + " default resp " _YELLOW_("%s"), uid_str, aid_str, ats_len, apdu_count, has_default_resp ? sprint_hex_inrow(default_resp, default_resp_len_sz) : "9000 (builtin)"); PrintAndLogEx(INFO, "Press " _GREEN_("pm3 button") " or " _GREEN_("") " to abort simulation"); diff --git a/client/src/cmdlf.c b/client/src/cmdlf.c index edb995872..6acbe0dad 100644 --- a/client/src/cmdlf.c +++ b/client/src/cmdlf.c @@ -1829,11 +1829,11 @@ int CmdLFRelay(const char *Cmd) { " --rdr : Reading device, act as IP client and reads LF tag and sends data\n" " --tag : Simulation device, act as IP server and simulates relayed data\n", _WHITE_("Device A, reading LF tag, client") "\n" - "lf relay --rdr --ip 192.168.1.141 -> Client, connect to IP 192.168.1.141:8000\n" - "lf relay --rdr --ip 192.168.1.141 -p 18111 -> Client, connect to IP 192.168.1.141:18111 \n\n" + "lf relay --rdr --ip 192.168.1.141 -> Client, connect to IP 192.168.1.141:8000\n" + "lf relay --rdr --ip 192.168.1.141 -p 18111 -> Client, connect to IP 192.168.1.141:18111 \n\n" _WHITE_("Device B, simulate LF tag, server") "\n" - "lf relay --tag -p 8111 -> Server listening port 8111, recv 40000 samples\n" - "lf relay --tag -s 10000 -> Server listening port 8000, recv 10000 samples\n" + "lf relay --tag -p 8111 -> Server listening port 8111, recv 40000 samples\n" + "lf relay --tag -s 10000 -> Server listening port 8000, recv 10000 samples\n" ); void *argtable[] = { diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index b07c4e015..fe75af79e 100644 --- a/client/src/cmdlft55xx.c +++ b/client/src/cmdlft55xx.c @@ -948,9 +948,9 @@ static int CmdT55xxReadBlock(const char *Cmd) { _CYAN_("Use of read with password on a tag not configured") "\n" _CYAN_("for a password can damage the tag") "\n" _RED_(" * * * * * * * * * *"), - "lf t55xx read -b 0 --> read data from block 0\n" - "lf t55xx read -b 0 --pwd 01020304 --> read data from block 0, pwd 01020304\n" - "lf t55xx read -b 0 --pwd 01020304 -o --> read data from block 0, pwd 01020304, override\n" + "lf t55xx read -b 0 --> read data from block 0\n" + "lf t55xx read -b 0 --pwd 01020304 --> read data from block 0, pwd 01020304\n" + "lf t55xx read -b 0 --pwd 01020304 -o --> read data from block 0, pwd 01020304, override\n" ); // 1 (help) + 4(four user specified params) + (5 T55XX_DLMODE_SINGLE) diff --git a/client/src/cmdtrace.c b/client/src/cmdtrace.c index c72eb4dac..d565fb2a1 100644 --- a/client/src/cmdtrace.c +++ b/client/src/cmdtrace.c @@ -1498,7 +1498,7 @@ int CmdTraceList(const char *Cmd) { if (protocol == LEGIC) PrintAndLogEx(INFO, _YELLOW_("LEGIC") " - Reader Mode: Timings are in ticks (1us == 1.5ticks)\n" - " Tag Mode: Timings are in sub carrier periods (1/212 kHz == 4.7us)"); + " Tag Mode: Timings are in sub carrier periods (1/212 kHz == 4.7us)"); if (protocol == ISO_14443B || protocol == PROTO_CRYPTORF) { if (use_us) diff --git a/client/src/flash.c b/client/src/flash.c index 25edb7c0f..584288779 100644 --- a/client/src/flash.c +++ b/client/src/flash.c @@ -124,7 +124,7 @@ static int build_segs_from_phdrs(flash_file_t *ctx, uint32_t flash_size) { offset); if (filesz != memsz) { PrintAndLogEx(ERR, "Error: PHDR file size does not equal memory size\n" - "(DATA+BSS PHDRs do not make sense on ROM platforms!)"); + "(DATA+BSS PHDRs do not make sense on ROM platforms!)"); return PM3_EFILE; } if (paddr < last_end) { diff --git a/client/src/mifare/gallaghercore.c b/client/src/mifare/gallaghercore.c index 3caba0b0a..07f83060d 100644 --- a/client/src/mifare/gallaghercore.c +++ b/client/src/mifare/gallaghercore.c @@ -300,10 +300,10 @@ void print_gallagher_creds(GallagherCredentials_t *creds) { return; } PrintAndLogEx(SUCCESS, "Gallagher - region: " _GREEN_("%c") " ( " _GREEN_("%u") " )" - ", facility: " _GREEN_("%u") - ", card number: " _GREEN_("%u") - ", issue level: " _GREEN_("%u"), - 'A' + creds->region_code, + ", facility: " _GREEN_("%u") + ", card number: " _GREEN_("%u") + ", issue level: " _GREEN_("%u"), + 'A' + creds->region_code, creds->region_code, creds->facility_code, creds->card_number, diff --git a/client/src/mifare/mifarehost.c b/client/src/mifare/mifarehost.c index 31e81cec6..47c0dbfc6 100644 --- a/client/src/mifare/mifarehost.c +++ b/client/src/mifare/mifarehost.c @@ -319,10 +319,10 @@ int mf_check_keys_fast_ex(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastCh PrintAndLogEx(NORMAL, ""); PrintAndLogEx(SUCCESS, "\nTarget block " _GREEN_("%4u") " key type " _GREEN_("%c") " -- found valid key [ " _GREEN_("%s") " ]", - block_no, - key_type ? 'B' : 'A', - sprint_hex_inrow(resp.data.asBytes, MIFARE_KEY_SIZE) - ); + block_no, + key_type ? 'B' : 'A', + sprint_hex_inrow(resp.data.asBytes, MIFARE_KEY_SIZE) + ); return PM3_SUCCESS; } diff --git a/client/src/pm3_luawrap.c b/client/src/pm3_luawrap.c index 65798a2e5..0d5753a9d 100644 --- a/client/src/pm3_luawrap.c +++ b/client/src/pm3_luawrap.c @@ -2756,9 +2756,9 @@ static int _wrap_new_pm3(lua_State *L) { } SWIG_Lua_pusherrstring(L, "Wrong arguments for overloaded function 'new_pm3'\n" - " Possible C/C++ prototypes are:\n" - " pm3::pm3()\n" - " pm3::pm3(char *)\n"); + " Possible C/C++ prototypes are:\n" + " pm3::pm3()\n" + " pm3::pm3(char *)\n"); lua_error(L); return 0; } diff --git a/client/src/pm3line_vocabulary.h b/client/src/pm3line_vocabulary.h index 285f50197..76f5de452 100644 --- a/client/src/pm3line_vocabulary.h +++ b/client/src/pm3line_vocabulary.h @@ -356,6 +356,7 @@ const static vocabulary_t vocabulary[] = { { 0, "hf legic rdbl" }, { 0, "hf legic reader" }, { 0, "hf legic restore" }, + { 0, "hf legic clone" }, { 0, "hf legic wipe" }, { 0, "hf legic wrbl" }, { 0, "hf legic sim" }, @@ -379,6 +380,7 @@ const static vocabulary_t vocabulary[] = { { 0, "hf mf nested" }, { 1, "hf mf hardnested" }, { 0, "hf mf staticnested" }, + { 0, "hf mf sen" }, { 0, "hf mf brute" }, { 0, "hf mf autopwn" }, { 0, "hf mf nack" }, @@ -465,6 +467,7 @@ const static vocabulary_t vocabulary[] = { { 0, "hf mfu countertear" }, { 0, "hf mfu cauth" }, { 0, "hf mfu cchk" }, + { 1, "hf mfu desbrute" }, { 0, "hf mfu aesauth" }, { 0, "hf mfu aeschk" }, { 0, "hf mfu setkey" }, diff --git a/client/src/proxmark3.c b/client/src/proxmark3.c index 3b9c69386..341b9ec0d 100644 --- a/client/src/proxmark3.c +++ b/client/src/proxmark3.c @@ -854,7 +854,7 @@ static int dumpmem_pm3(char *serial_port_name, const char *filename, uint32_t ad PrintAndLogEx(INFO, "Device is running the bootloader."); } else { PrintAndLogEx(ERR, "Device is running the bootloader, but the bootloader" - " doesn't understand the READ MEM command."); + " doesn't understand the READ MEM command."); goto finish2; } } diff --git a/common/bruteforce.h b/common/bruteforce.h index cab98c8c7..4a956801d 100644 --- a/common/bruteforce.h +++ b/common/bruteforce.h @@ -63,8 +63,8 @@ typedef struct { uint64_t current_key; // Use 64 bit and truncate when needed. uint8_t mode; uint8_t charset[ - BF_CHARSET_DIGITS_SIZE - + BF_CHARSET_UPPERCASE_SIZE + BF_CHARSET_DIGITS_SIZE + + BF_CHARSET_UPPERCASE_SIZE ]; uint8_t charset_length; diff --git a/common/iso15693tools.h b/common/iso15693tools.h index a18498a8d..0f9445c4d 100644 --- a/common/iso15693tools.h +++ b/common/iso15693tools.h @@ -73,14 +73,14 @@ static const int Iso15693FrameSOF[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - -1, -1, -1, -1, - -1, -1, -1, -1, - 1, 1, 1, 1, - 1, 1, 1, 1 - }; + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + -1, -1, -1, -1, + -1, -1, -1, -1, + 1, 1, 1, 1, + 1, 1, 1, 1 +}; static const int Iso15693Logic0[] = { 1, 1, 1, 1, 1, 1, 1, 1, @@ -89,10 +89,10 @@ static const int Iso15693Logic0[] = { }; static const int Iso15693Logic1[] = { -1, -1, -1, -1, - -1, -1, -1, -1, - 1, 1, 1, 1, - 1, 1, 1, 1 - }; + -1, -1, -1, -1, + 1, 1, 1, 1, + 1, 1, 1, 1 +}; // EOF defined as // 1) logic '0' (8 pulses of 423.75kHz followed by unmodulated for 18.88us) diff --git a/common/mbedtls/aesni.c b/common/mbedtls/aesni.c index 7a89a298b..7add8c1af 100644 --- a/common/mbedtls/aesni.c +++ b/common/mbedtls/aesni.c @@ -254,7 +254,7 @@ void mbedtls_aesni_inverse_key(unsigned char *invkey, for (fk -= 16, ik += 16; fk > fwdkey; fk -= 16, ik += 16) asm("movdqu (%0), %%xmm0 \n\t" AESIMC xmm0_xmm0 "\n\t" - "movdqu %%xmm0, (%1) \n\t" + "movdqu %%xmm0, (%1) \n\t" : : "r"(fk), "r"(ik) : "memory", "xmm0"); @@ -403,23 +403,23 @@ static void aesni_setkey_enc_256(unsigned char *rk, /* Set xmm2 to stuff:Y:stuff:stuff with Y = subword( r11 ) * and proceed to generate next round key from there */ AESKEYGENA xmm0_xmm2 ",0x00 \n\t" - "pshufd $0xaa, %%xmm2, %%xmm2 \n\t" - "pxor %%xmm1, %%xmm2 \n\t" - "pslldq $4, %%xmm1 \n\t" - "pxor %%xmm1, %%xmm2 \n\t" - "pslldq $4, %%xmm1 \n\t" - "pxor %%xmm1, %%xmm2 \n\t" - "pslldq $4, %%xmm1 \n\t" - "pxor %%xmm2, %%xmm1 \n\t" - "add $16, %0 \n\t" - "movdqu %%xmm1, (%0) \n\t" - "ret \n\t" + "pshufd $0xaa, %%xmm2, %%xmm2 \n\t" + "pxor %%xmm1, %%xmm2 \n\t" + "pslldq $4, %%xmm1 \n\t" + "pxor %%xmm1, %%xmm2 \n\t" + "pslldq $4, %%xmm1 \n\t" + "pxor %%xmm1, %%xmm2 \n\t" + "pslldq $4, %%xmm1 \n\t" + "pxor %%xmm2, %%xmm1 \n\t" + "add $16, %0 \n\t" + "movdqu %%xmm1, (%0) \n\t" + "ret \n\t" /* * Main "loop" - Generating one more key than necessary, * see definition of mbedtls_aes_context.buf */ - "2: \n\t" + "2: \n\t" AESKEYGENA xmm1_xmm2 ",0x01 \n\tcall 1b \n\t" AESKEYGENA xmm1_xmm2 ",0x02 \n\tcall 1b \n\t" AESKEYGENA xmm1_xmm2 ",0x04 \n\tcall 1b \n\t" diff --git a/common/mbedtls/camellia.c b/common/mbedtls/camellia.c index 7b49f9aae..56097c704 100644 --- a/common/mbedtls/camellia.c +++ b/common/mbedtls/camellia.c @@ -215,16 +215,16 @@ static const signed char indexes[2][4][20] = { }, /* KL -> RK */ { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - }, /* KR -> RK */ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + }, /* KR -> RK */ { 4, 5, 6, 7, 12, 13, 14, 15, 16, 17, 18, 19, -1, 24, 25, -1, 31, 28, 29, 30 }, /* KA -> RK */ { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - } /* KB -> RK */ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + } /* KB -> RK */ }, { { @@ -233,12 +233,12 @@ static const signed char indexes[2][4][20] = { }, /* KL -> RK */ { -1, -1, -1, -1, 8, 9, 10, 11, 16, 17, - 18, 19, -1, -1, -1, -1, 39, 36, 37, 38 - }, /* KR -> RK */ + 18, 19, -1, -1, -1, -1, 39, 36, 37, 38 + }, /* KR -> RK */ { -1, -1, -1, -1, 12, 13, 14, 15, 58, 59, - 56, 57, 31, 28, 29, 30, -1, -1, -1, -1 - }, /* KA -> RK */ + 56, 57, 31, 28, 29, 30, -1, -1, -1, -1 + }, /* KA -> RK */ { 4, 5, 6, 7, 65, 66, 67, 64, 20, 21, 22, 23, -1, -1, -1, -1, 43, 40, 41, 42 diff --git a/common/mbedtls/ctr_drbg.c b/common/mbedtls/ctr_drbg.c index f5d39d38d..ae42e93b1 100644 --- a/common/mbedtls/ctr_drbg.c +++ b/common/mbedtls/ctr_drbg.c @@ -119,7 +119,7 @@ void mbedtls_ctr_drbg_set_reseed_interval(mbedtls_ctr_drbg_context *ctx, static int block_cipher_df(unsigned char *output, const unsigned char *data, size_t data_len) { unsigned char buf[MBEDTLS_CTR_DRBG_MAX_SEED_INPUT + - MBEDTLS_CTR_DRBG_BLOCKSIZE + 16]; + MBEDTLS_CTR_DRBG_BLOCKSIZE + 16]; unsigned char tmp[MBEDTLS_CTR_DRBG_SEEDLEN]; unsigned char key[MBEDTLS_CTR_DRBG_KEYSIZE]; unsigned char chain[MBEDTLS_CTR_DRBG_BLOCKSIZE]; diff --git a/common/mbedtls/memory_buffer_alloc.c b/common/mbedtls/memory_buffer_alloc.c index a1e9accda..e3c16e74f 100644 --- a/common/mbedtls/memory_buffer_alloc.c +++ b/common/mbedtls/memory_buffer_alloc.c @@ -86,7 +86,7 @@ static void debug_header(memory_header *hdr) { #endif mbedtls_fprintf(stderr, "HDR: PTR(%10zu), PREV(%10zu), NEXT(%10zu), " - "ALLOC(%zu), SIZE(%10zu)\n", + "ALLOC(%zu), SIZE(%10zu)\n", (size_t) hdr, (size_t) hdr->prev, (size_t) hdr->next, hdr->alloc, hdr->size); mbedtls_fprintf(stderr, " FPREV(%10zu), FNEXT(%10zu)\n", @@ -164,7 +164,7 @@ static int verify_chain(void) { if (prv == NULL || verify_header(prv) != 0) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf(stderr, "FATAL: verification of first header " - "failed\n"); + "failed\n"); #endif return (1); } @@ -172,7 +172,7 @@ static int verify_chain(void) { if (heap.first->prev != NULL) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf(stderr, "FATAL: verification failed: " - "first->prev != NULL\n"); + "first->prev != NULL\n"); #endif return (1); } @@ -183,7 +183,7 @@ static int verify_chain(void) { if (verify_header(cur) != 0) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf(stderr, "FATAL: verification of header " - "failed\n"); + "failed\n"); #endif return (1); } @@ -191,7 +191,7 @@ static int verify_chain(void) { if (cur->prev != prv) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf(stderr, "FATAL: verification failed: " - "cur->prev != prv\n"); + "cur->prev != prv\n"); #endif return (1); } @@ -243,7 +243,7 @@ static void *buffer_alloc_calloc(size_t n, size_t size) { if (cur->alloc != 0) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf(stderr, "FATAL: block in free_list but allocated " - "data\n"); + "data\n"); #endif mbedtls_exit(1); } @@ -359,7 +359,7 @@ static void buffer_alloc_free(void *ptr) { if (p < heap.buf || p >= heap.buf + heap.len) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf(stderr, "FATAL: mbedtls_free() outside of managed " - "space\n"); + "space\n"); #endif mbedtls_exit(1); } @@ -373,7 +373,7 @@ static void buffer_alloc_free(void *ptr) { if (hdr->alloc != 1) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf(stderr, "FATAL: mbedtls_free() on unallocated " - "data\n"); + "data\n"); #endif mbedtls_exit(1); } diff --git a/common/mbedtls/ssl.h b/common/mbedtls/ssl.h index 7c78a698a..3603dc373 100644 --- a/common/mbedtls/ssl.h +++ b/common/mbedtls/ssl.h @@ -445,14 +445,14 @@ union mbedtls_ssl_premaster_secret { #endif #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) unsigned char _pms_dhe_psk[4 + MBEDTLS_MPI_MAX_SIZE - + MBEDTLS_PSK_MAX_LEN]; /* RFC 4279 3 */ + + MBEDTLS_PSK_MAX_LEN]; /* RFC 4279 3 */ #endif #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) unsigned char _pms_rsa_psk[52 + MBEDTLS_PSK_MAX_LEN]; /* RFC 4279 4 */ #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) unsigned char _pms_ecdhe_psk[4 + MBEDTLS_ECP_MAX_BYTES - + MBEDTLS_PSK_MAX_LEN]; /* RFC 5489 2 */ + + MBEDTLS_PSK_MAX_LEN]; /* RFC 5489 2 */ #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) unsigned char _pms_ecjpake[32]; /* Thread spec: SHA-256 output */ diff --git a/common/mbedtls/ssl_cli.c b/common/mbedtls/ssl_cli.c index b41b01167..cb4552a38 100644 --- a/common/mbedtls/ssl_cli.c +++ b/common/mbedtls/ssl_cli.c @@ -804,7 +804,7 @@ static int ssl_write_use_srtp_ext(mbedtls_ssl_context *ssl, */ MBEDTLS_SSL_DEBUG_MSG(3, ("client hello, " - "illegal DTLS-SRTP protection profile %d", + "illegal DTLS-SRTP protection profile %d", ssl->conf->dtls_srtp_profile_list[protection_profiles_index] )); return (MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED); diff --git a/common/mbedtls/ssl_msg.c b/common/mbedtls/ssl_msg.c index d13be766f..8eed325ec 100644 --- a/common/mbedtls/ssl_msg.c +++ b/common/mbedtls/ssl_msg.c @@ -3954,7 +3954,7 @@ static int ssl_buffer_message(mbedtls_ssl_context *ssl) { /* Silently ignore -- message too far in the future */ MBEDTLS_SSL_DEBUG_MSG(2, ("Ignore future HS message with sequence number %u, " - "buffering window %u - %u", + "buffering window %u - %u", recv_msg_seq, ssl->handshake->in_msg_seq, ssl->handshake->in_msg_seq + MBEDTLS_SSL_MAX_BUFFERED_HS - 1)); diff --git a/common/mbedtls/x509_crt.c b/common/mbedtls/x509_crt.c index 850893f0a..2e1cea165 100644 --- a/common/mbedtls/x509_crt.c +++ b/common/mbedtls/x509_crt.c @@ -2101,7 +2101,7 @@ int mbedtls_x509_crt_verify_info(char *buf, size_t size, const char *prefix, if (flags != 0) { ret = mbedtls_snprintf(p, n, "%sUnknown reason " - "(this should not happen)\n", prefix); + "(this should not happen)\n", prefix); MBEDTLS_X509_SAFE_SNPRINTF; } diff --git a/doc/commands.json b/doc/commands.json index 9e66171a6..f1c476b9d 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -2343,6 +2343,22 @@ ], "usage": "hf calypso list [-h1crux] [--frame] [-f ]" }, + "hf calypso probecmdcompat": { + "command": "hf calypso probecmdcompat", + "description": "Probe Calypso SELECT command compatibility", + "notes": [ + "hf calypso probecmdcompat", + "hf calypso probecmdcompat -v", + "hf calypso probecmdcompat --aid 315449432E494341" + ], + "offline": false, + "options": [ + "-h, --help This help", + "--aid Calypso application AID or AID prefix (5..16 bytes)", + "-v, --verbose verbose output" + ], + "usage": "hf calypso probecmdcompat [-hv] [--aid ]" + }, "hf cipurse aread": { "command": "hf cipurse aread", "description": "Read file attributes by file ID with key ID and key. If no key is supplied, default key of 737373...7373 will be used", @@ -4392,6 +4408,24 @@ ], "usage": "hf ksx6924 prec [-hka] " }, + "hf legic clone": { + "command": "hf legic clone", + "description": "Rewrite a LEGIC dump for a new target tag or MCC. Use --mcc to rewrite only the dump obfuscation, or --write to clone to the current tag.", + "notes": [ + "hf legic clone -f src.bin -c 39 -o clone.bin", + "hf legic clone -f src.bin --write", + "hf legic clone -f src.bin --write -o clone.bin" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-f, --file Source dump file", + "--mcc Target MCC byte for output-only cloning", + "-o, --output Output cloned dump file", + "-w, --write Write cloned dump to the currently attached tag" + ], + "usage": "hf legic clone [-hw] -f [--mcc ] [-o ]" + }, "hf legic crc": { "command": "hf legic crc", "description": "Calculates the legic crc8/crc16 on the given data", @@ -4572,18 +4606,20 @@ }, "hf legic sim": { "command": "hf legic sim", - "description": "Simulates a LEGIC Prime tag. Following types supported (MIM22, MIM256, MIM1024)", + "description": "Simulates a LEGIC Prime tag. If a file is supplied, it is loaded into emulator memory first.", "notes": [ - "hf legic sim --22" + "hf legic sim --22", + "hf legic sim -f myfile.bin --1024" ], "offline": false, "options": [ "-h, --help This help", "--22 LEGIC Prime MIM22", "--256 LEGIC Prime MIM256 (def)", - "--1024 LEGIC Prime MIM1024" + "--1024 LEGIC Prime MIM1024", + "-f, --file Optional dump file to load into emulator memory" ], - "usage": "hf legic sim [-h] [--22] [--256] [--1024]" + "usage": "hf legic sim [-h] [--22] [--256] [--1024] [-f ]" }, "hf legic view": { "command": "hf legic view", @@ -5844,6 +5880,28 @@ ], "usage": "hf mf restore [-h] [--mini] [--1k] [--2k] [--4k] [-u ] [-f ] [-k ] [--ka] [--force]" }, + "hf mf sen": { + "command": "hf mf sen", + "description": "Recover FM11RF08S keys using static encrypted nonce evidence in native client code", + "notes": [ + "hf mf sen", + "hf mf sen --keep-nonces", + "hf mf sen --no-oob", + "hf mf sen --reader" + ], + "offline": false, + "options": [ + "-h, --help This help", + "--keep-nonces save collected nonce/data JSON evidence", + "--no-oob do not include FM11RF08S out-of-bounds sector 32 in key file", + "--reader pre-pass: emulate this UID to a reader and digest recovered reader keys", + "--offline-only stop after offline filtering, do not verify online", + "--online-confirm only do online confirmation (skip generation if nonces loaded)", + "--max-online-candidates abort online phase if total candidates exceed this limit", + "--parity-mask parity filter mask 1..F (default 1 = vetted staticnested_1nt behavior)" + ], + "usage": "hf mf sen [-h] [--keep-nonces] [--no-oob] [--reader] [--offline-only] [--online-confirm] [--max-online-candidates ] [--parity-mask ]" + }, "hf mf setmod": { "command": "hf mf setmod", "description": "Sets the load modulation strength of a MIFARE Classic EV1 card", @@ -6461,6 +6519,41 @@ ], "usage": "hf mfdes createmacfile [-hav] [-n ] [-t ] [-k ] [--kdf ] [-i ] [-m ] [-c ] [--schann ] [--aid ] [--isoid ] [--fid ] [--amode ] [--rawrights ] [--rrights ] [--wrights ] [--rwrights ] [--chrights ] [--no-auth] [--mackey ] [--mackeyver ]" }, + "hf mfdes createmfcmapping": { + "command": "hf mfdes createmfcmapping", + "description": "Create a Mifare Classic mapping on a DESFire EV3C. The MFC License MAC key (AES only) must have been set previously as PICC key number 50.", + "notes": [ + "hf mfdes createmfcmapping --aid 123456 --fid 01 --mfc-keys FFFFFFFFFFFF111111111111222222222222 --mfc-blocks 4,5,6,8", + "-> Map blocks 4, 5, 6, 8 where sector 1 key A is FFFFFFFFFFFF with key B readable,", + "-> sector 2 keys are 111111111111 and 222222222222 with key B used for authentication" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-a, --apdu Show APDU requests and responses", + "-v, --verbose Verbose output", + "-n, --keyno Key number", + "-t, --algo Crypt algo", + "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "--kdf Key Derivation Function (KDF)", + "-i, --kdfi KDF input (1-31 hex bytes)", + "-m, --cmode Communicaton mode", + "-c, --ccset Communicaton command set", + "--schann Secure channel", + "--aid Application ID (3 hex bytes, big endian)", + "--isoid Application ISO ID (ISO DF ID) (2 hex bytes, big endian)", + "--fid File ID to map (1 hex byte)", + "--restore-fid Restore source when mapping value files to value blocks (1 hex byte)", + "-b, --blk [,[,...]] The MFC blocks to map, must be unique (use -b data for all data blocks, and -b trailer for all trailer blocks)", + "--mfc-license The MFC license (omit to use saved license and license MAC)", + "--mfc-license-mac The MFC license MAC (omit to use saved license and license MAC)", + "--ka Allow updating key A from inside sector trailers mapped to DESFire files", + "--kb Allow updating key B from inside sector trailers mapped to DESFire files", + "--access-conditions Allow updating the access conditions from inside sector trailers mapped to DESFire files", + "--restore-transfer Enable the RestoreTransfer command for the mapped value blocks" + ], + "usage": "hf mfdes createmfcmapping [-hav] [-n ] [-t ] [-k ] [--kdf ] [-i ] [-m ] [-c ] [--schann ] [--aid ] [--isoid ] [--fid ] [--restore-fid ] [-b [,[,...]]] [--mfc-license ] [--mfc-license-mac ] [--ka] [--kb] [--access-conditions] [--restore-transfer]" + }, "hf mfdes createrecordfile": { "command": "hf mfdes createrecordfile", "description": "Create Linear/Cyclic Record file in the application. Application master key needs to be provided or flag --no-auth set (depend on application settings).", @@ -7118,8 +7211,8 @@ "-v, --verbose Show more output", "-k, --key Key for computing the MAC, must be HEX 16(AES)", "-b, --blk [,[,...]] The MFC blocks to map, must be given in ascending order (use the special value 'all' for all blocks)", - "--key-a Allow updating key A from inside sector trailers mapped to DESFire files", - "--key-b Allow updating key B from inside sector trailers mapped to DESFire files", + "--ka Allow updating key A from inside sector trailers mapped to DESFire files", + "--kb Allow updating key B from inside sector trailers mapped to DESFire files", "--restrict Allow the restriction of data updates by the MFC side", "--map Allow mapping the blocks to DESFire files", "--access-conditions Allow updating the access conditions from inside sector trailers mapped to DESFire files", @@ -7127,7 +7220,7 @@ "--mfc-keys The concatenated MFC sector keys, one (if key B is readable) or two per sector", "-s, --save Save the license and license MAC for the next commands in this session" ], - "usage": "hf mfdes makemfclicense [-hvs] [-k ] [-b [,[,...]]] [--key-a] [--key-b] [--restrict] [--map] [--access-conditions] [-r ] [--mfc-keys ]" + "usage": "hf mfdes makemfclicense [-hvs] [-k ] [-b [,[,...]]] [--ka] [--kb] [--restrict] [--map] [--access-conditions] [-r ] [--mfc-keys ]" }, "hf mfdes pc": { "command": "hf mfdes pc", @@ -7913,6 +8006,29 @@ ], "usage": "hf mfu countertear [-h] [-c <0,1,2>] [-i ] [-l ] [-s ] [--fix ] [-x ]" }, + "hf mfu desbrute": { + "command": "hf mfu desbrute", + "description": "Recover one 4-byte segment of a MIFARE Ultralight-C 2TDEA key from known authentication ciphertexts.", + "notes": [ + "hf mfu desbrute --counterfeit --null F35C740106ECED87 --target E9E0DC67B35919FC --key 00000000000000000000000000000000 --segment 2", + "hf mfu desbrute --counterfeit --null 49C1603621CCAA72 --target 8122262EF5FA8DEB --key 48444C4A4044524200000000544E5846 --segment 3", + "hf mfu desbrute --reader --erndb EC9C5CF763244367 --cryptogram 2283BFE8DEBE1780922327794D0706EF --key 48444C4A4044524200000000544E5846 --segment 3" + ], + "offline": true, + "options": [ + "-h, --help This help", + "-c, --counterfeit Counterfeit nonce mode: --null and --target are ERndB blocks", + "-r, --reader Reader nonce mode: --erndb and --cryptogram are sniffed authentication blocks", + "--null Null-key ERndB, 8 hex bytes", + "--target Target-key ERndB, 8 hex bytes", + "--erndb Reader mode ERndB, 8 hex bytes", + "--cryptogram Reader mode ERndA|ERndB', 16 hex bytes", + "-k, --key Base 3DES key, 16 hex bytes", + "-s, --segment <1..4> 4-byte key segment to brute force", + "-t, --threads Worker threads (default: all logical CPUs)" + ], + "usage": "hf mfu desbrute [-hcr] [--null ] [--target ] [--erndb ] [--cryptogram ] -k -s <1..4> [-t ]" + }, "hf mfu dump": { "command": "hf mfu dump", "description": "Dump MIFARE Ultralight/NTAG tag to files (bin/json) It autodetects card type.Supports: Ultralight, Ultralight C, Ultralight AES, Ultralight EV1 NTAG 203, NTAG 210, NTAG 212, NTAG 213, NTAG 215, NTAG 216", @@ -7986,7 +8102,7 @@ }, "hf mfu help": { "command": "hf mfu help", - "description": "help This help list List MIFARE Ultralight / NTAG history keygen Generate DES/3DES/AES MIFARE diversified keys pwdgen Generate pwd from known algos view Display content from tag dump file --------------------------------------------------------------------------------------- hf mfu list available offline: yes Alias of `trace list -t 14a -c` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol", + "description": "help This help list List MIFARE Ultralight / NTAG history keygen Generate DES/3DES/AES MIFARE diversified keys pwdgen Generate pwd from known algos desbrute Ultralight-C - 3DES key segment brute force view Display content from tag dump file --------------------------------------------------------------------------------------- hf mfu list available offline: yes Alias of `trace list -t 14a -c` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol", "notes": [ "hf 14a list --frame -> show frame delay times", "hf 14a list -1 -> use trace buffer" @@ -14605,8 +14721,8 @@ } }, "metadata": { - "commands_extracted": 825, + "commands_extracted": 830, "extracted_by": "PM3Help2JSON v1.00", - "extracted_on": "2026-05-11T12:35:32" + "extracted_on": "2026-05-21T19:04:15+00:00" } } diff --git a/doc/commands.md b/doc/commands.md index 5e3f99a69..51e028ed4 100644 --- a/doc/commands.md +++ b/doc/commands.md @@ -297,6 +297,7 @@ Check column "offline" for their availability. |`hf calypso help `|Y |`This help` |`hf calypso info `|N |`Tag information` |`hf calypso dump `|N |`Dump readable files and records` +|`hf calypso probecmdcompat`|N |`Probe SELECT command compatibility` |`hf calypso list `|Y |`List Calypso history` @@ -542,6 +543,7 @@ Check column "offline" for their availability. |`hf legic rdbl `|N |`Read bytes from a LEGIC Prime tag` |`hf legic reader `|N |`LEGIC Prime Reader UID and tag info` |`hf legic restore `|N |`Restore a dump file onto a LEGIC Prime tag` +|`hf legic clone `|N |`Clone a LEGIC Prime dump to a new MCC or tag` |`hf legic wipe `|N |`Wipe a LEGIC Prime tag` |`hf legic wrbl `|N |`Write data to a LEGIC Prime tag` |`hf legic sim `|N |`Start tag simulator` @@ -581,6 +583,7 @@ Check column "offline" for their availability. |`hf mf nested `|N |`Nested attack` |`hf mf hardnested `|Y |`Nested attack for hardened MIFARE Classic cards` |`hf mf staticnested `|N |`Nested attack against static nonce MIFARE Classic cards` +|`hf mf sen `|N |`FM11RF08S Static Encrypted Nonce attack` |`hf mf brute `|N |`Smart bruteforce to exploit weak key generators` |`hf mf autopwn `|N |`Automatic key recovery tool for MIFARE Classic` |`hf mf nack `|N |`Test for MIFARE NACK bug` @@ -683,6 +686,7 @@ Check column "offline" for their availability. |`hf mfu countertear `|N |`Tear-off test on Ev1/NTAG Counter bits` |`hf mfu cauth `|N |`Ultralight-C - Authentication` |`hf mfu cchk `|N |`Ultralight-C - Authentication dictionary check` +|`hf mfu desbrute `|Y |`Ultralight-C - 3DES key segment brute force` |`hf mfu aesauth `|N |`Ultralight-AES - Authentication` |`hf mfu aeschk `|N |`Ultralight-AES - Authentication dictionary check` |`hf mfu setkey `|N |`Ultralight C/AES - Set 3DES/AES keys` @@ -755,6 +759,7 @@ Check column "offline" for their availability. |`hf mfdes value `|N |`Operations with value file (get/credit/limited credit/debit/clear)` |`hf mfdes clearrecfile `|N |`Clear record File` |`hf mfdes makemfclicense`|Y |`Generate a Mifare Classic license for DESFire EV3C` +|`hf mfdes createmfcmapping`|N |`Create a Mifare Classic mapping on a DESFire EV3C` |`hf mfdes verifycert `|N |`Validate cert from file and verify key possession` |`hf mfdes intauth `|N |`ISO Internal Authenticate (ECDSA challenge-response)` |`hf mfdes vdesign `|N |`VDE ECDSASign (EV charging signature over 32-byte challenge)` diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index d75ed5f01..6efe9f339 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -331,7 +331,7 @@ typedef struct { typedef struct { // 64KB SRAM -> 524288 bits(max sample num) < 2^30 -uint32_t samples : + uint32_t samples : LF_SAMPLES_BITS; bool realtime : 1; bool verbose : 1; diff --git a/pm3 b/pm3 index e7a22e56b..603ecec5c 100755 --- a/pm3 +++ b/pm3 @@ -136,14 +136,14 @@ function get_pm3_list_Windows { PM3LIST=() # Normal SERIAL PORTS (COM) - for DEV in $($PSHEXE -command "Get-CimInstance -ClassName Win32_serialport | Where-Object {\$_.PNPDeviceID -like '*VID_9AC4&PID_4B8F*' -or \$_.PNPDeviceID -like '*VID_2D2D&PID_504D*'} | Select -expandproperty DeviceID" 2>/dev/null); do + for DEV in $($PSHEXE -NoProfile -command "Get-CimInstance -ClassName Win32_serialport | Where-Object {\$_.PNPDeviceID -like '*VID_9AC4&PID_4B8F*' -or \$_.PNPDeviceID -like '*VID_2D2D&PID_504D*'} | Select -expandproperty DeviceID" 2>/dev/null); do _comport=$DEV #prevent soft bricking when using pm3-flash-all on an outdated bootloader if [ $(basename -- "$0") = "pm3-flash-all" ]; then - line=$($PSHEXE -command "Get-CimInstance -ClassName Win32_serialport | Where-Object {\$_.DeviceID -eq '$_comport'} | Select -expandproperty PNPDeviceID" 2>/dev/null); + line=$($PSHEXE -NoProfile -command "Get-CimInstance -ClassName Win32_serialport | Where-Object {\$_.DeviceID -eq '$_comport'} | Select -expandproperty PNPDeviceID" 2>/dev/null); if [[ ! $line =~ ^"USB\VID_9AC4&PID_4B8F\ICEMAN" ]]; then echo -e "\033[0;31m[!] Using pm3-flash-all on an oudated bootloader, use pm3-flash-bootrom first!" @@ -159,7 +159,7 @@ function get_pm3_list_Windows { #BT direct SERIAL PORTS (COM) if $FINDBTRFCOMM; then - for DEV in $($PSHEXE -command "Get-CimInstance -ClassName Win32_PnPEntity | Where-Object Caption -like 'Standard Serial over Bluetooth link (COM*' | Select Name" 2>/dev/null); do + for DEV in $($PSHEXE -NoProfile -command "Get-CimInstance -ClassName Win32_PnPEntity | Where-Object Caption -like 'Standard Serial over Bluetooth link (COM*' | Select Name" 2>/dev/null); do PM3LIST+=("$DEV") if [ ${#PM3LIST[*]} -ge "$N" ]; then return @@ -170,7 +170,7 @@ function get_pm3_list_Windows { #white BT dongle SERIAL PORTS (COM) if $FINDBTDONGLE; then - for DEV in $($PSHEXE -command "Get-CimInstance -ClassName Win32_serialport | Where-Object PNPDeviceID -like '*VID_10C4&PID_EA60*' | Select -expandproperty DeviceID" 2>/dev/null); do + for DEV in $($PSHEXE -NoProfile -command "Get-CimInstance -ClassName Win32_serialport | Where-Object PNPDeviceID -like '*VID_10C4&PID_EA60*' | Select -expandproperty DeviceID" 2>/dev/null); do PM3LIST+=("$DEV") if [ ${#PM3LIST[*]} -ge "$N" ]; then return diff --git a/tools/deprecated-hid-flasher/flasher/flash.c b/tools/deprecated-hid-flasher/flasher/flash.c index 179693d8b..ebef34397 100644 --- a/tools/deprecated-hid-flasher/flasher/flash.c +++ b/tools/deprecated-hid-flasher/flasher/flash.c @@ -71,7 +71,7 @@ static int build_segs_from_phdrs(flash_file_t *ctx, FILE *fd, Elf32_Phdr *phdrs, offset); if (filesz != memsz) { fprintf(stderr, "Error: PHDR file size does not equal memory size\n" - "(DATA+BSS PHDRs do not make sense on ROM platforms!)\n"); + "(DATA+BSS PHDRs do not make sense on ROM platforms!)\n"); return -1; } if (paddr < last_end) { diff --git a/tools/mfulc_des_brute/mfulc_des_brute.c b/tools/mfulc_des_brute/mfulc_des_brute.c index bf4495a46..23670005e 100644 --- a/tools/mfulc_des_brute/mfulc_des_brute.c +++ b/tools/mfulc_des_brute/mfulc_des_brute.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #define BLOCK_SIZE 8 // DES (and 3DES) block size in bytes @@ -23,9 +24,16 @@ typedef enum { LFSR_MFC = 2 // For USCUID-UL and FJ8010 } lfsr_t; +// Dynamic work pool: keyspace is split into many small slots; threads pull slots atomically. typedef struct { - uint32_t start; // starting candidate (inclusive) - uint32_t end; // ending candidate (exclusive) + _Atomic uint32_t next_slot; // index of the next slot to be claimed + uint32_t num_slots; + uint32_t slot_size; // number of candidates per slot (last slot may be smaller) + uint32_t total; // total candidate count (2^28) +} work_pool_t; + +typedef struct { + work_pool_t *pool; // shared work pool int key_mode; // 0 to 3 (i.e. brute force segment 1-4 as 0-indexed) union { unsigned char init_ciphertext[BLOCK_SIZE]; @@ -119,9 +127,8 @@ static lfsr_t detect_lfsr_type(unsigned char *init_ciphertext) { // Worker thread function using low-level DES functions. static void *worker(void *arg) { thread_args_t *targs = (thread_args_t *) arg; - uint32_t start = targs->start; - uint32_t end = targs->end; - int key_mode = targs->key_mode; + work_pool_t *pool = targs->pool; + int key_mode = targs->key_mode; // Determine which half is being brute forced. // For key_mode 0 or 1 the candidate is in K1; for key_mode 2 or 3 the candidate is in K2. @@ -154,8 +161,21 @@ static void *worker(void *arg) { else memcpy(base_half, targs->base_key + 8, 8); - // Loop over the candidate key indices in this thread's range. - for (uint32_t idx = start; idx < end; idx++) { + // Pull slots from the shared pool until exhausted. + for (;;) { + if (key_found && !BENCHMARK_FULL_KEYSPACE) + break; + + uint32_t slot = atomic_fetch_add(&pool->next_slot, 1); + if (slot >= pool->num_slots) + break; + + uint32_t start = slot * pool->slot_size; + uint32_t end = start + pool->slot_size; + if (end > pool->total) + end = pool->total; + + for (uint32_t idx = start; idx < end; idx++) { if (key_found && !BENCHMARK_FULL_KEYSPACE) break; // Some other thread already found the key. // Convert the candidate index (28 bits) into 4 bytes. @@ -229,7 +249,8 @@ static void *worker(void *arg) { if (!BENCHMARK_FULL_KEYSPACE) break; } - } + } // end slot inner loop + } // end pool slot loop return NULL; } @@ -333,8 +354,14 @@ int main(int argc, char **argv) { // Total candidate space: 2^28 keys. uint32_t total = (1UL << 28); - uint32_t chunk = total / num_threads; - uint32_t remainder = total % num_threads; + + // Build a work pool: split the keyspace into 20*num_threads slots so that + // threads keep running at full utilisation until the very end. + work_pool_t pool; + pool.total = total; + pool.num_slots = (uint32_t)num_threads * 20; + pool.slot_size = (total + pool.num_slots - 1) / pool.num_slots; // ceiling division + atomic_init(&pool.next_slot, 0); pthread_t *threads = malloc(num_threads * sizeof(pthread_t)); thread_args_t *targs = malloc(num_threads * sizeof(thread_args_t)); @@ -343,13 +370,8 @@ int main(int argc, char **argv) { return 1; } - // Divide the candidate space as equally as possible among threads. - uint32_t current = 0; for (int i = 0; i < num_threads; i++) { - targs[i].start = current; - targs[i].end = current + chunk; - if (i == num_threads - 1) - targs[i].end += remainder; + targs[i].pool = &pool; targs[i].key_mode = key_mode; targs[i].lfsr_type = lfsr_type; targs[i].is_reader_mode = is_reader_mode; @@ -362,7 +384,6 @@ int main(int argc, char **argv) { } memcpy(targs[i].base_key, base_key, KEY_SIZE); targs[i].thread_id = i; - current = targs[i].end; pthread_create(&threads[i], NULL, worker, &targs[i]); } diff --git a/tools/mfulc_des_brute_cuda/Makefile b/tools/mfulc_des_brute_cuda/Makefile new file mode 100644 index 000000000..464e4ac40 --- /dev/null +++ b/tools/mfulc_des_brute_cuda/Makefile @@ -0,0 +1,15 @@ +NVCC ?= nvcc +TARGET ?= mfulc_des_brute_cuda +SOURCES := main.cu desbrute.cu + +NVCCFLAGS ?= -O3 -std=c++14 + +.PHONY: all clean + +all: $(TARGET) + +$(TARGET): $(SOURCES) desbrute.h des_host.h + $(NVCC) $(NVCCFLAGS) -o $@ $(SOURCES) + +clean: + rm -f $(TARGET) \ No newline at end of file diff --git a/tools/mfulc_des_brute_cuda/des_host.h b/tools/mfulc_des_brute_cuda/des_host.h new file mode 100644 index 000000000..d13725ef6 --- /dev/null +++ b/tools/mfulc_des_brute_cuda/des_host.h @@ -0,0 +1,222 @@ +/* + * des_host.h — Self-contained CPU DES implementation (no OpenSSL, no CUDA). + * Used for LFSR detection before GPU launch. + * + * All uint64_t values are "big-endian packed": byte 0 of the DES block occupies + * bits 63-56, byte 7 occupies bits 7-0. This matches our GPU DES output format + * exactly, so the same LFSR / rotation checks work on both sides without bswap. + */ +#pragma once +#include +#include + +/* -------------------------------------------------------------------------- */ +/* DES constant tables (1-indexed bit positions, MSB = bit 1 = our bit 0) */ +/* -------------------------------------------------------------------------- */ + +static const uint8_t H_PC1[56] = { + 57,49,41,33,25,17, 9, 1, 58,50,42,34,26,18, + 10, 2,59,51,43,35,27,19, 11, 3,60,52,44,36, + 63,55,47,39,31,23,15, 7, 62,54,46,38,30,22, + 14, 6,61,53,45,37,29,21, 13, 5,28,20,12, 4 +}; + +static const uint8_t H_PC2[48] = { + 14,17,11,24, 1, 5, 3,28,15, 6,21,10, + 23,19,12, 4,26, 8, 16, 7,27,20,13, 2, + 41,52,31,37,47,55, 30,40,51,45,33,48, + 44,49,39,56,34,53, 46,42,50,36,29,32 +}; + +static const uint8_t H_SHIFTS[16] = { + 1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1 +}; + +static const uint8_t H_IP[64] = { + 58,50,42,34,26,18,10, 2, 60,52,44,36,28,20,12, 4, + 62,54,46,38,30,22,14, 6, 64,56,48,40,32,24,16, 8, + 57,49,41,33,25,17, 9, 1, 59,51,43,35,27,19,11, 3, + 61,53,45,37,29,21,13, 5, 63,55,47,39,31,23,15, 7 +}; + +static const uint8_t H_FP[64] = { + 40, 8,48,16,56,24,64,32, 39, 7,47,15,55,23,63,31, + 38, 6,46,14,54,22,62,30, 37, 5,45,13,53,21,61,29, + 36, 4,44,12,52,20,60,28, 35, 3,43,11,51,19,59,27, + 34, 2,42,10,50,18,58,26, 33, 1,41, 9,49,17,57,25 +}; + +static const uint8_t H_E[48] = { + 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, + 8, 9,10,11,12,13, 12,13,14,15,16,17, + 16,17,18,19,20,21, 20,21,22,23,24,25, + 24,25,26,27,28,29, 28,29,30,31,32, 1 +}; + +static const uint8_t H_P[32] = { + 16, 7,20,21,29,12,28,17, + 1,15,23,26, 5,18,31,10, + 2, 8,24,14,32,27, 3, 9, + 19,13,30, 6,22,11, 4,25 +}; + +static const uint8_t H_SBOX[8][4][16] = { + { {14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7}, /* S1 */ + {0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8}, + {4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0}, + {15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13} }, + { {15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10}, /* S2 */ + {3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5}, + {0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15}, + {13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9} }, + { {10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8}, /* S3 */ + {13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1}, + {13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7}, + {1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12} }, + { {7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15}, /* S4 */ + {13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9}, + {10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4}, + {3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14} }, + { {2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9}, /* S5 */ + {14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6}, + {4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14}, + {11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3} }, + { {12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11}, /* S6 */ + {10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8}, + {9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6}, + {4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13} }, + { {4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1}, /* S7 */ + {13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6}, + {1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2}, + {6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12} }, + { {13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7}, /* S8 */ + {1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2}, + {7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8}, + {2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11} } +}; + +/* -------------------------------------------------------------------------- */ +/* Utility */ +/* -------------------------------------------------------------------------- */ + +/* Convert 8-byte array (big-endian) → packed uint64 (byte 0 in bits 63-56) */ +static inline uint64_t bytes_to_u64(const uint8_t *b) +{ + return ((uint64_t)b[0] << 56) | ((uint64_t)b[1] << 48) | + ((uint64_t)b[2] << 40) | ((uint64_t)b[3] << 32) | + ((uint64_t)b[4] << 24) | ((uint64_t)b[5] << 16) | + ((uint64_t)b[6] << 8) | (uint64_t)b[7]; +} + +/* -------------------------------------------------------------------------- */ +/* CPU DES primitives */ +/* -------------------------------------------------------------------------- */ + +static inline uint64_t h_perm(uint64_t src, int src_bits, const uint8_t *tbl, int n) +{ + uint64_t dst = 0; + int i; + for (i = 0; i < n; i++) { + int sb = tbl[i] - 1; + dst |= ((src >> (src_bits - 1 - sb)) & 1ULL) << (n - 1 - i); + } + return dst; +} + +static inline void h_des_keyschedule(uint64_t key64, uint64_t sk[16]) +{ + uint64_t key56 = h_perm(key64, 64, H_PC1, 56); + uint32_t C = (uint32_t)(key56 >> 28) & 0x0FFFFFFFU; + uint32_t D = (uint32_t)(key56) & 0x0FFFFFFFU; + int i; + for (i = 0; i < 16; i++) { + int s = H_SHIFTS[i]; + C = ((C << s) | (C >> (28 - s))) & 0x0FFFFFFFU; + D = ((D << s) | (D >> (28 - s))) & 0x0FFFFFFFU; + sk[i] = h_perm(((uint64_t)C << 28) | D, 56, H_PC2, 48); + } +} + +static inline uint64_t h_des_crypt(uint64_t block, const uint64_t sk[16]) +{ + uint64_t ip = h_perm(block, 64, H_IP, 64); + uint32_t L = (uint32_t)(ip >> 32); + uint32_t R = (uint32_t)(ip); + int i; + for (i = 0; i < 16; i++) { + uint64_t eR = h_perm((uint64_t)R, 32, H_E, 48); + uint64_t x = eR ^ sk[i]; + uint32_t sout = 0; + int s; + for (s = 0; s < 8; s++) { + uint8_t b6 = (uint8_t)((x >> (42 - s * 6)) & 0x3F); + int row = ((b6 >> 5) & 1) * 2 + (b6 & 1); + int col = (b6 >> 1) & 0xF; + sout |= (uint32_t)H_SBOX[s][row][col] << (28 - s * 4); + } + uint32_t f = (uint32_t)h_perm((uint64_t)sout, 32, H_P, 32); + uint32_t nR = L ^ f; + L = R; R = nR; + } + return h_perm(((uint64_t)R << 32) | L, 64, H_FP, 64); +} + +static inline uint64_t h_des_decrypt(uint64_t block, const uint64_t sk[16]) +{ + uint64_t rsk[16]; + int i; + for (i = 0; i < 16; i++) rsk[i] = sk[15 - i]; + return h_des_crypt(block, rsk); +} + +/* -------------------------------------------------------------------------- */ +/* LFSR validators (input: BE uint64, byte 0 in bits 63-56) */ +/* -------------------------------------------------------------------------- */ + +static inline int h_valid_lfsr_ulcg(uint64_t x64) +{ + /* x64 is already B0=MSB; original code bswap'd from OpenSSL LE, we skip that */ + uint16_t x16 = (uint16_t)(x64 >> 48); + x16 = (uint16_t)(x16 << 15 | ((x16 >> 1) ^ ((x16 >> 3 ^ x16 >> 4 ^ x16 >> 6) & 1))); + if (x16 != (uint16_t)((x64 >> 32) & 0xFFFF)) return 0; + x16 = (uint16_t)(x16 << 15 | ((x16 >> 1) ^ ((x16 >> 3 ^ x16 >> 4 ^ x16 >> 6) & 1))); + if (x16 != (uint16_t)((x64 >> 16) & 0xFFFF)) return 0; + x16 = (uint16_t)(x16 << 15 | ((x16 >> 1) ^ ((x16 >> 3 ^ x16 >> 4 ^ x16 >> 6) & 1))); + if (x16 != (uint16_t)(x64 & 0xFFFF)) return 0; + return 1; +} + +static inline int h_valid_lfsr_mfc(uint64_t x64) +{ + uint16_t x16 = (uint16_t)(x64 & 0xFFFF); + int i; + for (i = 0; i < 16; i++) + x16 = (uint16_t)(x16 >> 1 | (x16 ^ x16 >> 2 ^ x16 >> 3 ^ x16 >> 5) << 15); + if (x16 != (uint16_t)((x64 >> 16) & 0xFFFF)) return 0; + for (i = 0; i < 16; i++) + x16 = (uint16_t)(x16 >> 1 | (x16 ^ x16 >> 2 ^ x16 >> 3 ^ x16 >> 5) << 15); + if (x16 != (uint16_t)((x64 >> 32) & 0xFFFF)) return 0; + for (i = 0; i < 16; i++) + x16 = (uint16_t)(x16 >> 1 | (x16 ^ x16 >> 2 ^ x16 >> 3 ^ x16 >> 5) << 15); + if (x16 != (uint16_t)((x64 >> 48) & 0xFFFF)) return 0; + return 1; +} + +/* + * Detect LFSR type from init_ciphertext (8 bytes). + * Decrypts with the all-zero DES key and checks LFSR structure. + * Returns 1=ULCG, 2=MFC, 0=unknown. + */ +static inline int h_detect_lfsr(const uint8_t init_ciphertext[8]) +{ + uint8_t zero_key[8]; + uint64_t sk[16]; + uint64_t ct, out; + memset(zero_key, 0, 8); + h_des_keyschedule(bytes_to_u64(zero_key), sk); + ct = bytes_to_u64(init_ciphertext); + out = h_des_decrypt(ct, sk); + if (h_valid_lfsr_ulcg(out)) return 1; + if (h_valid_lfsr_mfc(out)) return 2; + return 0; +} diff --git a/tools/mfulc_des_brute_cuda/desbrute.cu b/tools/mfulc_des_brute_cuda/desbrute.cu new file mode 100644 index 000000000..745b03aaa --- /dev/null +++ b/tools/mfulc_des_brute_cuda/desbrute.cu @@ -0,0 +1,835 @@ +/* + * desbrute.cu -- CUDA brute-force engine for 2TDEA key recovery. + */ + +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif +#include +#include "desbrute.h" + +#ifdef _WIN32 +typedef LARGE_INTEGER wall_time_t; + +static void wall_time_now(wall_time_t *t) +{ + QueryPerformanceCounter(t); +} + +static double wall_time_seconds(const wall_time_t *start, const wall_time_t *now) +{ + LARGE_INTEGER qpf; + QueryPerformanceFrequency(&qpf); + return (double)(now->QuadPart - start->QuadPart) / (double)qpf.QuadPart; +} + +static void sleep_ms(unsigned int ms) +{ + Sleep(ms); +} +#else +typedef struct timespec wall_time_t; + +static void wall_time_now(wall_time_t *t) +{ + clock_gettime(CLOCK_MONOTONIC, t); +} + +static double wall_time_seconds(const wall_time_t *start, const wall_time_t *now) +{ + time_t sec = now->tv_sec - start->tv_sec; + long nsec = now->tv_nsec - start->tv_nsec; + return (double)sec + (double)nsec / 1e9; +} + +static void sleep_ms(unsigned int ms) +{ + struct timespec req; + req.tv_sec = ms / 1000; + req.tv_nsec = (long)(ms % 1000) * 1000000L; + nanosleep(&req, NULL); +} +#endif + +/* ========================================================================== */ +/* CUDA error-checking */ +/* ========================================================================== */ + +/* + * CUDA_CHECK -- check a CUDA runtime call and jump to cleanup on failure. + * + * Requires the enclosing function to have: + * • A label cleanup: near the end. + * • All device handles/pointers initialised to NULL/nullptr before first use. + */ +#define CUDA_CHECK(call) do { \ + cudaError_t _ce = (call); \ + if (_ce != cudaSuccess) { \ + fprintf(stderr, "[cuda] %s:%d %s\n", \ + __FILE__, __LINE__, cudaGetErrorString(_ce)); \ + goto cleanup; \ + } \ +} while (0) + +/* ========================================================================== */ +/* DES constant tables */ +/* ========================================================================== */ + +__constant__ static uint8_t d_IP[64] = { + 58,50,42,34,26,18,10, 2, 60,52,44,36,28,20,12, 4, + 62,54,46,38,30,22,14, 6, 64,56,48,40,32,24,16, 8, + 57,49,41,33,25,17, 9, 1, 59,51,43,35,27,19,11, 3, + 61,53,45,37,29,21,13, 5, 63,55,47,39,31,23,15, 7 +}; +__constant__ static uint8_t d_FP[64] = { + 40, 8,48,16,56,24,64,32, 39, 7,47,15,55,23,63,31, + 38, 6,46,14,54,22,62,30, 37, 5,45,13,53,21,61,29, + 36, 4,44,12,52,20,60,28, 35, 3,43,11,51,19,59,27, + 34, 2,42,10,50,18,58,26, 33, 1,41, 9,49,17,57,25 +}; + +/* + * Combined S+P table: SP[s*64 + b6] is the contribution of S-box s with 6-bit + * input b6 to the 32-bit P-permutation output. Size: 8x64x4 = 2 KB. + * Precomputed on CPU in desbrute_launch() and uploaded via cudaMemcpyToSymbol. + */ +__constant__ static uint32_t d_SP[512]; + +/* Precomputed DES encryption subkeys for the fixed key half */ +__constant__ static uint64_t d_fixed_sk[16]; + +/* + * Key-schedule XOR tables for the variable (candidate) key half. + * + * The 4 variable bytes contribute 28 effective bits (7 bits each, parity + * discarded) to the 16x48-bit subkeys. Because the DES key schedule is a + * sequence of linear bit operations (PC1 permutation, half-rotations, PC2 + * permutation), the contribution of each input bit to every subkey bit is + * fixed and can be precomputed. + * + * d_cand_sk_base[r] = subkeys when all variable bytes are 0 + * d_cand_sk_contrib[b*16+r] = XOR contribution of effective bit b (0..27) + * to subkey round r (0..15) + * + * In the kernel, per candidate: + * cand_sk[r] = d_cand_sk_base[r] + * for b in 0..27 (unrolled, branchless): + * mask = -(uint64_t)((idx >> b) & 1) // 0 or 0xFFFFFFFFFFFFFFFF + * cand_sk[r] ^= d_cand_sk_contrib[b*16+r] & mask + * + * This replaces DPERM(PC1,56) + 16xDPERM(PC2,48) with 28x16 ALU ops. + * Size: (16 + 28*16) * 8 = 3712 bytes. + */ +__constant__ static uint64_t d_cand_sk_base[16]; +__constant__ static uint64_t d_cand_sk_contrib[28 * 16]; + +/* ========================================================================== */ +/* Bit permutation macro (used only for IP/FP in device code) */ +/* ========================================================================== */ + +#define DPERM(src, src_bits, tbl, N, dst) do { \ + int _i; (dst) = 0; \ + _Pragma("unroll") \ + for (_i = 0; _i < (N); _i++) { \ + int _sb = (tbl)[_i] - 1; \ + (dst) |= (((src) >> ((src_bits)-1-_sb)) & 1ULL) \ + << ((N)-1-_i); \ + } \ +} while(0) + +/* ========================================================================== */ +/* Device DES primitives */ +/* ========================================================================== */ + +/* + * Feistel f function using the shared-memory SP table. + * + * E expansion is inlined as direct bit extractions from R — eliminates the + * 48-iteration DPERM(E) loop entirely. Called 3x16 = 48 times per candidate. + * + * E table maps R bits (DES 1-indexed) to 6-bit S-box inputs (0-indexed from + * MSB of 48-bit eR): + * S1: E[0..5] = DES bits 32,1,2,3,4,5 → R bits 0,31,30,29,28,27 + * S2: E[6..11] = DES bits 4,5,6,7,8,9 → R bits 28,27,26,25,24,23 + * S3: = DES bits 8..13 → R bits 24..19 + * S4: = DES bits 12..17 → R bits 20..15 + * S5: = DES bits 16..21 → R bits 16..11 + * S6: = DES bits 20..25 → R bits 12..7 + * S7: = DES bits 24..29 → R bits 8..3 + * S8: = DES bits 28,29,30,31,32,1→ R bits 4,3,2,1,0,31 + * + * In our uint32_t R: DES bit i (1-based) = bit (32-i) from LSB. + */ +__device__ static __forceinline__ +uint32_t d_des_f(uint32_t R, uint64_t K, const uint32_t * __restrict__ sp) +{ + /* Extract 6-bit S-box inputs directly from R */ + uint32_t r0 = ((R & 1u) << 5) | ((R >> 27) & 0x1Fu); /* S1 */ + uint32_t r1 = (R >> 23) & 0x3Fu; /* S2 */ + uint32_t r2 = (R >> 19) & 0x3Fu; /* S3 */ + uint32_t r3 = (R >> 15) & 0x3Fu; /* S4 */ + uint32_t r4 = (R >> 11) & 0x3Fu; /* S5 */ + uint32_t r5 = (R >> 7) & 0x3Fu; /* S6 */ + uint32_t r6 = (R >> 3) & 0x3Fu; /* S7 */ + uint32_t r7 = ((R & 0x1Fu) << 1) | ((R >> 31) & 1u); /* S8 */ + + /* XOR with subkey 6-bit chunks (K is 48 bits in bits 47..0) */ + r0 ^= (uint32_t)((K >> 42) & 0x3Fu); + r1 ^= (uint32_t)((K >> 36) & 0x3Fu); + r2 ^= (uint32_t)((K >> 30) & 0x3Fu); + r3 ^= (uint32_t)((K >> 24) & 0x3Fu); + r4 ^= (uint32_t)((K >> 18) & 0x3Fu); + r5 ^= (uint32_t)((K >> 12) & 0x3Fu); + r6 ^= (uint32_t)((K >> 6) & 0x3Fu); + r7 ^= (uint32_t)(K & 0x3Fu); + + return sp[r0] ^ sp[64+r1] ^ sp[128+r2] ^ sp[192+r3] + ^ sp[256+r4] ^ sp[320+r5] ^ sp[384+r6] ^ sp[448+r7]; +} + +/* + * 16 Feistel rounds with NO Initial or Final Permutation. + * + * rev=0 encrypt (subkeys sk[0]..sk[15]) + * rev=1 decrypt (subkeys sk[15]..sk[0]) + * + * Input `block` must already have IP applied. + * Output is the pre-FP word (R16 || L16). + */ +__device__ static __forceinline__ +uint64_t d_des_rounds(uint64_t block, const uint64_t sk[16], int rev, + const uint32_t * __restrict__ sp) +{ + uint32_t L = (uint32_t)(block >> 32); + uint32_t R = (uint32_t)(block); + #pragma unroll 16 + for (int i = 0; i < 16; i++) { + uint64_t K = rev ? sk[15 - i] : sk[i]; + uint32_t nR = L ^ d_des_f(R, K, sp); + L = R; + R = nR; + } + return ((uint64_t)R << 32) | L; /* R16 || L16 (pre-FP) */ +} + +/* + * Optimised 2TDEA decrypt. + * + * One IP at entry + three rounds-only stages + one FP at exit. + * Saves 4 permutations vs. the naive DES_full x 3 approach. + * + * mode=0 K1=candidate, K2=fixed: D_cand -> E_fixed -> D_cand + * mode=1 K2=candidate, K1=fixed: D_fixed -> E_cand -> D_fixed + */ +__device__ static __forceinline__ +uint64_t d_tdea2_dec(uint64_t cipher, const uint64_t cand_sk[16], int mode, + const uint32_t * __restrict__ sp) +{ + uint64_t ip, t1, t2, t3, out; + DPERM(cipher, 64, d_IP, 64, ip); + if (mode == 0) { + t1 = d_des_rounds(ip, cand_sk, 1, sp); + t2 = d_des_rounds(t1, d_fixed_sk, 0, sp); + t3 = d_des_rounds(t2, cand_sk, 1, sp); + } else { + t1 = d_des_rounds(ip, d_fixed_sk, 1, sp); + t2 = d_des_rounds(t1, cand_sk, 0, sp); + t3 = d_des_rounds(t2, d_fixed_sk, 1, sp); + } + DPERM(t3, 64, d_FP, 64, out); + return out; +} + +/* ========================================================================== */ +/* LFSR validators (counterfeit mode only) */ +/* ========================================================================== */ + +__device__ static __forceinline__ int d_valid_lfsr_ulcg(uint64_t x64) +{ + uint16_t x = (uint16_t)(x64 >> 48); + x = (uint16_t)(x << 15 | ((x >> 1) ^ ((x >> 3 ^ x >> 4 ^ x >> 6) & 1))); + if (x != (uint16_t)((x64 >> 32) & 0xFFFF)) return 0; + x = (uint16_t)(x << 15 | ((x >> 1) ^ ((x >> 3 ^ x >> 4 ^ x >> 6) & 1))); + if (x != (uint16_t)((x64 >> 16) & 0xFFFF)) return 0; + x = (uint16_t)(x << 15 | ((x >> 1) ^ ((x >> 3 ^ x >> 4 ^ x >> 6) & 1))); + return (x == (uint16_t)(x64 & 0xFFFF)); +} + +__device__ static __forceinline__ int d_valid_lfsr_mfc(uint64_t x64) +{ + int i; + uint16_t x = (uint16_t)(x64 & 0xFFFF); + #pragma unroll 16 + for (i = 0; i < 16; i++) + x = (uint16_t)(x >> 1 | (x ^ x >> 2 ^ x >> 3 ^ x >> 5) << 15); + if (x != (uint16_t)((x64 >> 16) & 0xFFFF)) return 0; + #pragma unroll 16 + for (i = 0; i < 16; i++) + x = (uint16_t)(x >> 1 | (x ^ x >> 2 ^ x >> 3 ^ x >> 5) << 15); + if (x != (uint16_t)((x64 >> 32) & 0xFFFF)) return 0; + #pragma unroll 16 + for (i = 0; i < 16; i++) + x = (uint16_t)(x >> 1 | (x ^ x >> 2 ^ x >> 3 ^ x >> 5) << 15); + return (x == (uint16_t)((x64 >> 48) & 0xFFFF)); +} + +/* ========================================================================== */ +/* Brute-force kernel */ +/* ========================================================================== */ + +/* + * PROGRESS_STRIDE: candidates each thread processes between progress flushes. + * Lower = finer granularity, slightly more atomic overhead. + */ +#define PROGRESS_STRIDE 4096u + +__global__ void desbrute_kernel( + uint64_t ciphertext, + uint64_t init_ciphertext, + uint64_t prev_ciphertext, + int cand_mode, + int lfsr_type, + int is_reader_mode, + int *d_found, + uint32_t *d_result_idx, + unsigned long long *d_progress +) +{ + /* + * Step 1: load SP table from __constant__ into shared memory. + * + * Using shared memory avoids constant-cache serialisation: in a 32-thread + * warp each thread accesses a different S-box entry (divergent), so constant + * memory would serialize those 32 reads. Shared memory handles them in + * parallel with ~4-cycle latency. + */ + __shared__ uint32_t s_SP[512]; + for (int i = (int)threadIdx.x; i < 512; i += (int)blockDim.x) + s_SP[i] = d_SP[i]; + __syncthreads(); /* Barrier 1: SP table visible to all threads in block */ + + /* + * Step 2: initialise per-block early-exit flag. + * Separate barrier so the intent of each sync is clear. + */ + __shared__ int s_found; + if (threadIdx.x == 0) + s_found = *d_found; + __syncthreads(); /* Barrier 2: s_found visible before loop starts */ + + const uint32_t total = 1u << 28; + const uint32_t stride = (uint32_t)(gridDim.x * blockDim.x); + uint32_t idx = (uint32_t)(blockIdx.x * blockDim.x + threadIdx.x); + + /* + * candidates_tested semantics + * ---------------------------- + * no-match : sum of per-thread counters == total (2^28) + * match : approximate work done before early-exit; not necessarily + * idx+1 because threads run in parallel and some overshoot. + */ + unsigned long long local_count = 0; + + for (; idx < total; idx += stride) { + + /* + * Periodic progress flush and early-exit check. + * + * __syncthreads() is intentionally absent here. If it were present, + * threads that finish fewer iterations than PROGRESS_STRIDE could exit + * the loop while others hit the barrier -> deadlock. + * + * Only thread 0 flushes local_count and re-reads d_found. + * A __threadfence_block() after the write makes the updated s_found + * visible to other threads in the same block within a few cycles. + */ + if ((local_count & (PROGRESS_STRIDE - 1)) == 0) { + if (s_found) goto done; + if (threadIdx.x == 0) { + atomicAdd(d_progress, local_count); + local_count = 0; + s_found = *d_found; + __threadfence_block(); /* push s_found write to shared mem */ + } + } + local_count++; + + uint64_t cand_sk[16]; + #pragma unroll 16 + for (int r = 0; r < 16; r++) + cand_sk[r] = d_cand_sk_base[r]; + + #pragma unroll 28 + for (int b = 0; b < 28; b++) { + uint64_t mask = (uint64_t)(-(int64_t)((idx >> b) & 1u)); + #pragma unroll 16 + for (int r = 0; r < 16; r++) + cand_sk[r] ^= d_cand_sk_contrib[b * 16 + r] & mask; + } + + /* Optimised 2TDEA decrypt (single IP/FP for the whole chain) */ + uint64_t out = d_tdea2_dec(ciphertext, cand_sk, cand_mode, s_SP); + + /* Match check */ + int match = 0; + if (is_reader_mode) { + uint64_t init_out = d_tdea2_dec(init_ciphertext, cand_sk, + cand_mode, s_SP); + out ^= prev_ciphertext; + uint64_t rotated = (init_out << 8) | (init_out >> 56); + match = (out == rotated); + } else { + if (lfsr_type == LFSR_ULCG) match = d_valid_lfsr_ulcg(out); + else if (lfsr_type == LFSR_MFC) match = d_valid_lfsr_mfc(out); + } + + if (match) { + if (atomicCAS(d_found, 0, 1) == 0) + *d_result_idx = idx; + s_found = 1; + /* Do NOT increment local_count again here -- it was already + * counted above. An extra ++ would make candidates_tested + * off by one. */ + goto done; + } + } + +done: + /* Flush remaining local count to the global progress counter */ + if (local_count > 0) + atomicAdd(d_progress, local_count); +} + +/* ========================================================================== */ +/* CPU helpers */ +/* ========================================================================== */ + +static void cpu_des_keyschedule(uint64_t key64, uint64_t sk[16]) +{ + static const uint8_t PC1[56] = { + 57,49,41,33,25,17, 9, 1, 58,50,42,34,26,18, + 10, 2,59,51,43,35,27,19, 11, 3,60,52,44,36, + 63,55,47,39,31,23,15, 7, 62,54,46,38,30,22, + 14, 6,61,53,45,37,29,21, 13, 5,28,20,12, 4 + }; + static const uint8_t PC2[48] = { + 14,17,11,24, 1, 5, 3,28,15, 6,21,10, + 23,19,12, 4,26, 8, 16, 7,27,20,13, 2, + 41,52,31,37,47,55, 30,40,51,45,33,48, + 44,49,39,56,34,53, 46,42,50,36,29,32 + }; + static const uint8_t SHF[16] = {1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1}; + int i, j; + uint64_t key56 = 0; + for (i = 0; i < 56; i++) { + int sb = PC1[i] - 1; + key56 |= ((key64 >> (63 - sb)) & 1ULL) << (55 - i); + } + uint32_t C = (uint32_t)(key56 >> 28) & 0x0FFFFFFFu; + uint32_t D = (uint32_t)(key56) & 0x0FFFFFFFu; + for (i = 0; i < 16; i++) { + int s = SHF[i]; + C = ((C << s) | (C >> (28 - s))) & 0x0FFFFFFFu; + D = ((D << s) | (D >> (28 - s))) & 0x0FFFFFFFu; + uint64_t CD = ((uint64_t)C << 28) | D; + uint64_t sub = 0; + for (j = 0; j < 48; j++) { + int sb2 = PC2[j] - 1; + sub |= ((CD >> (55 - sb2)) & 1ULL) << (47 - j); + } + sk[i] = sub; + } +} + +static inline uint64_t cpu_bytes_to_u64(const uint8_t *b) +{ + return ((uint64_t)b[0] << 56) | ((uint64_t)b[1] << 48) | + ((uint64_t)b[2] << 40) | ((uint64_t)b[3] << 32) | + ((uint64_t)b[4] << 24) | ((uint64_t)b[5] << 16) | + ((uint64_t)b[6] << 8) | (uint64_t)b[7]; +} + +/* + * Precompute the combined S+P table on the CPU. + * + * For S-box s (0..7) and 6-bit input b6 (0..63): + * sval = SBOX[s][row][col] (4-bit output, 0..15) + * sval occupies sout bits [28-s*4 .. 31-s*4] (bit 0 = integer LSB) + * P permutation: pf[31-i] = sout[32 - P[i]] + * SP[s*64+b6] accumulates only pf bits from S-box s. + */ +static void cpu_compute_sp(uint32_t sp_out[512]) +{ + static const uint8_t SBOX[512] = { + /* S1 */ + 14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7, + 0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8, + 4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0, + 15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13, + /* S2 */ + 15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10, + 3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5, + 0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15, + 13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9, + /* S3 */ + 10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8, + 13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1, + 13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7, + 1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12, + /* S4 */ + 7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15, + 13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9, + 10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4, + 3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14, + /* S5 */ + 2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9, + 14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6, + 4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14, + 11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3, + /* S6 */ + 12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11, + 10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8, + 9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6, + 4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13, + /* S7 */ + 4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1, + 13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6, + 1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2, + 6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12, + /* S8 */ + 13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7, + 1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2, + 7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8, + 2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11 + }; + static const uint8_t P[32] = { + 16, 7,20,21,29,12,28,17, + 1,15,23,26, 5,18,31,10, + 2, 8,24,14,32,27, 3, 9, + 19,13,30, 6,22,11, 4,25 + }; + + int s, b6, i; + for (s = 0; s < 8; s++) { + for (b6 = 0; b6 < 64; b6++) { + int row = ((b6 >> 5) & 1) * 2 + (b6 & 1); + int col = (b6 >> 1) & 0xF; + int sval = SBOX[s * 64 + row * 16 + col]; /* 4-bit, 0..15 */ + + /* Accumulate pf contribution from this S-box only */ + uint32_t sp = 0; + for (i = 0; i < 32; i++) { + int sout_bit = 32 - P[i]; /* integer bit index (0=LSB) */ + int sbox_lo = 28 - s * 4; + int sbox_hi = 31 - s * 4; + if (sout_bit >= sbox_lo && sout_bit <= sbox_hi) { + int sval_bit = sout_bit - sbox_lo; /* 0..3 */ + if ((sval >> sval_bit) & 1) + sp |= (1u << (31 - i)); + } + } + sp_out[s * 64 + b6] = sp; + } + } +} + +/* + * Precompute the per-bit XOR contribution tables for the candidate key half. + * + * The 4 variable bytes (at byte positions var_offset..var_offset+3 within + * the 8-byte half-key) contribute 28 effective bits (7 each) to the 16 + * DES subkeys. Because PC1 and PC2 are linear bit selections, each input + * bit's contribution to every subkey bit is fixed and can be tabulated. + * + * For each of the 28 effective bit positions b (0..27): + * byte_in_half = b / 7 which variable byte (0..3) + * bit_in_byte = b % 7 which bit within that byte (0..6) + * actual bit in key byte = bit (bit_in_byte + 1) (parity at bit 0 is 0) + * + * We compute the key schedule for a half-key with only that one bit set, + * giving the XOR contribution of that bit to each subkey round. + * + * Outputs: + * sk_base[16] -- subkeys for candidate half with variable bytes=0 + * sk_contrib[28 * 16] -- contrib[b*16+r] = subkey[r] XOR contrib of bit b + */ +static void cpu_compute_sk_tables( + uint64_t base_half, + int var_offset, + uint64_t sk_base[16], + uint64_t sk_contrib[28 * 16]) +{ + /* Base: key schedule with variable bytes already zeroed (base_half has them 0) */ + cpu_des_keyschedule(base_half, sk_base); + + /* Per-bit contributions */ + int b, r; + for (b = 0; b < 28; b++) { + int byte_in_half = b / 7; + int bit_in_byte = b % 7; + + /* Build half-key with only this one effective bit set */ + uint8_t tmp[8]; + memset(tmp, 0, sizeof(tmp)); + tmp[var_offset + byte_in_half] = (uint8_t)(1u << (bit_in_byte + 1)); + + uint64_t bit_key = cpu_bytes_to_u64(tmp); + uint64_t sk_for_bit[16]; + cpu_des_keyschedule(bit_key, sk_for_bit); + + /* XOR contribution: because key schedule is linear over GF(2), the + * contribution of this bit equals the key schedule result for the + * half-key with only this bit set (base has variable bytes = 0, + * which means their contribution is 0 already). */ + for (r = 0; r < 16; r++) + sk_contrib[b * 16 + r] = sk_for_bit[r]; + } +} + +/* ========================================================================== */ +/* Public launch function */ +/* ========================================================================== */ + +void desbrute_launch( + uint64_t ciphertext_be, + uint64_t init_ciphertext_be, + uint64_t prev_ciphertext_be, + const uint8_t base_key[KEY_SIZE], + int key_mode, + int lfsr_type, + int is_reader_mode, + desbrute_result_t *result +) +{ + /* -- API-level validation ----------------------------------------------- */ + if (!result) + return; + + memset(result, 0, sizeof(*result)); + result->idx = UINT32_MAX; /* sentinel: no match yet */ + + if (!base_key) { return; } + if (key_mode < 0 || key_mode > 3) { return; } + if (is_reader_mode != 0 && is_reader_mode != 1) { return; } + if (!is_reader_mode && lfsr_type == LFSR_UNDEF) { return; } + + /* -- Declare all locals up-front so no goto bypasses an initialisation -- */ + cudaStream_t stream = NULL; + cudaStream_t progress_stream = NULL; + cudaEvent_t ev_start = NULL; + cudaEvent_t ev_stop = NULL; + int *d_found = NULL; + uint32_t *d_result_idx = NULL; + unsigned long long *d_progress = NULL; + int candidate_in_k1; + int cand_mode; + int var_offset; + uint64_t fixed_u64; + uint64_t base_half; + int block_size; + int min_grid; + int dev; + int dev_mp; + int grid_size; + uint64_t total_candidates; + wall_time_t qpc_start, qpc_now; + uint64_t h_fixed_sk[16]; + uint32_t h_SP[512]; + uint8_t cand_bytes[8]; + uint64_t h_cand_sk_base[16]; + uint64_t h_cand_sk_contrib[28 * 16]; + + /* -- Candidate / fixed half selection ----------------------------------- */ + candidate_in_k1 = (key_mode < 2) ? 1 : 0; + cand_mode = candidate_in_k1 ? 0 : 1; + if (candidate_in_k1) + var_offset = (key_mode % 2) * 4; + else + var_offset = ((key_mode - 2) % 2) * 4; + + /* -- Fixed-half subkeys ------------------------------------------------- */ + fixed_u64 = candidate_in_k1 + ? cpu_bytes_to_u64(base_key + 8) + : cpu_bytes_to_u64(base_key); + cpu_des_keyschedule(fixed_u64, h_fixed_sk); + + CUDA_CHECK(cudaMemcpyToSymbol(d_fixed_sk, h_fixed_sk, 16 * sizeof(uint64_t))); + + /* -- Precompute and upload SP table ------------------------------------- */ + cpu_compute_sp(h_SP); + CUDA_CHECK(cudaMemcpyToSymbol(d_SP, h_SP, 512 * sizeof(uint32_t))); + + /* -- Candidate half: zero out variable bytes ---------------------------- */ + if (candidate_in_k1) memcpy(cand_bytes, base_key, 8); + else memcpy(cand_bytes, base_key + 8, 8); + cand_bytes[var_offset] = 0; + cand_bytes[var_offset + 1] = 0; + cand_bytes[var_offset + 2] = 0; + cand_bytes[var_offset + 3] = 0; + base_half = cpu_bytes_to_u64(cand_bytes); + + /* -- Key-schedule tables (main throughput optimisation) ----------------- */ + cpu_compute_sk_tables(base_half, var_offset, h_cand_sk_base, h_cand_sk_contrib); + + CUDA_CHECK(cudaMemcpyToSymbol(d_cand_sk_base, h_cand_sk_base, + 16 * sizeof(uint64_t))); + CUDA_CHECK(cudaMemcpyToSymbol(d_cand_sk_contrib, h_cand_sk_contrib, + 28 * 16 * sizeof(uint64_t))); + + /* -- Device buffers ----------------------------------------------------- */ + CUDA_CHECK(cudaMalloc((void **)&d_found, sizeof(int))); + CUDA_CHECK(cudaMalloc((void **)&d_result_idx, sizeof(uint32_t))); + CUDA_CHECK(cudaMalloc((void **)&d_progress, sizeof(unsigned long long))); + + CUDA_CHECK(cudaMemset(d_found, 0, sizeof(int))); + CUDA_CHECK(cudaMemset(d_result_idx, 0xFF, sizeof(uint32_t))); /* UINT32_MAX */ + CUDA_CHECK(cudaMemset(d_progress, 0, sizeof(unsigned long long))); + + /* -- Launch configuration ----------------------------------------------- */ + block_size = 256; + min_grid = 0; + CUDA_CHECK(cudaOccupancyMaxPotentialBlockSize(&min_grid, &block_size, + desbrute_kernel, 0, 0)); + if (block_size > 256) block_size = 256; + + /* + * Use the CURRENT device (not hardcoded 0) so the grid is correctly sized + * when the user passes a non-zero [cuda_dev] argument. + */ + dev = 0; + dev_mp = 1; + CUDA_CHECK(cudaGetDevice(&dev)); + CUDA_CHECK(cudaDeviceGetAttribute(&dev_mp, cudaDevAttrMultiProcessorCount, dev)); + + grid_size = dev_mp * 64; + if (grid_size > 65535) grid_size = 65535; + total_candidates = 1ULL << 28; + + printf("\n[kernel] Grid: %d blocks x %d threads (64 waves/SM on dev %d)\n", + grid_size, block_size, dev); + printf("[kernel] Keyspace: 2^28 = %llu candidates\n", + (unsigned long long)total_candidates); + fflush(stdout); + + /* -- Streams and events ------------------------------------------------- + * Two streams: + * stream -- the kernel runs here + * progress_stream -- independent stream for live progress copies + * + * Because progress_stream has no dependency on the kernel stream, + * cudaMemcpyAsync on it reads d_progress while the kernel is still running. + * Atomic updates in the kernel commit to L2/DRAM so they are visible. + */ + CUDA_CHECK(cudaStreamCreate(&stream)); + CUDA_CHECK(cudaStreamCreate(&progress_stream)); + CUDA_CHECK(cudaEventCreate(&ev_start)); + CUDA_CHECK(cudaEventCreate(&ev_stop)); + + /* -- Wall-clock start --------------------------------------------------- */ + wall_time_now(&qpc_start); + + /* -- Launch ------------------------------------------------------------- */ + CUDA_CHECK(cudaEventRecord(ev_start, stream)); + + desbrute_kernel<<>>( + ciphertext_be, init_ciphertext_be, prev_ciphertext_be, + cand_mode, lfsr_type, is_reader_mode, + d_found, d_result_idx, d_progress + ); + + /* Check for launch errors immediately */ + CUDA_CHECK(cudaGetLastError()); + +#if defined(DEBUG) || defined(_DEBUG) + /* In debug builds, synchronise now to surface async execution errors close + * to the launch site rather than at a later sync point. */ + CUDA_CHECK(cudaStreamSynchronize(stream)); +#endif + + CUDA_CHECK(cudaEventRecord(ev_stop, stream)); + + /* -- Progress polling loop ---------------------------------------------- */ + printf("[search] Running\n"); + fflush(stdout); + + { + cudaError_t q; + while ((q = cudaStreamQuery(stream)) == cudaErrorNotReady) { + sleep_ms(150); + + /* Read progress via the independent progress_stream */ + unsigned long long prog = 0; + cudaMemcpyAsync(&prog, d_progress, sizeof(unsigned long long), + cudaMemcpyDeviceToHost, progress_stream); + cudaStreamSynchronize(progress_stream); + + wall_time_now(&qpc_now); + double wall_s = wall_time_seconds(&qpc_start, &qpc_now); + + double pct = (prog >= total_candidates) + ? 100.0 + : 100.0 * (double)prog / (double)total_candidates; + double kps = (wall_s > 0.001) ? (double)prog / wall_s : 0.0; + + int hf = 0; + cudaMemcpyAsync(&hf, d_found, sizeof(int), + cudaMemcpyDeviceToHost, progress_stream); + cudaStreamSynchronize(progress_stream); + + printf("\r[search] %6.2f%% | %8.2f M keys/s | %.2f s elapsed%s", + pct, kps / 1e6, wall_s, hf ? " [FOUND!]" : " "); + fflush(stdout); + } + + /* Any status other than cudaSuccess means an async error occurred */ + if (q != cudaSuccess) { + fprintf(stderr, "\n[cuda] stream error: %s\n", cudaGetErrorString(q)); + goto cleanup; + } + } + + CUDA_CHECK(cudaStreamSynchronize(stream)); + printf("\n"); + + /* -- Gather results ----------------------------------------------------- */ + wall_time_now(&qpc_now); + result->wall_ms = 1000.0 * wall_time_seconds(&qpc_start, &qpc_now); + + { + float gpu_ms = 0.0f; + CUDA_CHECK(cudaEventElapsedTime(&gpu_ms, ev_start, ev_stop)); + result->gpu_ms = gpu_ms; + + unsigned long long final_prog = 0; + CUDA_CHECK(cudaMemcpy(&final_prog, d_progress, + sizeof(unsigned long long), cudaMemcpyDeviceToHost)); + result->candidates_tested = (uint64_t)final_prog; + + if (gpu_ms > 0.0f) + result->keys_per_sec = (double)final_prog / (gpu_ms / 1000.0); + + int h_found = 0; + uint32_t h_result_idx = UINT32_MAX; + CUDA_CHECK(cudaMemcpy(&h_found, d_found, + sizeof(int), cudaMemcpyDeviceToHost)); + CUDA_CHECK(cudaMemcpy(&h_result_idx, d_result_idx, + sizeof(uint32_t), cudaMemcpyDeviceToHost)); + result->found = h_found; + result->idx = h_result_idx; + } + + /* -- Cleanup (also reached via CUDA_CHECK goto on error) ---------------- */ +cleanup: + if (ev_stop) cudaEventDestroy(ev_stop); + if (ev_start) cudaEventDestroy(ev_start); + if (progress_stream) cudaStreamDestroy(progress_stream); + if (stream) cudaStreamDestroy(stream); + if (d_progress) cudaFree(d_progress); + if (d_result_idx) cudaFree(d_result_idx); + if (d_found) cudaFree(d_found); +} diff --git a/tools/mfulc_des_brute_cuda/desbrute.h b/tools/mfulc_des_brute_cuda/desbrute.h new file mode 100644 index 000000000..b7d7e5487 --- /dev/null +++ b/tools/mfulc_des_brute_cuda/desbrute.h @@ -0,0 +1,40 @@ +/* + * desbrute.h — Shared types and GPU launch interface. + * No external dependencies beyond CUDA runtime. + */ +#pragma once +#include + +#define BLOCK_SIZE 8 +#define KEY_SIZE 16 + +#define LFSR_UNDEF 0 +#define LFSR_ULCG 1 +#define LFSR_MFC 2 + +/* Metrics returned by desbrute_launch */ +typedef struct { + int found; /* 1 if a key was found */ + uint32_t idx; /* winning candidate index (if found) */ + double wall_ms; /* wall-clock time in milliseconds */ + float gpu_ms; /* GPU kernel time (CUDA events) */ + uint64_t candidates_tested; /* total candidates processed before exit */ + double keys_per_sec; /* throughput: candidates / gpu_sec */ +} desbrute_result_t; + +/* + * desbrute_launch — brute-force 2^28 candidate key indices on the GPU. + * + * All uint64_t block values are big-endian packed (byte 0 in bits 63-56). + * The caller must have already called cudaSetDevice() if needed. + */ +void desbrute_launch( + uint64_t ciphertext_be, + uint64_t init_ciphertext_be, + uint64_t prev_ciphertext_be, + const uint8_t base_key[KEY_SIZE], + int key_mode, + int lfsr_type, + int is_reader_mode, + desbrute_result_t *result +); diff --git a/tools/mfulc_des_brute_cuda/main.cu b/tools/mfulc_des_brute_cuda/main.cu new file mode 100644 index 000000000..eaaa3845b --- /dev/null +++ b/tools/mfulc_des_brute_cuda/main.cu @@ -0,0 +1,332 @@ +/* + * main.cu - CUDA-accelerated 2TDEA key recovery. + * Written by C2Pwn + * + * Usage + * ----- + * Counterfeit mode (-c): + * desbrute -c [device] + * + * Reader nonce mode (-r): + * desbrute -r [device] + * + * [device] is optional. When omitted the best available GPU is chosen + * automatically (highest SM count). Pass an integer to force a specific + * CUDA device index. + */ + +#include +#include +#include +#include +#ifdef _WIN32 +#include +#endif +#include + +#include "des_host.h" +#include "desbrute.h" + +/* ========================================================================== */ +/* Helpers */ +/* ========================================================================== */ + +static int hex_to_bytes(const char *hex, uint8_t *buf, size_t len) +{ + size_t i; + if (strlen(hex) != len * 2) return 0; + for (i = 0; i < len; i++) { + unsigned int byte; + if (sscanf(hex + 2 * i, "%2x", &byte) != 1) return 0; + buf[i] = (uint8_t)byte; + } + return 1; +} + +static void print_hex(const uint8_t *buf, size_t len) +{ + size_t i; + for (i = 0; i < len; i++) printf("%02X", buf[i]); +} + +static void print_separator(void) +{ + printf("---------------------------------------------------------------\n"); +} + +static void print_usage(const char *name) +{ + fprintf(stderr, + "\nUsage:\n" + " Counterfeit: %s -c " + " [device]\n" + " Reader nonce: %s -r " + " [device]\n" + "\n" + " seg : 1-4 (which 4-byte block of the 16-byte key to brute-force)\n" + " device : optional CUDA device index (default: auto-select best GPU)\n" + "\n", + name, name); + exit(1); +} + +/* ========================================================================== */ +/* Auto device selection */ +/* ========================================================================== */ + +/* + * Pick the CUDA device with the most streaming multiprocessors. + * On a single-GPU system this always returns 0. + * On multi-GPU systems it chooses the most powerful card. + * Prints a one-line summary of all available devices. + */ +static int pick_best_device(void) +{ + int count = 0; + if (cudaGetDeviceCount(&count) != cudaSuccess || count == 0) { + fprintf(stderr, "[cuda] No CUDA devices found.\n"); + exit(1); + } + + int best_dev = 0, best_mp = 0; + int d; + for (d = 0; d < count; d++) { + struct cudaDeviceProp p; + if (cudaGetDeviceProperties(&p, d) != cudaSuccess) continue; + printf(" [dev %d] %s SM %d.%d %d MPs\n", + d, p.name, p.major, p.minor, p.multiProcessorCount); + if (p.multiProcessorCount > best_mp) { + best_mp = p.multiProcessorCount; + best_dev = d; + } + } + return best_dev; +} + +/* ========================================================================== */ +/* GPU info banner */ +/* ========================================================================== */ + +static void print_gpu_info(int dev) +{ + struct cudaDeviceProp p; + if (cudaGetDeviceProperties(&p, dev) != cudaSuccess) return; + + double bw_gbps = 2.0 * p.memoryClockRate * 1e3 + * p.memoryBusWidth / 8.0 / 1e9; + + /* Approximate CUDA core count — varies by architecture */ + int cores_per_mp = + (p.major == 9) ? 128 : + (p.major == 8 && p.minor == 9) ? 128 : + (p.major == 8 && p.minor == 6) ? 128 : + (p.major == 8 && p.minor == 0) ? 64 : + (p.major == 7 && p.minor == 5) ? 64 : + (p.major == 7) ? 64 : + (p.major == 6 && p.minor == 1) ? 128 : + (p.major == 6 && p.minor == 0) ? 64 : + (p.major == 5) ? 128 : 64; + + print_separator(); + printf(" GPU : %s [device %d]\n", p.name, dev); + printf(" SM : %d.%d | MPs: %d | CUDA cores: ~%d\n", + p.major, p.minor, p.multiProcessorCount, + p.multiProcessorCount * cores_per_mp); + printf(" Clock: %d MHz (mem: %d MHz, bus: %d-bit)\n", + p.clockRate / 1000, p.memoryClockRate / 1000, p.memoryBusWidth); + printf(" VRAM : %.0f MB | Peak BW: %.0f GB/s\n", + (double)p.totalGlobalMem / (1024.0 * 1024.0), bw_gbps); + printf(" L2 : %d KB | Warp size: %d\n", + p.l2CacheSize / 1024, p.warpSize); + print_separator(); +} + +/* ========================================================================== */ +/* main */ +/* ========================================================================== */ + +int main(int argc, char **argv) +{ + int is_reader_mode, seg, key_mode, cuda_dev, lfsr_type; + uint8_t init_ciphertext[BLOCK_SIZE]; + uint8_t tmp_blocks[2 * BLOCK_SIZE]; + uint8_t ciphertext[BLOCK_SIZE]; + uint8_t prev_ciphertext[BLOCK_SIZE]; + uint8_t base_key[KEY_SIZE]; + desbrute_result_t result; + + /* --- Argument parsing ------------------------------------------------- */ + if (argc < 2) print_usage(argv[0]); + + if (strcmp(argv[1], "-c") == 0) { + is_reader_mode = 0; + if (argc < 6 || argc > 7) { + fprintf(stderr, "Error: -c requires exactly 4 arguments" + " plus an optional device index.\n"); + print_usage(argv[0]); + } + } else if (strcmp(argv[1], "-r") == 0) { + is_reader_mode = 1; + if (argc < 6 || argc > 7) { + fprintf(stderr, "Error: -r requires exactly 4 arguments" + " plus an optional device index.\n"); + print_usage(argv[0]); + } + } else { + fprintf(stderr, "Error: first argument must be -c or -r\n"); + print_usage(argv[0]); + } + + /* --- Parse fixed positional args ------------------------------------- */ + if (is_reader_mode) { + if (!hex_to_bytes(argv[2], init_ciphertext, BLOCK_SIZE)) { + fprintf(stderr, "Error: ERndB must be exactly 16 hex chars (8 bytes)\n"); + return 1; + } + if (!hex_to_bytes(argv[3], tmp_blocks, 2 * BLOCK_SIZE)) { + fprintf(stderr, "Error: ERndA||RndB' must be exactly 32 hex chars (16 bytes)\n"); + return 1; + } + memcpy(prev_ciphertext, tmp_blocks, BLOCK_SIZE); + memcpy(ciphertext, tmp_blocks + BLOCK_SIZE, BLOCK_SIZE); + } else { + if (!hex_to_bytes(argv[2], init_ciphertext, BLOCK_SIZE)) { + fprintf(stderr, "Error: null-key ERndB must be exactly 16 hex chars (8 bytes)\n"); + return 1; + } + if (!hex_to_bytes(argv[3], ciphertext, BLOCK_SIZE)) { + fprintf(stderr, "Error: target ERndB must be exactly 16 hex chars (8 bytes)\n"); + return 1; + } + memset(prev_ciphertext, 0, BLOCK_SIZE); + } + + if (!hex_to_bytes(argv[4], base_key, KEY_SIZE)) { + fprintf(stderr, "Error: base key must be exactly 32 hex chars (16 bytes)\n"); + return 1; + } + + seg = atoi(argv[5]); + if (seg < 1 || seg > 4) { + fprintf(stderr, "Error: segment must be 1, 2, 3, or 4\n"); + return 1; + } + key_mode = seg - 1; + + /* --- CUDA device selection -------------------------------------------- */ + print_separator(); + printf(" DESBRUTE - CUDA 2TDEA key recovery engine\n"); + print_separator(); + + if (argc == 7) { + /* Explicit device requested */ + cuda_dev = atoi(argv[6]); + int count = 0; + cudaGetDeviceCount(&count); + if (cuda_dev < 0 || cuda_dev >= count) { + fprintf(stderr, + "[cuda] Device %d does not exist (%d device(s) available).\n" + " Re-run without the [device] argument to auto-select.\n", + cuda_dev, count); + return 1; + } + printf(" Device: %d (user-specified)\n", cuda_dev); + } else { + /* Auto-select best device */ + printf(" Auto-selecting best CUDA device...\n"); + cuda_dev = pick_best_device(); + printf(" Selected: device %d\n", cuda_dev); + } + + if (cudaSetDevice(cuda_dev) != cudaSuccess) { + fprintf(stderr, "[cuda] Failed to set device %d\n", cuda_dev); + return 1; + } + + /* --- LFSR detection (counterfeit mode only, CPU) ---------------------- */ + lfsr_type = LFSR_UNDEF; + if (!is_reader_mode) { + lfsr_type = h_detect_lfsr(init_ciphertext); + switch (lfsr_type) { + case LFSR_ULCG: + printf("[lfsr] Detected: ULCG\n"); break; + case LFSR_MFC: + printf("[lfsr] Detected: MFC (USCUID-UL / FJ8010)\n"); break; + default: + fprintf(stderr, "[lfsr] ERROR: unrecognised LFSR - cannot proceed\n"); + return 1; + } + } + + /* --- Banner ----------------------------------------------------------- */ + print_gpu_info(cuda_dev); + printf(" Mode : %s\n", is_reader_mode ? "Reader nonce (-r)" : "Counterfeit (-c)"); + printf(" Segment : %d (key_mode %d, bytes %d-%d of full key)\n", + seg, key_mode, key_mode * 4, key_mode * 4 + 3); + printf(" Base key : "); print_hex(base_key, KEY_SIZE); printf("\n"); + printf(" Ciphertext : "); print_hex(ciphertext, BLOCK_SIZE); printf("\n"); + printf(" Init CT : "); print_hex(init_ciphertext, BLOCK_SIZE); printf("\n"); + if (is_reader_mode) { + printf(" Prev CT : "); print_hex(prev_ciphertext, BLOCK_SIZE); printf("\n"); + } + print_separator(); + fflush(stdout); + + /* --- Launch GPU search ------------------------------------------------ */ + uint64_t ct_be = bytes_to_u64(ciphertext); + uint64_t init_be = bytes_to_u64(init_ciphertext); + uint64_t prev_be = bytes_to_u64(prev_ciphertext); + + desbrute_launch(ct_be, init_be, prev_be, + base_key, key_mode, lfsr_type, is_reader_mode, + &result); + + /* --- Metrics ---------------------------------------------------------- */ + print_separator(); + printf(" PERFORMANCE METRICS\n"); + print_separator(); + printf(" GPU kernel time : %.3f ms\n", result.gpu_ms); + printf(" Wall-clock time : %.3f ms\n", result.wall_ms); + printf(" Candidates : %llu / %llu\n", + (unsigned long long)result.candidates_tested, + (unsigned long long)(1ULL << 28)); + printf(" Throughput : %.2f M keys/s\n", result.keys_per_sec / 1e6); + { + double overhead_pct = (result.wall_ms > 0) + ? 100.0 * (result.wall_ms - result.gpu_ms) / result.wall_ms + : 0.0; + printf(" Host overhead : %.1f%%\n", overhead_pct); + } + print_separator(); + + /* --- Result ----------------------------------------------------------- */ + if (!result.found) { + printf(" RESULT: No matching key found.\n"); + print_separator(); + return 1; + } + + /* Reconstruct full key from winning index */ + uint8_t b0 = (uint8_t)(( result.idx & 0x7Fu) << 1); + uint8_t b1 = (uint8_t)(((result.idx >> 7) & 0x7Fu) << 1); + uint8_t b2 = (uint8_t)(((result.idx >> 14) & 0x7Fu) << 1); + uint8_t b3 = (uint8_t)(((result.idx >> 21) & 0x7Fu) << 1); + + uint8_t full_key[KEY_SIZE]; + memcpy(full_key, base_key, KEY_SIZE); + { + int seg_offset = key_mode * 4; + full_key[seg_offset] = b0; + full_key[seg_offset + 1] = b1; + full_key[seg_offset + 2] = b2; + full_key[seg_offset + 3] = b3; + } + + printf(" RESULT: KEY FOUND\n"); + printf(" Index : %u (0x%08X)\n", result.idx, result.idx); + printf(" Full key: "); print_hex(full_key, KEY_SIZE); printf("\n"); + print_separator(); + + cudaDeviceReset(); + return 0; +}