-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathttp_DB.c
1494 lines (1189 loc) · 70.5 KB
/
ttp_DB.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
// ========================================================================================================
// ========================================================================================================
// ************************************************* ttp.c ************************************************
// ========================================================================================================
// ========================================================================================================
//
//--------------------------------------------------------------------------------
// Company: IC-Safety, LLC and University of New Mexico
// Engineer: Professor Jim Plusquellic
// Exclusive License: IC-Safety, LLC
// Copyright: Univ. of New Mexico
//--------------------------------------------------------------------------------
#include "common.h"
#include "device_hardware.h"
#include "device_common.h"
#include "device_regen_funcs.h"
#include "commonDB_RT_PUFCash.h"
#include <signal.h>
#include <errno.h>
#include <pthread.h>
// ====================== DATABASE STUFF =========================
#include <sqlite3.h>
#include "commonDB.h"
#include "aes_128_ecb_openssl.h"
#include "aes_256_cbc_openssl.h"
// -----------------------------------------
// THREADS
typedef struct
{
int task_num;
int iteration_cnt;
char *history_file_name;
SRFHardwareParamsStruct *SHP_ptr;
int Bank_socket_desc;
int Device_socket_desc;
char customer_IP[16];
unsigned char *TTP_session_key;
int port_number;
int in_use;
int client_index;
int *client_sockets;
int num_TTPs;
int max_string_len;
int max_TTP_connect_attempts;
ClientInfoStruct *Client_CIArr;
int my_IP_pos;
int exclude_self;
int RANDOM;
int num_eCt_nonce_bytes;
pthread_mutex_t Thread_mutex;
pthread_cond_t Thread_cv;
} ThreadDataType;
// ========================================================================================================
// ========================================================================================================
// CUSTOMER ACCOUNT CREATION: Create accounts for customers with a default amount. First get a list of chip_nums
// (IDs) from the Bank and create an deposit record for each customer with transaction ID (TID) 0 with
// deposit_amt (currently $100).
int GetCustomerChipNums(int max_string_len, SRFHardwareParamsStruct *SHP_ptr, unsigned char *TTP_session_key,
int Bank_socket_desc, int TID, int deposit_amt)
{
char request_str[max_string_len];
int num_chips, chip_num, Alice_chip_num;
#ifdef DEBUG
printf("\nGetCustomerChipNums(): BEGIN!\n"); fflush(stdout);
#endif
// Sanity check. Customers are forced to deposit multiples of some amount, currently $5.
if ( (deposit_amt % MIN_WITHDRAW_INCREMENT) != 0 )
{ printf("ERROR: Default deposit Amt %d MUST be divisible by %d!\n", deposit_amt, MIN_WITHDRAW_INCREMENT); exit(EXIT_FAILURE); }
// Tell Bank we want a list of customer chip_nums
if ( SockSendB((unsigned char *)"TTP-GET-DEVICE-IDS", strlen("TTP-GET-DEVICE-IDS") + 1, Bank_socket_desc) < 0 )
{ printf("ERROR: Failed to send 'TTP-GET-DEVICE-IDS' to Bank!\n"); exit(EXIT_FAILURE); }
// Get and decrypt the number of chip_nums first.
unsigned char *eReq = Allocate1DUnsignedChar(AES_INPUT_NUM_BYTES);
if ( SockGetB(eReq, AES_INPUT_NUM_BYTES, Bank_socket_desc) != AES_INPUT_NUM_BYTES )
{ printf("ERROR: GetCustomerChipNums(): Failed to get 'number of chip_nums' from Bank!\n"); exit(EXIT_FAILURE); }
decrypt_256(TTP_session_key, SHP_ptr->AES_IV, eReq, AES_INPUT_NUM_BYTES, (unsigned char *)request_str);
sscanf(request_str, "%d", &num_chips);
// Sanity check
if ( num_chips <= 0 )
{ printf("ERROR: Number of chips sent by Bank is <= 0: %d!\n", num_chips); return 0; }
// Encrypt and transmit the chip_nums to the TTP.
for ( chip_num = 0; chip_num < num_chips; chip_num++ )
{
// Get encrypted Alice_chip_num.
if ( SockGetB(eReq, AES_INPUT_NUM_BYTES, Bank_socket_desc) != AES_INPUT_NUM_BYTES )
{ printf("ERROR: GetCustomerChipNums(): Failed to get 'chip_num' from Bank!\n"); exit(EXIT_FAILURE); }
decrypt_256(TTP_session_key, SHP_ptr->AES_IV, eReq, AES_INPUT_NUM_BYTES, (unsigned char *)request_str);
sscanf(request_str, "%d", &Alice_chip_num);
#ifdef DEBUG
printf("GetCustomerChipNums(): Adding Alice_chip_num %d to Accounts Table with TID %d\tDeposit Amount %d\n",
Alice_chip_num, TID, deposit_amt); fflush(stdout);
#endif
// Only allow one record to exist for each customer at this point.
if ( PUFCashAddAcctRec(max_string_len, SHP_ptr->DB_PUFCash_V3, Alice_chip_num, TID,
deposit_amt, MIN_WITHDRAW_INCREMENT) == 0 )
return 0;
}
if ( eReq != NULL )
free(eReq);
#ifdef DEBUG
printf("\nGetCustomerChipNums(): DONE!\n"); fflush(stdout);
#endif
return 1;
}
// ========================================================================================================
// ========================================================================================================
// The Bank and Alice need to generate a session key THROUGH THIS TTP. The TTP simply acts as a forwarding
// agent between the Bank and Alice during KEK_SessionKey generation. I need to replicate the actions
// taken when GenChlngDeliverSpreadFactorsToDevice() within verifier_regen_funcs.c is called, which
// first calls CommonCore, etc.
void AliceTTPBankSessionKeyGen(int max_string_len, SRFHardwareParamsStruct *SHP_ptr, int Alice_socket_desc,
int Bank_socket_desc)
{
char request_str[max_string_len];
int use_database_chlngs;
int num_PIs, num_POs;
printf("AliceTTPBankSessionKeyGen(): CALLED!\n"); fflush(stdout);
#ifdef DEBUG
#endif
// -------------------------------------------
// First get use_database_chlngs, num_PIs and num_POs (control information) that the verifier is using.
if ( SockGetB((unsigned char *)request_str, max_string_len, Bank_socket_desc) < 0 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to get 'use_database_chlngs' from Bank!\n"); exit(EXIT_FAILURE); }
if ( sscanf(request_str, "%d%d%d", &use_database_chlngs, &num_PIs, &num_POs) != 3 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to extract 'use_database_chlngs, num_PIs and num_POs' from Bank!\n"); exit(EXIT_FAILURE); }
#ifdef DEBUG
printf("AliceTTPBankSessionKeyGen(): 'use_database_chlngs' %d\tnum_PIs %d\tnum_POs %d!\n", use_database_chlngs, num_PIs, num_POs); fflush(stdout);
#endif
// -------------------------------------------
// verifier_regeneration.c/GenChlngDeliverSpreadFactorsToDevice()/CommonCore(), Part 1 -> GoSendVectors()
if ( SockGetB((unsigned char *)request_str, MAX_STRING_LEN, Alice_socket_desc) != 3 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to get 'GO' from Alice!\n"); exit(EXIT_FAILURE); }
if ( SockSendB((unsigned char *)request_str, strlen(request_str)+1, Bank_socket_desc) < 0 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to send 'GO' to Bank!\n"); exit(EXIT_FAILURE); }
#ifdef DEBUG
printf("AliceTTPBankSessionKeyGen(): Got and Sent 'GO' '%s'!\n", request_str); fflush(stdout);
#endif
// -------------------------------------------
// verifier_regeneration.c/common.c/GoSendVectors()
// the LFSR seed used by the server. Always send the seed independent of whether we are generating and sending
// vectors from the server (here) or if the device will generate them using only the DB_ChallengeGen_seed.
if ( SockGetB((unsigned char *)request_str, MAX_STRING_LEN, Bank_socket_desc) < 0 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to get 'DB_ChallengeGen_seed_str' from Bank!\n"); exit(EXIT_FAILURE); }
if ( SockSendB((unsigned char *)request_str, strlen(request_str)+1, Alice_socket_desc) < 0 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to send 'DB_ChallengeGen_seed_str' to Alice!\n"); exit(EXIT_FAILURE); }
#ifdef DEBUG
printf("AliceTTPBankSessionKeyGen(): Got and Sent 'DB_ChallengeGen_seed_str' '%s'!\n", request_str); fflush(stdout);
#endif
// -------------------------------------------
// verifier_regeneration.c/common.c/SendVectorsAndMask()
// If the server (and Alice) are NOT using client-side database-generated challenges, then we must get the vectors and
// re-transmit them.
unsigned char *vec = NULL;
unsigned char *mask = NULL;
if ( use_database_chlngs == 0 )
{
int num_vecs, num_rise_vecs, has_masks;
int vec_num;
vec = Allocate1DUnsignedChar(num_PIs/8);
mask = Allocate1DUnsignedChar(num_POs/8);
// Get num_vecs
if ( SockGetB((unsigned char *)request_str, MAX_STRING_LEN, Bank_socket_desc) < 0 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to get 'vecs string' from Bank!\n"); exit(EXIT_FAILURE); }
if ( SockSendB((unsigned char *)request_str, strlen(request_str)+1, Alice_socket_desc) < 0 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to send 'vecs string' to Alice!\n"); exit(EXIT_FAILURE); }
// Parse out the data.
if ( sscanf(request_str, "%d%d%d", &num_vecs, &num_rise_vecs, &has_masks) != 3 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to extract 'num_vecs, num_rise_vecs and has_masks' from Bank!\n"); exit(EXIT_FAILURE); }
#ifdef DEBUG
printf("AliceTTPBankSessionKeyGen(): use_database_chlngs is 0 %d\tnum_vecs %d\tnum_rise_vecs %d\thas_masks %d!\n",
use_database_chlngs, num_vecs, num_rise_vecs, has_masks); fflush(stdout);
#endif
// Send first_vecs and second_vecs to remote server.
for ( vec_num = 0; vec_num < num_vecs; vec_num++ )
{
if ( SockGetB(vec, num_PIs/8, Bank_socket_desc) != num_PIs/8 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to get 'first_vec[%d]' from Bank!\n", vec_num); exit(EXIT_FAILURE); }
if ( SockSendB(vec, num_PIs/8, Alice_socket_desc) < 0 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to send 'first_vec[%d]' to Alice!\n", vec_num); exit(EXIT_FAILURE); }
if ( SockGetB(vec, num_PIs/8, Bank_socket_desc) != num_PIs/8 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to get 'second_vec[%d]' from Bank!\n", vec_num); exit(EXIT_FAILURE); }
if ( SockSendB(vec, num_PIs/8, Alice_socket_desc) < 0 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to send 'second_vec[%d]' to Alice!\n", vec_num); exit(EXIT_FAILURE); }
if ( has_masks == 1 && SockGetB(mask, num_POs/8, Bank_socket_desc) != num_POs/8 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to get 'mask[%d]' from Bank!\n", vec_num); exit(EXIT_FAILURE); }
if ( has_masks == 1 && SockSendB(mask, num_POs/8, Alice_socket_desc) < 0 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to send 'mask[%d]' to Alice!\n", vec_num); exit(EXIT_FAILURE); }
}
#ifdef DEBUG
printf("AliceTTPBankSessionKeyGen(): Got and Sent server-side vectors (use_database_chlngs is 0)!\n"); fflush(stdout);
#endif
}
// -------------------------------------------
// verifier_regeneration.c/GenChlngDeliverSpreadFactorsToDevice()/CommonCore(), Part 1
// XOR_nonce exchange
unsigned char *nonce = Allocate1DUnsignedChar(SHP_ptr->num_required_nonce_bytes);
#ifdef DEBUG
printf("AliceTTPBankSessionKeyGen(): Get/Send 'verifier_n2/XOR_nonce'!\n"); fflush(stdout);
#endif
if ( SockGetB(nonce, SHP_ptr->num_required_nonce_bytes, Bank_socket_desc) != SHP_ptr->num_required_nonce_bytes )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to get 'verifier_n2' from Bank!\n"); exit(EXIT_FAILURE); }
if ( SockSendB(nonce, SHP_ptr->num_required_nonce_bytes, Alice_socket_desc) < 0 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to send 'verifier_n2' to Alice!\n"); exit(EXIT_FAILURE); }
if ( SockGetB(nonce, SHP_ptr->num_required_nonce_bytes, Alice_socket_desc) != SHP_ptr->num_required_nonce_bytes )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to get 'XOR_nonce' from Alice!\n"); exit(EXIT_FAILURE); }
if ( SockSendB(nonce, SHP_ptr->num_required_nonce_bytes, Bank_socket_desc) < 0 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to send 'XOR_nonce' to Bank!\n"); exit(EXIT_FAILURE); }
// -------------------------------------------
// verifier_regeneration.c/GenChlngDeliverSpreadFactorsToDevice()/CommonCore(), Part 2
// SelectParams (nothing), ComputeSendSpreadFactors(), KEK_SessionKey ALWAYS sends SF (independent of mode).
unsigned char *SF = Allocate1DUnsignedChar(SHP_ptr->num_SF_bytes);
int target_attempts = 0;
while (1)
{
#ifdef DEBUG
printf("AliceTTPBankSessionKeyGen(): Get/Send 'SF'\tTarget attempts %d!\n", target_attempts); fflush(stdout);
#endif
if ( SockGetB(SF, SHP_ptr->num_SF_bytes, Bank_socket_desc) != SHP_ptr->num_SF_bytes )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to get 'SF' from Bank!\n"); exit(EXIT_FAILURE); }
if ( SockSendB(SF, SHP_ptr->num_SF_bytes, Alice_socket_desc) < 0 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to send 'SF' to Alice!\n"); exit(EXIT_FAILURE); }
if ( SockGetB((unsigned char *)request_str, max_string_len, Alice_socket_desc) < 0 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to get 'SPREAD_FACTORS DONE' string from Alice!\n"); exit(EXIT_FAILURE); }
if ( SockSendB((unsigned char *)request_str, strlen(request_str)+1, Bank_socket_desc) < 0 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to send 'SPREAD_FACTORS DONE' string to Bank!\n"); exit(EXIT_FAILURE); }
target_attempts++;
if ( strcmp(request_str, "SPREAD_FACTORS DONE") == 0 )
break;
}
#ifdef DEBUG
printf("AliceTTPBankSessionKeyGen(): DONE 'SF'\tFINAL Target attempts %d!\n", target_attempts); fflush(stdout);
#endif
// -------------------------------------------
// verifier_regeneration.c/KEK_SessionKeyGen()
// Get/Send the XMR_SHD generated by Alice to the Bank.
#ifdef DEBUG
printf("AliceTTPBankSessionKeyGen(): Get/Send 'XHD'!\n"); fflush(stdout);
#endif
int XMR_num_bytes = target_attempts * SHP_ptr->num_required_PNDiffs/8;
unsigned char *XMR_SHD = Allocate1DUnsignedChar(XMR_num_bytes);
if ( SockGetB(XMR_SHD, XMR_num_bytes, Alice_socket_desc) != XMR_num_bytes )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to get 'XMR_SHD' from Alice!\n"); exit(EXIT_FAILURE); }
if ( SockSendB(XMR_SHD, XMR_num_bytes, Bank_socket_desc) < 0 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to send 'XMR_SHD' to Bank!\n"); exit(EXIT_FAILURE); }
// -------------------------------------------
// verifier_regeneration.c/KEK_SessionKeyGen()
// Trial encryption
unsigned char *trial_encryption = Allocate1DUnsignedChar(AES_INPUT_NUM_BITS/8);
#ifdef DEBUG
printf("AliceTTPBankSessionKeyGen(): Get/Send 'trial_encryption'!\n"); fflush(stdout);
#endif
if ( SockGetB(trial_encryption, AES_INPUT_NUM_BITS/8, Bank_socket_desc) != AES_INPUT_NUM_BITS/8 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to get 'trial_encryption' from Bank!\n"); exit(EXIT_FAILURE); }
if ( SockSendB(trial_encryption, AES_INPUT_NUM_BITS/8, Alice_socket_desc) < 0 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to send 'trial_encryption' to Alice!\n"); exit(EXIT_FAILURE); }
if ( SockGetB((unsigned char *)request_str, max_string_len, Alice_socket_desc) != 5 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to get 'PASS/FAIL' string from Alice!\n"); exit(EXIT_FAILURE); }
if ( SockSendB((unsigned char *)request_str, strlen(request_str)+1, Bank_socket_desc) < 0 )
{ printf("ERROR: AliceTTPBankSessionKeyGen(): Failed to send 'PASS/FAIL' string to Bank!\n"); exit(EXIT_FAILURE); }
if ( vec != NULL )
free(vec);
if ( mask != NULL )
free(mask);
if ( nonce != NULL )
free(nonce);
if ( SF != NULL )
free(SF);
if ( XMR_SHD != NULL )
free(XMR_SHD);
if ( trial_encryption != NULL )
free(trial_encryption);
printf("AliceTTPBankSessionKeyGen(): DONE!\n"); fflush(stdout);
#ifdef DEBUG
#endif
return;
}
// ========================================================================================================
// ========================================================================================================
// Alice withdrawal operation. Alice authenticates and generates session key with TTP using zero trust.
// She sends her withdrawal amount. TTP maintains Bank account and checks her balance. If okay, TTP
// forwards request to Bank.
void AliceWithdrawal(int max_string_len, SRFHardwareParamsStruct *SHP_ptr, int Alice_socket_desc,
pthread_mutex_t *PUFCash_Account_DB_mutex_ptr, pthread_mutex_t *ZeroTrust_AuthenToken_DB_mutex_ptr,
unsigned char *SK_TF, int min_withdraw_increment, int Bank_socket_desc, int port_number, int num_CIArr,
ClientInfoStruct *Client_CIArr, int My_TTP_index)
{
char request_str[max_string_len];
// ===============================
// ===============================
// ZeroTrust Alice-TTP authentication encryption key generation: Start by getting Alice_chip_num so we can get a specific AT
// from the Bank. Also needed to access her Account Table below.
int chip_num;
if ( SockGetB((unsigned char *)request_str, max_string_len, Alice_socket_desc) < 0 )
{ printf("ERROR: AliceWithdrawal(): Error receiving 'Alice_chip_num' from Alice!\n"); exit(EXIT_FAILURE); }
sscanf(request_str, "%d", &chip_num);
// When Alice makes a withdrawal, her and the TTP carry out ZeroTrust authentication, which means the TTP must have AT
// for the customers. The TTP created AT at startup with the IA, so when customer's request AT, they get the TTP ATs.
// But the TTP has NOT yet fetched AT for the customers (it is NOT menu driver like Alice and Bob where Alice and Bob
// explicitly get AT using a menu option). Get an AT for Alice from the Bank.
// Add an AT for Alice.
int is_TTP = 1;
ZeroTrust_GetATs(MAX_STRING_LEN, SHP_ptr, Bank_socket_desc, is_TTP, SK_TF, ZeroTrust_AuthenToken_DB_mutex_ptr, chip_num);
// ZeroTrust: Authentication and session key generation. Alice and Bob determine if each has an AT for the other (set local_AT_status
// and remote_AT_status) and then get each others chip IDs.
int local_AT_status, remote_AT_status, Alice_chip_num, I_am_Alice;
I_am_Alice = 0;
Alice_chip_num = ExchangeIDsConfirmATExists(max_string_len, SHP_ptr, SHP_ptr->chip_num, port_number, I_am_Alice, Alice_socket_desc,
&local_AT_status, &remote_AT_status);
// Sanity check
if ( chip_num != Alice_chip_num )
{
printf("ERROR: AliceWithdrawal(): chip_num sent by Alice to get AT %d differs from chip_num returned by 'ExchangeIDs...' %d\n",
chip_num, Alice_chip_num); exit(EXIT_FAILURE);
}
// Return FAILURE if both Alice and Bob do NOT have ATs for each other.
if ( remote_AT_status == -1 || local_AT_status == -1 )
{
printf("WARNING: AliceWithdrawal(): Alice does NOT have an AT for the TTP: remote_AT_status is 0 => %d!\n", remote_AT_status); fflush(stdout);
return;
}
// Sanity checks.
if ( num_CIArr != 1 || My_TTP_index != 0 )
{ printf("ERROR: AliceWithdrawal(): The number of CIArr is NOT 1 (%d) OR My_TTP_index is not 0 (%d)!\n", num_CIArr, My_TTP_index); exit(EXIT_FAILURE); }
// Now generate a shared key. Assume Alice and TTP have ATs on each other. Exchange the nonces in the ATs, hash them with
// the ZeroTrust_LLKs to create two ZHK_A_nonces, XOR them for the shared key. The shared key is stored in the Client_CIArr
// for the follow-up transaction.
I_am_Alice = 0;
if ( ZeroTrustGenSharedKey(max_string_len, SHP_ptr, Alice_chip_num, Alice_socket_desc, I_am_Alice, num_CIArr, Client_CIArr, My_TTP_index) == 1 )
{ printf("TTP SUCCEEDED in authenticating Alice and generating a shared key!\n"); fflush(stdout); }
else
{
printf("TTP FAILED in authenticating Alice and generating a shared key!\n"); fflush(stdout);
return;
}
// Get Alice-TTP shared key for ZeroTrust.
unsigned char *SK_FA = Client_CIArr[My_TTP_index].AliceBob_shared_key;
Client_CIArr[My_TTP_index].AliceBob_shared_key = NULL;
// Sanity check.
if ( SK_FA == NULL )
{ printf("ERROR: AliceWithdrawal(): SK_FA from ZeroTrust authen/key gen is NULL!\n"); exit(EXIT_FAILURE); }
// 1) Get Alice's chip_num and her encrypted withdrawal amount.
char *Alice_request_str[max_string_len];
int Alice_anon_chip_num, num_eCt;
unsigned char *eID_amt = Allocate1DUnsignedChar(AES_INPUT_NUM_BYTES);
// ****************************
// ADD CODE
// ****************************
// 2) Decrypt them
// ****************************
// ADD CODE
// ****************************
// ===============================
// 3) TTP checks Alice's Bank account and confirms she is allowed to withdraw this amount. NOTE: Use Alice's chip_num
// here (NOT her anonymous chip_num). The Bank gets the anonymous value if you decide to send it. Currently, only
// one TID allowed at this point.
int fail_or_pass;
int TID_DB, num_eCt_DB;
int do_update = 0;
int update_amt = 0;
pthread_mutex_lock(PUFCash_Account_DB_mutex_ptr);
PUFCashGetAcctRec(max_string_len, SHP_ptr->DB_PUFCash_V3, Alice_chip_num, &TID_DB, &num_eCt_DB, do_update, update_amt);
pthread_mutex_unlock(PUFCash_Account_DB_mutex_ptr);
// 4) Check request against balance, send ISF or HSF to Alice.
// ****************************
// ADD CODE
// ****************************
// 5) Start Bank transaction by sending Alice's request amount and chip_num (or anonomous chip_num).
if ( SockSendB((unsigned char *)"WITHDRAW", strlen("WITHDRAW") + 1, Bank_socket_desc) < 0 )
{ printf("ERROR: AliceWithdrawal(): Failed to send 'WITHDRAW' to Bank!\n"); exit(EXIT_FAILURE); }
// 6) Encrypt eID_amt with SK_TF
// ****************************
// ADD CODE
// ****************************
// 7) The Bank and Alice need to generate a session key. Normally Alice contacts the Bank to do this but we cannot
// break the chain of custody here between Alice->FI->TI, so the TTP will act as a forwarding agent between
// the Bank and Alice during KEK_SessionKeyGen process.
AliceTTPBankSessionKeyGen(max_string_len, SHP_ptr, Alice_socket_desc, Bank_socket_desc);
// ===============================
// 8) Get ACK/NAK from Bank
if ( SockGetB((unsigned char *)request_str, max_string_len, Bank_socket_desc) != 4 )
{ printf("ERROR: AliceWithdrawal(): Failed to get 'ACK/NAK' from Bank!\n"); exit(EXIT_FAILURE); }
if ( strcmp(request_str, "NAK") == 0 )
{
printf("WARNING: AliceWithdrawal(): Bank sent NAK -- cancelling transaction!\n");
return;
}
// 9) Get eeCt and heeCt and forward to Alice.
// ****************************
// ADD CODE
// ****************************
return;
}
// ========================================================================================================
// ========================================================================================================
// TTP thread.
void TTPThread(ThreadDataType *ThreadDataPtr)
{
SRFHardwareParamsStruct *SHP_ptr;
int Device_socket_desc;
unsigned char *SK_TF;
int Bank_socket_desc;
int client_index;
int *client_sockets;
int max_string_len;
char command_str[MAX_STRING_LEN];
static pthread_mutex_t PUFCash_Account_DB_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t ZeroTrust_AuthenToken_DB_mutex = PTHREAD_MUTEX_INITIALIZER;
printf("TTPThread: CREATED!\t(Task %d\tIterationCnt %d)\n", ThreadDataPtr->task_num, ThreadDataPtr->iteration_cnt); fflush(stdout);
#ifdef DEBUG
#endif
while (1)
{
// Sleep waiting for the main program to receive connect request from Alice or a TTP, and assign a Device_socket_desc
// No CPU cycles are wasted here in a busy wait, which is important when we query TTPs for performance information.
pthread_mutex_lock(&(ThreadDataPtr->Thread_mutex));
while ( ThreadDataPtr->in_use == 0 )
pthread_cond_wait(&(ThreadDataPtr->Thread_cv), &(ThreadDataPtr->Thread_mutex));
pthread_mutex_unlock(&(ThreadDataPtr->Thread_mutex));
struct timeval t1, t2;
long elapsed;
gettimeofday(&t2, 0);
#ifdef DEBUG
#endif
// task_num = ThreadDataPtr->task_num;
// iteration_cnt = ThreadDataPtr->iteration_cnt;
// Get local copies/pointers from the data structure.
SHP_ptr = ThreadDataPtr->SHP_ptr;
Device_socket_desc = ThreadDataPtr->Device_socket_desc;
SK_TF = ThreadDataPtr->TTP_session_key;
Bank_socket_desc = ThreadDataPtr->Bank_socket_desc;
client_index = ThreadDataPtr->client_index;
client_sockets = ThreadDataPtr->client_sockets;
max_string_len = ThreadDataPtr->max_string_len;
printf("\nTASK BEGIN: ID %d\tClient index %d\tDevice socket descriptor %d\tIterationCnt %d\n", ThreadDataPtr->task_num,
client_index, Device_socket_desc, ThreadDataPtr->iteration_cnt); fflush(stdout);
#ifdef DEBUG
#endif
// ====================================================================================================
// ====================================================================================================
// Originally did this but eliminated Bank requests in V3.0. These should never happen.
if ( client_index == 0 )
{
printf("Bank request!\n"); fflush(stdout);
exit(EXIT_FAILURE);
}
// All socket activity is from Alice or TTP (none ever from the Bank). Get the COMMAND string.
#ifdef DEBUG
printf("Alice request!\n"); fflush(stdout);
#endif
if ( SockGetB((unsigned char *)command_str, max_string_len, Device_socket_desc) < 0 )
{ printf("ERROR: TTPThread(): Error receiving 'command_str' from Alice!\n"); exit(EXIT_FAILURE); }
printf("\tProcessing command '%s'\tID %d\tITERATION %d\n", command_str, ThreadDataPtr->task_num, ThreadDataPtr->iteration_cnt); fflush(stdout);
#ifdef DEBUG
#endif
// =========================
// =========================
// PUF-Cash 3.0: Alice withdrawal.
if ( strcmp(command_str, "ALICE-WITHDRAWAL") == 0 )
AliceWithdrawal(max_string_len, SHP_ptr, Device_socket_desc, &PUFCash_Account_DB_mutex, &ZeroTrust_AuthenToken_DB_mutex, SK_TF,
MIN_WITHDRAW_INCREMENT, Bank_socket_desc, ThreadDataPtr->port_number, ThreadDataPtr->num_TTPs, ThreadDataPtr->Client_CIArr,
ThreadDataPtr->my_IP_pos);
// =========================
// =========================
// Unknown message type
else
{ printf("Unknown message '%s'\n", command_str); exit(EXIT_FAILURE); }
// ====================================================================================================
// Close the socket descriptor from another TTP or from Alice, BUT DO NOT CLOSE THE Bank socket descriptor at index 0.
if ( client_index != 0 )
{
printf("Closing Device socket %d\n", Device_socket_desc); fflush(stdout);
#ifdef DEBUG
#endif
close(Device_socket_desc);
// Restore activity on this client_socket_descriptor. Note this is a shared array among the threads but no semaphore needed here because
// each thread updates a unique element given by client_index.
client_sockets[client_index] = 0;
}
// Else restore the Bank socket descriptor on client socket 0. We assigned -1 to it when the thread was created to prevent main()
// OpenMultipleSocketServer() from processing activity while we service the request.
else
client_sockets[client_index] = Bank_socket_desc;
gettimeofday(&t1, 0); elapsed = (t1.tv_sec-t2.tv_sec)*1000000 + t1.tv_usec-t2.tv_usec; printf("\tElapsed: Command '%s'\tID %d\tITERATION %d\t%ld us\n\n",
command_str, ThreadDataPtr->task_num, ThreadDataPtr->iteration_cnt, (long)elapsed); fflush(stdout);
#ifdef DEBUG
#endif
// Indicate to the parent that this thread is available for reassignment.
pthread_mutex_lock(&(ThreadDataPtr->Thread_mutex));
ThreadDataPtr->in_use = 0;
pthread_mutex_unlock(&(ThreadDataPtr->Thread_mutex));
}
// Nope -- this generates some type of library required message -- an error. I'm not destroying threads any longer -- they get created and run forever.
// pthread_exit(NULL);
// We never return;
return;
}
// ========================================================================================================
// ========================================================================================================
// ========================================================================================================
// MEM LEAK
//#include <mcheck.h>
#define MAX_THREADS 20
SRFHardwareParamsStruct SHP[1];
ThreadDataType ThreadDataArr[MAX_THREADS] = {
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
{0, 0, NULL, NULL, 0, 0, "", NULL, 0, 0, 0, NULL, 0, 0, 0, NULL, 0, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER},
};
int main(int argc, char *argv[])
{
volatile unsigned int *CtrlRegA;
volatile unsigned int *DataRegA;
unsigned int ctrl_mask;
SRFHardwareParamsStruct *SHP_ptr;
char *history_file_name;
char *Bank_IP;
char *client_IP;
int *client_sockets;
int TTP_socket_desc = 0;
int Device_socket_desc = 0;
char *TTP_IP;
ClientInfoStruct *Client_CIArr;
int num_TTPs = 0;
int Bank_socket_desc;
int client_index;
int SD;
int RANDOM;
int nonce_base_address;
int num_eCt_nonce_bytes;
int num_KEK_authen_nonce_bytes;
int port_number;
int gen_session_key;
unsigned char *TTP_session_key;
int my_IP_pos;
int thread_num;
int exclude_self;
int fix_params;
int num_sams;
int num_PIs;
int num_POs;
int DUMP_BITSTRINGS;
int DEBUG_FLAG;
int PCR_or_PBD_or_PO;
// The PL-side TRNG_LFSR is 64 bits. Note that we currently only suport loading the low-order 8-bits of the seed register below.
unsigned char TRNG_LFSR_seed;
// ====================== DATABASE STUFF =========================
sqlite3 *DB_Challenges;
int rc;
char *DB_name_Challenges;
Allocate1DString(&DB_name_Challenges, MAX_STRING_LEN);
int use_database_chlngs;
char *Netlist_name;
char *Synthesis_name;
char *ChallengeSetName;
int design_index;
int num_PIs_DB, num_POs_DB;
int ChallengeGen_seed;
// Trust protocol
sqlite3 *DB_Trust_AT;
char *DB_name_Trust_AT;
Allocate1DString(&DB_name_Trust_AT, MAX_STRING_LEN);
// PUF-Cash V3.0 protocol
sqlite3 *DB_PUFCash_V3;
char *DB_name_PUFCash_V3;
Allocate1DString(&DB_name_PUFCash_V3, MAX_STRING_LEN);
float command_line_SC;
Allocate1DString(&TTP_IP, IP_LENGTH);
Allocate1DString(&Bank_IP, MAX_STRING_LEN);
Allocate1DString(&history_file_name, MAX_STRING_LEN);
// ======================================================================================================================
// COMMAND LINE
// ======================================================================================================================
if ( argc != 3 )
{
printf("ERROR: Parameters: Device IP (192.168.1.9) -- Bank IP (192.168.1.20)\n");
exit(EXIT_FAILURE);
}
strcpy(TTP_IP, argv[1]);
strcpy(Bank_IP, argv[2]);
fix_params = 0;
num_sams = 4;
PCR_or_PBD_or_PO = 0;
command_line_SC = 1.0;
// Sanity checks
if ( fix_params != 0 && fix_params != 1 )
{ printf("ERROR: 'fix_params' MUST be 0 or 1!\n"); exit(EXIT_FAILURE); }
if ( num_sams != 1 && num_sams != 4 && num_sams != 8 && num_sams != 16 )
{ printf("ERROR: 'num_sams' MUST be 1, 4, 8 or 16!\n"); exit(EXIT_FAILURE); }
if ( PCR_or_PBD_or_PO != 0 && PCR_or_PBD_or_PO != 1 && PCR_or_PBD_or_PO != 2 )
{ printf("ERROR: 'PCR_or_PBD_or_PO' MUST be 0, 1 or 2!\n"); exit(EXIT_FAILURE); }
// Upper limit is arbitrary -- they never get this big -- 3.2 looks to be the max.
if ( command_line_SC <= 0.0 || command_line_SC > (float)MAX_SCALING_VALUE )
{ printf("ERROR: 'command_line_SC' MUST be >= 0.0 and <= %f -- FIX ME!\n", (float)MAX_SCALING_VALUE); exit(EXIT_FAILURE); }
// This doesn't work yet -- still using command line value.
// GetMyIPAddr(MAX_STRING_LEN, "eth0", &TTP_IP);
Allocate1DString(&client_IP, MAX_STRING_LEN);
client_sockets = Allocate1DIntArray(MAX_CLIENTS);
Allocate1DString((char **)(&Netlist_name), MAX_STRING_LEN);
Allocate1DString((char **)(&Synthesis_name), MAX_STRING_LEN);
Allocate1DString((char **)(&ChallengeSetName), MAX_STRING_LEN);
// ====================================================== PARAMETERS ====================================================
strcpy(DB_name_Challenges, "Challenges.db");
strcpy(Netlist_name, "SR_RFM_V4_TDC");
strcpy(Synthesis_name, "SRFSyn1");
strcpy(ChallengeSetName, "Master1_OptKEK_TVN_0.00_WID_1.75");
strcpy(DB_name_Trust_AT, "AuthenticationToken.db");
strcpy(DB_name_PUFCash_V3, "PUFCash_V3.db");
// Must be set to 0 until I fully integrate this into all of the primitives.
use_database_chlngs = 0;
ChallengeGen_seed = 1;
char AES_IV[AES_IV_NUM_BYTES] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF};
// For Customer Acct Creation: Default transaction ID. We allow only one record for now.
int TID = 0;
// Default deposit amount for each customer ($100). Must be divisible by MIN_WITHDRAW_INCREMENT (500 or $5).
int default_deposit_amt = 10000;
// The PL-side TRNG_LFSR is 64 bits.
TRNG_LFSR_seed = 1;
strcpy(history_file_name, "TTP0_history.txt");
// Used only in the multiple TTP model.
exclude_self = 0;
// NOTE: ASSUMPTION:
// NUM_XOR_NONCE_BYTES <= num_eCt_nonce_bytes == SE_TARGET_NUM_KEY_BITS/8 <= NUM_REQUIRED_PNDIFFS/8
// 8 16 32 256
// We always use 8 bytes for the XOR_nonce (NUM_XOR_NONCE_BYTES) to SelectParams. My plan is to use 16 byte nonces
// (num_eCt_nonce_bytes), 32 bytes AES session keys (256 bits for SE_TARGET_NUM_KEY_BITS) and NUM_REQUIRED_PNDIFFS are always
// 2048/16 = 256.
num_eCt_nonce_bytes = ECT_NUM_BYTES;
num_KEK_authen_nonce_bytes = KEK_AUTHEN_NUM_NONCE_BITS/8;
// Base address, can be eliminated -- always 0.
nonce_base_address = 0;
port_number = 8888;
// These depend on the function unit. For SR_RFM, it's 784 and 64
num_PIs = NUM_PIS;
num_POs = NUM_POS;
// MEM LEAK -- also run 'export MALLOC_TRACE=./memtrace.txt' at the command line.
// mtrace();
// Enable/disable debug information.
DUMP_BITSTRINGS = 0;
DEBUG_FLAG = 0;
// ====================================================== PARAMETERS ====================================================
// Sanity check. With SF stored in (signed char) now, we can NOT allow TrimCodeConstant to be any larger than 64. See
// log notes on 1_1_2022.
if ( TRIMCODE_CONSTANT > 64 )
{ printf("ERROR: main(): TRIMCODE_CONSTANT %d MUST be <= 64\n", TRIMCODE_CONSTANT); exit(EXIT_FAILURE); }
// We also assume that the SHA-3 hash input and output are the same size as the AK_A/HK_As, which must be the same size as
// the KEK key (since we use KEK_Regen() below to regenerate it).
if ( HASH_IN_LEN_BITS != KEK_TARGET_NUM_KEY_BITS || HASH_OUT_LEN_BITS != KEK_TARGET_NUM_KEY_BITS )
{
printf("ERROR: main(): HASH_IN_LEN_BITS %d MUST be equal to HASH_OUT_LEN_BIT %d MUST be equal to KEK_TARGET_NUM_KEY_BITS %d\n",
HASH_IN_LEN_BITS, HASH_OUT_LEN_BITS, KEK_TARGET_NUM_KEY_BITS); exit(EXIT_FAILURE);
}
// Sanity check, constraint must be honored because of space allocations.
// NUM_XOR_NONCE_BYTES <= num_eCt_nonce_bytes <= SE_TARGET_NUM_KEY_BITS/8 <= NUM_REQUIRED_PNDIFFS/8
// 8 16 32 256
if ( !(NUM_XOR_NONCE_BYTES <= num_eCt_nonce_bytes && num_eCt_nonce_bytes <= SE_TARGET_NUM_KEY_BITS/8 &&
SE_TARGET_NUM_KEY_BITS/8 <= NUM_REQUIRED_PNDIFFS/8) )
{
printf("ERROR: Constraint violated: NUM_XOR_NONCE_BYTES %d <= num_eCt_nonce_bytes %d && \n\
num_eCt_nonce_bytes %d == SE_TARGET_NUM_KEY_BITS/8 %d <= NUM_REQUIRED_PNDIFFS/8 %d\n",
NUM_XOR_NONCE_BYTES, num_eCt_nonce_bytes, num_eCt_nonce_bytes, SE_TARGET_NUM_KEY_BITS/8, NUM_REQUIRED_PNDIFFS/8);
exit(EXIT_FAILURE);
}
printf("Parameters: This Device IP %s\tBank IP %s\tFIX PARAMS %d\tNum Sams %d\tPCR/PBD/PO %d\n", TTP_IP, Bank_IP, fix_params,
num_sams, PCR_or_PBD_or_PO); fflush(stdout);
// The number of samples is set BELOW after CtrlRegA is given an address.
ctrl_mask = 0;
// For handling Ctrl-C. We MUST exit gracefully to keep the hardware from quitting at a point where the
// fine phase of the MMCM is has not be set back to 0. If it isn't, then re-running this program will
// likely fail because my local fine phase register (which is zero initially after a RESET) is out-of-sync
// with the MMCM phase (which is NOT zero).
signal(SIGINT, intHandler);
// When we save output file, this tells us what we used.
printf("PARAMETERS: SE Target Num Bits %d\n\n", SE_TARGET_NUM_KEY_BITS);
// Open up the memory mapped device so we can access the GPIO registers.
int fd = open("/dev/mem", O_RDWR|O_SYNC);
if (fd < 0)
{ printf("ERROR: /dev/mem could NOT be opened!\n"); exit(EXIT_FAILURE); }
// Add 2 for the DataReg (for an SpreadFactor of 8 bytes for 32-bit integer variables)
DataRegA = mmap(0, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_0_BASE_ADDR);
CtrlRegA = DataRegA + 2;
// **********************************************************************************************************
// !!!!!!!!!! FOR TDC, THE LOW ORDER 4 BITS at RESET are dedicated to the TimingDivisor and MUST BE 0.
// Do a hardware reset. NOTE: We also load the initial seed for the TRNG here. Only the low-order 8 bits.
//
// 1_23_2022: Inspected /borg_data/FPGAs/ZYBO/SR_RFM/Verilog/COMMON/Top_TDC.v (and Top_MMCM.v) -- looks
// like I load TRNG_CP_LFSR_seed[7:0] with GPIO bits [15:8] at RESET in TRNG.v,
// assign TRNG_CP_LFSR_seed[7:0] = GPIO_Ins_tri_i[`WORD_SIZE_NB-1:8];
//
// *CtrlRegA = ctrl_mask | (1 << OUT_CP_RESET) | (unsigned int)(TRNG_LFSR_seed < 8);
*CtrlRegA = ctrl_mask | (1 << OUT_CP_RESET);
*CtrlRegA = ctrl_mask;
usleep(10000);
// Set the number of samples
if ( num_sams == 1 )
ctrl_mask = (0 << OUT_CP_NUM_SAM1) | (0 << OUT_CP_NUM_SAM0);
else if ( num_sams == 4 )
ctrl_mask = (0 << OUT_CP_NUM_SAM1) | (1 << OUT_CP_NUM_SAM0);
else if ( num_sams == 8 )
ctrl_mask = (1 << OUT_CP_NUM_SAM1) | (0 << OUT_CP_NUM_SAM0);
else if ( num_sams == 16 )
ctrl_mask = (1 << OUT_CP_NUM_SAM1) | (1 << OUT_CP_NUM_SAM0);
else
{ printf("ERROR: Number of samples MUST be 1, 4, 8 or 16!\n"); exit(EXIT_FAILURE); }
*CtrlRegA = ctrl_mask;
// ====================== DATABASE STUFF =========================
rc = sqlite3_open(":memory:", &DB_Challenges);
if ( rc != 0 )
{ printf("Failed to open Challenge Database: %s\n", sqlite3_errmsg(DB_Challenges)); sqlite3_close(DB_Challenges); exit(EXIT_FAILURE); }
#ifdef DEBUG
printf("Reading filesystem database '%s' into memory!\n", DB_name_Challenges); fflush(stdout);
#endif
if ( LoadOrSaveDb(DB_Challenges, DB_name_Challenges, 0) != 0 )
{ printf("Failed to open and copy into memory '%s': ERR: %s\n", DB_name_Challenges, sqlite3_errmsg(DB_Challenges)); sqlite3_close(DB_Challenges); exit(EXIT_FAILURE); }
// Get the PUFDesign parameters from the database.
if ( GetPUFDesignParams(MAX_STRING_LEN, DB_Challenges, Netlist_name, Synthesis_name, &design_index, &num_PIs_DB, &num_POs_DB) != 0 )
{ printf("ERROR: PUFDesign index NOT found for '%s', '%s'!\n", Netlist_name, Synthesis_name); exit(EXIT_FAILURE); }
// Sanity check
if ( num_PIs_DB != num_PIs || num_POs_DB != num_POs )
{
printf("ERROR: Number of PIs %d or POs %d in database do NOT match those in common.h %d and %d!\n", num_PIs_DB, num_POs_DB, num_PIs, num_POs);
exit(EXIT_FAILURE);
}
// Trust protocol
rc = sqlite3_open(":memory:", &DB_Trust_AT);
if ( rc != 0 )
{ printf("Failed to open Trust_AT Database: %s\n", sqlite3_errmsg(DB_Trust_AT)); sqlite3_close(DB_Trust_AT); exit(EXIT_FAILURE); }
#ifdef DEBUG
printf("Reading filesystem database '%s' into memory!\n", DB_name_Trust_AT); fflush(stdout);
#endif
if ( LoadOrSaveDb(DB_Trust_AT, DB_name_Trust_AT, 0) != 0 )
{ printf("Failed to open and copy into memory '%s': ERR: %s\n", DB_name_Trust_AT, sqlite3_errmsg(DB_Trust_AT)); sqlite3_close(DB_Trust_AT); exit(EXIT_FAILURE); }
// PUF-Cash V3.0
rc = sqlite3_open(":memory:", &DB_PUFCash_V3);
if ( rc != 0 )
{ printf("Failed to open PUFCash_V3 Database: %s\n", sqlite3_errmsg(DB_PUFCash_V3)); sqlite3_close(DB_PUFCash_V3); exit(EXIT_FAILURE); }
#ifdef DEBUG
printf("Reading filesystem database '%s' into memory!\n", DB_name_PUFCash_V3); fflush(stdout);
#endif
if ( LoadOrSaveDb(DB_PUFCash_V3, DB_name_PUFCash_V3, 0) != 0 )
{ printf("Failed to open and copy into memory '%s': ERR: %s\n", DB_name_PUFCash_V3, sqlite3_errmsg(DB_PUFCash_V3)); sqlite3_close(DB_PUFCash_V3); exit(EXIT_FAILURE); }
// ================================================================================================================================
// ================================================================================================================================
SHP_ptr = &(SHP[0]);
// NOTE: WE MUST DO THIS IN THE PARENT because we use it below.
static pthread_mutex_t GenChallenge_mutex = PTHREAD_MUTEX_INITIALIZER;
// If we set 'use_database_chlngs' to 1, then we can NOT allow more than one thread to run GenChallengeDB() at the same time because we
// call rand(). If the device or TTP is going to get the same set of random numbers as this verifier is than after srand() is seeded with
// 'DB_ChallengeGen_seed', we must block other threads until the vector sequence is completely generated, i.e., rand() is NOT re-entrant!
// We can do this in main() or here once we've initialized the GenChallenge_mutex mutex above (it is static and therefore global to all threads).
SHP_ptr->GenChallenge_mutex_ptr = &GenChallenge_mutex;
// =========================
// Set some of the params in the data structure. NOTE: This structure is not really used AFTER the authentication and session key generation
// with the Bank below. We need to be careful if we start using the PUF within the processing loop below. We must create an array of these SHP
// structures for each thread (using only one for now), and then protect calls to the PUF using semaphores.
SHP_ptr->CtrlRegA = CtrlRegA;
SHP_ptr->DataRegA = DataRegA;
SHP_ptr->ctrl_mask = ctrl_mask;
// After device authenticates successfully, verifier sends its ID from the Enrollment database to the device. The device will use this as it's ID.
SHP_ptr->chip_num = -1;
// NOT relevant here in the TTP.
SHP_ptr->anon_chip_num = -1;
SHP_ptr->DB_Challenges = DB_Challenges;
SHP_ptr->DB_name_Challenges = DB_name_Challenges;
SHP_ptr->use_database_chlngs = use_database_chlngs;
SHP_ptr->DB_design_index = design_index;
SHP_ptr->DB_ChallengeSetName = ChallengeSetName;
SHP_ptr->DB_ChallengeGen_seed = ChallengeGen_seed;
SHP_ptr->DB_Trust_AT = DB_Trust_AT;
SHP_ptr->DB_name_Trust_AT = DB_name_Trust_AT;
SHP_ptr->DB_PUFCash_V3 = DB_PUFCash_V3;
SHP_ptr->DB_name_PUFCash_V3 = DB_name_PUFCash_V3;
SHP_ptr->eCt_num_bytes = ECT_NUM_BYTES;