Merge pull request #2616 from jmichelp/fix14b
[RRG-proxmark3.git] / armsrc / epa.c
blobaa0f8723093b9569b7c2ed881be38e9cf75ce2e1
1 //-----------------------------------------------------------------------------
2 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // See LICENSE.txt for the text of the license.
15 //-----------------------------------------------------------------------------
16 // Routines to support the German electronic "Personalausweis" (ID card)
17 // Note that the functions which do not implement USB commands do NOT initialize
18 // the card (with iso14443a_select_card etc.). If You want to use these
19 // functions, You need to do the setup before calling them!
20 //-----------------------------------------------------------------------------
21 #include "epa.h"
23 #include "cmd.h"
24 #include "fpgaloader.h"
25 #include "iso14443a.h"
26 #include "iso14443b.h"
27 #include "string.h"
28 #include "util.h"
29 #include "dbprint.h"
30 #include "commonutil.h"
31 #include "ticks.h"
33 #ifdef WITH_ISO14443a
34 // Protocol and Parameter Selection Request for ISO 14443 type A cards
35 // use regular (1x) speed in both directions
36 // CRC is already included
37 static const uint8_t pps[] = {0xD0, 0x11, 0x00, 0x52, 0xA6};
38 #endif
40 // this struct is used by EPA_Parse_CardAccess and contains info about the
41 // PACE protocol supported by the chip
42 typedef struct {
43 uint8_t oid[10];
44 uint8_t version;
45 uint8_t parameter_id;
46 } pace_version_info_t;
48 // general functions
49 static void EPA_Finish(void);
50 static size_t EPA_Parse_CardAccess(const uint8_t *data, size_t length, pace_version_info_t *pace_info);
51 static int EPA_Read_CardAccess(uint8_t *buffer, size_t max_length);
52 static int EPA_Setup(void);
54 // PACE related functions
55 static int EPA_PACE_MSE_Set_AT(const pace_version_info_t pace_version_info, uint8_t password);
56 static int EPA_PACE_Get_Nonce(uint8_t requested_length, uint8_t *nonce);
58 // APDUs for communication with German Identification Card
60 // General Authenticate (request encrypted nonce) WITHOUT the Le at the end
61 static const uint8_t apdu_general_authenticate_pace_get_nonce[] = {
62 0x10, // CLA
63 0x86, // INS
64 0x00, // P1
65 0x00, // P2
66 0x02, // Lc
67 0x7C, // Type: Dynamic Authentication Data
68 0x00, // Length: 0 bytes
71 // MSE: Set AT (only CLA, INS, P1 and P2)
72 static const uint8_t apdu_mse_set_at_start[] = {
73 0x00, // CLA
74 0x22, // INS
75 0xC1, // P1
76 0xA4, // P2
79 // SELECT BINARY with the ID for EF.CardAccess
80 static const uint8_t apdu_select_binary_cardaccess[] = {
81 0x00, // CLA
82 0xA4, // INS
83 0x02, // P1
84 0x0C, // P2
85 0x02, // Lc
86 0x01, // ID
87 0x1C // ID
90 // READ BINARY
91 static const uint8_t apdu_read_binary[] = {
92 0x00, // CLA
93 0xB0, // INS
94 0x00, // P1
95 0x00, // P2
96 0x38 // Le
100 // the leading bytes of a PACE OID
101 static const uint8_t oid_pace_start[] = {
102 0x04, // itu-t, identified-organization
103 0x00, // etsi
104 0x7F, // reserved
105 0x00, // etsi-identified-organization
106 0x07, // bsi-de
107 0x02, // protocols
108 0x02, // smartcard
109 0x04 // id-PACE
112 // APDUs for replaying:
113 // MSE: Set AT (initiate PACE)
114 static uint8_t apdu_replay_mse_set_at_pace[41];
115 // General Authenticate (Get Nonce)
116 static uint8_t apdu_replay_general_authenticate_pace_get_nonce[8];
117 // General Authenticate (Map Nonce)
118 static uint8_t apdu_replay_general_authenticate_pace_map_nonce[75];
119 // General Authenticate (Mutual Authenticate)
120 static uint8_t apdu_replay_general_authenticate_pace_mutual_authenticate[75];
121 // General Authenticate (Perform Key Agreement)
122 static uint8_t apdu_replay_general_authenticate_pace_perform_key_agreement[18];
123 // pointers to the APDUs (for iterations)
124 static struct {
125 uint8_t len;
126 uint8_t *data;
127 } const apdus_replay[] = {
128 {sizeof(apdu_replay_mse_set_at_pace), apdu_replay_mse_set_at_pace},
129 {sizeof(apdu_replay_general_authenticate_pace_get_nonce), apdu_replay_general_authenticate_pace_get_nonce},
130 {sizeof(apdu_replay_general_authenticate_pace_map_nonce), apdu_replay_general_authenticate_pace_map_nonce},
131 {sizeof(apdu_replay_general_authenticate_pace_mutual_authenticate), apdu_replay_general_authenticate_pace_mutual_authenticate},
132 {sizeof(apdu_replay_general_authenticate_pace_perform_key_agreement), apdu_replay_general_authenticate_pace_perform_key_agreement}
135 // lengths of the replay APDUs
136 static uint8_t apdu_lengths_replay[5];
138 // type of card (ISO 14443 A or B)
139 static char iso_type = 0;
141 //-----------------------------------------------------------------------------
142 // Wrapper for sending APDUs to type A and B cards
143 //-----------------------------------------------------------------------------
144 static int EPA_APDU(uint8_t *apdu, size_t length, uint8_t *response, uint16_t respmaxlen) {
145 switch (iso_type) {
146 case 'a':
147 #ifdef WITH_ISO14443a
148 return iso14_apdu(apdu, (uint16_t) length, false, response, respmaxlen, NULL);
149 #else
150 (void) apdu;
151 (void) length;
152 (void) response;
153 (void) respmaxlen;
154 return PM3_ENOTIMPL;
155 #endif
156 case 'b':
157 #ifdef WITH_ISO14443b
158 return iso14443b_apdu(apdu, length, false, response, respmaxlen, NULL, NULL);
159 #else
160 (void) apdu;
161 (void) length;
162 (void) response;
163 (void) respmaxlen;
164 return PM3_ENOTIMPL;
165 #endif
166 default:
167 return 0;
171 //-----------------------------------------------------------------------------
172 // Closes the communication channel and turns off the field
173 //-----------------------------------------------------------------------------
174 static void EPA_Finish(void) {
175 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
176 LEDsoff();
177 iso_type = 0;
180 //-----------------------------------------------------------------------------
181 // Parses DER encoded data, e.g. from EF.CardAccess and fills out the given
182 // structs. If a pointer is 0, it is ignored.
183 // The function returns 0 on success and if an error occurred, it returns the
184 // offset where it occurred.
186 // TODO: This function can access memory outside of the given data if the DER
187 // encoding is broken
188 // TODO: Support skipping elements with a length > 0x7F
189 // TODO: Support OIDs with a length > 7F
190 // TODO: Support elements with long tags (tag is longer than 1 byte)
191 // TODO: Support proprietary PACE domain parameters
192 //-----------------------------------------------------------------------------
193 static size_t EPA_Parse_CardAccess(const uint8_t *data, size_t length, pace_version_info_t *pace_info) {
195 size_t index = 0;
197 while (index <= length - 2) {
198 // determine type of element
199 // SET or SEQUENCE
200 if (data[index] == 0x31 || data[index] == 0x30) {
201 // enter the set (skip tag + length)
202 index += 2;
203 // check for extended length
204 if ((data[index - 1] & 0x80) != 0) {
205 index += (data[index - 1] & 0x7F);
209 // OID
210 else if (data[index] == 0x06) {
211 // is this a PACE OID?
212 if (data[index + 1] == 0x0A // length matches
213 && memcmp(data + index + 2, oid_pace_start, sizeof(oid_pace_start)) == 0 // content matches
214 && pace_info != NULL) {
216 // first, clear the pace_info struct
217 memset(pace_info, 0, sizeof(pace_version_info_t));
219 memcpy(pace_info->oid, data + index + 2, sizeof(pace_info->oid));
221 // a PACE OID is followed by the version
222 index += data[index + 1] + 2;
224 if (data[index] == 02 && data[index + 1] == 01) {
225 pace_info->version = data[index + 2];
226 index += 3;
227 } else {
228 return index;
230 // after that there might(!) be the parameter ID
231 if (data[index] == 02 && data[index + 1] == 01) {
232 pace_info->parameter_id = data[index + 2];
233 index += 3;
236 } else {
237 // skip this OID
238 index += 2 + data[index + 1];
241 // if the length is 0, something is wrong
242 // TODO: This needs to be extended to support long tags
243 else if (data[index + 1] == 0) {
244 return index;
245 } else {
246 // skip this part
247 // TODO: This needs to be extended to support long tags
248 // TODO: This needs to be extended to support unknown elements with
249 // a size > 0x7F
250 index += 2 + data[index + 1];
254 // TODO: We should check whether we reached the end in error, but for that
255 // we need a better parser (e.g. with states like IN_SET or IN_PACE_INFO)
256 return 0;
259 //-----------------------------------------------------------------------------
260 // Read the file EF.CardAccess and save it into a buffer (at most max_length bytes)
261 // Returns -1 on failure or the length of the data on success
262 // TODO: for the moment this sends only 1 APDU regardless of the requested length
263 //-----------------------------------------------------------------------------
264 static int EPA_Read_CardAccess(uint8_t *buffer, size_t max_length) {
265 // the response APDU of the card
266 // since the card doesn't always care for the expected length we send it,
267 // we reserve 262 bytes here just to be safe (256-byte APDU + SW + ISO frame)
268 uint8_t response_apdu[262];
270 // select the file EF.CardAccess
271 int rapdu_length = EPA_APDU((uint8_t *)apdu_select_binary_cardaccess,
272 sizeof(apdu_select_binary_cardaccess),
273 response_apdu,
274 sizeof(response_apdu)
277 if (rapdu_length < 6
278 || response_apdu[rapdu_length - 4] != 0x90
279 || response_apdu[rapdu_length - 3] != 0x00) {
280 DbpString("Failed to select EF.CardAccess!");
281 return -1;
284 // read the file
285 rapdu_length = EPA_APDU((uint8_t *)apdu_read_binary,
286 sizeof(apdu_read_binary),
287 response_apdu,
288 sizeof(response_apdu)
291 if (rapdu_length <= 6
292 || response_apdu[rapdu_length - 4] != 0x90
293 || response_apdu[rapdu_length - 3] != 0x00) {
294 Dbprintf("Failed to read EF.CardAccess!");
295 return -1;
298 // copy the content into the buffer
299 // length of data available: apdu_length - 4 (ISO frame) - 2 (SW)
300 size_t len = rapdu_length - 6;
301 len = len < max_length ? len : max_length;
302 memcpy(buffer, response_apdu + 2, len);
303 return len;
306 //-----------------------------------------------------------------------------
307 // Abort helper function for EPA_PACE_Collect_Nonce
308 // sets relevant data in ack, sends the response
309 //-----------------------------------------------------------------------------
310 static void EPA_PACE_Collect_Nonce_Abort(uint32_t cmd, uint8_t step, int func_return) {
311 // power down the field
312 EPA_Finish();
314 // send the USB packet
315 reply_mix(cmd, step, func_return, 0, 0, 0);
318 //-----------------------------------------------------------------------------
319 // Acquire one encrypted PACE nonce
320 //-----------------------------------------------------------------------------
321 void EPA_PACE_Collect_Nonce(const PacketCommandNG *c) {
323 * ack layout:
324 * arg:
325 * 1. element
326 * step where the error occurred or 0 if no error occurred
327 * 2. element
328 * return code of the last executed function
329 * d:
330 * Encrypted nonce
332 // set up communication
333 int func_return = EPA_Setup();
334 if (func_return != 0) {
335 EPA_PACE_Collect_Nonce_Abort(CMD_HF_EPA_COLLECT_NONCE, 1, func_return);
336 return;
339 // read the CardAccess file
340 // this array will hold the CardAccess file
341 uint8_t card_access[256] = {0};
342 int cardlen = EPA_Read_CardAccess(card_access, 256);
343 // the response has to be at least this big to hold the OID
344 if (cardlen < 18) {
345 EPA_PACE_Collect_Nonce_Abort(CMD_HF_EPA_COLLECT_NONCE, 2, cardlen);
346 return;
349 // this will hold the PACE info of the card
350 pace_version_info_t pace_version_info;
352 // search for the PACE OID
353 func_return = EPA_Parse_CardAccess(card_access, cardlen, &pace_version_info);
355 if (func_return != 0 || pace_version_info.version == 0) {
356 EPA_PACE_Collect_Nonce_Abort(CMD_HF_EPA_COLLECT_NONCE, 3, func_return);
357 return;
360 // initiate the PACE protocol
361 // use the CAN for the password since that doesn't change
362 func_return = EPA_PACE_MSE_Set_AT(pace_version_info, 2);
363 // check if the command succeeded
364 if (func_return != 0) {
365 EPA_PACE_Collect_Nonce_Abort(CMD_HF_EPA_COLLECT_NONCE, 4, func_return);
366 return;
369 // now get the nonce
370 uint8_t nonce[256] = {0};
372 struct p {
373 uint32_t m;
374 } PACKED;
375 const struct p *packet = (const struct p *)c->data.asBytes;
377 func_return = EPA_PACE_Get_Nonce(packet->m, nonce);
378 // check if the command succeeded
379 if (func_return < 0) {
380 EPA_PACE_Collect_Nonce_Abort(CMD_HF_EPA_COLLECT_NONCE, 5, func_return);
381 return;
384 EPA_Finish();
386 // save received information
387 reply_mix(CMD_HF_EPA_COLLECT_NONCE, 0, func_return, 0, nonce, func_return);
390 //-----------------------------------------------------------------------------
391 // Performs the "Get Nonce" step of the PACE protocol and saves the returned
392 // nonce. The caller is responsible for allocating enough memory to store the
393 // nonce. Note that the returned size might be less or than or greater than the
394 // requested size!
395 // Returns the actual size of the nonce on success or a less-than-zero error
396 // code on failure.
397 //-----------------------------------------------------------------------------
398 static int EPA_PACE_Get_Nonce(uint8_t requested_length, uint8_t *nonce) {
400 // build the APDU
401 uint8_t apdu[sizeof(apdu_general_authenticate_pace_get_nonce) + 1];
403 // copy the constant part
404 memcpy(apdu, apdu_general_authenticate_pace_get_nonce, sizeof(apdu_general_authenticate_pace_get_nonce));
406 // append Le (requested length + 2 due to tag/length taking 2 bytes) in RAPDU
407 apdu[sizeof(apdu_general_authenticate_pace_get_nonce)] = requested_length + 4;
409 uint8_t response_apdu[262];
410 int send_return = EPA_APDU(apdu, sizeof(apdu), response_apdu, sizeof(response_apdu));
411 if (send_return < 6
412 || response_apdu[send_return - 4] != 0x90
413 || response_apdu[send_return - 3] != 0x00) {
414 return -1;
417 // if there is no nonce in the RAPDU, return here
418 if (send_return < 10) {
419 // no error
420 return 0;
422 // get the actual length of the nonce
423 uint8_t nonce_length = response_apdu[5];
424 if (nonce_length > send_return - 10) {
425 nonce_length = send_return - 10;
427 // copy the nonce
428 memcpy(nonce, response_apdu + 6, nonce_length);
430 return nonce_length;
433 //-----------------------------------------------------------------------------
434 // Initializes the PACE protocol by performing the "MSE: Set AT" step
435 // Returns 0 on success or a non-zero error code on failure
436 //-----------------------------------------------------------------------------
437 static int EPA_PACE_MSE_Set_AT(const pace_version_info_t pace_version_info, uint8_t password) {
438 // create the MSE: Set AT APDU
439 uint8_t apdu[23];
441 // the minimum length (will be increased as more data is added)
442 size_t apdu_length = 20;
444 // copy the constant part
445 memcpy(apdu, apdu_mse_set_at_start, sizeof(apdu_mse_set_at_start));
447 // type: OID
448 apdu[5] = 0x80;
450 // length of the OID
451 apdu[6] = sizeof(pace_version_info.oid);
453 // copy the OID
454 memcpy(apdu + 7, pace_version_info.oid, sizeof(pace_version_info.oid));
456 // type: password
457 apdu[17] = 0x83;
459 // length: 1
460 apdu[18] = 1;
462 // password
463 apdu[19] = password;
465 // if standardized domain parameters are used, copy the ID
466 if (pace_version_info.parameter_id != 0) {
467 apdu_length += 3;
468 // type: domain parameter
469 apdu[20] = 0x84;
470 // length: 1
471 apdu[21] = 1;
472 // copy the parameter ID
473 apdu[22] = pace_version_info.parameter_id;
476 // now set Lc to the actual length
477 apdu[4] = apdu_length - 5;
479 // send it
480 uint8_t response_apdu[6];
481 int send_return = EPA_APDU(apdu, apdu_length, response_apdu, sizeof(response_apdu));
483 Dbprintf("send ret %d bytes", send_return);
485 // Dbhexdump(send_return, response_apdu, false);
487 // check if the command succeeded
488 if (send_return != 6)
489 // && response_apdu[send_return - 4] != 0x90
490 // || response_apdu[send_return - 3] != 0x00)
492 return 1;
494 return 0;
497 //-----------------------------------------------------------------------------
498 // Perform the PACE protocol by replaying given APDUs
499 //-----------------------------------------------------------------------------
500 void EPA_PACE_Replay(const PacketCommandNG *c) {
502 uint32_t timings[ARRAYLEN(apdu_lengths_replay)] = {0};
504 // if an APDU has been passed, save it
505 if (c->oldarg[0] != 0) {
506 // make sure it's not too big
507 if (c->oldarg[2] > apdus_replay[c->oldarg[0] - 1].len) {
508 reply_mix(CMD_ACK, 1, 0, 0, NULL, 0);
510 memcpy(apdus_replay[c->oldarg[0] - 1].data + c->oldarg[1],
511 c->data.asBytes,
512 c->oldarg[2]);
513 // save/update APDU length
514 if (c->oldarg[1] == 0) {
515 apdu_lengths_replay[c->oldarg[0] - 1] = c->oldarg[2];
516 } else {
517 apdu_lengths_replay[c->oldarg[0] - 1] += c->oldarg[2];
519 reply_mix(CMD_ACK, 0, 0, 0, NULL, 0);
520 return;
523 // return value of a function
524 int func_return;
526 // set up communication
527 func_return = EPA_Setup();
528 if (func_return != 0) {
529 EPA_Finish();
530 reply_mix(CMD_ACK, 2, func_return, 0, NULL, 0);
531 return;
534 // increase the timeout (at least some cards really do need this!)/////////////
535 // iso14a_set_timeout(0x0003FFFF);
537 // response APDU
538 uint8_t response_apdu[300] = {0};
540 // now replay the data and measure the timings
541 for (int i = 0; i < ARRAYLEN(apdu_lengths_replay); i++) {
542 StartCountUS();
543 func_return = EPA_APDU(apdus_replay[i].data,
544 apdu_lengths_replay[i],
545 response_apdu,
546 sizeof(response_apdu)
548 timings[i] = GetCountUS();
549 // every step but the last one should succeed
550 if (i < ARRAYLEN(apdu_lengths_replay) - 1
551 && (func_return < 6
552 || response_apdu[func_return - 4] != 0x90
553 || response_apdu[func_return - 3] != 0x00)) {
554 EPA_Finish();
555 reply_mix(CMD_ACK, 3 + i, func_return, 0, timings, 20);
556 return;
559 EPA_Finish();
560 reply_mix(CMD_ACK, 0, 0, 0, timings, 20);
561 return;
564 //-----------------------------------------------------------------------------
565 // Set up a communication channel (Card Select, PPS)
566 // Returns 0 on success or a non-zero error code on failure
567 //-----------------------------------------------------------------------------
568 static int EPA_Setup(void) {
570 #ifdef WITH_ISO14443a
572 // first, look for type A cards
573 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
574 // power up the field
575 iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD);
576 iso14a_card_select_t card_a_info;
577 int return_code = iso14443a_select_card(NULL, &card_a_info, NULL, true, 0, false);
579 if (return_code == 1) {
580 uint8_t pps_response[3];
581 uint8_t pps_response_par[1];
582 // send the PPS request
583 ReaderTransmit((uint8_t *)pps, sizeof(pps), NULL);
584 return_code = ReaderReceive(pps_response, sizeof(pps_response), pps_response_par);
585 if (return_code != 3 || pps_response[0] != 0xD0) {
586 return return_code == 0 ? 2 : return_code;
588 Dbprintf("ISO 14443 Type A");
589 iso_type = 'a';
590 return 0;
593 #endif
594 #ifdef WITH_ISO14443b
596 // if we're here, there is no type A card, so we look for type B
597 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
598 // power up the field
599 iso14443b_setup();
600 iso14b_card_select_t card_b_info;
601 int return_code = iso14443b_select_card(&card_b_info);
603 if (return_code == 0) {
604 Dbprintf("ISO 14443 Type B");
605 iso_type = 'b';
606 return 0;
609 #endif
610 Dbprintf("No card found");
611 return 1;
614 void EPA_PACE_Simulate(const PacketCommandNG *c) {
616 //---------Initializing---------
618 // Get password from arguments
619 unsigned char pwd[6];
620 memcpy(pwd, c->data.asBytes, 6);
622 // Set up communication with the card
623 int res = EPA_Setup();
624 if (res != 0) {
625 EPA_PACE_Collect_Nonce_Abort(CMD_HF_EPA_PACE_SIMULATE, 1, res);
626 return;
629 // Read EF.CardAccess
630 uint8_t card_access[210] = {0};
631 int card_access_length = EPA_Read_CardAccess(card_access, 210);
633 // The response has to be at least this big to hold the OID
634 if (card_access_length < 18) {
635 EPA_PACE_Collect_Nonce_Abort(CMD_HF_EPA_PACE_SIMULATE, 2, card_access_length);
636 return;
639 // PACEInfo of the card
640 pace_version_info_t pace_version_info;
642 // Search for the PACE OID
643 res = EPA_Parse_CardAccess(card_access, card_access_length, &pace_version_info);
645 if (res != 0 || pace_version_info.version == 0) {
646 EPA_PACE_Collect_Nonce_Abort(CMD_HF_EPA_PACE_SIMULATE, 3, res);
647 return;
650 Dbprintf("Standardized Domain Parameter: %i", pace_version_info.parameter_id);
651 DbpString("");
652 DbpString("finished");