-
Notifications
You must be signed in to change notification settings - Fork 1
/
ssl.c
2021 lines (1786 loc) · 58.8 KB
/
ssl.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
/*********************************************************************
*
* File : $Source: /cvsroot/ijbswa/current/ssl.c,v $
*
* Purpose : File with TLS/SSL extension. Contains methods for
* creating, using and closing TLS/SSL connections
* using mbedTLS.
*
* Copyright : Written by and Copyright (c) 2017-2020 Vaclav Svec. FIT CVUT.
* Copyright (C) 2018-2021 by Fabian Keil <[email protected]>
*
* This program is free software; you can redistribute it
* and/or modify it under the terms of the GNU General
* Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public
* License for more details.
*
* The GNU General Public License should be included with
* this file. If not, you can view it at
* http://www.gnu.org/copyleft/gpl.html
* or write to the Free Software Foundation, Inc., 59
* Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*********************************************************************/
#include <string.h>
#include <unistd.h>
#if !defined(MBEDTLS_CONFIG_FILE)
# include "mbedtls/config.h"
#else
# include MBEDTLS_CONFIG_FILE
#endif
#include "mbedtls/md5.h"
#include "mbedtls/pem.h"
#include "mbedtls/base64.h"
#include "mbedtls/error.h"
#include "mbedtls/oid.h"
#include "mbedtls/asn1write.h"
#include "config.h"
#include "project.h"
#include "miscutil.h"
#include "errlog.h"
#include "jcc.h"
#include "ssl.h"
#include "ssl_common.h"
#include "encode.h"
/*
* Macros for searching begin and end of certificates.
* Necessary to convert structure mbedtls_x509_crt to crt file.
*/
#define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
#define PEM_END_CRT "-----END CERTIFICATE-----\n"
#define VALID_DATETIME_FMT "%Y%m%d%H%M%S"
#define VALID_DATETIME_BUFLEN 15
/*
* Macros for ssl.c
*/
#define CERTIFICATE_BUF_SIZE 16384 /* Size of buffer to save certificate. Value 4096 is mbedtls library buffer size for certificate in DER form */
#define PRIVATE_KEY_BUF_SIZE 16000 /* Size of buffer to save private key. Value 16000 is taken from mbed TLS library examples. */
#define CERT_SIGNATURE_ALGORITHM MBEDTLS_MD_SHA256 /* The MD algorithm to use for the signature */
#define CERT_PARAM_COMMON_NAME CERT_PARAM_COMMON_NAME_FCODE"="
#define CERT_PARAM_ORGANIZATION ","CERT_PARAM_ORGANIZATION_FCODE"="
#define CERT_PARAM_ORG_UNIT ","CERT_PARAM_ORG_UNIT_FCODE"="
#define CERT_PARAM_COUNTRY ","CERT_PARAM_COUNTRY_FCODE"="CERT_PARAM_COUNTRY_CODE
/*
* Properties of key for generating
*/
typedef struct {
mbedtls_pk_type_t type; /* type of key to generate */
int rsa_keysize; /* length of key in bits */
char *key_file_path; /* filename of the key file */
} key_options;
/* Variables for one common RNG for all SSL use */
static mbedtls_ctr_drbg_context ctr_drbg;
static mbedtls_entropy_context entropy;
static int rng_seeded;
static int generate_host_certificate(struct client_state *csp);
static int host_to_hash(struct client_state *csp);
static int ssl_verify_callback(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags);
static void free_client_ssl_structures(struct client_state *csp);
static void free_server_ssl_structures(struct client_state *csp);
static int seed_rng(struct client_state *csp);
static int *get_ciphersuites_from_string(const char *ciphersuites_string);
/*********************************************************************
*
* Function : is_ssl_pending
*
* Description : Tests if there are some waiting data on ssl connection.
* Only considers data that has actually been received
* locally and ignores data that is still on the fly
* or has not yet been sent by the remote end.
*
* Parameters :
* 1 : ssl_attr = SSL context to test
*
* Returns : 0 => No data are pending
* >0 => Pending data length
*
*********************************************************************/
extern size_t is_ssl_pending(struct ssl_attr *ssl_attr)
{
mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
if (ssl == NULL)
{
return 0;
}
return mbedtls_ssl_get_bytes_avail(ssl);
}
/*********************************************************************
*
* Function : ssl_send_data
*
* Description : Sends the content of buf (for n bytes) to given SSL
* connection context.
*
* Parameters :
* 1 : ssl_attr = SSL context to send data to
* 2 : buf = Pointer to data to be sent
* 3 : len = Length of data to be sent to the SSL context
*
* Returns : Length of sent data or negative value on error.
*
*********************************************************************/
extern int ssl_send_data(struct ssl_attr *ssl_attr, const unsigned char *buf, size_t len)
{
mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
int ret = 0;
size_t max_fragment_size = 0; /* Maximal length of data in one SSL fragment*/
int send_len = 0; /* length of one data part to send */
int pos = 0; /* Position of unsent part in buffer */
if (len == 0)
{
return 0;
}
/* Getting maximal length of data sent in one fragment */
max_fragment_size = mbedtls_ssl_get_max_frag_len(ssl);
/*
* Whole buffer must be sent in many fragments, because each fragment
* has its maximal length.
*/
while (pos < len)
{
/* Compute length of data, that can be send in next fragment */
if ((pos + (int)max_fragment_size) > len)
{
send_len = (int)len - pos;
}
else
{
send_len = (int)max_fragment_size;
}
log_error(LOG_LEVEL_WRITING, "TLS on socket %d: %N",
ssl_attr->mbedtls_attr.socket_fd.fd, send_len, buf+pos);
/*
* Sending one part of the buffer
*/
while ((ret = mbedtls_ssl_write(ssl,
(const unsigned char *)(buf + pos),
(size_t)send_len)) < 0)
{
if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
ret != MBEDTLS_ERR_SSL_WANT_WRITE)
{
char err_buf[ERROR_BUF_SIZE];
mbedtls_strerror(ret, err_buf, sizeof(err_buf));
log_error(LOG_LEVEL_ERROR,
"Sending data on socket %d over TLS/SSL failed: %s",
ssl_attr->mbedtls_attr.socket_fd.fd, err_buf);
return -1;
}
}
/* Adding count of sent bytes to position in buffer */
pos = pos + send_len;
}
return (int)len;
}
/*********************************************************************
*
* Function : ssl_recv_data
*
* Description : Receives data from given SSL context and puts
* it into buffer.
*
* Parameters :
* 1 : ssl_attr = SSL context to receive data from
* 2 : buf = Pointer to buffer where data will be written
* 3 : max_length = Maximum number of bytes to read
*
* Returns : Number of bytes read, 0 for EOF, or -1
* on error.
*
*********************************************************************/
extern int ssl_recv_data(struct ssl_attr *ssl_attr, unsigned char *buf, size_t max_length)
{
mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
int ret = 0;
memset(buf, 0, max_length);
/*
* Receiving data from SSL context into buffer
*/
do
{
ret = mbedtls_ssl_read(ssl, buf, max_length);
} while (ret == MBEDTLS_ERR_SSL_WANT_READ
|| ret == MBEDTLS_ERR_SSL_WANT_WRITE);
if (ret < 0)
{
char err_buf[ERROR_BUF_SIZE];
if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
{
log_error(LOG_LEVEL_CONNECT, "The peer notified us that "
"the connection on socket %d is going to be closed",
ssl_attr->mbedtls_attr.socket_fd.fd);
return 0;
}
mbedtls_strerror(ret, err_buf, sizeof(err_buf));
log_error(LOG_LEVEL_ERROR,
"Receiving data on socket %d over TLS/SSL failed: %s",
ssl_attr->mbedtls_attr.socket_fd.fd, err_buf);
return -1;
}
log_error(LOG_LEVEL_RECEIVED, "TLS from socket %d: %N",
ssl_attr->mbedtls_attr.socket_fd.fd, ret, buf);
return ret;
}
/*********************************************************************
*
* Function : create_client_ssl_connection
*
* Description : Creates TLS/SSL secured connection with client
*
* Parameters :
* 1 : csp = Current client state (buffers, headers, etc...)
*
* Returns : 0 on success, negative value if connection wasn't created
* successfully.
*
*********************************************************************/
extern int create_client_ssl_connection(struct client_state *csp)
{
struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
/* Paths to certificates file and key file */
char *key_file = NULL;
char *ca_file = NULL;
char *cert_file = NULL;
int ret = 0;
char err_buf[ERROR_BUF_SIZE];
/*
* Initializing mbedtls structures for TLS/SSL connection
*/
mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.server_cert));
mbedtls_pk_init(&(ssl_attr->mbedtls_attr.prim_key));
#if defined(MBEDTLS_SSL_CACHE_C)
mbedtls_ssl_cache_init(&(ssl_attr->mbedtls_attr.cache));
#endif
/*
* Preparing hash of host for creating certificates
*/
ret = host_to_hash(csp);
if (ret != 0)
{
log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
ret = -1;
goto exit;
}
/*
* Preparing paths to certificates files and key file
*/
ca_file = csp->config->ca_cert_file;
cert_file = make_certs_path(csp->config->certificate_directory,
(const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
key_file = make_certs_path(csp->config->certificate_directory,
(const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
if (cert_file == NULL || key_file == NULL)
{
ret = -1;
goto exit;
}
/*
* Generating certificate for requested host. Mutex to prevent
* certificate and key inconsistence must be locked.
*/
privoxy_mutex_lock(&certificate_mutex);
ret = generate_host_certificate(csp);
if (ret < 0)
{
log_error(LOG_LEVEL_ERROR,
"generate_host_certificate failed: %d", ret);
privoxy_mutex_unlock(&certificate_mutex);
ret = -1;
goto exit;
}
privoxy_mutex_unlock(&certificate_mutex);
/*
* Seed the RNG
*/
ret = seed_rng(csp);
if (ret != 0)
{
ret = -1;
goto exit;
}
/*
* Loading CA file, webpage certificate and key files
*/
ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
cert_file);
if (ret != 0)
{
mbedtls_strerror(ret, err_buf, sizeof(err_buf));
log_error(LOG_LEVEL_ERROR,
"Loading webpage certificate %s failed: %s", cert_file, err_buf);
ret = -1;
goto exit;
}
ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
ca_file);
if (ret != 0)
{
mbedtls_strerror(ret, err_buf, sizeof(err_buf));
log_error(LOG_LEVEL_ERROR,
"Loading CA certificate %s failed: %s", ca_file, err_buf);
ret = -1;
goto exit;
}
ret = mbedtls_pk_parse_keyfile(&(ssl_attr->mbedtls_attr.prim_key),
key_file, NULL);
if (ret != 0)
{
mbedtls_strerror(ret, err_buf, sizeof(err_buf));
log_error(LOG_LEVEL_ERROR,
"Loading and parsing webpage certificate private key %s failed: %s",
key_file, err_buf);
ret = -1;
goto exit;
}
/*
* Setting SSL parameters
*/
ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT);
if (ret != 0)
{
mbedtls_strerror(ret, err_buf, sizeof(err_buf));
log_error(LOG_LEVEL_ERROR,
"mbedtls_ssl_config_defaults failed: %s", err_buf);
ret = -1;
goto exit;
}
mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
mbedtls_ctr_drbg_random, &ctr_drbg);
#if defined(MBEDTLS_SSL_CACHE_C)
mbedtls_ssl_conf_session_cache(&(ssl_attr->mbedtls_attr.conf),
&(ssl_attr->mbedtls_attr.cache), mbedtls_ssl_cache_get,
mbedtls_ssl_cache_set);
#endif
/*
* Setting certificates
*/
ret = mbedtls_ssl_conf_own_cert(&(ssl_attr->mbedtls_attr.conf),
&(ssl_attr->mbedtls_attr.server_cert),
&(ssl_attr->mbedtls_attr.prim_key));
if (ret != 0)
{
mbedtls_strerror(ret, err_buf, sizeof(err_buf));
log_error(LOG_LEVEL_ERROR,
"mbedtls_ssl_conf_own_cert failed: %s", err_buf);
ret = -1;
goto exit;
}
if (csp->config->cipher_list != NULL)
{
ssl_attr->mbedtls_attr.ciphersuites_list =
get_ciphersuites_from_string(csp->config->cipher_list);
if (ssl_attr->mbedtls_attr.ciphersuites_list == NULL)
{
log_error(LOG_LEVEL_ERROR,
"Setting the cipher list '%s' for the client connection failed",
csp->config->cipher_list);
ret = -1;
goto exit;
}
mbedtls_ssl_conf_ciphersuites(&(ssl_attr->mbedtls_attr.conf),
ssl_attr->mbedtls_attr.ciphersuites_list);
}
ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
&(ssl_attr->mbedtls_attr.conf));
if (ret != 0)
{
mbedtls_strerror(ret, err_buf, sizeof(err_buf));
log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
ret = -1;
goto exit;
}
mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
&(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
mbedtls_net_recv, NULL);
mbedtls_ssl_session_reset(&(ssl_attr->mbedtls_attr.ssl));
/*
* Setting socket fd in mbedtls_net_context structure. This structure
* can't be set by mbedtls functions, because we already have created
* a TCP connection when this function is called.
*/
ssl_attr->mbedtls_attr.socket_fd.fd = csp->cfd;
/*
* Handshake with client
*/
log_error(LOG_LEVEL_CONNECT,
"Performing the TLS/SSL handshake with client. Hash of host: %s",
csp->http->hash_of_host_hex);
while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
{
if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
ret != MBEDTLS_ERR_SSL_WANT_WRITE)
{
mbedtls_strerror(ret, err_buf, sizeof(err_buf));
log_error(LOG_LEVEL_ERROR,
"medtls_ssl_handshake with client failed: %s", err_buf);
ret = -1;
goto exit;
}
}
log_error(LOG_LEVEL_CONNECT, "Client successfully connected over %s (%s).",
mbedtls_ssl_get_version(&(ssl_attr->mbedtls_attr.ssl)),
mbedtls_ssl_get_ciphersuite(&(ssl_attr->mbedtls_attr.ssl)));
csp->ssl_with_client_is_opened = 1;
exit:
/*
* Freeing allocated paths to files
*/
freez(cert_file);
freez(key_file);
/* Freeing structures if connection wasn't created successfully */
if (ret < 0)
{
free_client_ssl_structures(csp);
}
return ret;
}
/*********************************************************************
*
* Function : close_client_ssl_connection
*
* Description : Closes TLS/SSL connection with client. This function
* checks if this connection is already created.
*
* Parameters :
* 1 : csp = Current client state (buffers, headers, etc...)
*
* Returns : N/A
*
*********************************************************************/
extern void close_client_ssl_connection(struct client_state *csp)
{
struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
int ret = 0;
if (csp->ssl_with_client_is_opened == 0)
{
return;
}
/*
* Notifying the peer that the connection is being closed.
*/
do {
ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
} while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
free_client_ssl_structures(csp);
csp->ssl_with_client_is_opened = 0;
}
/*********************************************************************
*
* Function : free_client_ssl_structures
*
* Description : Frees structures used for SSL communication with
* client.
*
* Parameters :
* 1 : csp = Current client state (buffers, headers, etc...)
*
* Returns : N/A
*
*********************************************************************/
static void free_client_ssl_structures(struct client_state *csp)
{
struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
/*
* We can't use function mbedtls_net_free, because this function
* inter alia close TCP connection on set fd. Instead of this
* function, we change fd to -1, which is the same what does
* rest of mbedtls_net_free function.
*/
ssl_attr->mbedtls_attr.socket_fd.fd = -1;
/* Freeing mbedtls structures */
mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.server_cert));
mbedtls_pk_free(&(ssl_attr->mbedtls_attr.prim_key));
mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
freez(ssl_attr->mbedtls_attr.ciphersuites_list);
mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
#if defined(MBEDTLS_SSL_CACHE_C)
mbedtls_ssl_cache_free(&(ssl_attr->mbedtls_attr.cache));
#endif
}
/*********************************************************************
*
* Function : create_server_ssl_connection
*
* Description : Creates TLS/SSL secured connection with server.
*
* Parameters :
* 1 : csp = Current client state (buffers, headers, etc...)
*
* Returns : 0 on success, negative value if connection wasn't created
* successfully.
*
*********************************************************************/
extern int create_server_ssl_connection(struct client_state *csp)
{
struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
int ret = 0;
char err_buf[ERROR_BUF_SIZE];
char *trusted_cas_file = NULL;
int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
csp->server_certs_chain.next = NULL;
/* Setting path to file with trusted CAs */
trusted_cas_file = csp->config->trusted_cas_file;
/*
* Initializing mbedtls structures for TLS/SSL connection
*/
mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.ca_cert));
/*
* Setting socket fd in mbedtls_net_context structure. This structure
* can't be set by mbedtls functions, because we already have created
* TCP connection when calling this function.
*/
ssl_attr->mbedtls_attr.socket_fd.fd = csp->server_connection.sfd;
/*
* Seed the RNG
*/
ret = seed_rng(csp);
if (ret != 0)
{
ret = -1;
goto exit;
}
/*
* Loading file with trusted CAs
*/
ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.ca_cert),
trusted_cas_file);
if (ret < 0)
{
mbedtls_strerror(ret, err_buf, sizeof(err_buf));
log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
trusted_cas_file, err_buf);
ret = -1;
goto exit;
}
/*
* Set TLS/SSL options
*/
ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT);
if (ret != 0)
{
mbedtls_strerror(ret, err_buf, sizeof(err_buf));
log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
err_buf);
ret = -1;
goto exit;
}
/*
* Setting how strict should certificate verification be and other
* parameters for certificate verification
*/
if (csp->dont_verify_certificate)
{
auth_mode = MBEDTLS_SSL_VERIFY_NONE;
}
mbedtls_ssl_conf_authmode(&(ssl_attr->mbedtls_attr.conf), auth_mode);
mbedtls_ssl_conf_ca_chain(&(ssl_attr->mbedtls_attr.conf),
&(ssl_attr->mbedtls_attr.ca_cert), NULL);
/* Setting callback function for certificates verification */
mbedtls_ssl_conf_verify(&(ssl_attr->mbedtls_attr.conf),
ssl_verify_callback, (void *)csp);
mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
mbedtls_ctr_drbg_random, &ctr_drbg);
if (csp->config->cipher_list != NULL)
{
ssl_attr->mbedtls_attr.ciphersuites_list =
get_ciphersuites_from_string(csp->config->cipher_list);
if (ssl_attr->mbedtls_attr.ciphersuites_list == NULL)
{
log_error(LOG_LEVEL_ERROR,
"Setting the cipher list '%s' for the server connection failed",
csp->config->cipher_list);
ret = -1;
goto exit;
}
mbedtls_ssl_conf_ciphersuites(&(ssl_attr->mbedtls_attr.conf),
ssl_attr->mbedtls_attr.ciphersuites_list);
}
ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
&(ssl_attr->mbedtls_attr.conf));
if (ret != 0)
{
mbedtls_strerror(ret, err_buf, sizeof(err_buf));
log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
ret = -1;
goto exit;
}
/*
* Set the hostname to check against the received server certificate
*/
ret = mbedtls_ssl_set_hostname(&(ssl_attr->mbedtls_attr.ssl),
csp->http->host);
if (ret != 0)
{
mbedtls_strerror(ret, err_buf, sizeof(err_buf));
log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
err_buf);
ret = -1;
goto exit;
}
mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
&(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
mbedtls_net_recv, NULL);
/*
* Handshake with server
*/
log_error(LOG_LEVEL_CONNECT,
"Performing the TLS/SSL handshake with the server");
while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
{
if (ret != MBEDTLS_ERR_SSL_WANT_READ
&& ret != MBEDTLS_ERR_SSL_WANT_WRITE)
{
mbedtls_strerror(ret, err_buf, sizeof(err_buf));
if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
{
char reason[INVALID_CERT_INFO_BUF_SIZE];
csp->server_cert_verification_result =
mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
mbedtls_x509_crt_verify_info(reason, sizeof(reason), "",
csp->server_cert_verification_result);
/* Log the reason without the trailing new line */
log_error(LOG_LEVEL_ERROR,
"X509 certificate verification for %s failed: %N",
csp->http->hostport, strlen(reason)-1, reason);
ret = -1;
}
else
{
log_error(LOG_LEVEL_ERROR,
"mbedtls_ssl_handshake with server failed: %s", err_buf);
free_certificate_chain(csp);
ret = -1;
}
goto exit;
}
}
log_error(LOG_LEVEL_CONNECT, "Server successfully connected over %s (%s).",
mbedtls_ssl_get_version(&(ssl_attr->mbedtls_attr.ssl)),
mbedtls_ssl_get_ciphersuite(&(ssl_attr->mbedtls_attr.ssl)));
/*
* Server certificate chain is valid, so we can clean
* chain, because we will not send it to client.
*/
free_certificate_chain(csp);
csp->ssl_with_server_is_opened = 1;
csp->server_cert_verification_result =
mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
exit:
/* Freeing structures if connection wasn't created successfully */
if (ret < 0)
{
free_server_ssl_structures(csp);
}
return ret;
}
/*********************************************************************
*
* Function : close_server_ssl_connection
*
* Description : Closes TLS/SSL connection with server. This function
* checks if this connection is already opened.
*
* Parameters :
* 1 : csp = Current client state (buffers, headers, etc...)
*
* Returns : N/A
*
*********************************************************************/
extern void close_server_ssl_connection(struct client_state *csp)
{
struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
int ret = 0;
if (csp->ssl_with_server_is_opened == 0)
{
return;
}
/*
* Notifying the peer that the connection is being closed.
*/
do {
ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
} while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
free_server_ssl_structures(csp);
csp->ssl_with_server_is_opened = 0;
}
/*********************************************************************
*
* Function : free_server_ssl_structures
*
* Description : Frees structures used for SSL communication with server
*
* Parameters :
* 1 : csp = Current client state (buffers, headers, etc...)
*
* Returns : N/A
*
*********************************************************************/
static void free_server_ssl_structures(struct client_state *csp)
{
struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
/*
* We can't use function mbedtls_net_free, because this function
* inter alia close TCP connection on set fd. Instead of this
* function, we change fd to -1, which is the same what does
* rest of mbedtls_net_free function.
*/
ssl_attr->mbedtls_attr.socket_fd.fd = -1;
mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.ca_cert));
mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
freez(ssl_attr->mbedtls_attr.ciphersuites_list);
mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
}
/*====================== Certificates ======================*/
/*********************************************************************
*
* Function : write_certificate
*
* Description : Writes certificate into file.
*
* Parameters :
* 1 : crt = certificate to write into file
* 2 : output_file = path to save certificate file
* 3 : f_rng = mbedtls_ctr_drbg_random
* 4 : p_rng = mbedtls_ctr_drbg_context
*
* Returns : Length of written certificate on success or negative value
* on error
*
*********************************************************************/
static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
{
FILE *f = NULL;
size_t len = 0;
unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
int ret = 0;
char err_buf[ERROR_BUF_SIZE];
memset(cert_buf, 0, sizeof(cert_buf));
/*
* Writing certificate into PEM string. If buffer is too small, function
* returns specific error and no buffer overflow can happen.
*/
if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
{
mbedtls_strerror(ret, err_buf, sizeof(err_buf));
log_error(LOG_LEVEL_ERROR,
"Writing certificate into buffer failed: %s", err_buf);
return -1;
}
len = strlen((char *)cert_buf);
/*
* Saving certificate into file
*/
if ((f = fopen(output_file, "w")) == NULL)
{
log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
output_file);
return -1;
}
if (fwrite(cert_buf, 1, len, f) != len)
{
log_error(LOG_LEVEL_ERROR,
"Writing certificate into file %s failed", output_file);
fclose(f);
return -1;
}
fclose(f);
return (int)len;
}
/*********************************************************************
*
* Function : write_private_key
*
* Description : Writes private key into file and copies saved
* content into given pointer to string. If function
* returns 0 for success, this copy must be freed by
* caller.
*
* Parameters :
* 1 : key = key to write into file
* 2 : ret_buf = pointer to string with created key file content
* 3 : key_file_path = path where to save key file
*
* Returns : Length of written private key on success or negative value
* on error
*
*********************************************************************/
static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
const char *key_file_path)
{
size_t len = 0; /* Length of created key */
FILE *f = NULL; /* File to save certificate */
int ret = 0;
char err_buf[ERROR_BUF_SIZE];
/* Initializing buffer for key file content */
*ret_buf = zalloc_or_die(PRIVATE_KEY_BUF_SIZE + 1);
/*
* Writing private key into PEM string
*/
if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
{
mbedtls_strerror(ret, err_buf, sizeof(err_buf));
log_error(LOG_LEVEL_ERROR,
"Writing private key into PEM string failed: %s", err_buf);
ret = -1;
goto exit;
}
len = strlen((char *)*ret_buf);
/*
* Saving key into file
*/
if ((f = fopen(key_file_path, "wb")) == NULL)
{
log_error(LOG_LEVEL_ERROR,
"Opening file %s to save private key failed: %E",
key_file_path);
ret = -1;
goto exit;
}
if (fwrite(*ret_buf, 1, len, f) != len)
{
fclose(f);
log_error(LOG_LEVEL_ERROR,
"Writing private key into file %s failed",
key_file_path);
ret = -1;
goto exit;
}
fclose(f);
exit:
if (ret < 0)
{
freez(*ret_buf);
*ret_buf = NULL;
return ret;
}
return (int)len;
}
/*********************************************************************
*
* Function : generate_key
*
* Description : Tests if private key for host saved in csp already