-
Notifications
You must be signed in to change notification settings - Fork 4
/
smartcard_iso7816.c
2372 lines (2179 loc) · 68.9 KB
/
smartcard_iso7816.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "libc/stdio.h"
#include "libc/nostd.h"
#include "libc/string.h"
#include "libc/syscall.h"
#include "libdrviso7816.h"
#include "api/libiso7816.h"
static volatile uint32_t SC_current_sc_frequency = SMARTCARD_DEFAULT_CLK_FREQ;
/* Get the current smartcard configured frequency */
static uint32_t SC_get_sc_clock_freq(void){
return SC_current_sc_frequency;
}
static volatile uint32_t SC_current_sc_etu = SMARTCARD_DEFAULT_ETU;
/* Get the current smartcard configured ETU */
static uint32_t SC_get_sc_etu(void){
return SC_current_sc_etu;
}
/* Fixed delay of a given number of clock cycles */
static void SC_delay_sc_clock_cycles(uint32_t sc_clock_cycles_timeout){
uint64_t t, start_tick, curr_tick;
uint32_t clock_freq = SC_get_sc_clock_freq();
if(sc_clock_cycles_timeout == 0){
return;
}
/* The timeout is in smartcard clock cycles, which can be converted to MCU clock time
* using a simple conversion. The clock time is expressed in microseconds.
*/
if(clock_freq == 0){
/* Avoid division by zero */
return;
}
t = (sc_clock_cycles_timeout * 1000000ULL) / clock_freq;
start_tick = platform_get_microseconds_ticks();
/* Now wait */
curr_tick = start_tick;
while((curr_tick - start_tick) <= t){
curr_tick = platform_get_microseconds_ticks();
}
return;
}
/* Fixed delay of a given number of ETUs */
static void SC_delay_etu(uint32_t etu_timeout){
SC_delay_sc_clock_cycles(etu_timeout * SC_get_sc_etu());
return;
}
typedef enum {
SC_TS_DIRECT_CONVENTION = 0,
SC_TS_INVERSE_CONVENTION = 1,
} Sc_convention;
static volatile uint8_t SC_convention = SC_TS_DIRECT_CONVENTION;
static uint8_t SC_is_inverse_conv(void){
if(SC_convention == SC_TS_DIRECT_CONVENTION){
return 0;
}
else{
return 1;
}
}
static int SC_set_direct_conv(void){
/* Set the inverse convention */
SC_convention = SC_TS_DIRECT_CONVENTION;
return platform_SC_set_direct_conv();
}
static int SC_set_inverse_conv(void){
/* Set the inverse convention */
SC_convention = SC_TS_INVERSE_CONVENTION;
return platform_SC_set_inverse_conv();
}
static uint8_t SC_inverse_conv(uint8_t c){
unsigned int i;
uint8_t res = 0;
for(i = 0; i < 8; i++){
res |= (((~c) >> i) & 0x1) << (7-i);
}
return res;
}
/* Wait a delay when switching direction in order to respect the EMV co Book1
* specification.
* "For the ICC or terminal, the minimum interval between the leading edges of the
* start bits of the last character received and the first character sent in the
* opposite direction shall be 16 etus."
*
* We wait 4 ETUs since 12 ETUs has been spent receiving the last character received.
*/
static inline uint32_t SC_get_delay_EMV(void){
return 4;
}
static inline void SC_delay_EMV(void){
SC_delay_etu(SC_get_delay_EMV());
return;
}
/* Get a byte with a timeout. Timeout of 0 means forever. */
static int SC_getc_timeout(uint8_t *c, uint32_t etu_timeout){
uint64_t t, start_tick, curr_tick;
uint32_t clock_freq = SC_get_sc_clock_freq();
/* The timeout is in ETU times, which can be converted to sys ticks
* using the baud rate. The sys ticks are expressed in microseconds.
*/
if(clock_freq == 0){
/* Avoid division by zero */
return -1;
}
t = (etu_timeout * SC_get_sc_etu() * 1000000ULL) / clock_freq;
start_tick = platform_get_microseconds_ticks();
while(platform_SC_getc(c, t, 0)){
if(etu_timeout != 0){
curr_tick = platform_get_microseconds_ticks();
/* Check the timeout and return if time is elapsed */
if((curr_tick - start_tick) > t){
/* Reset our getc state machine in the lower layers ... */
platform_SC_getc(c, t, 1);
return -1;
}
}
}
if(SC_is_inverse_conv()){
*c = SC_inverse_conv(*c);
}
return 0;
}
static int SC_putc_timeout(uint8_t c, uint32_t etu_timeout){
uint64_t t, start_tick, curr_tick;
uint32_t clock_freq = SC_get_sc_clock_freq();
if(SC_is_inverse_conv()){
c = SC_inverse_conv(c);
}
/* The timeout is in ETU times, which can be converted to sys ticks
* using the baud rate. The sys ticks are expressed in microseconds.
*/
if(clock_freq == 0){
/* Avoid division by zero */
return -1;
}
t = (etu_timeout * SC_get_sc_etu() * 1000000ULL) / clock_freq;
start_tick = platform_get_microseconds_ticks();
while(platform_SC_putc(c, t, 0)){
if(etu_timeout != 0){
curr_tick = platform_get_microseconds_ticks();
/* Check the timeout and return if time is elapsed */
if((curr_tick - start_tick) > t){
/* Reset our putc state machine in the lower layers ... */
platform_SC_putc(c, t, 1);
return -1;
}
}
}
/* Wait for the character extra guard time after the stop bit */
SC_delay_etu(CGT_character_guard_time);
return 0;
}
static int SC_adapt_clocks(uint32_t etu, uint32_t frequency){
uint32_t tmp_etu = etu;
uint32_t tmp_frequency = frequency;
if(platform_SC_adapt_clocks(&tmp_etu, &tmp_frequency)){
return -1;
}
else{
SC_current_sc_frequency = tmp_frequency;
SC_current_sc_etu = tmp_etu;
return 0;
}
}
/* Get the ATR from the card */
int SC_get_ATR(SC_ATR *atr){
unsigned int i;
uint8_t curr_mask, checksum, do_check_checksum = 0;
if(atr == NULL){
goto err;
}
/* Cleanup our lower layer */
platform_SC_flush();
/* Default values per standard */
atr->D_i_curr = 1;
atr->F_i_curr = SMARTCARD_DEFAULT_ETU;
atr->f_max_curr = SMARTCARD_DEFAULT_CLK_FREQ;
atr->T_protocol_curr = 0;
atr->ifsc = 0;
for(i = 0; i < SETUP_LENGTH; i++){
atr->t_mask[i] = 0;
}
atr->h_num = 0;
/* Wait for the ATR reception with a timeout
* of 20160 ETU (20160 bauds).
*/
/******************************/
if(SC_getc_timeout(&(atr->ts), ATR_ETU_TIMEOUT)){
goto err;
}
/* First byte of the ATR has been received */
if(atr->ts == 0x3b){
if(SC_set_direct_conv()){
goto err;
}
}
else if(atr->ts == 0x03){
if(SC_set_inverse_conv()){
goto err;
}
atr->ts = SC_inverse_conv(atr->ts);
}
else{
goto err;
}
/* Get the format byte T0 */
if(SC_getc_timeout(&(atr->t0), WT_wait_time)){
goto err;
}
checksum = atr->t0;
/* Get the interface bytes */
curr_mask = (atr->t0) >> 4;
for(i = 0; i < SETUP_LENGTH; i++){
if(curr_mask & 0x1){
/* Should not happen but better safe than sorry ... */
if(i >= sizeof(atr->ta)){
goto err;
}
if(SC_getc_timeout(&(atr->ta[i]), WT_wait_time)){
goto err;
}
atr->t_mask[0] |= (0x1 << i);
checksum ^= atr->ta[i];
}
if(curr_mask & 0x2){
/* Should not happen but better safe than sorry ... */
if(i >= sizeof(atr->tb)){
goto err;
}
if(SC_getc_timeout(&(atr->tb[i]), WT_wait_time)){
goto err;
}
atr->t_mask[1] |= (0x1 << i);
checksum ^= atr->tb[i];
}
if(curr_mask & 0x4){
/* Should not happen but better safe than sorry ... */
if(i >= sizeof(atr->tc)){
goto err;
}
if(SC_getc_timeout(&(atr->tc[i]), WT_wait_time)){
goto err;
}
atr->t_mask[2] |= (0x1 << i);
checksum ^= atr->tc[i];
}
if(curr_mask & 0x8){
/* Should not happen but better safe than sorry ... */
if(i >= sizeof(atr->td)){
goto err;
}
if(SC_getc_timeout(&(atr->td[i]), WT_wait_time)){
goto err;
}
atr->t_mask[3] |= (0x1 << i);
checksum ^= atr->td[i];
curr_mask = atr->td[i] >> 4;
if((atr->td[i] & 0x0f) != 0){
do_check_checksum = 1;
}
}
else{
break;
}
}
/* Get the historical bytes */
atr->h_num = atr->t0 & 0x0f;
for(i = 0; i < atr->h_num; i++){
/* Check for overflow: should not happen but better
* safe than sorry
*/
if((i >= sizeof(atr->h)) || (atr->h_num > sizeof(atr->h))){
/* Overflow: get out! */
goto err;
}
if(SC_getc_timeout(&(atr->h[i]), WT_wait_time)){
goto err;
}
checksum ^= atr->h[i];
}
atr->tck = 0;
atr->tck_present = 0;
/* The checksum TCK is present if and only if any of the TDi encode a protocol != 0 */
if(do_check_checksum){
atr->tck_present = 1;
/* Get the checksum */
if(SC_getc_timeout(&(atr->tck), WT_wait_time)){
goto err;
}
/* Check the checksum */
if(checksum != atr->tck){
log_printf("Smartcard ATR checksum error ...\n");
goto err;
}
}
return 0;
err:
return -1;
}
/* Print the ATR on the console */
void SC_iso7816_print_ATR(SC_ATR *atr)
{
unsigned int i;
if(atr == NULL){
return;
}
log_printf("===== ATR ============\n");
log_printf("TS = %x, T0 = %x\n", atr->ts, atr->t0);
for(i = 0; i < 4; i++){
if(atr->t_mask[0] & (0x1 << i)){
log_printf("TA[%d] = %x\n", i, atr->ta[i]);
}
}
for(i = 0; i < 4; i++){
if(atr->t_mask[1] & (0x1 << i)){
log_printf("TB[%d] = %x\n", i, atr->tb[i]);
}
}
for(i = 0; i < 4; i++){
if(atr->t_mask[2] & (0x1 << i)){
log_printf("TC[%d] = %x\n", i, atr->tc[i]);
}
}
for(i = 0; i < 4; i++){
if(atr->t_mask[3] & (0x1 << i)){
log_printf("TD[%d] = %x\n", i, atr->td[i]);
}
}
for(i = 0; i < (atr->h_num & 0x0f); i++){
log_printf("H[%d] = %x\n", i, atr->h[i]);
}
if(atr->tck_present){
log_printf("TCK = %x\n", atr->tck);
}
log_printf("F=%d, D=%d, fmax=%d\n", atr->F_i_curr, atr->D_i_curr, atr->f_max_curr);
return;
}
/* Interval in ETU between the last received bye from the card and the next byte sent by the terminal */
uint32_t GT_receive_send_interval_etu = 0;
/* [RB] FIXME: for now, the PTS/PSS negotation is a work in
* progress and has not been exhaustively tested/debugged.
*/
/* PTS (Protocol Type Selection) negotiation.
* Returns the protocol that has been negotiated.
*/
static int SC_negotiate_PTS(SC_ATR *atr, uint8_t *T_protocol, uint8_t do_negotiate_pts, uint8_t do_change_baud_rate, uint8_t do_force_protocol, uint32_t do_force_etu){
uint8_t ta1, td1;
uint32_t etu_curr = 0;
uint8_t negotiable_mode = 1;
uint8_t extra_guard_time = 1;
uint8_t asked_ta1 = 0, asked_tc1 = 0;
uint8_t pck;
uint8_t c;
if((atr == NULL) || (T_protocol == NULL)){
goto err;
}
/* Cleanup our lower layer */
platform_SC_flush();
/* Check TA2 to see if we cannot negotiate */
if(atr->t_mask[0] & (0x1 << 1)){
/* The card supports specific mode */
log_printf("[Smartcard] TA2 present, implies specific mode\n");
negotiable_mode = 0;
}
else{
/* The card supports negotiable mode */
log_printf("[Smartcard] TA2 absent, implies negotiable mode\n");
negotiable_mode = 1;
}
/* Do we have TA1? If not, assume it is 0x11 (Fi = 372 and Di = 1) */
if(atr->t_mask[0] & 0x1){
ta1 = atr->ta[0];
asked_ta1 = 1;
}
else{
ta1 = 0x11;
}
/* T=0 is the default protocol if nothing is specified by the card */
*T_protocol = 0;
/* Do we have TD1? If yes, this is the preferred protocol. Use it, unless we have been overriden with
* a specific choice.
*/
if((atr->t_mask[3] & 0x1) && (do_force_protocol == 0)){
td1 = atr->td[0];
*T_protocol = td1 & 0x0f;
log_printf("[Smartcard] ATR prefered protocol T=%d\n", *T_protocol);
if((*T_protocol != 0) && (*T_protocol != 1)){
/* We do not support T=15 or protocols other than T=0/T=1 */
log_printf("[Smartcard] Asking for unsupported protocol T=%d\n", *T_protocol);
goto err;
}
}
if(do_force_protocol){
if(do_force_protocol > 2){
log_printf("[Smartcard] Asking for unsupported *user forced* protocol T=%d\n", (do_force_protocol - 1));
goto err;
}
*T_protocol = (do_force_protocol - 1);
}
atr->T_protocol_curr = *T_protocol;
if(do_change_baud_rate){
/* Get asked Di, Fi and fmax */
atr->D_i_curr = D_i[ta1 & 0x0f];
atr->F_i_curr = F_i[ta1 >> 4];
atr->f_max_curr = f_max[ta1 >> 4];
/* Is the using forcing a specific ETU? */
if(do_force_etu){
if(atr->D_i_curr != 0){
log_printf("[Smartcard] Current maximum Fi=%d, Di=%d, ETU=%d, user asked for %d ...\n", atr->F_i_curr, atr->D_i_curr, atr->F_i_curr / atr->D_i_curr, do_force_etu);
}
else{
log_printf("[Smartcard] Current maximum Fi=%d, Di=%d, user asked for %d ...\n", atr->F_i_curr, atr->D_i_curr, do_force_etu);
}
/* Find a suitable ETU with Fi and the possible values of Di */
unsigned int i = ta1 & 0x0f;
uint32_t etu_tmp = 0;
while(1){
if(i == 0){
log_printf("[Smartcard] Error: forcing ETU to %d failed ...\n", do_force_etu);
goto err;
}
if(D_i[i] != 0){
if((D_i[i] & 0xffff) == 0){
/* Di is not a fraction */
etu_tmp = atr->F_i_curr * (D_i[i] >> 16);
}
else{
/* Di is a fraction */
etu_tmp = atr->F_i_curr / D_i[i];
}
if(etu_tmp < do_force_etu){
i--;
}
else{
break;
}
}
else{
i--;
}
}
atr->D_i_curr = D_i[i];
log_printf("[Smartcard] Trying Fi=%d, Di=%d, ETU=%d as the best choice compared to asked %d\n", atr->F_i_curr, atr->D_i_curr, etu_tmp, do_force_etu);
}
/* If the card is asking for a forbidden value, return */
if((atr->D_i_curr == 0) || (atr->F_i_curr == 0) || (atr->f_max_curr == 0)){
log_printf("[Smartcard] PSS/PTS error (asking for impossible Fi = %d and/or Di = %d)\n", atr->F_i_curr, atr->D_i_curr);
goto err;
}
/* Compute our new ETU */
if((atr->D_i_curr & 0xffff) == 0){
/* Di is a fraction */
etu_curr = atr->F_i_curr * (atr->D_i_curr >> 16);
}
else{
/* Di is not a fraction */
etu_curr = atr->F_i_curr / atr->D_i_curr;
}
/* Adapt our baudrate and clock frequency to what the card is asking,
*/
/* In specific mode, we change the Baudrate *before* sending the PPS */
if(negotiable_mode == 0){
log_printf("[Smartcard] Switching to ETU = %d (Di = %d, Fi = %d), guard time = %d, max_frequency = %d, Protocol T=%d\n", etu_curr, atr->D_i_curr, atr->F_i_curr, extra_guard_time, atr->f_max_curr, *T_protocol);
if(SC_adapt_clocks(etu_curr, atr->f_max_curr)){
goto err;
}
}
}
/* Adapt the Guard Time per TC1 if necessary */
if(atr->t_mask[2] & 0x1){
/* We have a TC1 representing the prefered guard time */
extra_guard_time = atr->tc[0];
/* Handle special value 0xff */
if(extra_guard_time == 0xff){
if(*T_protocol == 0){
extra_guard_time = 0;
}
else if(*T_protocol == 1){
/* TC1 = 0xff means that we must reduce our standard 2 ETU guard time
* to 1 ETU for 'agressive' performance mode. Our underlying physical layer
* might not handle such a parameter, hence for now we return an error.
*/
if(platform_smartcard_set_1ETU_guardtime()){
log_printf("[Smartcard] PSS/PTS error: TC1=0xff for T=1 means unsupported ETU=1 ...\n");
goto err;
}
extra_guard_time = 0;
}
else{
goto err;
}
}
asked_tc1 = 1;
/* Add the extra guard time to our CGT */
CGT_character_guard_time += extra_guard_time;
}
if(do_negotiate_pts){
/* New baudrate to negotiate */
uint8_t new_baud_rate = 0;
/* Default TA1 in case where we do not want to neogtiate the baud rate */
uint8_t default_ta1 = 0x11;
/****** Send the PTS to the card ******/
/* Wait in order to respect the 16 ETU guard time
* specified by the EMV co specifications when switching direction
*/
SC_delay_EMV();
pck = 0;
/* Send PTSS */
if(SC_putc_timeout(0xff, WT_wait_time)){
log_printf("[Smartcard] PSS/PTS error (PSS byte 0xff)\n");
goto err;
}
pck ^= 0xff;
/* Send PTS0 telling that we will apply new Fi/Di (PTS1) */
if(SC_putc_timeout((asked_ta1 << 4) | (*T_protocol), WT_wait_time)){
log_printf("[Smartcard] PSS/PTS error (byte PTS0)\n");
goto err;
}
pck ^= (asked_ta1 << 4) | (*T_protocol);
/* Send PTS1 if necessary */
if(asked_ta1){
if(do_change_baud_rate){
unsigned int i;
for(i = 0; i < sizeof(F_i) / sizeof(uint32_t); i++){
if(atr->F_i_curr == F_i[i]){
new_baud_rate = (i << 4);
break;
}
}
for(i = 0; i < sizeof(D_i) / sizeof(uint32_t); i++){
if(atr->D_i_curr == D_i[i]){
new_baud_rate ^= (i & 0x0f);
break;
}
}
if(SC_putc_timeout(new_baud_rate, WT_wait_time)){
log_printf("[Smartcard] PSS/PTS error (byte PTS1)\n");
goto err;
}
pck ^= new_baud_rate;
}
else{
if(SC_putc_timeout(default_ta1, WT_wait_time)){
log_printf("[Smartcard] PSS/PTS error (byte PTS1)\n");
goto err;
}
pck ^= default_ta1;
}
}
/* Send the checksum */
if(SC_putc_timeout(pck, WT_wait_time)){
log_printf("[Smartcard] PSS/PTS error (byte PTS checksum)\n");
goto err;
}
/* Now check that the card agrees to our PTS */
/* Check for PSS = 0xff */
if(SC_getc_timeout(&c, WT_wait_time)){
log_printf("[Smartcard] PSS/PTS error (0xff ACK error in receive)\n");
goto err;
}
if(c != 0xff){
log_printf("[Smartcard] PSS/PTS error (0xff ACK error, values differ)\n");
goto err;
}
/* Check for PTS0 */
if(SC_getc_timeout(&c, WT_wait_time)){
log_printf("[Smartcard] PSS/PTS error (PTS0 ACK error in receive)\n");
goto err;
}
if(c != ((asked_ta1 << 4) | (*T_protocol))){
log_printf("[Smartcard] PSS/PTS error (PTS0 ACK error, values differ)\n");
goto err;
}
/* Optionally check for PTS1 */
if(asked_ta1){
if(SC_getc_timeout(&c, WT_wait_time)){
log_printf("[Smartcard] PSS/PTS error (PTS1 ACK error in receive)\n");
goto err;
}
if(do_change_baud_rate){
if(c != new_baud_rate){
log_printf("[Smartcard] PSS/PTS error (PTS1 ACK error, values differ)\n");
goto err;
}
}
else{
if(c != default_ta1){
log_printf("[Smartcard] PSS/PTS error (PTS1 ACK error, values differ)\n");
goto err;
}
}
}
/* Check for the PCK checksum */
if(SC_getc_timeout(&c, WT_wait_time)){
log_printf("[Smartcard] PSS/PTS error (PTS checksum ACK error in receive)\n");
goto err;
}
if(c != pck){
log_printf("[Smartcard] PSS/PTS error (PTS checksum ACK error, values differ)\n");
goto err;
}
log_printf("[Smartcard] PSS/PTS success: PTS sent and confirmed by the card!\n");
}
if(do_change_baud_rate){
/* Adapt the Work Waiting Time for T=0 */
uint8_t wi = 10; /* default value */
if(atr->t_mask[2] & (0x1 << 1)){
/* Handle the specific T=0 ATR TC2 byte here, specifying the Work Waiting Time.
* NOTE: TC2 = 0x00 is reserved for future use, so we do not update wi in this case.
*/
if(atr->tc[1] != 0){
wi = atr->tc[1];
}
}
/* Work Waiting Time = 960 x D x WI */
WT_wait_time = 960 * atr->D_i_curr * wi;
/* NOTE: since our lower layer only triggers a successful reception *after*
* a full byte reception, it is hard to detect the leading edge of the next full byte since
* it is being received. Hence, in order for our CWT to fully work, we instead use the more
* conservative "two bytes detection" and add to the standard duration 14 ETU since our current
* layer will detect the detection only after the byte has been fully receive.
* (14 ETU = 12 ETU for reception + guard time + 2 ETU for conservative value)
*/
WT_wait_time = WT_wait_time + 14;
/* Set the USART clocks to the new settings if it is not already done yet.
*/
if(negotiable_mode == 1){
log_printf("[Smartcard] Switching to ETU = %d (Di = %d, Fi = %d), guard time = %d, max_frequency = %d, Protocol T=%d\n", etu_curr, atr->D_i_curr, atr->F_i_curr, extra_guard_time, atr->f_max_curr, *T_protocol);
if(SC_adapt_clocks(etu_curr, atr->f_max_curr)){
goto err;
}
}
}
/* Some specific stuff in ISO7816 */
/* In T=0, When using D = 64, the interface device shall ensure a delay of at least 16 etu between the leading edge of
* the last received character and the leading edge of the character transmitted for initiating a command. */
if((atr->D_i_curr == 64) && (*T_protocol == 0)){
GT_receive_send_interval_etu = 16;
}
else{
GT_receive_send_interval_etu = 0;
}
return 0;
err:
return -1;
}
/* Get the response of an APDU from the card in T=0.
* The response is a "raw" one, and the response fragmentation is handled
* in our upper T=0 functions layer.
* pull_type == 0 => we wait for a procedure byte (ACK, NULL byte, SW1)
* pull_type == 1 => we wait to get data + SW1/SW2 with no possible NULL bytes
* pull_type == 2 => we wait to get data + SW1/SW2 with a possible NULL byte
*
* wait_all_bytes == 1 => we wait for all the bytes from the card regardless of
* wait_all_bytes == 0 => we stop waiting when we have reached the Le bytes in the current APDU
*/
static int SC_pull_RESP_T0(SC_T0_APDU_cmd *apdu, SC_T0_APDU_resp *resp, unsigned char pull_type, unsigned char wait_all_bytes){
int ret;
uint8_t c;
uint8_t ack;
uint8_t ack_one_byte;
if((apdu == NULL) || (resp == NULL)){
goto err;
}
ack = apdu->ins;
ack_one_byte = apdu->ins ^ 0xff;
if(pull_type != 0){
goto GET_RESP_BYTES;
}
/* First, we wait for the data with a timeout of
* around some ETUs.
*/
WAIT_AGAIN:
if(resp->le >= (SHORT_APDU_LE_MAX + 2)){
/* Overflow ... Return an error */
goto err;
}
if(SC_getc_timeout(&(resp->data[resp->le]), WT_wait_time)){
goto err;
}
/* Check the received procedure byte */
if(resp->data[resp->le] == 0x60){
/* We have received a NULL byte, this is a lose way in T=0 of
* telling us to wait ...
*/
goto WAIT_AGAIN;
}
if((resp->data[resp->le] == ack) && ((resp->data[resp->le] & 0xf0) != 0x60) && ((resp->data[resp->le] & 0xf0) != 0x90)){
/* This is an ACK, go and send or receive all the data */
return 1;
}
if((resp->data[resp->le] == ack_one_byte) && ((resp->data[resp->le] & 0xf0) != 0x60) && ((resp->data[resp->le] & 0xf0) != 0x90)){
/* This is an ACK to send or receive one byte */
if(apdu->lc != 0){
/* Send one byte (return to the upper layer to deal with this) */
return 2;
}
else{
/* Receive one byte and got back to wait for a procedure byte, the other bytes should follow ... */
ret = SC_getc_timeout(&(resp->data[resp->le]), WT_wait_time);
if(ret){
/* Timeout reached without any byte, get out */
goto END;
}
resp->le++;
goto WAIT_AGAIN;
}
}
/* Then, we get the data and SW1/SW2
*/
resp->le++;
GET_RESP_BYTES:
while(1){
ret = SC_getc_timeout(&c, WT_wait_time);
if(ret){
/* Timeout reached without any byte, get out */
goto END;
}
else{
if(resp->le >= (SHORT_APDU_LE_MAX + 2)){
/* Overflow ... Return an error */
goto err;
}
/* A byte has been received, continue */
if((c == 0x60) && (pull_type == 2) && (resp->le == 0)){
/* If this a WAIT NULL byte and we could expect a procedure byte, we
* drop it and go back to waiting other bytes.
* NB: the WAIT NULL byte can only be the first one received.
*/
goto GET_RESP_BYTES;
}
resp->data[resp->le++] = c;
}
/* Do we wait for unexpected bytes or not? */
if(wait_all_bytes == 0){
/* If we did not have any procedure byte and end here, this means that the card directly sends us SW1/SW2 */
if(pull_type == 0){
if(resp->le >= 2){
goto END;
}
}
/* Check how many bytes we have compared to the expected Le
* and early finish if we already have the expected number of bytes.
*/
if(apdu->send_le != 0){
if((apdu->le != 0) && (resp->le >= (apdu->le + 2))){
goto END;
}
}
else{
/* No Le expected, exit when we have SW1/SW2 */
if(resp->le >= 2){
goto END;
}
}
}
}
END:
if(resp->le < 2){
/* We should have received at least two bytes (SW1 and SW2).
* If this is not the case, this is an erroneous answer.
*/
goto err;
}
/* Split the status bytes from the received data */
resp->le -= 2;
/* Sanity checks on sizes */
if(resp->le > SHORT_APDU_LE_MAX){
goto err;
}
resp->sw1 = resp->data[resp->le];
resp->sw2 = resp->data[resp->le+1];
return 0;
err:
if(resp != NULL){
resp->le = 0;
}
return -1;
}
#define SC_T0_WAIT_ALL_BYTES 0
/* Push TPDU in T=0 and pull the response from the card */
static int SC_push_pull_APDU_T0(SC_T0_APDU_cmd *apdu, SC_T0_APDU_resp *resp){
unsigned int i;
int ret;
uint16_t curr_send_byte;
if((apdu == NULL) || (resp == NULL)){
goto err;
}
/* Sanity checks on the lengths */
if(apdu->le > SHORT_APDU_LE_MAX){
/* Note: apdu->lc is on an uint8_t, so no need to check */
/* Return an error: in T=0,
* extended APDUs are handled at the upper layer level with the
* ENVELOPE command.
*/
goto err;
}
/* Sanity check on Le and Lc: we should not have
* a case 4 APDU here since its specific fragmentation
* is handled in the upper layer ... See page 36 in ISO7816-3:2006.
* As a result, we return an error here if we have a case 4 APDU.
*/
if((apdu->send_le != 0) && (apdu->lc != 0)){
log_printf("[Smartcard] T=0 case 4 APDU not fragmented ...\n");
goto err;
}
/* Initialize our response length */
resp->le = 0;
if(GT_receive_send_interval_etu < SC_get_delay_EMV()){
/* Wait in order to respect the 16 ETU guard time
* specified by the EMV co specifications when switching direction
*/
SC_delay_EMV();
}
else{
/* See ISO7816-3:2006 10.2:
* When using D = 64, the interface device shall ensure a delay of at least 16 etu between the leading edge of
* the last received character and the leading edge of the character transmitted for initiating a command.
*/
SC_delay_etu(GT_receive_send_interval_etu);
}
/* Push the header */
/* Send the CLA */
if(SC_putc_timeout(apdu->cla, WT_wait_time)){
goto err;
}
/* Send the INS */
if(SC_putc_timeout(apdu->ins, WT_wait_time)){
goto err;
}
/* Send P1 */
if(SC_putc_timeout(apdu->p1, WT_wait_time)){
goto err;
}
/* Send P2 */
if(SC_putc_timeout(apdu->p2, WT_wait_time)){
goto err;
}
/* Push P3 */
if(apdu->lc != 0){
/* Send Lc in one byte */
if(SC_putc_timeout(apdu->lc, WT_wait_time)){
goto err;
}
}
else{
/* Case 1 APDU or case 2? */
if(apdu->send_le){
/* Case 2 APDU: send Le in one byte */
if(SC_putc_timeout((apdu->le) & 0xff, WT_wait_time)){
goto err;
}
}
else{
/* We send a 0 as P3 in a case 1 APDU */
if(SC_putc_timeout(0x00, WT_wait_time)){
goto err;
}
}
}
curr_send_byte = 0;
GET_PROCEDURE_BYTE:
/* Get the procedure byte(s) and possibly the answer from the card */
ret = SC_pull_RESP_T0(apdu, resp, 0, SC_T0_WAIT_ALL_BYTES);
if(ret == -1){
goto err;
}
else if((ret == 1) || (ret == 2)){
if((ret == 2) && (curr_send_byte < apdu->lc)){
/* Wait in order to respect the 16 ETU guard time
* specified by the EMV co specifications when switching direction
*/
SC_delay_EMV();
/* Send only one byte and go to waiting a procedure byte */
if(SC_putc_timeout(apdu->data[curr_send_byte], WT_wait_time)){
goto err;
}
curr_send_byte++;
goto GET_PROCEDURE_BYTE;
}
if((ret == 1) && (curr_send_byte < apdu->lc)){
/* We had an ACK to send all our data */
if(apdu->lc != 0){
/* Wait in order to respect the 16 ETU guard time
* specified by the EMV co specifications when switching direction
*/
SC_delay_EMV();
/* Send the remaining data in one block as asked by the smartcard */
for(i = curr_send_byte; i < apdu->lc; i++){
if(SC_putc_timeout(apdu->data[i], WT_wait_time)){
goto err;
}
}
}
}
if(apdu->send_le){
/* Get our response from the card with NO possible WAIT byte since
* we wait data from the card.
*/
ret = SC_pull_RESP_T0(apdu, resp, 1, SC_T0_WAIT_ALL_BYTES);
}
else{
/* Get our response from the card with a possible WAIT byte since
* we do not wait data from the card.
*/
ret = SC_pull_RESP_T0(apdu, resp, 2, SC_T0_WAIT_ALL_BYTES);
}
if(ret != 0){
goto err;
}
}
else if(ret == 0){
/* This is an answer from the card */
return 0;
}
else{
/* Unexpected case, this is an error */
goto err;
}
return 0;
err:
return -1;
}
/* This primitive sends an APDU in T=0 and handles the request/response fragmentation
* by using ENVELOPE and GET_RESPONSE instructions whenever necessary (extended APDUs,
* case 4 APDUs, ...).
*/
static int SC_send_APDU_T0(SC_APDU_cmd *apdu, SC_APDU_resp *resp){