textual
[RRG-proxmark3.git] / client / src / mifare / desfire_crypto.c
blob01c233de3c6ba6ee1fe53b62f4872e17bd7b7615
1 /*-
2 * Copyright (C) 2010, Romain Tartiere.
4 * This program is free software: you can redistribute it and/or modify it
5 * under the terms of the GNU Lesser General Public License as published by the
6 * Free Software Foundation, either version 3 of the License, or (at your
7 * option) any later version.
9 * This program is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 * more details.
14 * You should have received a copy of the GNU Lesser General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>
17 * $Id$
21 * This implementation was written based on information provided by the
22 * following documents:
24 * NIST Special Publication 800-38B
25 * Recommendation for Block Cipher Modes of Operation: The CMAC Mode for Authentication
26 * May 2005
28 #include "desfire_crypto.h"
29 #include <stdlib.h>
30 #include <string.h>
31 #include <util.h>
32 #include "commonutil.h"
33 #include "aes.h"
34 #include "des.h"
35 #include "ui.h"
36 #include "crc.h"
37 #include "crc16.h" // crc16 ccitt
38 #include "crc32.h"
40 #ifndef AddCrc14A
41 # define AddCrc14A(data, len) compute_crc(CRC_14443_A, (data), (len), (data)+(len), (data)+(len)+1)
42 #endif
44 static inline void update_key_schedules(desfirekey_t key);
46 static inline void update_key_schedules(desfirekey_t key) {
47 // DES_set_key ((DES_cblock *)key->data, &(key->ks1));
48 // DES_set_key ((DES_cblock *)(key->data + 8), &(key->ks2));
49 // if (T_3K3DES == key->type) {
50 // DES_set_key ((DES_cblock *)(key->data + 16), &(key->ks3));
51 // }
54 /******************************************************************************/
56 void des_encrypt(void *out, const void *in, const void *key) {
57 mbedtls_des_context ctx;
58 mbedtls_des_setkey_enc(&ctx, key);
59 mbedtls_des_crypt_ecb(&ctx, in, out);
62 void des_decrypt(void *out, const void *in, const void *key) {
63 mbedtls_des_context ctx;
64 mbedtls_des_setkey_dec(&ctx, key);
65 mbedtls_des_crypt_ecb(&ctx, in, out);
68 void tdes_nxp_receive(const void *in, void *out, size_t length, const void *key, unsigned char iv[8], int keymode) {
69 if (length % 8)
70 return;
72 mbedtls_des3_context ctx3;
73 if (keymode == 2)
74 mbedtls_des3_set2key_dec(&ctx3, key);
75 else
76 mbedtls_des3_set3key_dec(&ctx3, key);
78 uint8_t i;
79 unsigned char temp[8];
80 uint8_t *tin = (uint8_t *) in;
81 uint8_t *tout = (uint8_t *) out;
83 while (length > 0) {
84 memcpy(temp, tin, 8);
86 mbedtls_des3_crypt_ecb(&ctx3, tin, tout);
88 for (i = 0; i < 8; i++) {
89 tout[i] = (unsigned char)(tout[i] ^ iv[i]);
92 memcpy(iv, temp, 8);
94 tin += 8;
95 tout += 8;
96 length -= 8;
100 void tdes_nxp_send(const void *in, void *out, size_t length, const void *key, unsigned char iv[8], int keymode) {
101 if (length % 8)
102 return;
104 mbedtls_des3_context ctx3;
106 if (keymode == 2)
107 mbedtls_des3_set2key_enc(&ctx3, key);
108 else
109 mbedtls_des3_set3key_enc(&ctx3, key);
111 uint8_t i;
112 uint8_t *tin = (uint8_t *) in;
113 uint8_t *tout = (uint8_t *) out;
115 while (length > 0) {
116 for (i = 0; i < 8; i++) {
117 tin[i] = (unsigned char)(tin[i] ^ iv[i]);
120 mbedtls_des3_crypt_ecb(&ctx3, tin, tout);
122 memcpy(iv, tout, 8);
124 tin += 8;
125 tout += 8;
126 length -= 8;
131 void Desfire_des_key_new(const uint8_t value[8], desfirekey_t key) {
132 uint8_t data[8];
133 memcpy(data, value, 8);
134 for (int n = 0; n < 8; n++) {
135 data[n] &= 0xFE;
137 Desfire_des_key_new_with_version(data, key);
140 void Desfire_des_key_new_with_version(const uint8_t value[8], desfirekey_t key) {
141 if (key != NULL) {
142 key->type = T_DES;
143 memcpy(key->data, value, 8);
144 memcpy(key->data + 8, value, 8);
145 update_key_schedules(key);
149 void Desfire_3des_key_new(const uint8_t value[16], desfirekey_t key) {
150 uint8_t data[16];
151 memcpy(data, value, 16);
152 for (int n = 0; n < 8; n++) {
153 data[n] &= 0xFE;
155 for (int n = 8; n < 16; n++) {
156 data[n] |= 0x01;
158 Desfire_3des_key_new_with_version(data, key);
161 void Desfire_3des_key_new_with_version(const uint8_t value[16], desfirekey_t key) {
162 if (key != NULL) {
163 key->type = T_3DES;
164 memcpy(key->data, value, 16);
165 update_key_schedules(key);
169 void Desfire_3k3des_key_new(const uint8_t value[24], desfirekey_t key) {
170 uint8_t data[24];
171 memcpy(data, value, 24);
172 for (int n = 0; n < 8; n++) {
173 data[n] &= 0xFE;
175 Desfire_3k3des_key_new_with_version(data, key);
178 void Desfire_3k3des_key_new_with_version(const uint8_t value[24], desfirekey_t key) {
179 if (key != NULL) {
180 key->type = T_3K3DES;
181 memcpy(key->data, value, 24);
182 update_key_schedules(key);
186 void Desfire_aes_key_new(const uint8_t value[16], desfirekey_t key) {
187 Desfire_aes_key_new_with_version(value, 0, key);
190 void Desfire_aes_key_new_with_version(const uint8_t value[16], uint8_t version, desfirekey_t key) {
191 if (key != NULL) {
192 memcpy(key->data, value, 16);
193 key->type = T_AES;
194 key->aes_version = version;
198 uint8_t Desfire_key_get_version(desfirekey_t key) {
199 uint8_t version = 0;
201 for (int n = 0; n < 8; n++) {
202 version |= ((key->data[n] & 1) << (7 - n));
204 return version;
207 void Desfire_key_set_version(desfirekey_t key, uint8_t version) {
208 for (int n = 0; n < 8; n++) {
209 uint8_t version_bit = ((version & (1 << (7 - n))) >> (7 - n));
211 key->data[n] &= 0xFE;
212 key->data[n] |= version_bit;
214 if (key->type == T_DES) {
215 key->data[n + 8] = key->data[n];
216 } else {
217 // Write ~version to avoid turning a 3DES key into a DES key
218 key->data[n + 8] &= 0xFE;
219 key->data[n + 8] |= ~version_bit;
224 void Desfire_session_key_new(const uint8_t rnda[], const uint8_t rndb[], desfirekey_t authkey, desfirekey_t key) {
226 uint8_t buffer[24];
228 switch (authkey->type) {
229 case T_DES:
230 memcpy(buffer, rnda, 4);
231 memcpy(buffer + 4, rndb, 4);
232 Desfire_des_key_new_with_version(buffer, key);
233 break;
234 case T_3DES:
235 memcpy(buffer, rnda, 4);
236 memcpy(buffer + 4, rndb, 4);
237 memcpy(buffer + 8, rnda + 4, 4);
238 memcpy(buffer + 12, rndb + 4, 4);
239 Desfire_3des_key_new_with_version(buffer, key);
240 break;
241 case T_3K3DES:
242 memcpy(buffer, rnda, 4);
243 memcpy(buffer + 4, rndb, 4);
244 memcpy(buffer + 8, rnda + 6, 4);
245 memcpy(buffer + 12, rndb + 6, 4);
246 memcpy(buffer + 16, rnda + 12, 4);
247 memcpy(buffer + 20, rndb + 12, 4);
248 Desfire_3k3des_key_new(buffer, key);
249 break;
250 case T_AES:
251 memcpy(buffer, rnda, 4);
252 memcpy(buffer + 4, rndb, 4);
253 memcpy(buffer + 8, rnda + 12, 4);
254 memcpy(buffer + 12, rndb + 12, 4);
255 Desfire_aes_key_new(buffer, key);
256 break;
260 static size_t key_macing_length(desfirekey_t key);
262 // iceman, see memxor inside string.c, dest/src swapped..
263 static void xor(const uint8_t *ivect, uint8_t *data, const size_t len) {
264 for (size_t i = 0; i < len; i++) {
265 data[i] ^= ivect[i];
269 void cmac_generate_subkeys(desfirekey_t key, MifareCryptoDirection direction) {
270 int kbs = key_block_size(key);
271 const uint8_t R = (kbs == 8) ? 0x1B : 0x87;
273 uint8_t l[kbs];
274 memset(l, 0, kbs);
276 uint8_t ivect[kbs];
277 memset(ivect, 0, kbs);
279 mifare_cypher_blocks_chained(NULL, key, ivect, l, kbs, direction, MCO_ENCYPHER);
281 bool txor = false;
283 // Used to compute CMAC on complete blocks
284 memcpy(key->cmac_sk1, l, kbs);
285 txor = l[0] & 0x80;
286 lsl(key->cmac_sk1, kbs);
287 if (txor) {
288 key->cmac_sk1[kbs - 1] ^= R;
291 // Used to compute CMAC on the last block if non-complete
292 memcpy(key->cmac_sk2, key->cmac_sk1, kbs);
293 txor = key->cmac_sk1[0] & 0x80;
294 lsl(key->cmac_sk2, kbs);
295 if (txor) {
296 key->cmac_sk2[kbs - 1] ^= R;
300 void cmac(const desfirekey_t key, uint8_t *ivect, const uint8_t *data, size_t len, uint8_t *cmac) {
301 int kbs = key_block_size(key);
302 if (kbs == 0) {
303 return;
306 uint8_t *buffer = calloc(padded_data_length(len, kbs), sizeof(uint8_t));
307 if (buffer == NULL) {
308 PrintAndLogEx(WARNING, "failed to allocate memory");
309 return;
312 memcpy(buffer, data, len);
314 if ((!len) || (len % kbs)) {
315 buffer[len++] = 0x80;
316 while (len % kbs) {
317 buffer[len++] = 0x00;
319 xor(key->cmac_sk2, buffer + len - kbs, kbs);
320 } else {
321 xor(key->cmac_sk1, buffer + len - kbs, kbs);
324 mifare_cypher_blocks_chained(NULL, key, ivect, buffer, len, MCD_SEND, MCO_ENCYPHER);
326 memcpy(cmac, ivect, kbs);
327 free(buffer);
330 // This function is almot like cmac(...). but with some key differences.
331 void mifare_kdf_an10922(const desfirekey_t key, const uint8_t *data, size_t len) {
332 int kbs = key_block_size(key);
333 int kbs2 = kbs * 2;
334 if (key == NULL || kbs == 0 || data == NULL || len < 1 || len > 31) {
335 return;
338 cmac_generate_subkeys(key, MCD_SEND);
340 // reserv atleast 32bytes.
341 uint8_t *buffer = calloc(len, sizeof(uint8_t));
342 if (buffer == NULL) {
343 PrintAndLogEx(WARNING, "failed to allocate memory");
344 return;
346 uint8_t *ivect = calloc(kbs, sizeof(uint8_t));
347 if (ivect == NULL) {
348 PrintAndLogEx(WARNING, "failed to allocate memory");
349 return;
352 buffer[0] = 0x01;
353 memcpy(&buffer[1], data, len++);
355 if (len != (kbs2)) {
356 buffer[len++] = 0x80;
357 while (len % kbs2) {
358 buffer[len++] = 0x00;
360 xor(key->cmac_sk2, buffer + kbs, kbs);
361 } else {
362 xor(key->cmac_sk1, buffer + kbs, kbs);
365 mbedtls_aes_context actx;
366 mbedtls_aes_init(&actx);
367 mbedtls_aes_setkey_enc(&actx, key->data, kbs * 8);
368 mbedtls_aes_crypt_cbc(&actx, MBEDTLS_AES_ENCRYPT, kbs2, ivect, buffer, buffer);
369 mbedtls_aes_free(&actx);
371 memcpy(key->data, buffer + kbs, kbs);
372 free(ivect);
373 free(buffer);
376 size_t key_block_size(const desfirekey_t key) {
377 if (key == NULL) {
378 return 0;
380 size_t block_size = 8;
381 switch (key->type) {
382 case T_DES:
383 case T_3DES:
384 case T_3K3DES:
385 block_size = 8;
386 break;
387 case T_AES:
388 block_size = 16;
389 break;
391 return block_size;
395 * Size of MACing produced with the key.
397 static size_t key_macing_length(const desfirekey_t key) {
398 size_t mac_length = MAC_LENGTH;
399 switch (key->type) {
400 case T_DES:
401 case T_3DES:
402 mac_length = MAC_LENGTH;
403 break;
404 case T_3K3DES:
405 case T_AES:
406 mac_length = CMAC_LENGTH;
407 break;
409 return mac_length;
413 * Size required to store nbytes of data in a buffer of size n*block_size.
415 size_t padded_data_length(const size_t nbytes, const size_t block_size) {
416 if ((!nbytes) || (nbytes % block_size))
417 return ((nbytes / block_size) + 1) * block_size;
418 else
419 return nbytes;
423 * Buffer size required to MAC nbytes of data
425 size_t maced_data_length(const desfirekey_t key, const size_t nbytes) {
426 return nbytes + key_macing_length(key);
429 * Buffer size required to encipher nbytes of data and a two bytes CRC.
431 size_t enciphered_data_length(const desfiretag_t tag, const size_t nbytes, int communication_settings) {
432 size_t crc_length = 0;
433 if (!(communication_settings & NO_CRC)) {
434 switch (DESFIRE(tag)->authentication_scheme) {
435 case AS_LEGACY:
436 crc_length = 2;
437 break;
438 case AS_NEW:
439 crc_length = 4;
440 break;
444 size_t block_size = DESFIRE(tag)->session_key ? key_block_size(DESFIRE(tag)->session_key) : 1;
446 return padded_data_length(nbytes + crc_length, block_size);
449 void *mifare_cryto_preprocess_data(desfiretag_t tag, void *data, size_t *nbytes, size_t offset, int communication_settings) {
450 uint8_t *res = data;
451 uint8_t mac[4];
452 size_t edl;
453 bool append_mac = true;
454 desfirekey_t key = DESFIRE(tag)->session_key;
456 if (!key)
457 return data;
459 switch (communication_settings & MDCM_MASK) {
460 case MDCM_PLAIN: {
461 if (AS_LEGACY == DESFIRE(tag)->authentication_scheme)
462 break;
465 * When using new authentication methods, PLAIN data transmission from
466 * the PICC to the PCD are CMACed, so we have to maintain the
467 * cryptographic initialisation vector up-to-date to check data
468 * integrity later.
470 * The only difference with CMACed data transmission is that the CMAC
471 * is not apended to the data send by the PCD to the PICC.
474 append_mac = false;
476 /* pass through */
477 case MDCM_MACED: {
478 communication_settings |= NO_CRC;
480 switch (DESFIRE(tag)->authentication_scheme) {
481 case AS_LEGACY:
482 if (!(communication_settings & MAC_COMMAND))
483 break;
485 /* pass through */
486 edl = padded_data_length(*nbytes - offset, key_block_size(DESFIRE(tag)->session_key)) + offset;
488 // Fill in the crypto buffer with data ...
489 memcpy(res, data, *nbytes);
490 // ... and 0 padding
491 memset(res + *nbytes, 0, edl - *nbytes);
493 mifare_cypher_blocks_chained(tag, NULL, NULL, res + offset, edl - offset, MCD_SEND, MCO_ENCYPHER);
495 memcpy(mac, res + edl - 8, 4);
497 // Copy again provided data (was overwritten by mifare_cypher_blocks_chained)
498 memcpy(res, data, *nbytes);
500 if (!(communication_settings & MAC_COMMAND))
501 break;
502 // Append MAC
503 size_t bla = maced_data_length(DESFIRE(tag)->session_key, *nbytes - offset) + offset;
504 bla++;
506 memcpy(res + *nbytes, mac, 4);
508 *nbytes += 4;
509 break;
510 case AS_NEW:
511 if (!(communication_settings & CMAC_COMMAND))
512 break;
513 cmac(key, DESFIRE(tag)->ivect, res, *nbytes, DESFIRE(tag)->cmac);
515 if (append_mac) {
516 size_t len = maced_data_length(key, *nbytes);
517 ++len;
518 memcpy(res, data, *nbytes);
519 memcpy(res + *nbytes, DESFIRE(tag)->cmac, CMAC_LENGTH);
520 *nbytes += CMAC_LENGTH;
522 break;
525 break;
527 case MDCM_ENCIPHERED: {
528 /* |<-------------- data -------------->|
529 * |<--- offset -->| |
530 * +---------------+--------------------+-----+---------+
531 * | CMD + HEADERS | DATA TO BE SECURED | CRC | PADDING |
532 * +---------------+--------------------+-----+---------+ ----------------
533 * | |<~~~~v~~~~~~~~~~~~~>| ^ | | (DES / 3DES)
534 * | | `---- crc16() ----' | |
535 * | | | ^ | | ----- *or* -----
536 * |<~~~~~~~~~~~~~~~~~~~~v~~~~~~~~~~~~~>| ^ | | (3K3DES / AES)
537 * | `---- crc32() ----' | |
538 * | | ---- *then* ----
539 * |<---------------------------------->|
540 * encypher()/decypher()
543 if (!(communication_settings & ENC_COMMAND))
544 break;
546 edl = enciphered_data_length(tag, *nbytes - offset, communication_settings) + offset;
548 // Fill in the crypto buffer with data ...
549 memcpy(res, data, *nbytes);
551 if (!(communication_settings & NO_CRC)) {
552 // ... CRC ...
553 switch (DESFIRE(tag)->authentication_scheme) {
554 case AS_LEGACY: {
555 AddCrc14A(res + offset, *nbytes - offset);
556 *nbytes += 2;
557 break;
559 case AS_NEW: {
560 crc32_append(res, *nbytes);
561 *nbytes += 4;
562 break;
566 // ... and padding
567 memset(res + *nbytes, 0, edl - *nbytes);
569 *nbytes = edl;
571 mifare_cypher_blocks_chained(tag, NULL, NULL, res + offset, *nbytes - offset, MCD_SEND, (AS_NEW == DESFIRE(tag)->authentication_scheme) ? MCO_ENCYPHER : MCO_DECYPHER);
572 break;
574 default: {
575 *nbytes = -1;
576 res = NULL;
577 break;
581 return res;
585 void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes, int communication_settings) {
586 void *res = data;
587 void *edata = NULL;
588 tag->crypto_buffer_size = *nbytes * 2;
589 tag->crypto_buffer = (uint8_t *)calloc(tag->crypto_buffer_size, sizeof(uint8_t));
591 uint8_t first_cmac_byte = 0x00;
593 desfirekey_t key = DESFIRE(tag)->session_key;
595 if (!key)
596 return data;
598 // Return directly if we just have a status code.
599 if (1 == *nbytes)
600 return res;
602 switch (communication_settings & MDCM_MASK) {
603 case MDCM_PLAIN:
605 if (AS_LEGACY == DESFIRE(tag)->authentication_scheme)
606 break;
608 /* pass through */
609 case MDCM_MACED:
610 communication_settings |= NO_CRC;
611 switch (DESFIRE(tag)->authentication_scheme) {
612 case AS_LEGACY:
613 if (communication_settings & MAC_VERIFY) {
614 *nbytes -= key_macing_length(key);
615 if (*nbytes == 0) {
616 *nbytes = -1;
617 res = NULL;
618 #ifdef WITH_DEBUG
619 Dbprintf("No room for MAC!");
620 #endif
621 break;
624 size_t edl = enciphered_data_length(tag, *nbytes, communication_settings);
625 edata = calloc(edl, sizeof(uint8_t));
627 memcpy(edata, data, *nbytes);
628 memset((uint8_t *)edata + *nbytes, 0, edl - *nbytes);
630 mifare_cypher_blocks_chained(tag, NULL, NULL, edata, edl, MCD_SEND, MCO_ENCYPHER);
632 if (0 != memcmp((uint8_t *)data + *nbytes, (uint8_t *)edata + edl - 8, 4)) {
633 #ifdef WITH_DEBUG
634 PrintAndLogEx(NORMAL, "Expected MAC %s", sprint_hex(data + *nbytes, key_macing_length(key)));
635 PrintAndLogEx(NORMAL, "Actual MAC %s", sprint_hex(edata + edl - 8, key_macing_length(key)));
636 #endif
637 #ifdef WITH_DEBUG
638 Dbprintf("MACing not verified");
639 hexdump((uint8_t *)data + *nbytes, key_macing_length(key), "Expect ", 0);
640 hexdump((uint8_t *)edata + edl - 8, key_macing_length(key), "Actual ", 0);
641 #endif
642 DESFIRE(tag)->last_pcd_error = CRYPTO_ERROR;
643 *nbytes = -1;
644 res = NULL;
647 break;
648 case AS_NEW:
649 if (!(communication_settings & CMAC_COMMAND))
650 break;
651 if (communication_settings & CMAC_VERIFY) {
652 if (*nbytes < 9) {
653 *nbytes = -1;
654 res = NULL;
655 break;
657 first_cmac_byte = ((uint8_t *)data)[*nbytes - 9];
658 ((uint8_t *)data)[*nbytes - 9] = ((uint8_t *)data)[*nbytes - 1];
661 int n = (communication_settings & CMAC_VERIFY) ? 8 : 0;
662 cmac(key, DESFIRE(tag)->ivect, ((uint8_t *)data), *nbytes - n, DESFIRE(tag)->cmac);
664 if (communication_settings & CMAC_VERIFY) {
665 ((uint8_t *)data)[*nbytes - 9] = first_cmac_byte;
666 if (0 != memcmp(DESFIRE(tag)->cmac, (uint8_t *)data + *nbytes - 9, 8)) {
667 #ifdef WITH_DEBUG
668 Dbprintf("CMAC NOT verified :-(");
669 hexdump((uint8_t *)data + *nbytes - 9, 8, "Expect ", 0);
670 hexdump(DESFIRE(tag)->cmac, 8, "Actual ", 0);
671 #endif
672 DESFIRE(tag)->last_pcd_error = CRYPTO_ERROR;
673 *nbytes = -1;
674 res = NULL;
675 } else {
676 *nbytes -= 8;
679 break;
682 free(edata);
684 break;
685 case MDCM_ENCIPHERED: {
686 bool verified = false;
687 int crc_pos = 0x00;
688 int end_crc_pos = 0x00;
689 uint8_t x;
692 * AS_LEGACY:
693 * ,-----------------+-------------------------------+--------+
694 * \ BLOCK n-1 | BLOCK n | STATUS |
695 * / PAYLOAD | CRC0 | CRC1 | 0x80? | 0x000000000000 | 0x9100 |
696 * `-----------------+-------------------------------+--------+
698 * <------------ DATA ------------>
699 * FRAME = PAYLOAD + CRC(PAYLOAD) + PADDING
701 * AS_NEW:
702 * ,-------------------------------+-----------------------------------------------+--------+
703 * \ BLOCK n-1 | BLOCK n | STATUS |
704 * / PAYLOAD | CRC0 | CRC1 | CRC2 | CRC3 | 0x80? | 0x0000000000000000000000000000 | 0x9100 |
705 * `-------------------------------+-----------------------------------------------+--------+
706 * <----------------------------------- DATA ------------------------------------->|
708 * <----------------- DATA ---------------->
709 * FRAME = PAYLOAD + CRC(PAYLOAD + STATUS) + PADDING + STATUS
710 * `------------------'
713 mifare_cypher_blocks_chained(tag, NULL, NULL, res, *nbytes, MCD_RECEIVE, MCO_DECYPHER);
716 * Look for the CRC and ensure it is followed by NULL padding. We
717 * can't start by the end because the CRC is supposed to be 0 when
718 * verified, and accumulating 0's in it should not change it.
720 switch (DESFIRE(tag)->authentication_scheme) {
721 case AS_LEGACY:
722 crc_pos = *nbytes - 8 - 1; // The CRC can be over two blocks
723 if (crc_pos < 0) {
724 /* Single block */
725 crc_pos = 0;
727 break;
728 case AS_NEW:
729 /* Move status between payload and CRC */
730 res = DESFIRE(tag)->crypto_buffer;
731 if (res != NULL) {
732 memcpy(res, data, *nbytes);
734 size_t padding_start_pos = *nbytes - 1;
735 while (padding_start_pos > 0 && ((uint8_t *) res)[padding_start_pos] == 0x00) {
736 padding_start_pos--;
738 //TODO: Add support for cases where there is no padding. Uncommon but possible.
739 crc_pos = padding_start_pos - 4;
741 memcpy((uint8_t *) res + crc_pos + 1, (uint8_t *) res + crc_pos, *nbytes - crc_pos);
742 ((uint8_t *) res)[crc_pos] = 0x00;
743 crc_pos++;
744 *nbytes += 1;
746 break;
749 do {
750 uint16_t crc_16 = 0x00;
751 uint32_t crc = 0x00;
752 switch (DESFIRE(tag)->authentication_scheme) {
753 case AS_LEGACY:
754 AddCrc14A((uint8_t *)res, end_crc_pos);
755 end_crc_pos = crc_pos + 2;
759 crc = crc_16;
760 break;
761 case AS_NEW:
762 end_crc_pos = crc_pos + 4;
763 crc32_ex(res, end_crc_pos, (uint8_t *)&crc);
764 break;
766 if (!crc) {
767 verified = true;
768 for (int n = end_crc_pos; n < *nbytes - 1; n++) {
769 uint8_t byte = ((uint8_t *)res)[n];
770 if (!((0x00 == byte) || ((0x80 == byte) && (n == end_crc_pos))))
771 verified = false;
774 if (verified) {
775 *nbytes = crc_pos;
776 switch (DESFIRE(tag)->authentication_scheme) {
777 case AS_LEGACY:
778 ((uint8_t *)data)[(*nbytes)++] = 0x00;
779 break;
780 case AS_NEW:
781 *nbytes = crc_pos - 1;
782 /* The status byte was already before the CRC */
783 break;
785 } else {
786 switch (DESFIRE(tag)->authentication_scheme) {
787 case AS_LEGACY:
788 break;
789 case AS_NEW:
790 x = ((uint8_t *)res)[crc_pos - 1];
791 ((uint8_t *)res)[crc_pos - 1] = ((uint8_t *)res)[crc_pos];
792 ((uint8_t *)res)[crc_pos] = x;
793 break;
795 crc_pos++;
797 } while (!verified && (end_crc_pos < *nbytes));
799 if (!verified) {
800 #ifdef WITH_DEBUG
801 /* FIXME In some configurations, the file is transmitted PLAIN */
802 Dbprintf("CRC not verified in decyphered stream");
803 #endif
804 DESFIRE(tag)->last_pcd_error = CRYPTO_ERROR;
805 *nbytes = -1;
806 res = NULL;
809 break;
811 default:
812 PrintAndLogEx(ERR, "Unknown communication settings");
813 *nbytes = -1;
814 res = NULL;
815 break;
818 free(tag->crypto_buffer);
819 tag->crypto_buffer_size = 0;
820 tag->crypto_buffer = NULL;
821 return res;
825 void mifare_cypher_single_block(desfirekey_t key, uint8_t *data, uint8_t *ivect, MifareCryptoDirection direction, MifareCryptoOperation operation, size_t block_size) {
826 uint8_t ovect[MAX_CRYPTO_BLOCK_SIZE];
827 if (direction == MCD_SEND) {
828 xor(ivect, data, block_size);
829 } else {
830 memcpy(ovect, data, block_size);
833 uint8_t edata[MAX_CRYPTO_BLOCK_SIZE];
835 switch (key->type) {
836 case T_DES:
837 switch (operation) {
838 case MCO_ENCYPHER:
839 //DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_ENCRYPT);
840 des_encrypt(edata, data, key->data);
841 break;
842 case MCO_DECYPHER:
843 //DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_DECRYPT);
844 des_decrypt(edata, data, key->data);
845 break;
847 break;
848 case T_3DES:
849 switch (operation) {
850 case MCO_ENCYPHER: {
851 mbedtls_des3_context ctx3;
852 mbedtls_des3_set2key_enc(&ctx3, key->data);
853 mbedtls_des3_crypt_ecb(&ctx3, data, edata);
854 // DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_ENCRYPT);
855 // DES_ecb_encrypt ((DES_cblock *) edata, (DES_cblock *) data, &(key->ks2), DES_DECRYPT);
856 // DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_ENCRYPT);
857 break;
859 case MCO_DECYPHER: {
860 mbedtls_des3_context ctx3;
861 mbedtls_des3_set2key_dec(&ctx3, key->data);
862 mbedtls_des3_crypt_ecb(&ctx3, data, edata);
863 // DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_DECRYPT);
864 // DES_ecb_encrypt ((DES_cblock *) edata, (DES_cblock *) data, &(key->ks2), DES_ENCRYPT);
865 // DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_DECRYPT);
866 break;
869 break;
870 case T_3K3DES:
871 switch (operation) {
872 case MCO_ENCYPHER: {
873 mbedtls_des3_context ctx3;
874 mbedtls_des3_set3key_enc(&ctx3, key->data);
875 mbedtls_des3_crypt_ecb(&ctx3, data, edata);
876 // DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_ENCRYPT);
877 // DES_ecb_encrypt ((DES_cblock *) edata, (DES_cblock *) data, &(key->ks2), DES_DECRYPT);
878 // DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks3), DES_ENCRYPT);
879 break;
881 case MCO_DECYPHER: {
882 mbedtls_des3_context ctx3;
883 mbedtls_des3_set3key_dec(&ctx3, key->data);
884 mbedtls_des3_crypt_ecb(&ctx3, data, edata);
885 // DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks3), DES_DECRYPT);
886 // DES_ecb_encrypt ((DES_cblock *) edata, (DES_cblock *) data, &(key->ks2), DES_ENCRYPT);
887 // DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_DECRYPT);
888 break;
891 break;
892 case T_AES:
893 switch (operation) {
894 case MCO_ENCYPHER: {
895 mbedtls_aes_context actx;
896 mbedtls_aes_init(&actx);
897 mbedtls_aes_setkey_enc(&actx, key->data, 128);
898 mbedtls_aes_crypt_ecb(&actx, MBEDTLS_AES_ENCRYPT, data, edata);
899 mbedtls_aes_free(&actx);
900 break;
902 case MCO_DECYPHER: {
903 mbedtls_aes_context actx;
904 mbedtls_aes_init(&actx);
905 mbedtls_aes_setkey_dec(&actx, key->data, 128);
906 mbedtls_aes_crypt_ecb(&actx, MBEDTLS_AES_DECRYPT, data, edata);
907 mbedtls_aes_free(&actx);
908 break;
911 break;
914 memcpy(data, edata, block_size);
916 if (direction == MCD_SEND) {
917 memcpy(ivect, data, block_size);
918 } else {
919 xor(ivect, data, block_size);
920 memcpy(ivect, ovect, block_size);
925 * This function performs all CBC cyphering / deciphering.
927 * The tag argument may be NULL, in which case both key and ivect shall be set.
928 * When using the tag session_key and ivect for processing data, these
929 * arguments should be set to NULL.
931 * Because the tag may contain additional data, one may need to call this
932 * function with tag, key and ivect defined.
934 void mifare_cypher_blocks_chained(desfiretag_t tag, desfirekey_t key, uint8_t *ivect, uint8_t *data, size_t data_size, MifareCryptoDirection direction, MifareCryptoOperation operation) {
935 if (tag) {
936 if (key == NULL)
937 key = DESFIRE(tag)->session_key;
938 if (ivect == NULL)
939 ivect = DESFIRE(tag)->ivect;
941 switch (DESFIRE(tag)->authentication_scheme) {
942 case AS_LEGACY:
943 memset(ivect, 0, MAX_CRYPTO_BLOCK_SIZE);
944 break;
945 case AS_NEW:
946 break;
950 size_t block_size = key_block_size(key);
951 size_t offset = 0;
952 while (offset < data_size) {
953 mifare_cypher_single_block(key, data + offset, ivect, direction, operation, block_size);
954 offset += block_size;
958 void desfire_crc32(const uint8_t *data, const size_t len, uint8_t *crc) {
959 crc32_ex(data, len, crc);
962 void desfire_crc32_append(uint8_t *data, const size_t len) {
963 crc32_ex(data, len, data + len);
966 void iso14443a_crc_append(uint8_t *data, size_t len) {
967 return compute_crc(CRC_14443_A, data, len, data + len, data + len + 1);
970 void iso14443a_crc(uint8_t *data, size_t len, uint8_t *pbtCrc) {
971 return compute_crc(CRC_14443_A, data, len, pbtCrc, pbtCrc + 1);