-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssl_transport_security.cc
1627 lines (1478 loc) · 57.7 KB
/
ssl_transport_security.cc
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
/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "src/core/tsi/ssl_transport_security.h"
#include <grpc/support/port_platform.h>
#include <limits.h>
#include <string.h>
/* TODO(jboeuf): refactor inet_ntop into a portability header. */
/* Note: for whomever reads this and tries to refactor this, this
can't be in grpc, it has to be in gpr. */
#ifdef GPR_WINDOWS
#include <ws2tcpip.h>
#else
#include <arpa/inet.h>
#include <sys/socket.h>
#endif
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpc/support/thd.h>
extern "C" {
#include <openssl/bio.h>
#include <openssl/crypto.h> /* For OPENSSL_free */
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
}
#include "src/core/tsi/ssl_types.h"
#include "src/core/tsi/transport_security.h"
/* --- Constants. ---*/
#define TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND 16384
#define TSI_SSL_MAX_PROTECTED_FRAME_SIZE_LOWER_BOUND 1024
/* Putting a macro like this and littering the source file with #if is really
bad practice.
TODO(jboeuf): refactor all the #if / #endif in a separate module. */
#ifndef TSI_OPENSSL_ALPN_SUPPORT
#define TSI_OPENSSL_ALPN_SUPPORT 1
#endif
/* TODO(jboeuf): I have not found a way to get this number dynamically from the
SSL structure. This is what we would ultimately want though... */
#define TSI_SSL_MAX_PROTECTION_OVERHEAD 100
/* --- Structure definitions. ---*/
struct tsi_ssl_handshaker_factory {
const tsi_ssl_handshaker_factory_vtable* vtable;
gpr_refcount refcount;
};
struct tsi_ssl_client_handshaker_factory {
tsi_ssl_handshaker_factory base;
SSL_CTX* ssl_context;
unsigned char* alpn_protocol_list;
size_t alpn_protocol_list_length;
};
struct tsi_ssl_server_handshaker_factory {
/* Several contexts to support SNI.
The tsi_peer array contains the subject names of the server certificates
associated with the contexts at the same index. */
tsi_ssl_handshaker_factory base;
SSL_CTX** ssl_contexts;
tsi_peer* ssl_context_x509_subject_names;
size_t ssl_context_count;
unsigned char* alpn_protocol_list;
size_t alpn_protocol_list_length;
};
typedef struct {
tsi_handshaker base;
SSL* ssl;
BIO* network_io;
tsi_result result;
tsi_ssl_handshaker_factory* factory_ref;
} tsi_ssl_handshaker;
typedef struct {
tsi_frame_protector base;
SSL* ssl;
BIO* network_io;
unsigned char* buffer;
size_t buffer_size;
size_t buffer_offset;
} tsi_ssl_frame_protector;
/* --- Library Initialization. ---*/
static gpr_once init_openssl_once = GPR_ONCE_INIT;
static gpr_mu* openssl_mutexes = nullptr;
static void openssl_locking_cb(int mode, int type, const char* file,
int line) GRPC_UNUSED;
static unsigned long openssl_thread_id_cb(void) GRPC_UNUSED;
static void openssl_locking_cb(int mode, int type, const char* file, int line) {
if (mode & CRYPTO_LOCK) {
gpr_mu_lock(&openssl_mutexes[type]);
} else {
gpr_mu_unlock(&openssl_mutexes[type]);
}
}
static unsigned long openssl_thread_id_cb(void) {
return static_cast<unsigned long>(gpr_thd_currentid());
}
static void init_openssl(void) {
int i;
int num_locks;
SSL_library_init();
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
num_locks = CRYPTO_num_locks();
GPR_ASSERT(num_locks > 0);
openssl_mutexes = static_cast<gpr_mu*>(
gpr_malloc(static_cast<size_t>(num_locks) * sizeof(gpr_mu)));
for (i = 0; i < CRYPTO_num_locks(); i++) {
gpr_mu_init(&openssl_mutexes[i]);
}
CRYPTO_set_locking_callback(openssl_locking_cb);
CRYPTO_set_id_callback(openssl_thread_id_cb);
}
/* --- Ssl utils. ---*/
static const char* ssl_error_string(int error) {
switch (error) {
case SSL_ERROR_NONE:
return "SSL_ERROR_NONE";
case SSL_ERROR_ZERO_RETURN:
return "SSL_ERROR_ZERO_RETURN";
case SSL_ERROR_WANT_READ:
return "SSL_ERROR_WANT_READ";
case SSL_ERROR_WANT_WRITE:
return "SSL_ERROR_WANT_WRITE";
case SSL_ERROR_WANT_CONNECT:
return "SSL_ERROR_WANT_CONNECT";
case SSL_ERROR_WANT_ACCEPT:
return "SSL_ERROR_WANT_ACCEPT";
case SSL_ERROR_WANT_X509_LOOKUP:
return "SSL_ERROR_WANT_X509_LOOKUP";
case SSL_ERROR_SYSCALL:
return "SSL_ERROR_SYSCALL";
case SSL_ERROR_SSL:
return "SSL_ERROR_SSL";
default:
return "Unknown error";
}
}
/* TODO(jboeuf): Remove when we are past the debugging phase with this code. */
static void ssl_log_where_info(const SSL* ssl, int where, int flag,
const char* msg) {
if ((where & flag) && tsi_tracing_enabled.enabled()) {
gpr_log(GPR_INFO, "%20.20s - %30.30s - %5.10s", msg,
SSL_state_string_long(ssl), SSL_state_string(ssl));
}
}
/* Used for debugging. TODO(jboeuf): Remove when code is mature enough. */
static void ssl_info_callback(const SSL* ssl, int where, int ret) {
if (ret == 0) {
gpr_log(GPR_ERROR, "ssl_info_callback: error occured.\n");
return;
}
ssl_log_where_info(ssl, where, SSL_CB_LOOP, "LOOP");
ssl_log_where_info(ssl, where, SSL_CB_HANDSHAKE_START, "HANDSHAKE START");
ssl_log_where_info(ssl, where, SSL_CB_HANDSHAKE_DONE, "HANDSHAKE DONE");
}
/* Returns 1 if name looks like an IP address, 0 otherwise.
This is a very rough heuristic, and only handles IPv6 in hexadecimal form. */
static int looks_like_ip_address(const char* name) {
size_t i;
size_t dot_count = 0;
size_t num_size = 0;
for (i = 0; i < strlen(name); i++) {
if (name[i] == ':') {
/* IPv6 Address in hexadecimal form, : is not allowed in DNS names. */
return 1;
}
if (name[i] >= '0' && name[i] <= '9') {
if (num_size > 3) return 0;
num_size++;
} else if (name[i] == '.') {
if (dot_count > 3 || num_size == 0) return 0;
dot_count++;
num_size = 0;
} else {
return 0;
}
}
if (dot_count < 3 || num_size == 0) return 0;
return 1;
}
/* Gets the subject CN from an X509 cert. */
static tsi_result ssl_get_x509_common_name(X509* cert, unsigned char** utf8,
size_t* utf8_size) {
int common_name_index = -1;
X509_NAME_ENTRY* common_name_entry = nullptr;
ASN1_STRING* common_name_asn1 = nullptr;
X509_NAME* subject_name = X509_get_subject_name(cert);
int utf8_returned_size = 0;
if (subject_name == nullptr) {
gpr_log(GPR_ERROR, "Could not get subject name from certificate.");
return TSI_NOT_FOUND;
}
common_name_index =
X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
if (common_name_index == -1) {
gpr_log(GPR_ERROR,
"Could not get common name of subject from certificate.");
return TSI_NOT_FOUND;
}
common_name_entry = X509_NAME_get_entry(subject_name, common_name_index);
if (common_name_entry == nullptr) {
gpr_log(GPR_ERROR, "Could not get common name entry from certificate.");
return TSI_INTERNAL_ERROR;
}
common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry);
if (common_name_asn1 == nullptr) {
gpr_log(GPR_ERROR,
"Could not get common name entry asn1 from certificate.");
return TSI_INTERNAL_ERROR;
}
utf8_returned_size = ASN1_STRING_to_UTF8(utf8, common_name_asn1);
if (utf8_returned_size < 0) {
gpr_log(GPR_ERROR, "Could not extract utf8 from asn1 string.");
return TSI_OUT_OF_RESOURCES;
}
*utf8_size = static_cast<size_t>(utf8_returned_size);
return TSI_OK;
}
/* Gets the subject CN of an X509 cert as a tsi_peer_property. */
static tsi_result peer_property_from_x509_common_name(
X509* cert, tsi_peer_property* property) {
unsigned char* common_name;
size_t common_name_size;
tsi_result result =
ssl_get_x509_common_name(cert, &common_name, &common_name_size);
if (result != TSI_OK) {
if (result == TSI_NOT_FOUND) {
common_name = nullptr;
common_name_size = 0;
} else {
return result;
}
}
result = tsi_construct_string_peer_property(
TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY,
common_name == nullptr ? "" : reinterpret_cast<const char*>(common_name),
common_name_size, property);
OPENSSL_free(common_name);
return result;
}
/* Gets the X509 cert in PEM format as a tsi_peer_property. */
static tsi_result add_pem_certificate(X509* cert, tsi_peer_property* property) {
BIO* bio = BIO_new(BIO_s_mem());
if (!PEM_write_bio_X509(bio, cert)) {
BIO_free(bio);
return TSI_INTERNAL_ERROR;
}
char* contents;
long len = BIO_get_mem_data(bio, &contents);
if (len <= 0) {
BIO_free(bio);
return TSI_INTERNAL_ERROR;
}
tsi_result result = tsi_construct_string_peer_property(
TSI_X509_PEM_CERT_PROPERTY, (const char*)contents,
static_cast<size_t>(len), property);
BIO_free(bio);
return result;
}
/* Gets the subject SANs from an X509 cert as a tsi_peer_property. */
static tsi_result add_subject_alt_names_properties_to_peer(
tsi_peer* peer, GENERAL_NAMES* subject_alt_names,
size_t subject_alt_name_count) {
size_t i;
tsi_result result = TSI_OK;
/* Reset for DNS entries filtering. */
peer->property_count -= subject_alt_name_count;
for (i = 0; i < subject_alt_name_count; i++) {
GENERAL_NAME* subject_alt_name =
sk_GENERAL_NAME_value(subject_alt_names, TSI_SIZE_AS_SIZE(i));
/* Filter out the non-dns entries names. */
if (subject_alt_name->type == GEN_DNS) {
unsigned char* name = nullptr;
int name_size;
name_size = ASN1_STRING_to_UTF8(&name, subject_alt_name->d.dNSName);
if (name_size < 0) {
gpr_log(GPR_ERROR, "Could not get utf8 from asn1 string.");
result = TSI_INTERNAL_ERROR;
break;
}
result = tsi_construct_string_peer_property(
TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY,
reinterpret_cast<const char*>(name), static_cast<size_t>(name_size),
&peer->properties[peer->property_count++]);
OPENSSL_free(name);
} else if (subject_alt_name->type == GEN_IPADD) {
char ntop_buf[INET6_ADDRSTRLEN];
int af;
if (subject_alt_name->d.iPAddress->length == 4) {
af = AF_INET;
} else if (subject_alt_name->d.iPAddress->length == 16) {
af = AF_INET6;
} else {
gpr_log(GPR_ERROR, "SAN IP Address contained invalid IP");
result = TSI_INTERNAL_ERROR;
break;
}
const char* name = inet_ntop(af, subject_alt_name->d.iPAddress->data,
ntop_buf, INET6_ADDRSTRLEN);
if (name == nullptr) {
gpr_log(GPR_ERROR, "Could not get IP string from asn1 octet.");
result = TSI_INTERNAL_ERROR;
break;
}
result = tsi_construct_string_peer_property_from_cstring(
TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY, name,
&peer->properties[peer->property_count++]);
}
if (result != TSI_OK) break;
}
return result;
}
/* Gets information about the peer's X509 cert as a tsi_peer object. */
static tsi_result peer_from_x509(X509* cert, int include_certificate_type,
tsi_peer* peer) {
/* TODO(jboeuf): Maybe add more properties. */
GENERAL_NAMES* subject_alt_names = static_cast<GENERAL_NAMES*>(
X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
int subject_alt_name_count =
(subject_alt_names != nullptr)
? static_cast<int>(sk_GENERAL_NAME_num(subject_alt_names))
: 0;
size_t property_count;
tsi_result result;
GPR_ASSERT(subject_alt_name_count >= 0);
property_count = (include_certificate_type ? static_cast<size_t>(1) : 0) +
2 /* common name, certificate */ +
static_cast<size_t>(subject_alt_name_count);
result = tsi_construct_peer(property_count, peer);
if (result != TSI_OK) return result;
do {
if (include_certificate_type) {
result = tsi_construct_string_peer_property_from_cstring(
TSI_CERTIFICATE_TYPE_PEER_PROPERTY, TSI_X509_CERTIFICATE_TYPE,
&peer->properties[0]);
if (result != TSI_OK) break;
}
result = peer_property_from_x509_common_name(
cert, &peer->properties[include_certificate_type ? 1 : 0]);
if (result != TSI_OK) break;
result = add_pem_certificate(
cert, &peer->properties[include_certificate_type ? 2 : 1]);
if (result != TSI_OK) break;
if (subject_alt_name_count != 0) {
result = add_subject_alt_names_properties_to_peer(
peer, subject_alt_names, static_cast<size_t>(subject_alt_name_count));
if (result != TSI_OK) break;
}
} while (0);
if (subject_alt_names != nullptr) {
sk_GENERAL_NAME_pop_free(subject_alt_names, GENERAL_NAME_free);
}
if (result != TSI_OK) tsi_peer_destruct(peer);
return result;
}
/* Logs the SSL error stack. */
static void log_ssl_error_stack(void) {
unsigned long err;
while ((err = ERR_get_error()) != 0) {
char details[256];
ERR_error_string_n(static_cast<uint32_t>(err), details, sizeof(details));
gpr_log(GPR_ERROR, "%s", details);
}
}
/* Performs an SSL_read and handle errors. */
static tsi_result do_ssl_read(SSL* ssl, unsigned char* unprotected_bytes,
size_t* unprotected_bytes_size) {
int read_from_ssl;
GPR_ASSERT(*unprotected_bytes_size <= INT_MAX);
read_from_ssl = SSL_read(ssl, unprotected_bytes,
static_cast<int>(*unprotected_bytes_size));
if (read_from_ssl <= 0) {
read_from_ssl = SSL_get_error(ssl, read_from_ssl);
switch (read_from_ssl) {
case SSL_ERROR_ZERO_RETURN: /* Received a close_notify alert. */
case SSL_ERROR_WANT_READ: /* We need more data to finish the frame. */
*unprotected_bytes_size = 0;
return TSI_OK;
case SSL_ERROR_WANT_WRITE:
gpr_log(
GPR_ERROR,
"Peer tried to renegotiate SSL connection. This is unsupported.");
return TSI_UNIMPLEMENTED;
case SSL_ERROR_SSL:
gpr_log(GPR_ERROR, "Corruption detected.");
log_ssl_error_stack();
return TSI_DATA_CORRUPTED;
default:
gpr_log(GPR_ERROR, "SSL_read failed with error %s.",
ssl_error_string(read_from_ssl));
return TSI_PROTOCOL_FAILURE;
}
}
*unprotected_bytes_size = static_cast<size_t>(read_from_ssl);
return TSI_OK;
}
/* Performs an SSL_write and handle errors. */
static tsi_result do_ssl_write(SSL* ssl, unsigned char* unprotected_bytes,
size_t unprotected_bytes_size) {
int ssl_write_result;
GPR_ASSERT(unprotected_bytes_size <= INT_MAX);
ssl_write_result = SSL_write(ssl, unprotected_bytes,
static_cast<int>(unprotected_bytes_size));
if (ssl_write_result < 0) {
ssl_write_result = SSL_get_error(ssl, ssl_write_result);
if (ssl_write_result == SSL_ERROR_WANT_READ) {
gpr_log(GPR_ERROR,
"Peer tried to renegotiate SSL connection. This is unsupported.");
return TSI_UNIMPLEMENTED;
} else {
gpr_log(GPR_ERROR, "SSL_write failed with error %s.",
ssl_error_string(ssl_write_result));
return TSI_INTERNAL_ERROR;
}
}
return TSI_OK;
}
/* Loads an in-memory PEM certificate chain into the SSL context. */
static tsi_result ssl_ctx_use_certificate_chain(SSL_CTX* context,
const char* pem_cert_chain,
size_t pem_cert_chain_size) {
tsi_result result = TSI_OK;
X509* certificate = nullptr;
BIO* pem;
GPR_ASSERT(pem_cert_chain_size <= INT_MAX);
pem = BIO_new_mem_buf((void*)pem_cert_chain,
static_cast<int>(pem_cert_chain_size));
if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
do {
certificate = PEM_read_bio_X509_AUX(pem, nullptr, nullptr, (void*)"");
if (certificate == nullptr) {
result = TSI_INVALID_ARGUMENT;
break;
}
if (!SSL_CTX_use_certificate(context, certificate)) {
result = TSI_INVALID_ARGUMENT;
break;
}
while (1) {
X509* certificate_authority =
PEM_read_bio_X509(pem, nullptr, nullptr, (void*)"");
if (certificate_authority == nullptr) {
ERR_clear_error();
break; /* Done reading. */
}
if (!SSL_CTX_add_extra_chain_cert(context, certificate_authority)) {
X509_free(certificate_authority);
result = TSI_INVALID_ARGUMENT;
break;
}
/* We don't need to free certificate_authority as its ownership has been
transfered to the context. That is not the case for certificate though.
*/
}
} while (0);
if (certificate != nullptr) X509_free(certificate);
BIO_free(pem);
return result;
}
/* Loads an in-memory PEM private key into the SSL context. */
static tsi_result ssl_ctx_use_private_key(SSL_CTX* context, const char* pem_key,
size_t pem_key_size) {
tsi_result result = TSI_OK;
EVP_PKEY* private_key = nullptr;
BIO* pem;
GPR_ASSERT(pem_key_size <= INT_MAX);
pem = BIO_new_mem_buf((void*)pem_key, static_cast<int>(pem_key_size));
if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
do {
private_key = PEM_read_bio_PrivateKey(pem, nullptr, nullptr, (void*)"");
if (private_key == nullptr) {
result = TSI_INVALID_ARGUMENT;
break;
}
if (!SSL_CTX_use_PrivateKey(context, private_key)) {
result = TSI_INVALID_ARGUMENT;
break;
}
} while (0);
if (private_key != nullptr) EVP_PKEY_free(private_key);
BIO_free(pem);
return result;
}
/* Loads in-memory PEM verification certs into the SSL context and optionally
returns the verification cert names (root_names can be NULL). */
static tsi_result ssl_ctx_load_verification_certs(SSL_CTX* context,
const char* pem_roots,
size_t pem_roots_size,
STACK_OF(X509_NAME) *
*root_names) {
tsi_result result = TSI_OK;
size_t num_roots = 0;
X509* root = nullptr;
X509_NAME* root_name = nullptr;
BIO* pem;
X509_STORE* root_store;
GPR_ASSERT(pem_roots_size <= INT_MAX);
pem = BIO_new_mem_buf((void*)pem_roots, static_cast<int>(pem_roots_size));
root_store = SSL_CTX_get_cert_store(context);
if (root_store == nullptr) return TSI_INVALID_ARGUMENT;
if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
if (root_names != nullptr) {
*root_names = sk_X509_NAME_new_null();
if (*root_names == nullptr) return TSI_OUT_OF_RESOURCES;
}
while (1) {
root = PEM_read_bio_X509_AUX(pem, nullptr, nullptr, (void*)"");
if (root == nullptr) {
ERR_clear_error();
break; /* We're at the end of stream. */
}
if (root_names != nullptr) {
root_name = X509_get_subject_name(root);
if (root_name == nullptr) {
gpr_log(GPR_ERROR, "Could not get name from root certificate.");
result = TSI_INVALID_ARGUMENT;
break;
}
root_name = X509_NAME_dup(root_name);
if (root_name == nullptr) {
result = TSI_OUT_OF_RESOURCES;
break;
}
sk_X509_NAME_push(*root_names, root_name);
root_name = nullptr;
}
if (!X509_STORE_add_cert(root_store, root)) {
gpr_log(GPR_ERROR, "Could not add root certificate to ssl context.");
result = TSI_INTERNAL_ERROR;
break;
}
X509_free(root);
num_roots++;
}
if (num_roots == 0) {
gpr_log(GPR_ERROR, "Could not load any root certificate.");
result = TSI_INVALID_ARGUMENT;
}
if (result != TSI_OK) {
if (root != nullptr) X509_free(root);
if (root_names != nullptr) {
sk_X509_NAME_pop_free(*root_names, X509_NAME_free);
*root_names = nullptr;
if (root_name != nullptr) X509_NAME_free(root_name);
}
}
BIO_free(pem);
return result;
}
/* Populates the SSL context with a private key and a cert chain, and sets the
cipher list and the ephemeral ECDH key. */
static tsi_result populate_ssl_context(
SSL_CTX* context, const tsi_ssl_pem_key_cert_pair* key_cert_pair,
const char* cipher_list) {
tsi_result result = TSI_OK;
if (key_cert_pair != nullptr) {
if (key_cert_pair->cert_chain != nullptr) {
result = ssl_ctx_use_certificate_chain(context, key_cert_pair->cert_chain,
strlen(key_cert_pair->cert_chain));
if (result != TSI_OK) {
gpr_log(GPR_ERROR, "Invalid cert chain file.");
return result;
}
}
if (key_cert_pair->private_key != nullptr) {
result = ssl_ctx_use_private_key(context, key_cert_pair->private_key,
strlen(key_cert_pair->private_key));
if (result != TSI_OK || !SSL_CTX_check_private_key(context)) {
gpr_log(GPR_ERROR, "Invalid private key.");
return result != TSI_OK ? result : TSI_INVALID_ARGUMENT;
}
}
}
if ((cipher_list != nullptr) &&
!SSL_CTX_set_cipher_list(context, cipher_list)) {
gpr_log(GPR_ERROR, "Invalid cipher list: %s.", cipher_list);
return TSI_INVALID_ARGUMENT;
}
{
EC_KEY* ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
if (!SSL_CTX_set_tmp_ecdh(context, ecdh)) {
gpr_log(GPR_ERROR, "Could not set ephemeral ECDH key.");
EC_KEY_free(ecdh);
return TSI_INTERNAL_ERROR;
}
SSL_CTX_set_options(context, SSL_OP_SINGLE_ECDH_USE);
EC_KEY_free(ecdh);
}
return TSI_OK;
}
/* Extracts the CN and the SANs from an X509 cert as a peer object. */
static tsi_result extract_x509_subject_names_from_pem_cert(const char* pem_cert,
tsi_peer* peer) {
tsi_result result = TSI_OK;
X509* cert = nullptr;
BIO* pem;
pem = BIO_new_mem_buf((void*)pem_cert, static_cast<int>(strlen(pem_cert)));
if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
cert = PEM_read_bio_X509(pem, nullptr, nullptr, (void*)"");
if (cert == nullptr) {
gpr_log(GPR_ERROR, "Invalid certificate");
result = TSI_INVALID_ARGUMENT;
} else {
result = peer_from_x509(cert, 0, peer);
}
if (cert != nullptr) X509_free(cert);
BIO_free(pem);
return result;
}
/* Builds the alpn protocol name list according to rfc 7301. */
static tsi_result build_alpn_protocol_name_list(
const char** alpn_protocols, uint16_t num_alpn_protocols,
unsigned char** protocol_name_list, size_t* protocol_name_list_length) {
uint16_t i;
unsigned char* current;
*protocol_name_list = nullptr;
*protocol_name_list_length = 0;
if (num_alpn_protocols == 0) return TSI_INVALID_ARGUMENT;
for (i = 0; i < num_alpn_protocols; i++) {
size_t length =
alpn_protocols[i] == nullptr ? 0 : strlen(alpn_protocols[i]);
if (length == 0 || length > 255) {
gpr_log(GPR_ERROR, "Invalid protocol name length: %d.",
static_cast<int>(length));
return TSI_INVALID_ARGUMENT;
}
*protocol_name_list_length += length + 1;
}
*protocol_name_list =
static_cast<unsigned char*>(gpr_malloc(*protocol_name_list_length));
if (*protocol_name_list == nullptr) return TSI_OUT_OF_RESOURCES;
current = *protocol_name_list;
for (i = 0; i < num_alpn_protocols; i++) {
size_t length = strlen(alpn_protocols[i]);
*(current++) = static_cast<uint8_t>(length); /* max checked above. */
memcpy(current, alpn_protocols[i], length);
current += length;
}
/* Safety check. */
if ((current < *protocol_name_list) ||
(static_cast<uintptr_t>(current - *protocol_name_list) !=
*protocol_name_list_length)) {
return TSI_INTERNAL_ERROR;
}
return TSI_OK;
}
// The verification callback is used for clients that don't really care about
// the server's certificate, but we need to pull it anyway, in case a higher
// layer wants to look at it. In this case the verification may fail, but
// we don't really care.
static int NullVerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
return 1;
}
/* --- tsi_frame_protector methods implementation. ---*/
static tsi_result ssl_protector_protect(tsi_frame_protector* self,
const unsigned char* unprotected_bytes,
size_t* unprotected_bytes_size,
unsigned char* protected_output_frames,
size_t* protected_output_frames_size) {
tsi_ssl_frame_protector* impl =
reinterpret_cast<tsi_ssl_frame_protector*>(self);
int read_from_ssl;
size_t available;
tsi_result result = TSI_OK;
/* First see if we have some pending data in the SSL BIO. */
int pending_in_ssl = static_cast<int>(BIO_pending(impl->network_io));
if (pending_in_ssl > 0) {
*unprotected_bytes_size = 0;
GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
static_cast<int>(*protected_output_frames_size));
if (read_from_ssl < 0) {
gpr_log(GPR_ERROR,
"Could not read from BIO even though some data is pending");
return TSI_INTERNAL_ERROR;
}
*protected_output_frames_size = static_cast<size_t>(read_from_ssl);
return TSI_OK;
}
/* Now see if we can send a complete frame. */
available = impl->buffer_size - impl->buffer_offset;
if (available > *unprotected_bytes_size) {
/* If we cannot, just copy the data in our internal buffer. */
memcpy(impl->buffer + impl->buffer_offset, unprotected_bytes,
*unprotected_bytes_size);
impl->buffer_offset += *unprotected_bytes_size;
*protected_output_frames_size = 0;
return TSI_OK;
}
/* If we can, prepare the buffer, send it to SSL_write and read. */
memcpy(impl->buffer + impl->buffer_offset, unprotected_bytes, available);
result = do_ssl_write(impl->ssl, impl->buffer, impl->buffer_size);
if (result != TSI_OK) return result;
GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
static_cast<int>(*protected_output_frames_size));
if (read_from_ssl < 0) {
gpr_log(GPR_ERROR, "Could not read from BIO after SSL_write.");
return TSI_INTERNAL_ERROR;
}
*protected_output_frames_size = static_cast<size_t>(read_from_ssl);
*unprotected_bytes_size = available;
impl->buffer_offset = 0;
return TSI_OK;
}
static tsi_result ssl_protector_protect_flush(
tsi_frame_protector* self, unsigned char* protected_output_frames,
size_t* protected_output_frames_size, size_t* still_pending_size) {
tsi_result result = TSI_OK;
tsi_ssl_frame_protector* impl =
reinterpret_cast<tsi_ssl_frame_protector*>(self);
int read_from_ssl = 0;
int pending;
if (impl->buffer_offset != 0) {
result = do_ssl_write(impl->ssl, impl->buffer, impl->buffer_offset);
if (result != TSI_OK) return result;
impl->buffer_offset = 0;
}
pending = static_cast<int>(BIO_pending(impl->network_io));
GPR_ASSERT(pending >= 0);
*still_pending_size = static_cast<size_t>(pending);
if (*still_pending_size == 0) return TSI_OK;
GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
static_cast<int>(*protected_output_frames_size));
if (read_from_ssl <= 0) {
gpr_log(GPR_ERROR, "Could not read from BIO after SSL_write.");
return TSI_INTERNAL_ERROR;
}
*protected_output_frames_size = static_cast<size_t>(read_from_ssl);
pending = static_cast<int>(BIO_pending(impl->network_io));
GPR_ASSERT(pending >= 0);
*still_pending_size = static_cast<size_t>(pending);
return TSI_OK;
}
static tsi_result ssl_protector_unprotect(
tsi_frame_protector* self, const unsigned char* protected_frames_bytes,
size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
size_t* unprotected_bytes_size) {
tsi_result result = TSI_OK;
int written_into_ssl = 0;
size_t output_bytes_size = *unprotected_bytes_size;
size_t output_bytes_offset = 0;
tsi_ssl_frame_protector* impl =
reinterpret_cast<tsi_ssl_frame_protector*>(self);
/* First, try to read remaining data from ssl. */
result = do_ssl_read(impl->ssl, unprotected_bytes, unprotected_bytes_size);
if (result != TSI_OK) return result;
if (*unprotected_bytes_size == output_bytes_size) {
/* We have read everything we could and cannot process any more input. */
*protected_frames_bytes_size = 0;
return TSI_OK;
}
output_bytes_offset = *unprotected_bytes_size;
unprotected_bytes += output_bytes_offset;
*unprotected_bytes_size = output_bytes_size - output_bytes_offset;
/* Then, try to write some data to ssl. */
GPR_ASSERT(*protected_frames_bytes_size <= INT_MAX);
written_into_ssl = BIO_write(impl->network_io, protected_frames_bytes,
static_cast<int>(*protected_frames_bytes_size));
if (written_into_ssl < 0) {
gpr_log(GPR_ERROR, "Sending protected frame to ssl failed with %d",
written_into_ssl);
return TSI_INTERNAL_ERROR;
}
*protected_frames_bytes_size = static_cast<size_t>(written_into_ssl);
/* Now try to read some data again. */
result = do_ssl_read(impl->ssl, unprotected_bytes, unprotected_bytes_size);
if (result == TSI_OK) {
/* Don't forget to output the total number of bytes read. */
*unprotected_bytes_size += output_bytes_offset;
}
return result;
}
static void ssl_protector_destroy(tsi_frame_protector* self) {
tsi_ssl_frame_protector* impl =
reinterpret_cast<tsi_ssl_frame_protector*>(self);
if (impl->buffer != nullptr) gpr_free(impl->buffer);
if (impl->ssl != nullptr) SSL_free(impl->ssl);
if (impl->network_io != nullptr) BIO_free(impl->network_io);
gpr_free(self);
}
static const tsi_frame_protector_vtable frame_protector_vtable = {
ssl_protector_protect,
ssl_protector_protect_flush,
ssl_protector_unprotect,
ssl_protector_destroy,
};
/* --- tsi_server_handshaker_factory methods implementation. --- */
static void tsi_ssl_handshaker_factory_destroy(
tsi_ssl_handshaker_factory* self) {
if (self == nullptr) return;
if (self->vtable != nullptr && self->vtable->destroy != nullptr) {
self->vtable->destroy(self);
}
/* Note, we don't free(self) here because this object is always directly
* embedded in another object. If tsi_ssl_handshaker_factory_init allocates
* any memory, it should be free'd here. */
}
static tsi_ssl_handshaker_factory* tsi_ssl_handshaker_factory_ref(
tsi_ssl_handshaker_factory* self) {
if (self == nullptr) return nullptr;
gpr_refn(&self->refcount, 1);
return self;
}
static void tsi_ssl_handshaker_factory_unref(tsi_ssl_handshaker_factory* self) {
if (self == nullptr) return;
if (gpr_unref(&self->refcount)) {
tsi_ssl_handshaker_factory_destroy(self);
}
}
static tsi_ssl_handshaker_factory_vtable handshaker_factory_vtable = {nullptr};
/* Initializes a tsi_ssl_handshaker_factory object. Caller is responsible for
* allocating memory for the factory. */
static void tsi_ssl_handshaker_factory_init(
tsi_ssl_handshaker_factory* factory) {
GPR_ASSERT(factory != nullptr);
factory->vtable = &handshaker_factory_vtable;
gpr_ref_init(&factory->refcount, 1);
}
/* --- tsi_handshaker methods implementation. ---*/
static tsi_result ssl_handshaker_get_bytes_to_send_to_peer(tsi_handshaker* self,
unsigned char* bytes,
size_t* bytes_size) {
tsi_ssl_handshaker* impl = reinterpret_cast<tsi_ssl_handshaker*>(self);
int bytes_read_from_ssl = 0;
if (bytes == nullptr || bytes_size == nullptr || *bytes_size == 0 ||
*bytes_size > INT_MAX) {
return TSI_INVALID_ARGUMENT;
}
GPR_ASSERT(*bytes_size <= INT_MAX);
bytes_read_from_ssl =
BIO_read(impl->network_io, bytes, static_cast<int>(*bytes_size));
if (bytes_read_from_ssl < 0) {
*bytes_size = 0;
if (!BIO_should_retry(impl->network_io)) {
impl->result = TSI_INTERNAL_ERROR;
return impl->result;
} else {
return TSI_OK;
}
}
*bytes_size = static_cast<size_t>(bytes_read_from_ssl);
return BIO_pending(impl->network_io) == 0 ? TSI_OK : TSI_INCOMPLETE_DATA;
}
static tsi_result ssl_handshaker_get_result(tsi_handshaker* self) {
tsi_ssl_handshaker* impl = reinterpret_cast<tsi_ssl_handshaker*>(self);
if ((impl->result == TSI_HANDSHAKE_IN_PROGRESS) &&
SSL_is_init_finished(impl->ssl)) {
impl->result = TSI_OK;
}
return impl->result;
}
static tsi_result ssl_handshaker_process_bytes_from_peer(
tsi_handshaker* self, const unsigned char* bytes, size_t* bytes_size) {
tsi_ssl_handshaker* impl = reinterpret_cast<tsi_ssl_handshaker*>(self);
int bytes_written_into_ssl_size = 0;
if (bytes == nullptr || bytes_size == nullptr || *bytes_size > INT_MAX) {
return TSI_INVALID_ARGUMENT;
}
GPR_ASSERT(*bytes_size <= INT_MAX);
bytes_written_into_ssl_size =
BIO_write(impl->network_io, bytes, static_cast<int>(*bytes_size));
if (bytes_written_into_ssl_size < 0) {
gpr_log(GPR_ERROR, "Could not write to memory BIO.");
impl->result = TSI_INTERNAL_ERROR;
return impl->result;
}
*bytes_size = static_cast<size_t>(bytes_written_into_ssl_size);
if (!tsi_handshaker_is_in_progress(self)) {
impl->result = TSI_OK;
return impl->result;
} else {
/* Get ready to get some bytes from SSL. */
int ssl_result = SSL_do_handshake(impl->ssl);
ssl_result = SSL_get_error(impl->ssl, ssl_result);
switch (ssl_result) {
case SSL_ERROR_WANT_READ:
if (BIO_pending(impl->network_io) == 0) {
/* We need more data. */
return TSI_INCOMPLETE_DATA;
} else {
return TSI_OK;
}
case SSL_ERROR_NONE:
return TSI_OK;
default: {
char err_str[256];
ERR_error_string_n(ERR_get_error(), err_str, sizeof(err_str));
gpr_log(GPR_ERROR, "Handshake failed with fatal error %s: %s.",
ssl_error_string(ssl_result), err_str);
impl->result = TSI_PROTOCOL_FAILURE;
return impl->result;
}
}
}
}
static tsi_result ssl_handshaker_extract_peer(tsi_handshaker* self,
tsi_peer* peer) {
tsi_result result = TSI_OK;