-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.cpp
1734 lines (1507 loc) · 57.5 KB
/
server.cpp
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 <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <limits.h>
#include <sys/mman.h>
#include <semaphore.h>
#include <sys/wait.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/x509_vfy.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <errno.h>
#include <fcntl.h>
#include "constant.h"
#include "util.h"
#include "crypto.h"
using namespace std;
using uchar=unsigned char;
typedef void (*sighandler_t)(int);
/*
* socket_id: if equal to -1 the user is not connected to the service
*/
struct user_info {
string username;
int socket_id;
int busy =0;
};
struct msg_to_relay{
long type;
char buffer[RELAY_MSG_SIZE];
};
//---------------- GLOBAL VARIABLES ------------------//
int client_user_id;
int comm_socket_id;
msg_to_relay relay_msg;
//Parameters of connection
const char *srv_ipv4 = "127.0.0.1";
const int srv_port = 4242;
void* server_privk;
uchar* session_key;
uint32_t session_key_len;
//Handling mutual exclusion for accessing the user datastore
const char* sem_user_store_name = "/user_store";
const char* message_queue_name = "/user_message_queue";
void* create_shared_memory(ssize_t size);
//Shared memory for storing data of users
void* shmem = create_shared_memory(sizeof(user_info)*REGISTERED_USERS);
int send_secure(int comm_socket_id, uchar* pt, uint pt_len);
int recv_secure(int comm_socket_id, unsigned char** plaintext);
void* create_shared_memory(ssize_t size){
int protection = PROT_READ | PROT_WRITE; //Processes can read/write the contents of the memory
int visibility = MAP_SHARED | MAP_ANONYMOUS; //Memory pages are shared across processes
return mmap(NULL, size, protection, visibility, -1, 0);
}
// ---------------------------------------------------------------------
// FUNCTIONS for accessing to the USER DATASTORE
// ---------------------------------------------------------------------
/**
* @brief prologue for granting mutual exclusion by using named semaphore sem_id
* @return -1 in case of errors, 0 otherwise
*/
int sem_prologue(sem_t* sem_id){
vlog("sem_enter");
if(sem_id == nullptr){
log("sem_prologue: nullptr found");
return -1;
}
if(sem_id == SEM_FAILED){
log("SEM_FAILED");
return -1;
}
if(-1 == sem_wait(sem_id)){
log("ERROR on sem_wait");
return -1;
}
return 0;
}
/**
* @brief epilogue for granting mutual exclusion by using named semaphore sem_id
* @return -1 in case of errors, 0 otherwise
*/
int sem_epilogue(sem_t* sem_id){
vlog("sem_exit");
if(sem_id == nullptr){
log("sem_epilogue: nullptr found");
return -1;
}
if(-1 == sem_post(sem_id)){
log("ERROR on sem_exit");
return -1;
}
if(-1 == sem_close(sem_id)){
log("ERROR on sem_close");
return -1;
}
return 0;
}
/**
* @brief test socket of communication in the user data store
* @return return -1 in case the user is offline, -2 in case of errors, the socket_id otherwise
*/
int get_user_socket_by_user_id(int user_id){
if(user_id < 0 || user_id >= REGISTERED_USERS){
log("ERROR: Invalid user id");
return -2;
}
sem_t* sem_id= sem_open(sem_user_store_name, O_CREAT, 0600, 1);
if(-1 == sem_prologue(sem_id)){
log("ERROR on sem_prologue");
return -2;
}
user_info* user_status = (user_info*)shmem;
int socket_id = user_status[user_id].socket_id;
if(-1 == sem_epilogue(sem_id)){
log("ERROR on sem_epilogue");
return -2;
}
return socket_id;
}
/**
* @brief test if the user is buidi in a chat request
*
* @param user_id
* @return int 0 if busy, 1 if free, -1 on error(s)
*/
int test_user_busy_by_user_id(int user_id){
if(user_id < 0 || user_id >= REGISTERED_USERS){
log("ERROR: Invalid user id");
return -1;
}
sem_t* sem_id= sem_open(sem_user_store_name, O_CREAT, 0600, 1);
if(-1 == sem_prologue(sem_id)){
log("ERROR on sem_prologue");
return -1;
}
user_info* user_status = (user_info*)shmem;
int ret=user_status[user_id].busy;
if(-1 == sem_epilogue(sem_id)){
log("ERROR on sem_epilogue");
return -1;
}
return !ret;
}
/**
* @brief set the user busy flag
*
* @param user_id
* @param busy
* @return 1 on succes, -1 on error
*/
int set_user_busy_by_user_id(int user_id, int busy){
if(user_id < 0 || user_id >= REGISTERED_USERS){
log("ERROR: Invalid user id");
return -1;
}
sem_t* sem_id= sem_open(sem_user_store_name, O_CREAT, 0600, 1);
if(-1 == sem_prologue(sem_id)){
log("ERROR on sem_prologue");
return -1;
}
user_info* user_status = (user_info*)shmem;
user_status[user_id].busy=busy;
if(-1 == sem_epilogue(sem_id)){
log("ERROR on sem_epilogue");
return -1;
}
return 1;
}
/**
* @brief test socket of communication in the user data store
* @return return -1 in case of errors, 0 otherwise
*/
int set_user_socket(string username, int socket){
if(socket < -1){ //Sanitization (-1 indicate that the user will be offline)
log("SOCKET fd invalid"); //since file descriptors can have only values >= 0
return -1;
}
sem_t* sem_id= sem_open(sem_user_store_name, O_CREAT, 0600, 1);
if(-1 == sem_prologue(sem_id)){
log("ERROR on sem_prologue");
return -1;
}
user_info* user_status = (user_info*)shmem;
int found = 0;
for(int i=0; i<REGISTERED_USERS; i++){
if(user_status[i].username.compare(username) == 0){
user_status[i].socket_id = socket;
if(socket==-1)
vlog("\n\n***** logout of client " +username+" *****\n\n");
vlog("Set socket of " + username + " correctly");
found = 1;
break;
}
}
if(-1 == sem_epilogue(sem_id)){
log("ERROR on sem_epilogue");
return -1;
}
return found;
}
/**
* @brief prints content of user datastore for debugging purposes
*/
void print_user_data_store(){
sem_t* sem_id= sem_open(sem_user_store_name, O_CREAT, 0600, 1);
if(-1 == sem_prologue(sem_id)){
log("ERROR on sem_prologue");
return;
}
user_info* user_status = (user_info*)shmem;
cout << "\n\n****** USER STATUS *******\n\n" << endl;
for(int i=0; i<REGISTERED_USERS; i++){
cout << "[" << i << "] " << user_status[i].username << " | " << user_status[i].socket_id << " | " << " | " << ((user_status[i].socket_id==-1)?"offline":"online") << endl;
}
cout << "\n\n**************************\n\n" << endl;
if(-1 == sem_epilogue(sem_id)){
log("ERROR on sem_epilogue");
return;
}
}
/**
* @brief obtain a copy of the user datastore
* @return the copy of the user datastore, nullptr in case of errors
*/
user_info* get_user_datastore_copy(){
sem_t* sem_id= sem_open(sem_user_store_name, O_CREAT, 0600, 1);
if(-1 == sem_prologue(sem_id)){
log("ERROR on sem_prologue");
return nullptr;
}
int ret;
char buf;
//Obtain a copy of the user datastore
user_info* user_status = (user_info*)malloc(REGISTERED_USERS*sizeof(user_info));
if(!user_status){
log("ERROR on malloc");
return nullptr;
}
memcpy(user_status, shmem, REGISTERED_USERS*sizeof(user_info));
if(-1 == sem_epilogue(sem_id)){
log("ERROR on sem_epilogue");
return nullptr;
}
return user_status;
}
/**
* @brief initialize content of user datastore which is used to simulate a database
* @return 0 in case of errors, 1 in case of success
*/
int initialize_user_info(user_info* user_status){
if(user_status == nullptr){
return 0;
}
vector<string> usernames {"alice", "bob", "charlie", "dave", "ethan"};
for(int i=0; i < REGISTERED_USERS; i++){
user_status[i].username = usernames[i];
user_status[i].socket_id = -1;
}
return 1;
}
int get_user_id_by_username(string username){
vlog("Entering get id by username");
if(username.empty()){
log("INVALID usernam on get_user_id_by_username");
return -1;
}
sem_t* sem_id= sem_open(sem_user_store_name, O_CREAT, 0600, 1);
if(-1 == sem_prologue(sem_id)){
log("ERROR on sem_prologue");
return -1;
}
int ret = -1;
user_info* user_status = (user_info*)shmem;
for(int i=0; i<REGISTERED_USERS; i++){
if(user_status[i].username.compare(username) == 0){
vlog("Found username " + username + " in the datastore with user_id " + to_string(i));
ret = i;
break;
}
}
if(-1 == sem_epilogue(sem_id)){
log("ERROR on sem_epilogue");
return -1;
}
return ret;
}
/**
* @return username or empty string in case of errors
*/
string get_username_by_user_id(size_t id){
vlog("get username by id");
if(id >= REGISTERED_USERS){
log(" ERR - User_id not present");
errorHandler(GEN_ERR);
}
sem_t* sem_id= sem_open(sem_user_store_name, O_CREAT, 0600, 1);
if(-1 == sem_prologue(sem_id)){
log("ERROR on sem_prologue");
return string();
}
user_info* user_status = (user_info*)shmem;
string username = user_status[id].username;
vlog("Obtained username of " + username);
if(-1 == sem_epilogue(sem_id)){
log("ERROR on sem_epilogue");
return string();
}
return username;
}
/**
* @brief Removes traces of other execution due to the utilization of "named" data structures (semaphores and pipes) that can survive
*/
void prior_cleanup(){
sem_unlink(sem_user_store_name); //Remove traces of usage for older execution
key_t key = ftok(message_queue_name, 65);
int msgid = msgget(key, 0666 | IPC_CREAT);
msgctl(msgid, IPC_RMID, NULL);
msgid = msgget(key, 0666 | IPC_CREAT);
//Add more space to buffer
struct msqid_ds buf;
msgctl(msgid, IPC_STAT, &buf);
buf.msg_qbytes = 600000;
int ret = msgctl(msgid, IPC_SET, &buf);
msgctl(msgid, IPC_STAT, &buf);
vlog("Message queue size: " + to_string(buf.msg_qbytes));
}
// ---------------------------------------------------------------------
// FUNCTIONS of INTER-PROCESS COMMUNICATION
// ---------------------------------------------------------------------
/**
* Send message to message queue of to_user_id
* @return 0 in case of success, -1 in case of error
*/
int relay_write(uint to_user_id, msg_to_relay msg){
if(to_user_id >= REGISTERED_USERS)
return -1;
vlog("Entering relay_write for " + to_string(to_user_id));
msg.type = to_user_id + 1;
key_t key = ftok(message_queue_name, 65);
vlog("Key of ftok returned is " + to_string(key));
int msgid = msgget(key, 0666 | IPC_CREAT);
vlog("msgid is " + to_string(msgid));
return msgsnd(msgid, &msg, sizeof(msg_to_relay), 0);
}
/**
* @brief read from message queue of user_id (blocking)
* @return -1 if no message has been read otherwise return the bytes copied
**/
int relay_read(int user_id, msg_to_relay& msg, bool blocking){
uint time_remained;
if(user_id >= REGISTERED_USERS || user_id < 0)
return -1;
if(blocking)
time_remained = alarm(0);
int ret = -1;
vlog("relay_read of user_id " + to_string(user_id) + " [" + (blocking? "blocking": "non blocking") + "]");
//Read from the message queue
key_t key = ftok(message_queue_name, 65);
vlog("Key of ftok returned is " + to_string(key));
//msg.type = 0;
int msgid = msgget(key, 0666 | IPC_CREAT);
vlog("msgid is " + to_string(msgid));
ret = msgrcv(msgid, &msg, sizeof(msg), user_id+1, (blocking? 0: IPC_NOWAIT));
if(ret == -1)
vlog("read nothing");
if(blocking){
if(time_remained > 0)
alarm(time_remained);
else
alarm(RELAY_CONTROL_TIME);
}
return ret;
}
// ---------------------------------------------------------------------
// FUNCTIONS of HANDLING SIGNALS
// ---------------------------------------------------------------------
/**
* @brief Handler that handles the SIG_ALARM, this represents the fact that every REQUEST_CONTROL_TIME the client must control for chat request
* @param sig
*/
void signal_handler(int sig)
{
vlog("signal handler");
int ret;
uint8_t opcode;
int bytes_copied = relay_read(client_user_id, relay_msg, false);
uint msg_len;
if(bytes_copied > 0){
opcode = relay_msg.buffer[0];
log("Found request to relay with opcode: " + to_string(opcode));
if(opcode == CHAT_CMD) {
uint username_length, username_length_net;
memcpy(&username_length_net, (void*)(relay_msg.buffer + 5), sizeof(int));
username_length = ntohl(username_length_net);
vlog("USERNAME LENGTH: " + to_string(username_length));
if(username_length > UINT_MAX - 9 - PUBKEY_DEFAULT_SER){
log("ERROR: unsigned wrap");
return;
}
msg_len = 9 + username_length + PUBKEY_DEFAULT_SER;
// Send reply of the peer to the client
ret = send_secure(comm_socket_id, (uchar*)relay_msg.buffer, msg_len);
if(ret == 0){
log("ERROR on send_secure");
close(comm_socket_id);
exit(1);
}
// log("Sent to client : ");
// BIO_dump_fp(stdout, (const char*)relay_msg.buffer, msg_len);
} else if(opcode == AUTH || opcode == CHAT_RESPONSE){
memcpy(&msg_len, relay_msg.buffer + 1, sizeof(int)); //Added len field
if(msg_len < 1){
log("ERROR: msg_len < 1");
close(comm_socket_id);
exit(1);
}
uchar* msg_to_send = (uchar*)malloc(msg_len);
if(!msg_to_send){
log("ERROR on malloc");
close(comm_socket_id);
exit(1);
}
msg_to_send[0] = opcode;
memcpy(msg_to_send + 1, relay_msg.buffer + 5, msg_len - 1);
ret = send_secure(comm_socket_id, (uchar*)msg_to_send, msg_len);
if(ret == 0){
log("ERROR on send_secure");
close(comm_socket_id);
free(msg_to_send);
exit(1);
}
// log("Sent to client : ");
// BIO_dump_fp(stdout, (const char*)msg_to_send, msg_len);
free(msg_to_send);
} else if(opcode == STOP_CHAT || opcode == CHAT_NEG){
msg_len = 5;
// Send reply of the peer to the client
ret = send_secure(comm_socket_id, (uchar*)relay_msg.buffer, msg_len);
if(ret == 0){
log("ERROR on send_secure");
close(comm_socket_id);
exit(1);
}
// log("Sent to client : ");
// BIO_dump_fp(stdout, (const char*)relay_msg.buffer, msg_len);
} else {
log("OPCODE not recognized (" + to_string(opcode) + ")");
}
}
alarm(RELAY_CONTROL_TIME);
return;
}
// ---------------------------------------------------------------------
// FUNCTIONS of SECURITY
// ---------------------------------------------------------------------
uint32_t send_counter=0;
/**
* @brief perform a an authenticad encryption and then a send operation
* @param pt: pointer to plaintext without sequence number
* @return 1 in case of success, 0 in case of error
*/
int send_secure(int comm_socket_id, uchar* pt, uint pt_len){
if(pt_len < 0 || comm_socket_id < 0){
log("ERROR invalid parameters on send_secure");
return 0;
}
int ret;
uchar *tag, *iv, *ct, *aad;
//alarm(0);
uint aad_len;
// log("Plaintext to send:");
// BIO_dump_fp(stdout, (const char*)pt, pt_len);
uint32_t header_len = sizeof(uint32_t)+IV_DEFAULT+TAG_DEFAULT;
// adding sequence number
uint32_t counter_n=htonl(send_counter);
// cout <<" adding sequrnce number " << send_counter << endl;
if(pt_len > UINT_MAX - sizeof(uint32_t)){
log("ERROR: unsigned wrap");
return 0;
}
uchar* pt_seq = (uchar*)malloc(pt_len+sizeof(uint32_t));
memcpy(pt_seq , &counter_n, sizeof(uint32_t));
memcpy(pt_seq+ sizeof(uint32_t), pt, pt_len);
pt=pt_seq;
pt_len+=sizeof(uint32_t);
// log("Plaintext to send (with seq):");
// BIO_dump_fp(stdout, (const char*)pt, pt_len);
uint aad_ct_len_net = htonl(pt_len); //Since we use GCM ciphertext == plaintext
uint ct_len = auth_enc_encrypt(pt, pt_len, (uchar*)&aad_ct_len_net, sizeof(uint), session_key, &tag, &iv, &ct);
if(ct_len == 0){
log("auth_enc_encrypt failed");
return 0;
}
// log("ct_len: " + to_string(ct_len));
if(ct_len > UINT_MAX - header_len){
log("ERROR: unsigned wrap");
return 0;
}
uint msg_to_send_len = ct_len + header_len, bytes_copied = 0;
uchar* msg_to_send = (uchar*)malloc(msg_to_send_len);
if(!msg_to_send){
// errorHandler(MALLOC_ERR);
return 0;
}
// cout << aad_ct_len_net << " -> " << ntohl(aad_ct_len_net) << endl;
memcpy(msg_to_send + bytes_copied, &aad_ct_len_net, sizeof(uint));
bytes_copied += sizeof(uint);
memcpy(msg_to_send + bytes_copied, iv, IV_DEFAULT);
bytes_copied += IV_DEFAULT;
memcpy(msg_to_send + bytes_copied, tag, TAG_DEFAULT);
bytes_copied += TAG_DEFAULT;
memcpy(msg_to_send + bytes_copied, ct, ct_len);
bytes_copied += sizeof(uint);
// log("Msg (authenticated and encrypted) to send, (copied " + to_string(bytes_copied) + " of " + to_string(msg_to_send_len) + "):");
// BIO_dump_fp(stdout, (const char*)msg_to_send, msg_to_send_len);
//-----------------------------------------------------------
// Controllo encr/decr
unsigned char* pt_test = NULL;
int pt_len_test = auth_enc_decrypt(ct, ct_len, (uchar*)&aad_ct_len_net, sizeof(uint32_t), session_key, tag, iv, &pt_test);
if(pt_len_test == 0){
log("auth_enc_decrypt failed");
return 0;
}
// log(" plaintext ");
// BIO_dump_fp(stdout, (const char*)pt_test, pt_len_test);
safe_free(pt, pt_len);
//------------------------------------------------------
ret = send(comm_socket_id, msg_to_send, msg_to_send_len, 0);
if(ret <= 0 || ret != msg_to_send_len){
errorHandler(SEND_ERR);
safe_free(msg_to_send, msg_to_send_len);
return 0;
}
send_counter++;
if(send_counter == 0){
log("ERROR: unsigned wrap on SEND COUNTER");
return 0;
}
safe_free(msg_to_send, msg_to_send_len);
//alarm(RELAY_CONTROL_TIME);
return 1;
}
uint32_t receive_counter=0;
/**
* @brief Receive in a secure way the messages sent by the server, decipher it and return the plaintext in the correspodent parameter. It
* also control the sequence number
*
* @param socket socket id
* @param plaintext plaintext obtained by the decryption of the ciphertext
* @return int plaintext length or -1 if error
*/
int recv_secure(int comm_socket_id, unsigned char** plaintext)
{
// if(comm_socket_id < 0){
// log("INVALID parameters on recv_secure");
// return -1;
// }
vlog(" SECURE RECEIVE ");
uint32_t header_len = sizeof(uint32_t)+IV_DEFAULT+TAG_DEFAULT;
uint32_t ct_len;
unsigned char* ciphertext = NULL;
uint32_t pt_len;
int ret;
//alarm(0);
unsigned char* header = (unsigned char*)malloc(header_len);
if(!header){
cerr << " Error in malloc for header " << endl;
return -1;
}
unsigned char* iv = (unsigned char*)malloc(IV_DEFAULT);
if(!iv){
cerr << " Error in malloc for iv " << endl;
safe_free(header, header_len);
return -1;
}
unsigned char* tag = (unsigned char*)malloc(TAG_DEFAULT);
if(!tag){
cerr << " Error in malloc for tag " << endl;
safe_free(header, header_len);
safe_free(iv, IV_DEFAULT);
return -1;
}
// Receive Header
//cout << " DBG - Before recv " << endl;
//BIO_dump_fp(stdout, (const char*)header, header_len);
ret = recv(comm_socket_id, (void*)header, header_len, 0);
if(ret <= 0 || ret != header_len){
cerr << " Error in header reception " << ret << endl;
close(comm_socket_id);
BIO_dump_fp(stdout, (const char*)header, header_len);
safe_free(tag, TAG_DEFAULT);
safe_free(header, header_len);
safe_free(iv, IV_DEFAULT);
return -1;
}
// BIO_dump_fp(stdout, (const char*)header, header_len);
// Open header
memcpy((void*)&ct_len, header, sizeof(uint32_t));
// log(" ct_len :");
// BIO_dump_fp(stdout, (const char*)&ct_len, sizeof(uint32_t));
memcpy(iv, header+sizeof(uint32_t), IV_DEFAULT);
// log(" iv :");
// BIO_dump_fp(stdout, (const char*)iv, IV_DEFAULT);
memcpy(tag, header+sizeof(uint32_t)+IV_DEFAULT, TAG_DEFAULT);
// log(" tag :");
// BIO_dump_fp(stdout, (const char*)tag, TAG_DEFAULT);
unsigned char* aad = (unsigned char*)malloc(sizeof(uint32_t));
if(!aad){
cerr << " Error in aad malloc " << endl;
safe_free(tag, TAG_DEFAULT);
safe_free(header, header_len);
safe_free(iv, IV_DEFAULT);
return -1;
}
memcpy(aad, header, sizeof(uint32_t));
// log(" AAD : ");
// BIO_dump_fp(stdout, (const char*)aad, sizeof(uint32_t));
// Receive ciphertext
// cout << " DBG - ct_len before ntohl is " << ct_len << endl;
ct_len = ntohl(ct_len);
// cout << " DBG - ct_len real is " << ct_len << endl;
ciphertext = (unsigned char*)malloc(ct_len);
if(!ciphertext){
cerr << " Error in malloc for ciphertext " << endl;
safe_free(tag, TAG_DEFAULT);
safe_free(header, header_len);
safe_free(iv, IV_DEFAULT);
safe_free(aad, sizeof(uint32_t));
return -1;
}
ret = recv(comm_socket_id, (void*)ciphertext, ct_len, 0);
if(ret <= 0){
cerr << " Error in AAD reception " << endl;
safe_free(ciphertext, ct_len);
safe_free(tag, TAG_DEFAULT);
safe_free(header, header_len);
safe_free(iv, IV_DEFAULT);
safe_free(aad, sizeof(uint32_t));
return -1;
}
// cout << " ciphertext is: " << endl;
// BIO_dump_fp(stdout, (const char*)ciphertext, ct_len);
// Decryption
// cout<<"Session key:"<<endl;
// BIO_dump_fp(stdout, (const char*) session_key, 32);
pt_len = auth_enc_decrypt(ciphertext, ct_len, aad, sizeof(uint32_t), session_key, tag, iv, plaintext);
if(pt_len == 0 || pt_len!=ct_len){
cerr << " Error during decryption " << endl;
safe_free(*plaintext, pt_len);
safe_free(ciphertext, ct_len);
safe_free(tag, TAG_DEFAULT);
safe_free(header, header_len);
safe_free(iv, IV_DEFAULT);
safe_free(aad, sizeof(uint32_t));
return -1;
}
// cout << " ciphertext is: " << endl;
// BIO_dump_fp(stdout, (const char*)ciphertext, ct_len);
// cout << " plaintext is " << endl;
// BIO_dump_fp(stdout, (const char*)*plaintext, pt_len);
safe_free(ciphertext, ct_len);
safe_free(tag, TAG_DEFAULT);
safe_free(header, header_len);
safe_free(iv, IV_DEFAULT);
safe_free(aad, sizeof(uint32_t));
// check seq number
uint32_t sequece_number = ntohl(*(uint32_t*) (*plaintext));
// cout << " received sequence number " << sequece_number << " aka " << *(uint32_t*) (*plaintext) << endl;
// cout << " Expected sequence number " << receive_counter << endl;
if(sequece_number<receive_counter){
cerr << " Error: wrong seq number " << endl;
safe_free(*plaintext, pt_len);
return -1;
}
receive_counter=sequece_number+1;
if(receive_counter == 0){
log("ERROR: unsigned wrap on receive_counter");
return -1;
}
//alarm(RELAY_CONTROL_TIME);
return pt_len;
}
/**
* @brief handle authentication with the client
* @return user_id of the client or -1 in case of errors
*/
int handle_client_authentication(string pwd_for_keys){
/*************************************************************
* M1 - R1 and Username
*************************************************************/
int ret;
uchar* R1 = (uchar*)malloc(NONCE_SIZE);
if(!R1){
errorHandler(MALLOC_ERR);
return -1;
}
ret = recv(comm_socket_id, (void *)R1, NONCE_SIZE, 0);
if (ret <= 0 || ret != NONCE_SIZE){
errorHandler(REC_ERR);
safe_free(R1, NONCE_SIZE);
return -1;
}
// log("M1 auth (0) Received R1: ");
// BIO_dump_fp(stdout, (const char*)R1, NONCE_SIZE);
uint32_t client_username_len;
ret = recv(comm_socket_id, (void *)&client_username_len, sizeof(uint32_t), 0);
if (ret <= 0 || ret != sizeof(uint32_t)){
errorHandler(REC_ERR);
safe_free(R1, NONCE_SIZE);
return -1;
}
client_username_len = ntohl(client_username_len);
vlog("M1 auth (1) Received username size: " + to_string(client_username_len));
char* username = (char*)malloc(client_username_len);
if(!username){
errorHandler(MALLOC_ERR);
safe_free(R1, NONCE_SIZE);
return -1;
}
ret = recv(comm_socket_id, (void *)username, client_username_len, 0);
if (ret <= 0 || ret != client_username_len){
errorHandler(REC_ERR);
safe_free((uchar*)username, client_username_len);
safe_free(R1, NONCE_SIZE);
return -1;
}
string client_username(username);
vlog("M1 auth (2) Received username: " + client_username);
if(get_user_socket_by_user_id(get_user_id_by_username(username)) != -1){
log("ERROR user already online");
safe_free((uchar*)username, client_username_len);
safe_free(R1, NONCE_SIZE);
return -1;
}
safe_free((uchar*)username, client_username_len);
/*************************************************************
* M2 - Send R2,pubkey_eph,signature,certificate
*************************************************************/
uchar* R2 = (uchar*)malloc(NONCE_SIZE);
if(!R2){
errorHandler(MALLOC_ERR);
safe_free(R1, NONCE_SIZE);
return -1;
}
//Generate pair of ephermeral DH keys
void* eph_privkey_s;
uchar* eph_pubkey_s;
uint eph_pubkey_s_len;
ret = eph_key_generate(&eph_privkey_s, &eph_pubkey_s, &eph_pubkey_s_len);
if(ret != 1){
log("Error on EPH_KEY_GENERATE");
safe_free(R1, NONCE_SIZE);
safe_free(R2, NONCE_SIZE);
safe_free_privkey(eph_privkey_s);
safe_free(eph_pubkey_s, eph_pubkey_s_len);
return -1;
}
// log("M2 auth (1) pubkey: ");
// BIO_dump_fp(stdout, (const char*)eph_pubkey_s, eph_pubkey_s_len);
//Generate nuance R2
ret = random_generate(NONCE_SIZE, R2);
if(ret != 1){
log("Error on random_generate");
safe_free(R1, NONCE_SIZE);
safe_free(R2, NONCE_SIZE);
safe_free_privkey(eph_privkey_s);
safe_free(eph_pubkey_s, eph_pubkey_s_len);
return -1;
}
// log("auth (2) R2: ");
// BIO_dump_fp(stdout, (const char*)R2, NONCE_SIZE);
//Get certificate of Server
FILE* cert_file = fopen("certification/SecureCom_cert.pem", "rb");
if(!cert_file){
log("Error on opening cert file");
safe_free(R1, NONCE_SIZE);
safe_free(R2, NONCE_SIZE);
safe_free_privkey(eph_privkey_s);
safe_free(eph_pubkey_s, eph_pubkey_s_len);
return -1;
}
uchar* certificate_ser;
uint certificate_len = serialize_certificate(cert_file, &certificate_ser);
if(certificate_len == 0){
log("Error on serialize certificate");
fclose(cert_file);
safe_free(R1, NONCE_SIZE);
safe_free(R2, NONCE_SIZE);
safe_free_privkey(eph_privkey_s);
safe_free(eph_pubkey_s, eph_pubkey_s_len);
return -1;
}
// log("auth (3) certificate: ");
// BIO_dump_fp(stdout, (const char*)certificate_ser, certificate_len);
if(eph_pubkey_s_len > UINT_MAX - NONCE_SIZE*2){
log("ERROR: unsigned wrap");
return -1;
}
uint M2_to_sign_length = (NONCE_SIZE*2) + eph_pubkey_s_len, M2_signed_length;
uchar* M2_signed;
uchar* M2_to_sign = (uchar*)malloc(M2_to_sign_length);
if(!M2_to_sign){
log("Error on M2_to_sign");
safe_free(R1, NONCE_SIZE);
safe_free(R2, NONCE_SIZE);
safe_free_privkey(eph_privkey_s);
safe_free(eph_pubkey_s, eph_pubkey_s_len);
fclose(cert_file);
return -1;
}
memcpy(M2_to_sign, R1, NONCE_SIZE);
memcpy((void*)(M2_to_sign + NONCE_SIZE), R2, NONCE_SIZE);
memcpy((void*)(M2_to_sign + (2*NONCE_SIZE)), eph_pubkey_s, eph_pubkey_s_len);
// log("auth (4) M2_to_sign: ");
// BIO_dump_fp(stdout, (const char*)M2_to_sign, M2_to_sign_length);
ret = sign_document(M2_to_sign, M2_to_sign_length, server_privk,&M2_signed, &M2_signed_length);
if(ret != 1){
log("Error on signing part on M2");
safe_free(M2_to_sign, M2_to_sign_length);
safe_free(R1, NONCE_SIZE);
safe_free(R2, NONCE_SIZE);
safe_free_privkey(eph_privkey_s);
safe_free(eph_pubkey_s, eph_pubkey_s_len);
fclose(cert_file);
return -1;
}
//Send M2 part by part
if(eph_pubkey_s_len > UINT_MAX - 3*sizeof(uint) - M2_signed_length){
log("ERROR unsigned_wrap");
return -1;
}
if(certificate_len > UINT_MAX - 3*sizeof(uint) - eph_pubkey_s_len - M2_signed_length){
log("ERROR unsigned_wrap");
return -1;
}
uint M2_size = NONCE_SIZE + 3*sizeof(uint) + eph_pubkey_s_len + M2_signed_length + certificate_len;
uint offset = 0;
uchar* M2 = (uchar*)malloc(M2_size);
if(!M2){
log("ERROR on malloc");
safe_free(M2_to_sign, M2_to_sign_length);
safe_free(R1, NONCE_SIZE);
safe_free(R2, NONCE_SIZE);
safe_free_privkey(eph_privkey_s);
safe_free(eph_pubkey_s, eph_pubkey_s_len);
return -1;
}
uint eph_pubkey_s_len_net = htonl(eph_pubkey_s_len);
uint M2_signed_length_net = htonl(M2_signed_length);
uint certificate_len_net = htonl(certificate_len);
vlog("Copying");
memcpy((void*)(M2 + offset), R2, NONCE_SIZE);
offset += NONCE_SIZE;
memcpy((void*)(M2 + offset), &eph_pubkey_s_len_net, sizeof(uint));
offset += sizeof(uint);
memcpy((void*)(M2 + offset), eph_pubkey_s, eph_pubkey_s_len);
offset += eph_pubkey_s_len;
memcpy((void*)(M2 + offset), &M2_signed_length_net ,sizeof(uint));