Repository navigation
Expand file tree
/
Copy pathtoken.c
More file actions
1870 lines (1677 loc) · 59.6 KB
/
Copy pathtoken.c
File metadata and controls
1870 lines (1677 loc) · 59.6 KB
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
/* Inlude elements related to ISO7816 and the board */
#include "autoconf.h"
#include "api/libtoken.h"
#include "libc/syscall.h"
#define SMARTCARD_DEBUG CONFIG_SMARTCARD_DEBUG
/* #define MEASURE_TOKEN_PERF */
#include "libc/stdio.h"
#include "libc/nostd.h"
#include "libc/string.h"
#include "libc/random.h"
#include "libc/sanhandlers.h"
/****** Token operations **************/
/* [RB] FIXME: the layer handling the encryption and the integrity should
* be abstracted and not dependent with the physical layer. For now these
* layers are mixed because of the way ISO7816-3 mixes layers, but there should
* be a clean way to split this and keep all the crypto code and the secure channel
* code independent of the transport layer (so that the exact same code handles
* tokens on ISO7816, I2C, SPI and so on).
*/
/* We describe hereafter the 'physical' layer to
* communicate with our token. the rationale is to
* distinguish between a 'clear text' channel before the
* ECDH, and a secure channel protected in confidentiality
* with AES-CTR and in integrity with a HMAC SHA256.
* We are deemed to use AES with 128-bit keys because of
* a limitation of our masked AES (robust against SCA) being
* limited to 128-bit key, and also to improve support with
* mainstream Javacard cards.
*/
#define MEASURE_TOKEN_PERF
/**** Load the curve parameters once and for all (optimization) ***/
static volatile bool curve_params_loaded = false;
static volatile ec_curve_type curr_curve_type = UNKNOWN_CURVE;
static ec_params g_curve_params;
int load_curve_parameters(ec_curve_type curve_type, ec_params **curve_p)
{
curve_params_loaded = false;
if(curve_p == NULL){
goto err;
}
*curve_p = NULL;
if((curve_params_loaded == true) && (curr_curve_type == curve_type)){
*curve_p = &g_curve_params;
curve_params_loaded = true;
return 0;
}
curr_curve_type = UNKNOWN_CURVE;
/* libecc internal structure holding the curve parameters */
const ec_str_params *the_curve_const_parameters;
the_curve_const_parameters = ec_get_curve_params_by_type(curve_type);
/* Get out if getting the parameters went wrong */
if (the_curve_const_parameters == NULL) {
goto err;
}
/* Now map the curve parameters to our libecc internal representation */
import_params(&g_curve_params, the_curve_const_parameters);
curr_curve_type = curve_type;
*curve_p = &g_curve_params;
curve_params_loaded = true;
return 0;
err:
return -1;
}
/* Token error recovery function */
void do_error_recovery_sleep(token_channel *channel){
if((channel != NULL) && (channel->error_recovery_sleep != 0)){
/* Choose a random value <= channel->error_recovery_sleep */
uint32_t rand_wait = 0;
if(get_random((unsigned char*)&rand_wait, sizeof(rand_wait))){
sys_sleep(channel->error_recovery_sleep, SLEEP_MODE_DEEP);
}
else{
sys_sleep(rand_wait % (channel->error_recovery_sleep), SLEEP_MODE_DEEP);
}
}
return;
}
/* Self-synchronization anti-replay window of 10 attempts of a maximum size of AES blocks in an APDU */
#define ANTI_REPLAY_SELF_SYNC_WINDOW (10*16)
int token_send_receive(token_channel *channel, SC_APDU_cmd *apdu, SC_APDU_resp *resp);
secbool check_hmac_again(const uint8_t *hmac, const uint8_t *hmac_recv, uint32_t size);
int decrypt_platform_keys(token_channel *channel, const char *pet_pin, uint32_t pet_pin_len, const databag *keybag, uint32_t keybag_num, databag *decrypted_keybag, uint32_t decrypted_keybag_num, uint32_t pbkdf2_iterations)
{
uint8_t pbkdf[SHA512_DIGEST_SIZE];
uint32_t pbkdf_len;
hmac_context hmac_ctx;
uint8_t hmac[SHA256_DIGEST_SIZE];
uint32_t hmac_len = sizeof(hmac);
aes_context aes_context;
uint8_t *platform_salt = NULL;
uint32_t platform_salt_len = 0;
uint8_t *platform_iv = NULL;
uint32_t platform_iv_len = 0;
uint8_t *platform_hmac_tag = NULL;
uint32_t platform_hmac_tag_len = 0;
unsigned int i;
uint8_t token_key[SHA512_DIGEST_SIZE];
SC_APDU_cmd apdu;
SC_APDU_resp resp;
/* SHA-256 context for platform keys hash */
sha256_context sha256_ctx;
/* Sanity checks */
if((pet_pin == NULL) || (keybag == NULL) || (decrypted_keybag == NULL)) {
printf("one of pet_pin, keyback, decrypted_keybag is null\n");
goto err;
}
/* Sanity checks on lengths
* A Keybag contains at least an IV, a salt and a HMAC tag
*/
if(keybag_num < 3) {
printf("keybag_num is %d\n", keybag_num);
goto err;
}
if(decrypted_keybag_num < (keybag_num - 3)) {
printf("decrypted_keybag_num is %d\n", decrypted_keybag_num);
goto err;
}
platform_iv = keybag[0].data;
platform_iv_len = keybag[0].size;
platform_salt = keybag[1].data;
platform_salt_len = keybag[1].size;
platform_hmac_tag = keybag[2].data;
platform_hmac_tag_len = keybag[2].size;
/* First of all, we derive our decryption and HMAC keys
* from the PET PIN using PBKDF2.
*/
#if SMARTCARD_DEBUG
printf("sending hmac_pbkdf2\n");
#endif
pbkdf_len = sizeof(pbkdf);
if(hmac_pbkdf2(SHA512, (const unsigned char*)pet_pin, pet_pin_len, platform_salt, platform_salt_len, pbkdf2_iterations, SHA512_DIGEST_SIZE, pbkdf, &pbkdf_len))
{
goto err;
}
/* Once we have derived our PBKDF2 key, we ask the token for the decryption key */
/* Sanity check: the secure channel must not be already negotiated */
if((channel == NULL) || (channel->secure_channel == 1)) {
printf("channel == NULL\n");
goto err;
}
apdu.cla = 0x00; apdu.ins = TOKEN_INS_DERIVE_LOCAL_PET_KEY; apdu.p1 = 0x00; apdu.p2 = 0x00;
apdu.lc = SHA512_DIGEST_SIZE; apdu.le = SHA512_DIGEST_SIZE; apdu.send_le = 1;
memcpy(apdu.data, pbkdf, pbkdf_len);
#if SMARTCARD_DEBUG
printf("sending to token\n");
#endif
if(token_send_receive(channel, &apdu, &resp)) {
printf("token send received fail\n");
goto err;
}
/******* Smartcard response ***********************************/
if((resp.sw1 != (TOKEN_RESP_OK >> 8)) || (resp.sw2 != (TOKEN_RESP_OK & 0xff))) {
/* The smartcard responded an error */
printf("token response fails\n");
goto err;
}
if(resp.le != SHA512_DIGEST_SIZE) {
/* Bad response lenght */
printf("bad response length\n");
goto err;
}
memcpy(token_key, resp.data, SHA512_DIGEST_SIZE);
/* First, we check the HMAC value, the HMAC key is the 256 right most bits of
* the PBKDF2 value.
*
* [RB] NOTE: we use the platform data hash (SHA-256) as the HMAC Key because of possible SCA attacks
* on HMAC (see https://www.cryptoexperts.com/sbelaid/articleHMAC.pdf). Although this
* usage seems a bit counter-intuitive, this prevents extracting the encrypted data
* through side-channels (consumption, EM, etc.).
*/
/* First we hash our local encrypted platform data to form the HMAC key */
/* NOTE: we reuse our hmac buffer to save SRAM space here! */
sha256_init(&sha256_ctx);
sha256_update(&sha256_ctx, platform_iv, platform_iv_len);
sha256_update(&sha256_ctx, platform_salt, platform_salt_len);
for(i = 0; i < (keybag_num - 3); i++){
sha256_update(&sha256_ctx, keybag[i+3].data, keybag[i+3].size);
}
sha256_final(&sha256_ctx, hmac);
/* NOTE: we reuse our hmac buffer to save SRAM space here! */
if(hmac_init(&hmac_ctx, hmac, SHA256_DIGEST_SIZE, SHA256))
{
printf("hmac init error\n");
goto err;
}
#if SMARTCARD_DEBUG
printf("hmac init OK\n");
#endif
hmac_update(&hmac_ctx, token_key+32, SHA256_DIGEST_SIZE);
hmac_finalize(&hmac_ctx, hmac, &hmac_len);
#if SMARTCARD_DEBUG
printf("hmac final OK\n");
#endif
/* Check the HMAC tag and return an error if there is an issue */
if((hmac_len != SHA256_DIGEST_SIZE) || (platform_hmac_tag_len != SHA256_DIGEST_SIZE)){
goto err;
}
if(!are_equal(hmac, platform_hmac_tag, hmac_len)){
goto err;
}
/* Sanity check against faults */
if(check_hmac_again(hmac, platform_hmac_tag, hmac_len) != sectrue){
goto err;
}
#if SMARTCARD_DEBUG
printf("hmac equal OK\n");
#endif
/* HMAC is OK, we can decrypt our data */
#if defined(__arm__)
/* Use the protected masked AES for the platform keys decryption */
if(aes_init(&aes_context, token_key, AES128, platform_iv, CTR, AES_DECRYPT, PROTECTED_AES, NULL, NULL, -1, -1)){
#else
/* [RB] NOTE: if not on our ARM target, we use regular portable implementation for simulations */
if(aes_init(&aes_context, token_key, AES128, platform_iv, CTR, AES_DECRYPT, AES_SOFT_UNMASKED, NULL, NULL, -1, -1)){
#endif
goto err;
}
#if SMARTCARD_DEBUG
printf("aes init OK\n");
#endif
/* Decrypt all our data encapsulated in the keybag */
for(i = 0; i < (keybag_num - 3); i++){
if(keybag[i+3].size < decrypted_keybag[i].size){
printf("overflow: %d, %d", keybag[i+3].size, decrypted_keybag[i].size);
goto err;
}
decrypted_keybag[i].size = keybag[i+3].size;
if(aes_exec(&aes_context, keybag[i+3].data, decrypted_keybag[i].data, keybag[i+3].size, -1, -1)){
goto err;
}
}
#if SMARTCARD_DEBUG
printf("aes OK\n");
#endif
/* Erase the token key */
memset(token_key, 0, sizeof(token_key));
/* Copy the PBKDF2 iterations, the platform salt and the platform salt length in the secure channel context since
* we will need it later.
*/
if(platform_salt_len > sizeof(channel->platform_salt)){
goto err;
}
channel->pbkdf2_iterations = pbkdf2_iterations;
channel->platform_salt_len = platform_salt_len;
memcpy(channel->platform_salt, platform_salt, platform_salt_len);
return 0;
err:
/* Erase the token key */
memset(token_key, 0, sizeof(token_key));
#if SMARTCARD_DEBUG
printf("Error: decrypt_platform_keys\n");
#endif
return -1;
}
/* Secure channel negotiation:
* We use an ECDH with mutual authentication in order to derive our session key and IV.
*/
/* [RB] FIXME: clean the sensitive values when they are no more used ... */
static int token_negotiate_secure_channel(token_channel *channel, const unsigned char *decrypted_platform_priv_key_data, uint32_t decrypted_platform_priv_key_data_len, const unsigned char *decrypted_platform_pub_key_data, uint32_t decrypted_platform_pub_key_data_len, const unsigned char *decrypted_token_pub_key_data, uint32_t decrypted_token_pub_key_data_len, ec_curve_type curve_type, unsigned int *remaining_tries){
SC_APDU_cmd apdu;
SC_APDU_resp resp;
/* Our ECDSA key pair */
ec_key_pair our_key_pair;
/* The token ECDSA public key */
ec_pub_key token_pub_key;
/* The projective point we will use */
prj_pt Q;
nn d;
uint8_t siglen;
struct ec_sign_context sig_ctx;
struct ec_verify_context verif_ctx;
/* SHA256 context used to derive our secrets */
sha256_context sha256_ctx;
/* Shared secret buffer */
uint8_t shared_secret[NN_MAX_BIT_LEN / 8];
uint8_t digest[SHA256_DIGEST_SIZE];
/* the token challenge */
uint8_t token_challenge[16];
/* Sanity checks */
if((channel == NULL) || (decrypted_platform_priv_key_data == NULL) || (decrypted_platform_pub_key_data == NULL) || (decrypted_token_pub_key_data == NULL) || (remaining_tries == NULL)){
goto err;
}
#ifdef MEASURE_TOKEN_PERF
uint64_t start, end;
sys_get_systick(&start, PREC_MILLI);
#endif
/* Get the challenge from the token */
apdu.cla = 0x00; apdu.ins = TOKEN_INS_GET_CHALLENGE; apdu.p1 = 0x00; apdu.p2 = 0x00;
apdu.lc = 0;
apdu.le = sizeof(token_challenge); apdu.send_le = 1;
if(token_send_receive(channel, &apdu, &resp)){
goto err;
}
/******* Smartcard response ***********************************/
if((resp.sw1 != (TOKEN_RESP_OK >> 8)) || (resp.sw2 != (TOKEN_RESP_OK & 0xff))){
goto err;
}
if(resp.le != sizeof(token_challenge)){
/* This is not the size we expect */
goto err;
}
memcpy(token_challenge, resp.data, sizeof(token_challenge));
/* ECDH core */
/******* Reader answer ***********************************/
/* Importing specific curve parameters from its type.
*/
ec_params *curve_params;
if(load_curve_parameters(curve_type, &curve_params)){
goto err;
}
if(curve_params == NULL){
goto err;
}
if(ec_get_sig_len(curve_params, ECDSA, SHA256, &siglen)){
goto err;
}
/* If there is not enough room in the short APDU for Q and the signature, get out */
if(((3 * BYTECEIL(curve_params->ec_fp.p_bitlen)) + siglen) > SHORT_APDU_LC_MAX){
goto err;
}
/* Import our platform ECDSA private and public keys */
if(ec_structured_priv_key_import_from_buf(&(our_key_pair.priv_key), curve_params, decrypted_platform_priv_key_data, decrypted_platform_priv_key_data_len, ECDSA)){
goto err;
}
if(ec_structured_pub_key_import_from_buf(&(our_key_pair.pub_key), curve_params, decrypted_platform_pub_key_data, decrypted_platform_pub_key_data_len, ECDSA)){
goto err;
}
/* Initialize our projective point with the curve parameters */
prj_pt_init(&Q, &(curve_params->ec_curve));
/* Generate our ECDH parameters: a private scalar d and a public value Q = dG where G is the
* curve generator.
* d = random mod (q) where q is the order of the generator G.
* Note: we have chosen to do this the 'explicit way', but we could have used the ECDSA key pair generation
* primitive to handle the random private scalar d and its public counter part dG.
*/
nn_init(&d, 0);
if (nn_get_random_mod(&d, &(curve_params->ec_gen_order))) {
goto err;
}
#ifdef MEASURE_TOKEN_PERF
sys_get_systick(&end, PREC_MILLI);
printf("[Token] BEGIN = %lld milliseconds\n", (end - start));
sys_get_systick(&start, PREC_MILLI);
#endif
/* Q = dG */
#ifdef USE_SIG_BLINDING
if(prj_pt_mul_monty_blind(&Q, &d, &(curve_params->ec_gen))){
goto err;
}
#else
prj_pt_mul_monty(&Q, &d, &(curve_params->ec_gen));
#endif
#ifdef MEASURE_TOKEN_PERF
sys_get_systick(&end, PREC_MILLI);
printf("[Token] Q = dG Time taken = %lld milliseconds\n", (end - start));
sys_get_systick(&start, PREC_MILLI);
#endif
/* Normalize Q to have the unique representation (affine equivalent) */
prj_pt_unique(&Q, &Q);
/* Export Q to serialize it in the APDU.
* Our export size is exactly 3 coordinates in Fp, so this should be 3 times the size
* of an element in Fp.
*/
if(prj_pt_export_to_buf(&Q, apdu.data,
3 * BYTECEIL(curve_params->ec_fp.p_bitlen))){
goto err;
}
apdu.lc = 3 * BYTECEIL(curve_params->ec_fp.p_bitlen);
/* Now compute the ECDSA signature of Q */
if(ec_sign_init(&sig_ctx, &our_key_pair, ECDSA, SHA256, NULL, 0)){
goto err;
}
if(ec_sign_update(&sig_ctx, (const uint8_t*)apdu.data, apdu.lc)){
goto err;
}
/* Update with the challenge sent by the token */
if(ec_sign_update(&sig_ctx, token_challenge, sizeof(token_challenge))){
goto err;
}
/* Append the signature in the APDU */
if(ec_sign_finalize(&sig_ctx, &(apdu.data[apdu.lc]), siglen)){
goto err;
}
apdu.lc += siglen;
#ifdef MEASURE_TOKEN_PERF
sys_get_systick(&end, PREC_MILLI);
printf("[Token] ECDSA SIGN = %lld milliseconds\n", (end - start));
#endif
do_error_recovery_sleep(channel);
/* The instruction to perform an ECDH is TOKEN_INS_SECURE_CHANNEL_INIT: the reader sends its random scalar
* and receives the card random scalar.
*/
apdu.cla = 0x00; apdu.ins = TOKEN_INS_SECURE_CHANNEL_INIT; apdu.p1 = 0x00; apdu.p2 = 0x00;
apdu.le = apdu.lc; apdu.send_le = 1;
if(token_send_receive(channel, &apdu, &resp)){
goto err;
}
/******* Smartcard response ***********************************/
if((resp.sw1 != (TOKEN_RESP_OK >> 8)) || (resp.sw2 != (TOKEN_RESP_OK & 0xff))){
/* The smartcard responded an error */
if((((resp.sw1 << 8) | (resp.sw2 & 0xff)) == TOKEN_RESP_NOK) && (resp.le == 2)){
/* Get the remaining tries */
*remaining_tries = (resp.data[0] << 8) | resp.data[1];
}
goto err;
}
if(resp.le != ((3 * BYTECEIL(curve_params->ec_fp.p_bitlen)) + (uint32_t)siglen)){
/* This is not the size we are waiting for ... */
goto err;
}
/* Import the token public key */
if(ec_structured_pub_key_import_from_buf(&token_pub_key, curve_params, decrypted_token_pub_key_data, decrypted_token_pub_key_data_len, ECDSA)){
goto err;
}
#ifdef MEASURE_TOKEN_PERF
sys_get_systick(&start, PREC_MILLI);
#endif
/* Verify the signature */
if(ec_verify_init(&verif_ctx, &token_pub_key, &(resp.data[resp.le-siglen]), siglen, ECDSA, SHA256, NULL, 0)){
goto err;
}
if(ec_verify_update(&verif_ctx, resp.data, resp.le-siglen)){
goto err;
}
if(ec_verify_finalize(&verif_ctx)){
goto err;
}
#ifdef MEASURE_TOKEN_PERF
sys_get_systick(&end, PREC_MILLI);
printf("[Token] ECDSA VERIFY = %lld milliseconds\n", (end - start));
#endif
/* Signature is OK, now extract the point from the APDU */
if(prj_pt_import_from_buf(&Q, resp.data, 3 * BYTECEIL(curve_params->ec_fp.p_bitlen), &(curve_params->ec_curve))){
/* NB: prj_pt_import_from_buf checks if the point is indeed on the
* curve or not, and returns an error if this is not the case ...
*/
goto err;
}
#ifdef MEASURE_TOKEN_PERF
sys_get_systick(&start, PREC_MILLI);
#endif
/* Now compute dQ where d is our secret */
#ifdef USE_SIG_BLINDING
if(prj_pt_mul_monty_blind(&Q, &d, &Q)){
goto err;
}
#else
prj_pt_mul_monty(&Q, &d, &Q);
#endif
#ifdef MEASURE_TOKEN_PERF
sys_get_systick(&end, PREC_MILLI);
printf("[Token] dQ = %lld milliseconds\n", (end - start));
sys_get_systick(&start, PREC_MILLI);
#endif
/* Clear d */
nn_uninit(&d);
/* Get the unique representation of the point
* (the other party should send us a normalized point, but nevermind do it anyways).
*/
prj_pt_unique(&Q, &Q);
/* The shared secret is Q.X, which is 32 bytes:
* we derive our AES 256-bit secret key, our 256-bit HMAC key as well as our initial IV from this value.
*/
fp_export_to_buf(shared_secret, BYTECEIL(curve_params->ec_fp.p_bitlen), &(Q.X));
/* AES Key = SHA-256("AES_SESSION_KEY" | shared_secret) (first 128 bits) */
sha256_init(&sha256_ctx);
sha256_update(&sha256_ctx, (const uint8_t*)"AES_SESSION_KEY", sizeof("AES_SESSION_KEY")-1);
sha256_update(&sha256_ctx, shared_secret, BYTECEIL(curve_params->ec_fp.p_bitlen));
sha256_final(&sha256_ctx, digest);
memcpy(channel->AES_key, digest, 16);
/* HMAC Key = SHA-256("HMAC_SESSION_KEY" | shared_secret) (256 bits) */
sha256_init(&sha256_ctx);
sha256_update(&sha256_ctx, (const uint8_t*)"HMAC_SESSION_KEY", sizeof("HMAC_SESSION_KEY")-1);
sha256_update(&sha256_ctx, shared_secret, BYTECEIL(curve_params->ec_fp.p_bitlen));
sha256_final(&sha256_ctx, channel->HMAC_key);
/* IV = SHA-256("SESSION_IV" | shared_secret) (first 128 bits) */
sha256_init(&sha256_ctx);
sha256_update(&sha256_ctx, (const uint8_t*)"SESSION_IV", sizeof("SESSION_IV")-1);
sha256_update(&sha256_ctx, shared_secret, BYTECEIL(curve_params->ec_fp.p_bitlen));
sha256_final(&sha256_ctx, digest);
memcpy(channel->IV, digest, 16);
memcpy(channel->first_IV, channel->IV, 16);
#ifdef MEASURE_TOKEN_PERF
sys_get_systick(&end, PREC_MILLI);
printf("[Token] Symmetric crypto = %lld milliseconds\n", (end - start));
#endif
/* Our secure channel is initialized */
channel->secure_channel = 1;
/* Uninit local variables */
prj_pt_uninit(&Q);
return 0;
err:
#if SMARTCARD_DEBUG
printf("Error: token_negotiate_secure_channel\n");
#endif
return -1;
}
/* APDU encryption and integrity */
static int token_apdu_cmd_encrypt(token_channel *channel, SC_APDU_cmd *apdu){
hmac_context hmac_ctx;
uint8_t hmac[SHA256_DIGEST_SIZE];
uint8_t tmp;
uint32_t hmac_len = sizeof(hmac);
/* Sanitiy checks */
if((channel == NULL) || (apdu == NULL)){
goto err;
}
if(!channel->secure_channel){
/* Why encrypt since we do not have a secure channel yet? */
goto err;
}
if((apdu->le > SHORT_APDU_LE_MAX) || (apdu->lc > SHORT_APDU_LC_MAX)){
/* Sanity check: we only deal with short APDUs */
goto err;
}
if(apdu->lc > (SHORT_APDU_LC_MAX - sizeof(hmac))){
/* Not enough room for our HMAC */
goto err;
}
/* Compute the integrity on the full encrypted data + CLA/INS/P1/P2, lc and le on 1 byte since we deal only with short APDUs */
if(hmac_init(&hmac_ctx, channel->HMAC_key, sizeof(channel->HMAC_key), SHA256)){
goto err;
}
/* Pre-append the IV for anti-replay on the integrity with empty data */
hmac_update(&hmac_ctx, channel->IV, sizeof(channel->IV));
hmac_update(&hmac_ctx, &(apdu->cla), 1);
hmac_update(&hmac_ctx, &(apdu->ins), 1);
hmac_update(&hmac_ctx, &(apdu->p1), 1);
hmac_update(&hmac_ctx, &(apdu->p2), 1);
if(apdu->lc != 0){
/* Encryption */
aes_context aes_context;
/* Encrypt the APDU data with AES-CTR */
#if defined(__arm__)
/* [RB] NOTE: we use a software masked AES for robustness against side channel attacks */
if(aes_init(&aes_context, channel->AES_key, AES128, channel->IV, CTR, AES_ENCRYPT, PROTECTED_AES, NULL, NULL, -1, -1)){
#else
/* [RB] NOTE: if not on our ARM target, we use regular portable implementation for simulations */
if(aes_init(&aes_context, channel->AES_key, AES128, channel->IV, CTR, AES_ENCRYPT, AES_SOFT_UNMASKED, NULL, NULL, -1, -1)){
#endif
goto err;
}
if(aes_exec(&aes_context, apdu->data, apdu->data, apdu->lc, -1, -1)){
goto err;
}
/* Increment the IV by as many blocks as necessary */
add_iv(channel->IV, apdu->lc / AES_BLOCK_SIZE);
/* Update the HMAC */
tmp = (uint8_t)apdu->lc & 0xff;
hmac_update(&hmac_ctx, &tmp, 1);
hmac_update(&hmac_ctx, apdu->data, apdu->lc);
}
/* Always increment our anti-replay counter manually at least once fot the next data batch to send/receive */
increment_iv(channel->IV);
/* When encrypting an APDU, we always expect a response with at least 32 bytes of HMAC.
* In order to avoid any issue, we ask for a Le = 0 meaning that we expect a maximum amount of
* 256 bytes.
*/
apdu->send_le = 1;
apdu->le = 0;
tmp = (uint8_t)apdu->le & 0xff;
hmac_update(&hmac_ctx, &tmp, 1);
/* Add the integrity HMAC tag to the APDU data and increment the Lc
* size accordingly.
*/
if(hmac_finalize(&hmac_ctx, hmac, &hmac_len)){
goto err;
}
if(hmac_len != sizeof(hmac)){
goto err;
}
/* Double check against faults */
if(apdu->lc > (SHORT_APDU_LC_MAX - sizeof(hmac))){
/* Not enough room for our HMAC */
goto err;
}
memcpy(&(apdu->data[apdu->lc]), hmac, sizeof(hmac));
apdu->lc += sizeof(hmac);
return 0;
err:
#if SMARTCARD_DEBUG
printf("Error: token_apdu_cmd_encrypt\n");
#endif
return -1;
}
#ifdef __GNUC__
#ifdef __clang__
# pragma clang optimize off
#else
# pragma GCC push_options
# pragma GCC optimize("O0")
#endif
#endif
secbool check_hmac_again(const uint8_t *hmac, const uint8_t *hmac_recv, uint32_t size){
if((hmac == NULL) || (hmac_recv == NULL)){
goto err;
}
if(!are_equal(hmac, hmac_recv, size)){
goto err;
}
if(!are_equal(hmac_recv, hmac, size)){
goto err;
}
return sectrue;
err:
return secfalse;
}
#ifdef __GNUC__
#ifdef __clang__
# pragma clang optimize on
#else
# pragma GCC pop_options
#endif
#endif
static int token_apdu_resp_decrypt(token_channel *channel, SC_APDU_resp *resp){
hmac_context hmac_ctx;
uint8_t hmac[SHA256_DIGEST_SIZE];
uint8_t hmac_recv[SHA256_DIGEST_SIZE];
uint8_t tmp;
int self_sync_attempts = ANTI_REPLAY_SELF_SYNC_WINDOW;
uint32_t hmac_len = sizeof(hmac);
/* Sanity check */
if((channel == NULL) || (resp == NULL)){
printf("%s : %d\n",__FILE__,__LINE__);
goto err;
}
if(!channel->secure_channel){
printf("%s : %d\n",__FILE__,__LINE__);
goto err;
}
/* Response data contains at least a HMAC */
if(resp->le < sizeof(hmac_recv)){
printf("%s : %d\n",__FILE__,__LINE__);
goto err;
}
/* If we have not received a short APDU, this is an error */
if(resp->le > SHORT_APDU_LE_MAX){
printf("%s : %d\n",__FILE__,__LINE__);
goto err;
}
/* Copy the received HMAC */
memcpy(hmac_recv, &(resp->data[resp->le - sizeof(hmac_recv)]), sizeof(hmac_recv));
resp->le -= sizeof(hmac_recv);
CHECK_INTEGRITY_AGAIN:
/* Check the integrity */
if(hmac_init(&hmac_ctx, channel->HMAC_key, sizeof(channel->HMAC_key), SHA256)){
printf("%s : %d\n",__FILE__,__LINE__);
goto err;
}
/* Pre-append the IV for anti-replay on the integrity with empty data */
hmac_update(&hmac_ctx, channel->IV, sizeof(channel->IV));
/* Update the HMAC with SW1 and SW2 */
hmac_update(&hmac_ctx, &(resp->sw1), 1);
hmac_update(&hmac_ctx, &(resp->sw2), 1);
/* If we have data, update the HMAC */
if(resp->le > 0){
tmp = (uint8_t)resp->le & 0xff;
hmac_update(&hmac_ctx, &tmp, 1);
hmac_update(&hmac_ctx, resp->data, resp->le);
}
/* Finalize the HMAC */
if(hmac_finalize(&hmac_ctx, hmac, &hmac_len)){
printf("%s : %d\n",__FILE__,__LINE__);
goto err;
}
if(hmac_len != sizeof(hmac)){
printf("%s : %d\n",__FILE__,__LINE__);
goto err;
}
/* Compare the computed HMAC and the received HMAC */
if(!are_equal(hmac, hmac_recv, sizeof(hmac))){
/* Integrity is not OK, try to self-synchronize a bit ... */
if(self_sync_attempts == 0){
/* We have exhausted our self-sync attempts: return an error */
printf("%s : %d\n",__FILE__,__LINE__);
goto err;
}
self_sync_attempts--;
increment_iv(channel->IV);
goto CHECK_INTEGRITY_AGAIN;
}
/* Sanity check against faults */
if(check_hmac_again(hmac, hmac_recv, sizeof(hmac)) != sectrue){
printf("%s : %d\n",__FILE__,__LINE__);
goto err;
}
/* Decrypt our data in place if there are some */
if(resp->le != 0){
aes_context aes_context;
/* Decrypt the APDU response data with AES-CTR */
#if defined(__arm__)
/* [RB] NOTE: we use a software masked AES for robustness against side channel attacks */
if(aes_init(&aes_context, channel->AES_key, AES128, channel->IV, CTR, AES_DECRYPT, PROTECTED_AES, NULL, NULL, -1, -1)){
#else
/* [RB] NOTE: if not on our ARM target, we use regular portable implementation for simulations */
if(aes_init(&aes_context, channel->AES_key, AES128, channel->IV, CTR, AES_DECRYPT, AES_SOFT_UNMASKED, NULL, NULL, -1, -1)){
#endif
printf("%s : %d\n",__FILE__,__LINE__);
goto err;
}
if(aes_exec(&aes_context, resp->data, resp->data, resp->le, -1, -1)){
printf("%s : %d\n",__FILE__,__LINE__);
goto err;
}
/* Increment the IV by as many blocks as necessary */
add_iv(channel->IV, resp->le / AES_BLOCK_SIZE);
}
/* Always increment our anti-replay counter manually at least once fot the next data batch to send/receive */
increment_iv(channel->IV);
return 0;
err:
#if SMARTCARD_DEBUG
printf("Error: token_apdu_cmd_encrypt\n");
#endif
return -1;
}
/*
* Try to send an APDU on the physical line multiple times
* in case of possible errors before giving up ...
*/
static int SC_send_APDU_with_errors(token_channel *channel, SC_APDU_cmd *apdu, SC_APDU_resp *resp, SC_Card *card){
unsigned int num_tries;
int ret;
num_tries = 0;
if(channel == NULL){
ret = -1;
goto err;
}
while(1){
ret = SC_send_APDU(apdu, resp, card);
num_tries++;
if(!ret){
return 0;
}
#if SMARTCARD_DEBUG
printf("...retrying!\n");
#endif
do_error_recovery_sleep(channel);
if(ret && (num_tries >= channel->error_recovery_max_send_retries)){
goto err;
}
if(!SC_is_smartcard_inserted(card)){
/* Smartcard has been lost ... */
goto err;
}
/* Wait the requested timeout with the card to reset the current APDU */
SC_wait_card_timeout(card);
}
err:
return ret;
}
/* The token 'send'/'receive' primitive. Depending on the secure channel state, we
* send raw or encrypted APDU data.
* Because we want our secure channel to be compatible in T=0 and T=1, and since T=0
* mixes the ISO layers and needs CLA/INS/P1/P2/P3, we do not encrypt these. They
* are however part of the integrity tag computation in order to avoid integrity issues.
*
*/
int token_send_receive(token_channel *channel, SC_APDU_cmd *apdu, SC_APDU_resp *resp){
#ifdef MEASURE_TOKEN_PERF
uint64_t start, end;
#endif
/* Sanity check */
if((channel == NULL) || (apdu == NULL) || (resp == NULL)){
goto err;
}
#if SMARTCARD_DEBUG
SC_print_APDU(apdu);
#endif
#ifdef MEASURE_TOKEN_PERF
sys_get_systick(&start, PREC_MILLI);
#endif
/* Channel is not initialized */
if(!channel->channel_initialized){
printf("%s : %d\n",__FILE__,__LINE__);
goto err;
}
/* Channel is initialized: are we in secure channel mode? */
if(channel->secure_channel){
/* In secure channel mode, we encrypt everything and send it.
* Encrypt the APDU "in place" in order to avoid memory loss */
/* If we have not space in the APDU, get out ... */
if(apdu->lc > (SHORT_APDU_LC_MAX - SHA256_DIGEST_SIZE)){
/* We must have some place for the integrity tag */
printf("%s : %d\n",__FILE__,__LINE__);
goto err;
}
/* Encrypt the APDU and append the integrity tag */
if(token_apdu_cmd_encrypt(channel, apdu)){
printf("%s : %d\n",__FILE__,__LINE__);
goto err;
}
/* Send the encrypted APDU and receive the encrypted response */
if(SC_send_APDU_with_errors(channel, apdu, resp, &(channel->card))){
printf("%s : %d\n",__FILE__,__LINE__);
goto err;
}
/* Decrypt the response in place and check its integrity */
if(token_apdu_resp_decrypt(channel, resp)){
printf("%s : %d\n",__FILE__,__LINE__);
goto err;
}
}
else{
/* In non secure channel mode, we do not encrypt: send the raw
* APDU and receive the raw response.
*/
if(SC_send_APDU_with_errors(channel, apdu, resp, &(channel->card))){
printf("%s : %d\n",__FILE__,__LINE__);
goto err;
}
}
#ifdef MEASURE_TOKEN_PERF
sys_get_systick(&end, PREC_MILLI);
#endif
#if SMARTCARD_DEBUG
SC_print_RESP(resp);
#endif
#ifdef MEASURE_TOKEN_PERF
printf("[Token] [++++++++++++++] APDU send/receive took %lld milliseconds [++++++++++++++]\n", (end - start));
#endif
return 0;
err:
#if SMARTCARD_DEBUG
printf("APDU send/receive error (secure channel or lower layers errors)\n");
#endif
return -1;
}
/* Update AES and HMAC session keys given an input string */
void token_channel_session_keys_update(token_channel *channel, const char *in, unsigned int in_len, unsigned char use_iv){
uint8_t digest[SHA256_DIGEST_SIZE];
sha256_context sha256_ctx;
unsigned int i;
/* Sanity check */
if((channel == NULL) || (in == NULL)){
return;
}
sha256_init(&sha256_ctx);
sha256_update(&sha256_ctx, (const unsigned char*)in, in_len);
if(use_iv == 1){
sha256_update(&sha256_ctx, channel->IV, sizeof(channel->IV));
}
sha256_final(&sha256_ctx, digest);
for(i = 0; i < sizeof(channel->AES_key); i++){
channel->AES_key[i] ^= digest[i];
}
for(i = 0; i < sizeof(channel->HMAC_key); i++){
channel->HMAC_key[i] ^= digest[i];
}
return;
}
/****** Smartcard low level APDUs ****/
/* Select an applet */
int token_select_applet(token_channel *channel, const unsigned char *aid, unsigned int aid_len){
SC_APDU_cmd apdu;
SC_APDU_resp resp;
if((channel == NULL) || (aid == NULL)){
goto err;
}
apdu.cla = 0x00; apdu.ins = TOKEN_INS_SELECT_APPLET; apdu.p1 = 0x04; apdu.p2 = 0x00; apdu.lc = aid_len;
apdu.le = 0x00; apdu.send_le = 1;
memcpy(apdu.data, aid, aid_len);
if(token_send_receive(channel, &apdu, &resp)){
goto err;
}
/* Check return status */
if((resp.sw1 != (TOKEN_RESP_OK >> 8)) || (resp.sw2 != (TOKEN_RESP_OK & 0xff))){
goto err;
}
return 0;
err:
return -1;
}
/* Send a pin */
int token_send_pin(token_channel *channel, const char *pin, unsigned int pin_len, unsigned char *pin_ok, unsigned int *remaining_tries, token_pin_types pin_type){
unsigned int i;
SC_APDU_cmd apdu;
SC_APDU_resp resp;
char padded_pin[16];
if((pin == NULL) || (pin_ok == NULL) || (remaining_tries == NULL)){
goto err;
}
*remaining_tries = 0;
*pin_ok = 0;
/* Some sanity checks here */
if(pin_len > (SHORT_APDU_LC_MAX - SHA256_DIGEST_SIZE)){
goto err;
}
if(pin_len > 15){
goto err;
}
for(i = 0; i < pin_len; i++){
padded_pin[i] = pin[i];
}
for(i= pin_len; i < (sizeof(padded_pin)-1); i++){
padded_pin[i] = 0;
}
padded_pin[15] = pin_len;