-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.cpp
625 lines (503 loc) · 17.1 KB
/
client.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
#include "commonlib/net_wrapper.h"
#include "commonlib/net_exception.h"
#include "commonlib/messages.h"
#include "commonlib/commonlib.h"
#include "commonlib/log.h"
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include <iostream>
#include <stdexcept>
using namespace std;
// --------- Console Functions ----------
#include <stdlib.h>
#include <termios.h>
struct termios oflags, nflags;
void disable_console_echo()
{
tcgetattr(fileno(stdin), &oflags);
nflags = oflags;
nflags.c_lflag &= ~ECHO;
nflags.c_lflag |= ECHONL;
if (tcsetattr(fileno(stdin), TCSANOW, &nflags) != 0) {
throw std::runtime_error("can't disable echo");
}
}
void enable_console_echo()
{
if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) {
perror("tcsetattr");
throw std::runtime_error("can't enable echo");
}
}
// --------------------------------------
my_buffer my_buff;
uint64_t cl_nonce;
uint64_t sr_nonce;
uint64_t cl_seq_num;
uint64_t sr_seq_num;
unsigned char session_key[16];
unsigned char hmac_key[16];
int send_hello_msg(int sock) {
hello_msg h;
h.t = CLIENT_HELLO;
h.nonce = cl_nonce = cl_seq_num = generate_nonce();
convert_to_network_order(&h);
LOG_DEBUG("client sends nonce: %ld\n",cl_nonce);
return send_data(sock,(unsigned char*)&h, sizeof(h));
}
bool recv_hello_msg(int sock)
{
if( recv_data(sock, &my_buff) < sizeof(simple_msg) )
return false;
convert_to_host_order(my_buff.buf);
simple_msg *p = (simple_msg*)my_buff.buf;
switch( p->t ) {
case SERVER_HELLO:
sr_nonce = sr_seq_num = ((hello_msg*)p)->nonce;
LOG_DEBUG("Server nonce received: %ld\n",sr_nonce);
break;
default:
return false;
}
return true;
}
bool verify_server_identity(int sd)
{
int signature_len = recv_data(sd, &my_buff);
if(signature_len <= 0)
{
LOG_ERROR("verify_server_identity: cannot recv signature_len\n");
return false;
}
unsigned char *signature = new unsigned char[signature_len];
memcpy(signature, my_buff.buf, signature_len);
SignatureVerifier sv("keys/rsa_server_digsign_pubkey.pem");
unsigned char expected_signed[16];
memcpy(expected_signed, &cl_nonce, 8);
memcpy(expected_signed + 8, &sr_nonce, 8);
sv.verify(expected_signed, 16);
// compare nonces
if(!sv.verify_end(signature, signature_len))
{
LOG_ERROR("Signature not verified!\n");
return false;
}
LOG_INFO("Server Authentication Success!\n");
return true;
}
bool send_client_identification(int sd, char auth_username[], char auth_secret[])
{
// generate session key
generate_session_key(session_key);
// generate hmac key
generate_session_key(hmac_key);
// setup PublicKey cipher
EncryptSession asymm_authclient_cipher("keys/rsa_server_pubkey.pem");
// ## plaintext data
// send iv and encrypted key generated by EncryptSession
unsigned char *auth_iv = asymm_authclient_cipher.get_iv();
unsigned char *auth_pk_encrypted_key;
unsigned int auth_pk_encrypted_key_len = asymm_authclient_cipher.get_session_key(&auth_pk_encrypted_key);
send_data(sd, auth_pk_encrypted_key, auth_pk_encrypted_key_len);
send_data(sd, auth_iv, EVP_CIPHER_iv_length(EVP_aes_128_cbc()));
// ## ciphered data
unsigned char *auth_ciphertext;
unsigned int auth_cipherlen;
// client nonce encrypt
asymm_authclient_cipher.encrypt((unsigned char*)&sr_nonce, 8);
// session key encrypt
asymm_authclient_cipher.encrypt(session_key, 16);
// hmac key encrypt
asymm_authclient_cipher.encrypt(hmac_key, 16);
// username encrypt
asymm_authclient_cipher.encrypt((unsigned char*)auth_username, strlen(auth_username) + 1);
// password encrypt
asymm_authclient_cipher.encrypt((unsigned char*)auth_secret, strlen(auth_secret) + 1);
asymm_authclient_cipher.encrypt_end();
auth_cipherlen = asymm_authclient_cipher.flush_ciphertext(&auth_ciphertext);
// send client auth header (server needs sizes)
client_auth auth_header_msg = {CLIENT_AUTHENTICATION, auth_cipherlen, (unsigned int)strlen(auth_username) + 1, (unsigned int)strlen(auth_secret) + 1};
LOG_DEBUG("client header: ciphertext_len = %u, username_length = %u, password_length = %u\n",
auth_header_msg.total_ciphertext_size, auth_header_msg.username_length, auth_header_msg.password_length);
convert_to_network_order(&auth_header_msg);
send_data(sd, (unsigned char*)&auth_header_msg, sizeof(auth_header_msg));
// send ciphertext and padded ciphertext
send_data(sd, auth_ciphertext, auth_cipherlen);
return true;
}
bool wait_for_authentication_response(int sd)
{
bool result = false;
simple_msg auth_response_msg;
// getting iv
unsigned char *resp_iv = new unsigned char[EVP_CIPHER_iv_length(EVP_aes_128_cbc())];
unsigned int resp_iv_len = recv_data(sd, &my_buff);
memcpy(resp_iv, my_buff.buf, resp_iv_len);
// getting {auth status,clnonce}_Ksess
unsigned int resp_cipherlen = recv_data(sd, &my_buff);
unsigned char *resp_ciphertext = new unsigned char[resp_cipherlen];
memcpy(resp_ciphertext, my_buff.buf, resp_cipherlen);
// getting HMAC_Ksess{auth status,clnonce}_Ksess
unsigned int resp_hmac_len = recv_data(sd, &my_buff);
unsigned char *resp_hmac = new unsigned char[resp_hmac_len];
memcpy(resp_hmac, my_buff.buf, resp_hmac_len);
// verifying HMAC_Ksess{auth status,clnonce}_Ksess
unsigned char *resp_computed_hmac;
HMACMaker hm(hmac_key, 16);
hm.hash(resp_ciphertext, resp_cipherlen);
hm.hash_end(&resp_computed_hmac);
if(CRYPTO_memcmp(resp_computed_hmac, resp_hmac, HMAC_LENGTH) != 0)
{
LOG_ERROR("Authentication Response HMAC verification failed!\n");
return false;
}
// decipher
SymmetricCipher sc(EVP_aes_128_cbc(), session_key, resp_iv);
sc.decrypt(resp_ciphertext, resp_cipherlen);
sc.decrypt_end();
unsigned char* resp_plaintext;
unsigned int resp_plainlen = sc.flush_plaintext(&resp_plaintext);
// security check
if(resp_plainlen < sizeof(auth_response_msg) + sizeof(uint64_t))
return false;
// extracting things
unsigned int resp_plaintext_offset = 0;
// auth status
memcpy(&auth_response_msg, resp_plaintext, sizeof(auth_response_msg));
resp_plaintext_offset += sizeof(auth_response_msg);
// received cl_nonce
uint64_t verification_cl_nonce;
memcpy(&verification_cl_nonce, resp_plaintext + resp_plaintext_offset, sizeof(uint64_t));
resp_plaintext_offset += sizeof(uint64_t);
if(cl_nonce != verification_cl_nonce)
{
LOG_ERROR("Authentication Response Client nonce verification failed! (%lu, %lu)\n", cl_nonce, verification_cl_nonce);
return false;
}
if(auth_response_msg.t == AUTHENTICATION_FAILED )
{
LOG_ERROR("Authentication Failed!\n");
result = false;
} else
result = true;
delete[] resp_computed_hmac;
return result;
}
bool send_command(int sd, void *msg_str, size_t msg_len)
{
unsigned char *command_iv = new unsigned char[EVP_CIPHER_iv_length(EVP_aes_128_cbc())];
generate_iv(command_iv);
send_data(sd, command_iv, EVP_CIPHER_iv_length(EVP_aes_128_cbc()));
SymmetricCipher sc(EVP_aes_128_cbc(), session_key, command_iv);
convert_to_network_order(msg_str);
// encrypt sr_seq_num|command_str
sc.encrypt((unsigned char*)&sr_seq_num, sizeof(sr_seq_num));
sc.encrypt((unsigned char*)msg_str, msg_len);
sc.encrypt_end();
unsigned char *command_ciphertext;
unsigned int command_cipherlen = sc.flush_ciphertext(&command_ciphertext);
LOG_DEBUG("command_cipherlen:%d\n",command_cipherlen);
// send {seqnum|command_str}_Ksess
send_data(sd, command_ciphertext, command_cipherlen);
// make hmac from {seqnum|command_str}_Ksess
unsigned char *hash_result;
unsigned int hash_len;
HMACMaker hc(hmac_key, 16);
hc.hash(command_ciphertext, command_cipherlen);
hash_len = hc.hash_end(&hash_result);
// send HMAC_Ksess{ eqnum|command_str}_Ksess }
send_data(sd, hash_result, hash_len);
// increment server sequence number
sr_seq_num++;
delete[] command_iv;
return true;
}
bool receive_str_response(int sd, unsigned char **received_data, unsigned int* received_data_len)
{
// getting iv
unsigned char *command_iv = new unsigned char[EVP_CIPHER_iv_length(EVP_aes_128_cbc())];
unsigned int command_iv_len = recv_data(sd, &my_buff);
memcpy(command_iv, my_buff.buf, command_iv_len);
// getting {seqnum|command_str}_Ksess
unsigned int command_ciphertext_len = recv_data(sd, &my_buff);
unsigned char *command_ciphertext = new unsigned char[command_ciphertext_len];
memcpy(command_ciphertext, my_buff.buf, command_ciphertext_len);
// getting HMAC_Ksess{seqnum|command_str}_Ksess
unsigned int command_hmac_len = recv_data(sd, &my_buff);
unsigned char *command_hmac = new unsigned char[command_hmac_len];
memcpy(command_hmac, my_buff.buf, command_hmac_len);
// making HMAC_Ksess{seqnum|command_str}_Ksess
unsigned char *computed_hmac;
HMACMaker hm(hmac_key, 16);
hm.hash(command_ciphertext, command_ciphertext_len);
hm.hash_end(&computed_hmac);
if(CRYPTO_memcmp(computed_hmac, command_hmac, HMAC_LENGTH) != 0)
{
LOG_INFO("receive_str_response: HMAC authentication failed!\n");
return false;
}
LOG_INFO("receive_str_response: HMAC authentication success!\n");
// decrypt {seqnum|command_str}_Ksess
SymmetricCipher sc(EVP_aes_128_cbc(), session_key, command_iv);
unsigned char *command_plaintext;
unsigned int command_plainlen;
sc.decrypt(command_ciphertext, command_ciphertext_len);
sc.decrypt_end();
command_plainlen = sc.flush_plaintext(&command_plaintext);
delete[] command_iv;
delete[] command_ciphertext;
delete[] command_hmac;
delete[] computed_hmac;
// verify sequence number
uint64_t received_seqno;
memcpy((void*)&received_seqno, command_plaintext, sizeof(uint64_t));
char *data_text = (char*)&command_plaintext[sizeof(uint64_t)];
unsigned int data_text_len = command_plainlen - sizeof(uint64_t); // Must be checked
if(received_seqno != cl_seq_num)
{
LOG_INFO("receive_str_response: Invalid sequence number! (%lu != %lu)\n", received_seqno, cl_seq_num);
return false;
}
// increment server sequence number
cl_seq_num++;
// return receive command
*received_data = new unsigned char[data_text_len];
memcpy(*received_data, data_text, data_text_len);
*received_data_len = data_text_len;
LOG_DEBUG("receive_str_response: size = %u\n", data_text_len);
return true;
}
bool receive_file_response(int sd, const char filename[])
{
// getting iv
unsigned char *iv = new unsigned char[EVP_CIPHER_iv_length(EVP_aes_128_cbc())];
unsigned int iv_len = recv_data(sd, &my_buff);
memcpy(iv, my_buff.buf, iv_len);
// get file transfer header
send_file_msg s_msg;
if(!recv_msg(sd, &s_msg, SEND_FILE)) {
LOG_ERROR("Errore ricezione messaggio SEND_FILE \n");
return -1;
}
// if file does not exist
if(s_msg.response_code == 0) {
printf("File does not exist!\n");
return false; // we can't go on
}
FILE *fp;
open_file_w(filename, &fp);
SymmetricCipher sc(EVP_aes_128_cbc(), session_key, iv);
HMACMaker hm(hmac_key, 16);
unsigned int total_plainlen = 0;
// initialize receive buffer
my_buffer chunk_cipher;
chunk_cipher.buf = NULL;
chunk_cipher.size = 0;
for(unsigned int i=0; i < s_msg.chunk_number; i++)
{
// get chunk from tcp socket
int chunk_cipherlen = recv_data(sd, &chunk_cipher);
if(chunk_cipherlen < 0)
{
LOG_ERROR("receive_file_response: cannot recv chunk_cipher\n");
return false;
}
LOG_DEBUG("decrypting chunk(%d) of %d ciphertext bytes\n", i, chunk_cipherlen);
// hash partial encrypted text
hm.hash(chunk_cipher.buf, chunk_cipherlen);
// do decryption
unsigned char* chunk_plaintext;
sc.decrypt(chunk_cipher.buf, chunk_cipherlen);
unsigned int chunk_plainlen = sc.flush_plaintext(&chunk_plaintext);
unsigned char* original_chunk_plaintext = chunk_plaintext;
// if first chunk, nonce must be extracted and verified
if(i == 0)
{
if(chunk_cipherlen < (int)sizeof(uint64_t))
{
LOG_ERROR("receive_file_response: cannot recv sequence number\n");
return false;
}
uint64_t received_seqno;
memcpy((void*)&received_seqno, chunk_plaintext, sizeof(uint64_t));
// verify sequence number
if(received_seqno != cl_seq_num) {
LOG_ERROR("receive_str_response: Invalid sequence number! (%lu != %lu)\n", received_seqno, cl_seq_num);
return false;
}
// chunk_plaintext must be purified from received
chunk_plaintext += sizeof(uint64_t);
chunk_plainlen -= sizeof(uint64_t);
}
total_plainlen += chunk_plainlen;
// write to file
fwrite(chunk_plaintext, 1, chunk_plainlen, fp);
// if latest chunk, compute padding
if(i == s_msg.chunk_number-1)
{
unsigned char *padding_plaintext;
sc.decrypt_end();
unsigned padding_plainlen = sc.flush_plaintext(&padding_plaintext);
total_plainlen += padding_plainlen;
LOG_DEBUG("adding last padded block of %d bytes\n", padding_plainlen);
// write latest block (without padding)
fwrite(padding_plaintext, 1, padding_plainlen, fp);
delete[] padding_plaintext;
}
delete[] original_chunk_plaintext;
}
// getting from client HMAC_Ksess{seqnum|command_str}_Ksess
unsigned int received_hmac_len = recv_data(sd, &my_buff);
unsigned char *received_hmac = new unsigned char[received_hmac_len];
memcpy(received_hmac, my_buff.buf, received_hmac_len);
// finally compute HMAC_Ksess{seqnum|command_str}_Ksess
unsigned char *computed_hmac;
hm.hash_end(&computed_hmac);
// verify hash
if(CRYPTO_memcmp(computed_hmac, received_hmac, HMAC_LENGTH) != 0)
{
LOG_INFO("receive_str_response: HMAC authentication failed!\n");
return false;
}
LOG_INFO("receive_str_response: HMAC authentication success!\n");
// increment server sequence number
cl_seq_num++;
fclose(fp);
return true;
}
void quit_command(int sd)
{
// 6) Send Command
// send {seqnum|command_str}_Ksess | HMAC{{seqnum|command_str}_Ksess}_Khmac
simple_msg cmd = {QUIT_SESSION};
if(!send_command(sd, &cmd, sizeof(cmd)))
throw runtime_error("cannot send QUIT_SESSION command");
}
void list_command(int sd, string parameters)
{
// 6) Send Command
// send {seqnum|command_str}_Ksess | HMAC{{seqnum|command_str}_Ksess}_Khmec
simple_msg cmd = {LIST_FILE};
if(!send_command(sd, &cmd, sizeof(cmd)))
throw runtime_error("cannot send LIST_FILE command");
// 7) Receive Response
// receive {seqnum|data}_Ksess | HMAC{{seqnum|data}_Ksess}_Kmac
unsigned char *received_data;
unsigned int received_data_len;
if(!receive_str_response(sd, &received_data, &received_data_len) || received_data_len == 0)
throw runtime_error("cannot receive response");
received_data[received_data_len-1] = '\0';
printf("%s", received_data);
}
void download_command(int sd, string parameters)
{
if(parameters.length() > 255)
{
printf("Error: Too long filename size\n");
return;
}
// 6) Send Command
// send {seqnum|command_str}_Ksess | HMAC{{seqnum|command_str}_Ksess}_Ksess
download_file cmd;
cmd.t = DOWNLOAD_FILE;
cmd.filename_len = parameters.length();
memcpy(cmd.filename, parameters.c_str(), cmd.filename_len);
if(!send_command(sd, &cmd, sizeof(cmd)))
throw runtime_error("cannot send command");
receive_file_response(sd, parameters.c_str());
}
int main(int argc, char **argv)
{
ERR_load_crypto_strings();
int sd;
uint16_t server_port;
my_buff.buf = NULL;
my_buff.size = 0;
// Parsing parameters
if( argc < 3 ){
perror("use: ./client server_ip port");
return -1;
}
sscanf(argv[2],"%hd",&server_port);
sd = start_tcp_connection(argv[1], server_port);
if( sd < 0 )
return -1;
// 1) Send Client Nonce
send_hello_msg(sd);
// 2) Get Server Nonce
if( !recv_hello_msg(sd) )
{
printf("Hello message from server not received! \n");
return -1;
}
// 3) Verify Server Identity
// receive E(Kpriv, client_nonce|server_nonce)
if(!verify_server_identity(sd)){
printf("Server verification failed \n");
return -1;
}
// 4) Send client verification infos and KeySession
// send {client_nonce|session key|username|password}_Kpub
// ask for credentials
char *auth_username = NULL;
char *auth_secret = NULL;
cout << "Username: ";
fflush(stdout);
scanf("%ms", &auth_username);
if(!auth_username)
return -1;
cout << "Password: ";
fflush(stdout);
disable_console_echo();
scanf("%ms", &auth_secret);
enable_console_echo();
if(!auth_secret)
return -1;
if(!send_client_identification(sd, auth_username, auth_secret))
return -1;
// 5) Waiting for AuthOK or AuthFailed
if(!wait_for_authentication_response(sd))
return -1;
cout << "Authentication success!" << endl;
cin.ignore();
while(true)
{
cout << auth_username << "@" << argv[1] << "$ " << flush;
string entered_string;
if(!(std::getline(std::cin, entered_string))) {
quit_command(sd);
break;
}
// extract command and parameter
string cmd_str = entered_string.substr(0, entered_string.find(string(" ")));
entered_string.erase(0, entered_string.find(" ") + 1);
string params_str(entered_string);
//cout << "cmd_str:" << cmd_str << " params_str:" << params_str << endl;
if(cmd_str == "list")
list_command(sd, params_str);
else if(cmd_str == "download")
download_command(sd, params_str);
else if(cmd_str == "exit" || cmd_str == "quit") {
quit_command(sd);
break;
}
else if(cmd_str == "help")
cout << "Commands:" << endl << "\tlist, download <filename>" << endl << "\thelp, exit, quit" << endl;
else if(cmd_str != "")
cout << "unrecognized command" << endl;
}
printf("\n");
close(sd);
delete[] auth_username;
secure_zero(auth_secret, strlen(auth_secret));
delete[] auth_secret;
return 0;
}