From: Oleg Moiseenko <807634+merlokk@users.noreply.github.com> Date: Fri, 26 Oct 2018 17:18:53 +0000 (+0300) Subject: Mfp read plain (#704) X-Git-Url: https://git.zerfleddert.de/cgi-bin/gitweb.cgi/proxmark3-svn/commitdiff_plain/c8a0f5503172f25620670a9ba992d8c923b5df95?ds=inline Mfp read plain (#704) * added aes-cmac-128 * aes-cmac added to cryptosystem. not works( --- diff --git a/client/Makefile b/client/Makefile index 72d5080d..1b211d4f 100644 --- a/client/Makefile +++ b/client/Makefile @@ -107,6 +107,7 @@ CMDSRCS = $(SRC_SMARTCARD) \ crapto1/crypto1.c\ polarssl/des.c \ polarssl/aes.c\ + polarssl/aes_cmac128.c\ polarssl/bignum.c\ polarssl/rsa.c\ polarssl/sha1.c\ diff --git a/client/cliparser/cliparser.h b/client/cliparser/cliparser.h index c4bc7068..05910ea4 100644 --- a/client/cliparser/cliparser.h +++ b/client/cliparser/cliparser.h @@ -19,6 +19,7 @@ #define arg_get_lit(n)(((struct arg_lit*)argtable[n])->count) #define arg_get_int_count(n)(((struct arg_int*)argtable[n])->count) #define arg_get_int(n)(((struct arg_int*)argtable[n])->ival[0]) +#define arg_get_int_def(n,def)(arg_get_int_count(n)?(arg_get_int(n)):(def)) #define arg_get_str(n)((struct arg_str*)argtable[n]) #define arg_get_str_len(n)(strlen(((struct arg_str*)argtable[n])->sval[0])) diff --git a/client/cmdhfmfp.c b/client/cmdhfmfp.c index a4c53f56..c5fd8eed 100644 --- a/client/cmdhfmfp.c +++ b/client/cmdhfmfp.c @@ -35,6 +35,9 @@ typedef struct { static const PlusErrorsElm PlusErrors[] = { {0xFF, ""}, {0x00, "Unknown error"}, + {0x06, "Block use error"}, + {0x07, "Command use error"}, + {0x08, "Invalid write command"}, {0x09, "Invalid block number"}, {0x0b, "Command code error"}, {0x0c, "Length error"}, @@ -82,6 +85,37 @@ int MFPCommitPerso(bool activateField, bool leaveSignalON, uint8_t *dataout, int return intExchangeRAW14aPlus(rcmd, sizeof(rcmd), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen); } +int MFPReadBlock(mf4Session *session, bool plain, uint8_t blockNum, uint8_t blockCount, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac) { + uint8_t rcmd[4 + 8] = {(plain?(0x37):(0x33)), blockNum, 0x00, blockCount}; + if (!plain && session) + CalculateMAC(session, rcmd, 4, &rcmd[4], VerboseMode); + + int res = intExchangeRAW14aPlus(rcmd, plain?4:sizeof(rcmd), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen); + if(res) + return res; + + if(session && mac) + CalculateMAC(session, dataout, *dataoutlen, mac, VerboseMode); + + return 0; +} + +int MFPWriteBlock(mf4Session *session, uint8_t blockNum, uint8_t *data, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac) { + uint8_t rcmd[1 + 2 + 16 + 8] = {0xA3, blockNum, 0x00}; + memmove(&rcmd[3], data, 16); + if (session) + CalculateMAC(session, rcmd, 19, &rcmd[19], VerboseMode); + + int res = intExchangeRAW14aPlus(rcmd, sizeof(rcmd), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen); + if(res) + return res; + + if(session && mac) + CalculateMAC(session, dataout, *dataoutlen, mac, VerboseMode); + + return 0; +} + int CmdHFMFPInfo(const char *cmd) { if (cmd && strlen(cmd) > 0) @@ -349,7 +383,7 @@ int CmdHFMFPAuth(const char *cmd) { int keylen = 0; CLIParserInit("hf mfp auth", - "Executes AES authentication command in ISO14443-4", + "Executes AES authentication command for Mifare Plus card", "Usage:\n\thf mfp auth 4000 000102030405060708090a0b0c0d0e0f -> executes authentication\n" "\thf mfp auth 9003 FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF -v -> executes authentication and shows all the system data\n"); @@ -381,20 +415,307 @@ int CmdHFMFPAuth(const char *cmd) { } int CmdHFMFPRdbl(const char *cmd) { - //mf4Session session - //int res = MifareAuth4(&session, keyn, key, true, false, verbose); - //res = Read(); + uint8_t keyn[2] = {0}; + uint8_t key[250] = {0}; + int keylen = 0; + + CLIParserInit("hf mfp rdbl", + "Reads several blocks from Mifare Plus card in plain mode.", + "Usage:\n\thf mfp rdbl 0 000102030405060708090a0b0c0d0e0f -> executes authentication and read block 0 data\n" + "\thf mfp rdbl 1 -v -> executes authentication and shows sector 1 data with default key 0xFF..0xFF and some additional data\n"); + + void* argtable[] = { + arg_param_begin, + arg_lit0("vV", "verbose", "show internal data."), + arg_int0("nN", "count", "blocks count (by default 1).", NULL), + arg_lit0("bB", "keyb", "use key B (by default keyA)."), + arg_lit0("pP", "plain", "plain communication between reader and card."), + arg_int1(NULL, NULL, "", NULL), + arg_str0(NULL, NULL, "", NULL), + arg_param_end + }; + CLIExecWithReturn(cmd, argtable, false); + + bool verbose = arg_get_lit(1); + int blocksCount = arg_get_int_def(2, 1); + bool keyB = arg_get_lit(3); + int plain = arg_get_lit(4) | true; + uint32_t blockn = arg_get_int(5); + CLIGetHexWithReturn(6, key, &keylen); + CLIParserFree(); + + SetVerboseMode(verbose); + + if (!keylen) { + memmove(key, DefaultKey, 16); + keylen = 16; + } + + if (blockn > 255) { + PrintAndLog("ERROR: must be in range [0..255] instead of: %d", blockn); + return 1; + } + + if (keylen != 16) { + PrintAndLog("ERROR: must be 16 bytes long instead of: %d", keylen); + return 1; + } + + // 3 blocks - wo iso14443-4 chaining + if (blocksCount > 3) { + PrintAndLog("ERROR: blocks count must be less than 3 instead of: %d", blocksCount); + return 1; + } + + uint8_t sectorNum = mfSectorNum(blockn & 0xff); + uint16_t uKeyNum = 0x4000 + sectorNum * 2 + (keyB ? 1 : 0); + keyn[0] = uKeyNum >> 8; + keyn[1] = uKeyNum & 0xff; + if (verbose) + PrintAndLog("--block:%d sector[%d]:%02x key:%04x", blockn, mfNumBlocksPerSector(sectorNum), sectorNum, uKeyNum); + + mf4Session session; + int res = MifareAuth4(&session, keyn, key, true, true, verbose); + if (res) { + PrintAndLog("Authentication error: %d", res); + return res; + } + + uint8_t data[250] = {0}; + int datalen = 0; + uint8_t mac[8] = {0}; + res = MFPReadBlock(&session, plain, blockn & 0xff, blocksCount, false, false, data, sizeof(data), &datalen, mac); + if (res) { + PrintAndLog("Read error: %d", res); + return res; + } + + if (datalen && data[0] != 0x90) { + PrintAndLog("Card read error: %02x %s", data[0], GetErrorDescription(data[0])); + return 6; + } + + if (datalen != 1 + blocksCount * 16 + 8 + 2) { + PrintAndLog("Error return length:%d", datalen); + return 5; + } + + int indx = blockn; + for(int i = 0; i < blocksCount; i++) { + PrintAndLog("data[%03d]: %s", indx, sprint_hex(&data[1 + i * 16], 16)); + indx++; + if (mfIsSectorTrailer(indx)){ + PrintAndLog("data[%03d]: ------------------- trailer -------------------", indx); + indx++; + } + } + + if (!memcmp(&data[blocksCount * 16 + 1], mac, 8)) { + PrintAndLog("WARNING: mac not equal..."); + PrintAndLog("MAC card: %s", sprint_hex(&data[blocksCount * 16 + 1], 8)); + PrintAndLog("MAC reader: %s", sprint_hex(mac, 8)); + } else { + if(verbose) + PrintAndLog("MAC: %s", sprint_hex(&data[blocksCount * 16 + 1], 8)); + } return 0; } int CmdHFMFPRdsc(const char *cmd) { + uint8_t keyn[2] = {0}; + uint8_t key[250] = {0}; + int keylen = 0; + + CLIParserInit("hf mfp rdsc", + "Reads one sector from Mifare Plus card in plain mode.", + "Usage:\n\thf mfp rdsc 0 000102030405060708090a0b0c0d0e0f -> executes authentication and read sector 0 data\n" + "\thf mfp rdsc 1 -v -> executes authentication and shows sector 1 data with default key 0xFF..0xFF and some additional data\n"); + + void* argtable[] = { + arg_param_begin, + arg_lit0("vV", "verbose", "show internal data."), + arg_lit0("bB", "keyb", "use key B (by default keyA)."), + arg_lit0("pP", "plain", "plain communication between reader and card."), + arg_int1(NULL, NULL, "", NULL), + arg_str0(NULL, NULL, "", NULL), + arg_param_end + }; + CLIExecWithReturn(cmd, argtable, false); + + bool verbose = arg_get_lit(1); + bool keyB = arg_get_lit(2); + bool plain = arg_get_lit(3) | true; + uint32_t sectorNum = arg_get_int(4); + CLIGetHexWithReturn(5, key, &keylen); + CLIParserFree(); + + SetVerboseMode(verbose); + + if (!keylen) { + memmove(key, DefaultKey, 16); + keylen = 16; + } + + if (sectorNum > 39) { + PrintAndLog("ERROR: must be in range [0..39] instead of: %d", sectorNum); + return 1; + } + + if (keylen != 16) { + PrintAndLog("ERROR: must be 16 bytes long instead of: %d", keylen); + return 1; + } + + uint16_t uKeyNum = 0x4000 + sectorNum * 2 + (keyB ? 1 : 0); + keyn[0] = uKeyNum >> 8; + keyn[1] = uKeyNum & 0xff; + if (verbose) + PrintAndLog("--sector[%d]:%02x key:%04x", mfNumBlocksPerSector(sectorNum), sectorNum, uKeyNum); + + mf4Session session; + int res = MifareAuth4(&session, keyn, key, true, true, verbose); + if (res) { + PrintAndLog("Authentication error: %d", res); + return res; + } + + uint8_t data[250] = {0}; + int datalen = 0; + uint8_t mac[8] = {0}; + for(int n = mfFirstBlockOfSector(sectorNum); n < mfFirstBlockOfSector(sectorNum) + mfNumBlocksPerSector(sectorNum); n++) { + res = MFPReadBlock(&session, plain, n & 0xff, 1, false, true, data, sizeof(data), &datalen, mac); + if (res) { + PrintAndLog("Read error: %d", res); + DropField(); + return res; + } + + if (datalen && data[0] != 0x90) { + PrintAndLog("Card read error: %02x %s", data[0], GetErrorDescription(data[0])); + DropField(); + return 6; + } + if (datalen != 1 + 16 + 8 + 2) { + PrintAndLog("Error return length:%d", datalen); + DropField(); + return 5; + } + + PrintAndLog("data[%03d]: %s", n, sprint_hex(&data[1], 16)); + + if (!memcmp(&data[1 + 16], mac, 8)) { + PrintAndLog("WARNING: mac on block %d not equal...", n); + PrintAndLog("MAC card: %s", sprint_hex(&data[1 + 16], 8)); + PrintAndLog("MAC reader: %s", sprint_hex(mac, 8)); + } else { + if(verbose) + PrintAndLog("MAC: %s", sprint_hex(&data[1 + 16], 8)); + } + } + DropField(); return 0; } int CmdHFMFPWrbl(const char *cmd) { + uint8_t keyn[2] = {0}; + uint8_t key[250] = {0}; + int keylen = 0; + uint8_t datain[250] = {0}; + int datainlen = 0; + + CLIParserInit("hf mfp wrbl", + "Writes one block to Mifare Plus card.", + "Usage:\n\thf mfp wrbl 1 ff0000000000000000000000000000ff 000102030405060708090a0b0c0d0e0f -> writes block 1 data\n" + "\thf mfp wrbl 2 ff0000000000000000000000000000ff -v -> writes block 2 data with default key 0xFF..0xFF and some additional data\n"); + + void* argtable[] = { + arg_param_begin, + arg_lit0("vV", "verbose", "show internal data."), + arg_lit0("bB", "keyb", "use key B (by default keyA)."), + arg_int1(NULL, NULL, "", NULL), + arg_str1(NULL, NULL, "", NULL), + arg_str0(NULL, NULL, "", NULL), + arg_param_end + }; + CLIExecWithReturn(cmd, argtable, false); + + bool verbose = arg_get_lit(1); + bool keyB = arg_get_lit(2); + uint32_t blockNum = arg_get_int(3); + CLIGetHexWithReturn(4, datain, &datainlen); + CLIGetHexWithReturn(5, key, &keylen); + CLIParserFree(); + + SetVerboseMode(verbose); + + if (!keylen) { + memmove(key, DefaultKey, 16); + keylen = 16; + } + + if (blockNum > 39) { + PrintAndLog("ERROR: must be in range [0..255] instead of: %d", blockNum); + return 1; + } + + if (keylen != 16) { + PrintAndLog("ERROR: must be 16 bytes long instead of: %d", keylen); + return 1; + } + + if (datainlen != 16) { + PrintAndLog("ERROR: must be 16 bytes long instead of: %d", datainlen); + return 1; + } + uint8_t sectorNum = mfSectorNum(blockNum & 0xff); + uint16_t uKeyNum = 0x4000 + sectorNum * 2 + (keyB ? 1 : 0); + keyn[0] = uKeyNum >> 8; + keyn[1] = uKeyNum & 0xff; + if (verbose) + PrintAndLog("--block:%d sector[%d]:%02x key:%04x", blockNum & 0xff, mfNumBlocksPerSector(sectorNum), sectorNum, uKeyNum); + + mf4Session session; + int res = MifareAuth4(&session, keyn, key, true, true, verbose); + if (res) { + PrintAndLog("Authentication error: %d", res); + return res; + } + + uint8_t data[250] = {0}; + int datalen = 0; + uint8_t mac[8] = {0}; + res = MFPWriteBlock(&session, blockNum & 0xff, datain, false, false, data, sizeof(data), &datalen, mac); + if (res) { + PrintAndLog("Write error: %d", res); + DropField(); + return res; + } + + if (datalen != 3 && (datalen != 3 + 8)) { + PrintAndLog("Error return length:%d", datalen); + DropField(); + return 5; + } + + if (datalen && data[0] != 0x90) { + PrintAndLog("Card write error: %02x %s", data[0], GetErrorDescription(data[0])); + DropField(); + return 6; + } + + if (!memcmp(&data[1], mac, 8)) { + PrintAndLog("WARNING: mac not equal..."); + PrintAndLog("MAC card: %s", sprint_hex(&data[1], 8)); + PrintAndLog("MAC reader: %s", sprint_hex(mac, 8)); + } else { + if(verbose) + PrintAndLog("MAC: %s", sprint_hex(&data[1], 8)); + } + + DropField(); return 0; } @@ -405,9 +726,9 @@ static command_t CommandTable[] = {"wrp", CmdHFMFPWritePerso, 0, "Write Perso command"}, {"initp", CmdHFMFPInitPerso, 0, "Fills all the card's keys"}, {"commitp", CmdHFMFPCommitPerso, 0, "Move card to SL1 or SL3 mode"}, - {"auth", CmdHFMFPAuth, 0, "Authentication in iso1443-4"}, -// {"rdbl", CmdHFMFPRdbl, 0, "Read blocks"}, -// {"rdsc", CmdHFMFPRdsc, 0, "Read sectors"}, + {"auth", CmdHFMFPAuth, 0, "Authentication"}, + {"rdbl", CmdHFMFPRdbl, 0, "Read blocks"}, + {"rdsc", CmdHFMFPRdsc, 0, "Read sectors"}, // {"wrbl", CmdHFMFPWrbl, 0, "Write blocks"}, {NULL, NULL, 0, NULL} }; diff --git a/client/emv/test/cryptotest.c b/client/emv/test/cryptotest.c index a6d06e68..b778d256 100644 --- a/client/emv/test/cryptotest.c +++ b/client/emv/test/cryptotest.c @@ -14,6 +14,7 @@ #include "bignum.h" #include "aes.h" +#include "aes_cmac128.h" #include "des.h" #include "rsa.h" #include "sha1.h" @@ -32,7 +33,10 @@ int ExecuteCryptoTests(bool verbose) { res = aes_self_test(verbose); if (res) TestFail = true; - + + res = aes_cmac_self_test(verbose); + if (res) TestFail = true; + res = des_self_test(verbose); if (res) TestFail = true; diff --git a/client/mifare4.c b/client/mifare4.c index 3489c857..e1021196 100644 --- a/client/mifare4.c +++ b/client/mifare4.c @@ -16,6 +16,18 @@ #include "ui.h" #include "polarssl/libpcrypto.h" +int CalculateMAC(mf4Session *session, uint8_t *data, int datalen, uint8_t *mac, bool verbose) { + if (!session || !session->Authenticated || !mac || !data || !datalen) + return 1; + + memset(mac, 0x00, 8); + + if (verbose) + PrintAndLog("MAC data[%d]: %s", datalen, sprint_hex(data, datalen)); + + return aes_cmac8(NULL, session->Key, data, mac, datalen); +} + int MifareAuth4(mf4Session *session, uint8_t *keyn, uint8_t *key, bool activateField, bool leaveSignalON, bool verbose) { uint8_t data[257] = {0}; int datalen = 0; @@ -71,7 +83,7 @@ int MifareAuth4(mf4Session *session, uint8_t *keyn, uint8_t *key, bool activateF if (verbose) PrintAndLog(">phase2: %s", sprint_hex(cmd2, 33)); - res = ExchangeRAW14a(cmd2, sizeof(cmd2), false, false, data, sizeof(data), &datalen); + res = ExchangeRAW14a(cmd2, sizeof(cmd2), false, true, data, sizeof(data), &datalen); if (res) { PrintAndLog("ERROR exchande raw error: %d", res); DropField(); @@ -109,6 +121,7 @@ int MifareAuth4(mf4Session *session, uint8_t *keyn, uint8_t *key, bool activateF session->KeyNum = keyn[1] + (keyn[0] << 8); memmove(session->Rnd1, Rnd1, 16); memmove(session->Rnd2, Rnd2, 16); + memmove(session->Key, key, 16); } PrintAndLog("Authentication OK"); @@ -116,3 +129,38 @@ int MifareAuth4(mf4Session *session, uint8_t *keyn, uint8_t *key, bool activateF return 0; } +// Mifare Memory Structure: up to 32 Sectors with 4 blocks each (1k and 2k cards), +// plus evtl. 8 sectors with 16 blocks each (4k cards) +uint8_t mfNumBlocksPerSector(uint8_t sectorNo) { + if (sectorNo < 32) + return 4; + else + return 16; +} + +uint8_t mfFirstBlockOfSector(uint8_t sectorNo) { + if (sectorNo < 32) + return sectorNo * 4; + else + return 32 * 4 + (sectorNo - 32) * 16; +} + +uint8_t mfSectorTrailer(uint8_t blockNo) { + if (blockNo < 32*4) { + return (blockNo | 0x03); + } else { + return (blockNo | 0x0f); + } +} + +bool mfIsSectorTrailer(uint8_t blockNo) { + return (blockNo == mfSectorTrailer(blockNo)); +} + +uint8_t mfSectorNum(uint8_t blockNo) { + if (blockNo < 32 * 4) + return blockNo / 4; + else + return 32 + (blockNo - 32 * 4) / 16; + +} diff --git a/client/mifare4.h b/client/mifare4.h index 70711847..5b789a70 100644 --- a/client/mifare4.h +++ b/client/mifare4.h @@ -17,14 +17,21 @@ typedef struct { bool Authenticated; + uint8_t Key[16]; uint16_t KeyNum; uint8_t Rnd1[16]; uint8_t Rnd2[16]; }mf4Session; +extern int CalculateMAC(mf4Session *session, uint8_t *data, int datalen, uint8_t *mac, bool verbose); extern int MifareAuth4(mf4Session *session, uint8_t *keyn, uint8_t *key, bool activateField, bool leaveSignalON, bool verbose); +extern uint8_t mfNumBlocksPerSector(uint8_t sectorNo); +extern uint8_t mfFirstBlockOfSector(uint8_t sectorNo); +extern uint8_t mfSectorTrailer(uint8_t blockNo); +extern bool mfIsSectorTrailer(uint8_t blockNo); +extern uint8_t mfSectorNum(uint8_t blockNo); #endif // mifare4.h diff --git a/common/polarssl/aes_cmac128.c b/common/polarssl/aes_cmac128.c new file mode 100644 index 00000000..595f89b8 --- /dev/null +++ b/common/polarssl/aes_cmac128.c @@ -0,0 +1,322 @@ +/* + * AES-CMAC from NIST Special Publication 800-38B — Recommendation for block cipher modes of operation: The CMAC mode for authentication. + * + * Copyright (C) 2006-2014, Brainspark B.V. + * Copyright (C) 2014, Anargyros Plemenos + * Tests added Merkok, 2018 + * + * This file is part of PolarSSL (http://www.polarssl.org) + * Lead Maintainer: Paul Bakker + * + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Reference : https://polarssl.org/discussions/generic/authentication-token + * NIST Special Publication 800-38B — Recommendation for block cipher modes of operation: The CMAC mode for authentication. + * Tests here: + * https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Standards-and-Guidelines/documents/examples/AES_CMAC.pdf +*/ + +#include "polarssl/aes_cmac128.h" +#include + +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define _MSB(x) (((x)[0] & 0x80)?1:0) + +#if !defined(POLARSSL_CONFIG_FILE) +#include "polarssl_config.h" +#else +#include POLARSSL_CONFIG_FILE +#endif + +#if defined(POLARSSL_AES_C) +#include "aes.h" +#endif + +#if defined(POLARSSL_PLATFORM_C) +#include "polarssl/platform.h" +#else +#define polarssl_printf printf +#endif + + +/** + * zero a structure + */ +#define ZERO_STRUCT(x) memset((char *)&(x), 0, sizeof(x)) + +/** + * zero a structure given a pointer to the structure + */ +#define ZERO_STRUCTP(x) do{ if((x) != NULL) memset((char *)(x), 0, sizeof(*(x)));} while(0) + + +/* For CMAC Calculation */ +static unsigned char const_Rb[16] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87 +}; +static unsigned char const_Zero[16] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +}; + +static inline void aes_cmac_128_left_shift_1(const uint8_t in[16], uint8_t out[16]) +{ + uint8_t overflow = 0; + int8_t i; + + for (i = 15; i >= 0; i--) { + out[i] = in[i] << 1; + out[i] |= overflow; + overflow = _MSB(&in[i]); + } +} + +static inline void aes_cmac_128_xor(const uint8_t in1[16], const uint8_t in2[16], + uint8_t out[16]) +{ + uint8_t i; + + for (i = 0; i < 16; i++) { + out[i] = in1[i] ^ in2[i]; + } +} + +/* + * AES-CMAC-128 context setup + */ +void aes_cmac128_starts(aes_cmac128_context *ctx, const uint8_t K[16]) +{ + uint8_t L[16]; + + /* Zero struct of aes_context */ + ZERO_STRUCTP(ctx); + /* Initialize aes_context */ + aes_setkey_enc(&ctx->aes_key, K, 128); + + /* step 1 - generate subkeys k1 and k2 */ + aes_crypt_ecb(&ctx->aes_key, AES_ENCRYPT, const_Zero, L); + + if (_MSB(L) == 0) { + aes_cmac_128_left_shift_1(L, ctx->K1); + } else { + uint8_t tmp_block[16]; + + aes_cmac_128_left_shift_1(L, tmp_block); + aes_cmac_128_xor(tmp_block, const_Rb, ctx->K1); + ZERO_STRUCT(tmp_block); + } + + if (_MSB(ctx->K1) == 0) { + aes_cmac_128_left_shift_1(ctx->K1, ctx->K2); + } else { + uint8_t tmp_block[16]; + + aes_cmac_128_left_shift_1(ctx->K1, tmp_block); + aes_cmac_128_xor(tmp_block, const_Rb, ctx->K2); + ZERO_STRUCT(tmp_block); + } + + ZERO_STRUCT(L); +} + +/* + * AES-CMAC-128 process message + */ +void aes_cmac128_update(aes_cmac128_context *ctx, const uint8_t *_msg, size_t _msg_len) +{ + uint8_t tmp_block[16]; + uint8_t Y[16]; + const uint8_t *msg = _msg; + size_t msg_len = _msg_len; + + /* + * copy the remembered last block + */ + ZERO_STRUCT(tmp_block); + if (ctx->last_len) { + memcpy(tmp_block, ctx->last, ctx->last_len); + } + + /* + * check if we expand the block + */ + if (ctx->last_len < 16) { + size_t len = MIN(16 - ctx->last_len, msg_len); + + memcpy(&tmp_block[ctx->last_len], msg, len); + memcpy(ctx->last, tmp_block, 16); + msg += len; + msg_len -= len; + ctx->last_len += len; + } + + if (msg_len == 0) { + /* if it is still the last block, we are done */ + ZERO_STRUCT(tmp_block); + return; + } + + /* + * It is not the last block anymore + */ + ZERO_STRUCT(ctx->last); + ctx->last_len = 0; + + /* + * now checksum everything but the last block + */ + aes_cmac_128_xor(ctx->X, tmp_block, Y); + aes_crypt_ecb(&ctx->aes_key, AES_ENCRYPT, Y, ctx->X); + + while (msg_len > 16) { + memcpy(tmp_block, msg, 16); + msg += 16; + msg_len -= 16; + + aes_cmac_128_xor(ctx->X, tmp_block, Y); + aes_crypt_ecb(&ctx->aes_key, AES_ENCRYPT, Y, ctx->X); + } + + /* + * copy the last block, it will be processed in + * aes_cmac128_final(). + */ + memcpy(ctx->last, msg, msg_len); + ctx->last_len = msg_len; + + ZERO_STRUCT(tmp_block); + ZERO_STRUCT(Y); +} + +/* + * AES-CMAC-128 compute T + */ +void aes_cmac128_final(aes_cmac128_context *ctx, uint8_t T[16]) +{ + uint8_t tmp_block[16]; + uint8_t Y[16]; + + if (ctx->last_len < 16) { + ctx->last[ctx->last_len] = 0x80; + aes_cmac_128_xor(ctx->last, ctx->K2, tmp_block); + } else { + aes_cmac_128_xor(ctx->last, ctx->K1, tmp_block); + } + + aes_cmac_128_xor(tmp_block, ctx->X, Y); + aes_crypt_ecb(&ctx->aes_key, AES_ENCRYPT, Y, T); + + ZERO_STRUCT(tmp_block); + ZERO_STRUCT(Y); + ZERO_STRUCTP(ctx); +} + +/* + * Checkup routine + * + * https://csrc.nist.gov/projects/cryptographic-standards-and-guidelines/example-values + * https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Standards-and-Guidelines/documents/examples/AES_CMAC.pdf + */ +int aes_cmac_self_test( int verbose ) +{ + unsigned char key[16] = {0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C}; + unsigned char mac[16] = {0}; + aes_cmac128_context ctx; + int ret; + + // check Example1: + if( verbose != 0 ) + polarssl_printf( " AES-CMAC-128 zero length data: " ); + unsigned char ex1data[16] = {0}; + aes_cmac128_starts(&ctx, key); + aes_cmac128_update(&ctx, ex1data, 0); + aes_cmac128_final(&ctx, mac); + unsigned char ex1res[16] = {0xBB, 0x1D, 0x69, 0x29, 0xE9, 0x59, 0x37, 0x28, 0x7F, 0xA3, 0x7D, 0x12, 0x9B, 0x75, 0x67, 0x46}; + if(!memcmp(mac, ex1res, 16)) { + if( verbose != 0 ) + polarssl_printf( "passed\n" ); + } else { + polarssl_printf( "failed\n" ); + ret = 1; + goto exit; + } + + // check Example2: + if( verbose != 0 ) + polarssl_printf( " AES-CMAC-128 one block data : " ); + unsigned char ex2data[16] = {0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96, 0xE9, 0x3D, 0x7E, 0x11, 0x73, 0x93, 0x17, 0x2A}; + aes_cmac128_starts(&ctx, key); + aes_cmac128_update(&ctx, ex2data, sizeof(ex2data)); + aes_cmac128_final(&ctx, mac); + unsigned char ex2res[16] = {0x07, 0x0A, 0x16, 0xB4, 0x6B, 0x4D, 0x41, 0x44, 0xF7, 0x9B, 0xDD, 0x9D, 0xD0, 0x4A, 0x28, 0x7C}; + if(!memcmp(mac, ex2res, 16)) { + if( verbose != 0 ) + polarssl_printf( "passed\n" ); + } else { + polarssl_printf( "failed\n" ); + ret = 1; + goto exit; + } + + // check Example3: + if( verbose != 0 ) + polarssl_printf( " AES-CMAC-128 20 bytes of data: " ); + unsigned char ex3data[20] = {0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96, 0xE9, 0x3D, 0x7E, 0x11, 0x73, 0x93, 0x17, 0x2A, + 0xAE, 0x2D, 0x8A, 0x57}; + aes_cmac128_starts(&ctx, key); + aes_cmac128_update(&ctx, ex3data, sizeof(ex3data)); + aes_cmac128_final(&ctx, mac); + unsigned char ex3res[16] = {0x7D, 0x85, 0x44, 0x9E, 0xA6, 0xEA, 0x19, 0xC8, 0x23, 0xA7, 0xBF, 0x78, 0x83, 0x7D, 0xFA, 0xDE}; + if(!memcmp(mac, ex3res, 16)) { + if( verbose != 0 ) + polarssl_printf( "passed\n" ); + } else { + polarssl_printf( "failed\n" ); + ret = 1; + goto exit; + } + + // check Example4: + if( verbose != 0 ) + polarssl_printf( " AES-CMAC-128 4 blocks of data: " ); + unsigned char ex4data[64] = {0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96, 0xE9, 0x3D, 0x7E, 0x11, 0x73, 0x93, 0x17, 0x2A, + 0xAE, 0x2D, 0x8A, 0x57, 0x1E, 0x03, 0xAC, 0x9C, 0x9E, 0xB7, 0x6F, 0xAC, 0x45, 0xAF, 0x8E, 0x51, + 0x30, 0xC8, 0x1C, 0x46, 0xA3, 0x5C, 0xE4, 0x11, 0xE5, 0xFB, 0xC1, 0x19, 0x1A, 0x0A, 0x52, 0xEF, + 0xF6, 0x9F, 0x24, 0x45, 0xDF, 0x4F, 0x9B, 0x17, 0xAD, 0x2B, 0x41, 0x7B, 0xE6, 0x6C, 0x37, 0x10}; + aes_cmac128_starts(&ctx, key); + aes_cmac128_update(&ctx, ex4data, sizeof(ex4data)); + aes_cmac128_final(&ctx, mac); + unsigned char ex4res[16] = {0x51, 0xF0, 0xBE, 0xBF, 0x7E, 0x3B, 0x9D, 0x92, 0xFC, 0x49, 0x74, 0x17, 0x79, 0x36, 0x3C, 0xFE}; + if(!memcmp(mac, ex4res, 16)) { + if( verbose != 0 ) + polarssl_printf( "passed\n" ); + } else { + polarssl_printf( "failed\n" ); + ret = 1; + goto exit; + } + + if( verbose != 0 ) + polarssl_printf( "\n" ); + + ret = 0; + +exit: + return( ret ); +} + diff --git a/common/polarssl/aes_cmac128.h b/common/polarssl/aes_cmac128.h new file mode 100644 index 00000000..b792755f --- /dev/null +++ b/common/polarssl/aes_cmac128.h @@ -0,0 +1,81 @@ +/* + * AES-CMAC from NIST Special Publication 800-38B — Recommendation for block cipher modes of operation: The CMAC mode for authentication. + * + * Copyright (C) 2006-2014, Brainspark B.V. + * Copyright (C) 2014, Anargyros Plemenos + * Tests added Merkok, 2018 + * + * This file is part of PolarSSL (http://www.polarssl.org) + * Lead Maintainer: Paul Bakker + * + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Reference : https://polarssl.org/discussions/generic/authentication-token + * NIST Special Publication 800-38B — Recommendation for block cipher modes of operation: The CMAC mode for authentication. + * Tests here: + * https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Standards-and-Guidelines/documents/examples/AES_CMAC.pdf +*/ + +#include +#include +#include "aes.h" + +typedef struct aes_cmac_128_context { + aes_context aes_key; + + uint8_t K1[16]; + uint8_t K2[16]; + + uint8_t X[16]; + + uint8_t last[16]; + size_t last_len; +} +aes_cmac128_context; + +/* + * \brief AES-CMAC-128 context setup + * + * \param ctx context to be initialized + * \param key secret key for AES-128 + */ +void aes_cmac128_starts(aes_cmac128_context *ctx, const uint8_t K[16]); + +/* + * \brief AES-CMAC-128 process message + * + * \param ctx context to be initialized + * \param _msg the given message + * \param _msg_len the length of message + */ +void aes_cmac128_update(aes_cmac128_context *ctx, const uint8_t *_msg, size_t _msg_len); + +/* + * \brief AES-CMAC-128 compute T + * + * \param ctx context to be initialized + * \param T the generated MAC which is used to validate the message + */ +void aes_cmac128_final(aes_cmac128_context *ctx, uint8_t T[16]); + +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if the test failed + */ +int aes_cmac_self_test( int verbose ); + diff --git a/common/polarssl/libpcrypto.c b/common/polarssl/libpcrypto.c index 032c3a18..9be9fd26 100644 --- a/common/polarssl/libpcrypto.c +++ b/common/polarssl/libpcrypto.c @@ -10,7 +10,9 @@ #include "polarssl/libpcrypto.h" #include +#include +// NIST Special Publication 800-38A — Recommendation for block cipher modes of operation: methods and techniques, 2001. int aes_encode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int length){ uint8_t iiv[16] = {0}; if (iv) @@ -41,4 +43,41 @@ int aes_decode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int l aes_free(&aes); return 0; -} \ No newline at end of file +} + +// NIST Special Publication 800-38B — Recommendation for block cipher modes of operation: The CMAC mode for authentication. +// https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Standards-and-Guidelines/documents/examples/AES_CMAC.pdf +int aes_cmac(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int length) { + memset(mac, 0x00, 16); + uint8_t iiv[16] = {0}; + if (iv) + memcpy(iiv, iv, 16); + + // padding: ISO/IEC 9797-1 Message Authentication Codes (MACs) - Part 1: Mechanisms using a block cipher + uint8_t data[2049] = {0}; // length + 16 + memcpy(data, input, length); + data[length] = 0x80; + int datalen = (length & 0xfffffff0) + 0x10; + + // NIST 800-38B + aes_cmac128_context ctx; + aes_cmac128_starts(&ctx, key); + aes_cmac128_update(&ctx, data, datalen); + aes_cmac128_final(&ctx, mac); + + return 0; +} + +int aes_cmac8(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int length) { + uint8_t cmac[16] = {0}; + memset(mac, 0x00, 8); + + int res = aes_cmac(iv, key, input, cmac, length); + if (res) + return res; + + for(int i = 0; i < 8; i++) + mac[i] = cmac[i * 2 + 1]; + + return 0; +} diff --git a/common/polarssl/libpcrypto.h b/common/polarssl/libpcrypto.h index 84732cd3..1b74c143 100644 --- a/common/polarssl/libpcrypto.h +++ b/common/polarssl/libpcrypto.h @@ -16,5 +16,7 @@ extern int aes_encode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int length); extern int aes_decode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int length); +extern int aes_cmac(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int length); +extern int aes_cmac8(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int length); #endif /* libpcrypto.h */