forked from nghttp2/nghttp2
/
shrpx_tls.cc
2072 lines (1724 loc) · 59.8 KB
/
shrpx_tls.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
/*
* nghttp2 - HTTP/2 C Library
*
* Copyright (c) 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "shrpx_tls.h"
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif // HAVE_SYS_SOCKET_H
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif // HAVE_NETDB_H
#include <netinet/tcp.h>
#include <pthread.h>
#include <sys/types.h>
#include <vector>
#include <string>
#include <iomanip>
#include <iostream>
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/rand.h>
#include <openssl/dh.h>
#ifndef OPENSSL_NO_OCSP
#include <openssl/ocsp.h>
#endif // OPENSSL_NO_OCSP
#include <nghttp2/nghttp2.h>
#include "shrpx_log.h"
#include "shrpx_client_handler.h"
#include "shrpx_config.h"
#include "shrpx_worker.h"
#include "shrpx_downstream_connection_pool.h"
#include "shrpx_http2_session.h"
#include "shrpx_memcached_request.h"
#include "shrpx_memcached_dispatcher.h"
#include "shrpx_connection_handler.h"
#include "util.h"
#include "tls.h"
#include "template.h"
#include "ssl_compat.h"
#include "timegm.h"
using namespace nghttp2;
namespace shrpx {
namespace tls {
#if !OPENSSL_1_1_API
namespace {
const unsigned char *ASN1_STRING_get0_data(ASN1_STRING *x) {
return ASN1_STRING_data(x);
}
} // namespace
#endif // !OPENSSL_1_1_API
namespace {
int next_proto_cb(SSL *s, const unsigned char **data, unsigned int *len,
void *arg) {
auto &prefs = get_config()->tls.alpn_prefs;
*data = prefs.data();
*len = prefs.size();
return SSL_TLSEXT_ERR_OK;
}
} // namespace
namespace {
int verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
if (!preverify_ok) {
int err = X509_STORE_CTX_get_error(ctx);
int depth = X509_STORE_CTX_get_error_depth(ctx);
if (err == X509_V_ERR_CERT_HAS_EXPIRED && depth == 0 &&
get_config()->tls.client_verify.tolerate_expired) {
LOG(INFO) << "The client certificate has expired, but is accepted by "
"configuration";
return 1;
}
LOG(ERROR) << "client certificate verify error:num=" << err << ":"
<< X509_verify_cert_error_string(err) << ":depth=" << depth;
}
return preverify_ok;
}
} // namespace
int set_alpn_prefs(std::vector<unsigned char> &out,
const std::vector<StringRef> &protos) {
size_t len = 0;
for (const auto &proto : protos) {
if (proto.size() > 255) {
LOG(FATAL) << "Too long ALPN identifier: " << proto.size();
return -1;
}
len += 1 + proto.size();
}
if (len > (1 << 16) - 1) {
LOG(FATAL) << "Too long ALPN identifier list: " << len;
return -1;
}
out.resize(len);
auto ptr = out.data();
for (const auto &proto : protos) {
*ptr++ = proto.size();
ptr = std::copy(std::begin(proto), std::end(proto), ptr);
}
return 0;
}
namespace {
int ssl_pem_passwd_cb(char *buf, int size, int rwflag, void *user_data) {
auto config = static_cast<Config *>(user_data);
auto len = static_cast<int>(config->tls.private_key_passwd.size());
if (size < len + 1) {
LOG(ERROR) << "ssl_pem_passwd_cb: buf is too small " << size;
return 0;
}
// Copy string including last '\0'.
memcpy(buf, config->tls.private_key_passwd.c_str(), len + 1);
return len;
}
} // namespace
namespace {
// *al is set to SSL_AD_UNRECOGNIZED_NAME by openssl, so we don't have
// to set it explicitly.
int servername_callback(SSL *ssl, int *al, void *arg) {
auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
auto handler = static_cast<ClientHandler *>(conn->data);
auto worker = handler->get_worker();
auto rawhost = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
if (rawhost == nullptr) {
return SSL_TLSEXT_ERR_NOACK;
}
auto len = strlen(rawhost);
// NI_MAXHOST includes terminal NULL.
if (len == 0 || len + 1 > NI_MAXHOST) {
return SSL_TLSEXT_ERR_NOACK;
}
std::array<uint8_t, NI_MAXHOST> buf;
auto end_buf = std::copy_n(rawhost, len, std::begin(buf));
util::inp_strlower(std::begin(buf), end_buf);
auto hostname = StringRef{std::begin(buf), end_buf};
auto cert_tree = worker->get_cert_lookup_tree();
auto idx = cert_tree->lookup(hostname);
if (idx == -1) {
return SSL_TLSEXT_ERR_NOACK;
}
handler->set_tls_sni(hostname);
auto conn_handler = worker->get_connection_handler();
const auto &ssl_ctx_list = conn_handler->get_indexed_ssl_ctx(idx);
assert(!ssl_ctx_list.empty());
#if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) && \
OPENSSL_VERSION_NUMBER >= 0x10002000L
auto num_shared_curves = SSL_get_shared_curve(ssl, -1);
for (auto i = 0; i < num_shared_curves; ++i) {
auto shared_curve = SSL_get_shared_curve(ssl, i);
for (auto ssl_ctx : ssl_ctx_list) {
auto cert = SSL_CTX_get0_certificate(ssl_ctx);
#if OPENSSL_1_1_API
auto pubkey = X509_get0_pubkey(cert);
#else // !OPENSSL_1_1_API
auto pubkey = X509_get_pubkey(cert);
#endif // !OPENSSL_1_1_API
if (EVP_PKEY_base_id(pubkey) != EVP_PKEY_EC) {
continue;
}
#if OPENSSL_1_1_API
auto eckey = EVP_PKEY_get0_EC_KEY(pubkey);
#else // !OPENSSL_1_1_API
auto eckey = EVP_PKEY_get1_EC_KEY(pubkey);
#endif // !OPENSSL_1_1_API
if (eckey == nullptr) {
continue;
}
auto ecgroup = EC_KEY_get0_group(eckey);
auto cert_curve = EC_GROUP_get_curve_name(ecgroup);
#if !OPENSSL_1_1_API
EC_KEY_free(eckey);
EVP_PKEY_free(pubkey);
#endif // !OPENSSL_1_1_API
if (shared_curve == cert_curve) {
SSL_set_SSL_CTX(ssl, ssl_ctx);
return SSL_TLSEXT_ERR_OK;
}
}
}
#endif // !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) &&
// OPENSSL_VERSION_NUMBER >= 0x10002000L
SSL_set_SSL_CTX(ssl, ssl_ctx_list[0]);
return SSL_TLSEXT_ERR_OK;
}
} // namespace
#ifndef OPENSSL_IS_BORINGSSL
namespace {
std::shared_ptr<std::vector<uint8_t>>
get_ocsp_data(TLSContextData *tls_ctx_data) {
#ifdef HAVE_ATOMIC_STD_SHARED_PTR
return std::atomic_load_explicit(&tls_ctx_data->ocsp_data,
std::memory_order_acquire);
#else // !HAVE_ATOMIC_STD_SHARED_PTR
std::lock_guard<std::mutex> g(tls_ctx_data->mu);
return tls_ctx_data->ocsp_data;
#endif // !HAVE_ATOMIC_STD_SHARED_PTR
}
} // namespace
namespace {
int ocsp_resp_cb(SSL *ssl, void *arg) {
auto ssl_ctx = SSL_get_SSL_CTX(ssl);
auto tls_ctx_data =
static_cast<TLSContextData *>(SSL_CTX_get_app_data(ssl_ctx));
auto data = get_ocsp_data(tls_ctx_data);
if (!data) {
return SSL_TLSEXT_ERR_OK;
}
auto buf =
static_cast<uint8_t *>(CRYPTO_malloc(data->size(), __FILE__, __LINE__));
if (!buf) {
return SSL_TLSEXT_ERR_OK;
}
std::copy(std::begin(*data), std::end(*data), buf);
SSL_set_tlsext_status_ocsp_resp(ssl, buf, data->size());
return SSL_TLSEXT_ERR_OK;
}
} // namespace
#endif // OPENSSL_IS_BORINGSSL
constexpr auto MEMCACHED_SESSION_CACHE_KEY_PREFIX =
StringRef::from_lit("nghttpx:tls-session-cache:");
namespace {
int tls_session_client_new_cb(SSL *ssl, SSL_SESSION *session) {
auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
if (conn->tls.client_session_cache == nullptr) {
return 0;
}
try_cache_tls_session(conn->tls.client_session_cache, session,
ev_now(conn->loop));
return 0;
}
} // namespace
namespace {
int tls_session_new_cb(SSL *ssl, SSL_SESSION *session) {
auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
auto handler = static_cast<ClientHandler *>(conn->data);
auto worker = handler->get_worker();
auto dispatcher = worker->get_session_cache_memcached_dispatcher();
auto &balloc = handler->get_block_allocator();
#ifdef TLS1_3_VERSION
if (SSL_version(ssl) == TLS1_3_VERSION) {
return 0;
}
#endif // TLS1_3_VERSION
const unsigned char *id;
unsigned int idlen;
id = SSL_SESSION_get_id(session, &idlen);
if (LOG_ENABLED(INFO)) {
LOG(INFO) << "Memcached: cache session, id=" << util::format_hex(id, idlen);
}
auto req = make_unique<MemcachedRequest>();
req->op = MEMCACHED_OP_ADD;
req->key = MEMCACHED_SESSION_CACHE_KEY_PREFIX.str();
req->key +=
util::format_hex(balloc, StringRef{id, static_cast<size_t>(idlen)});
auto sessionlen = i2d_SSL_SESSION(session, nullptr);
req->value.resize(sessionlen);
auto buf = &req->value[0];
i2d_SSL_SESSION(session, &buf);
req->expiry = 12_h;
req->cb = [](MemcachedRequest *req, MemcachedResult res) {
if (LOG_ENABLED(INFO)) {
LOG(INFO) << "Memcached: session cache done. key=" << req->key
<< ", status_code=" << res.status_code << ", value="
<< std::string(std::begin(res.value), std::end(res.value));
}
if (res.status_code != 0) {
LOG(WARN) << "Memcached: failed to cache session key=" << req->key
<< ", status_code=" << res.status_code << ", value="
<< std::string(std::begin(res.value), std::end(res.value));
}
};
assert(!req->canceled);
dispatcher->add_request(std::move(req));
return 0;
}
} // namespace
namespace {
SSL_SESSION *tls_session_get_cb(SSL *ssl,
#if OPENSSL_1_1_API && !LIBRESSL_1_1_API
const unsigned char *id,
#else // !OPENSSL_1_1_API
unsigned char *id,
#endif // !OPENSSL_1_1_API
int idlen, int *copy) {
auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
auto handler = static_cast<ClientHandler *>(conn->data);
auto worker = handler->get_worker();
auto dispatcher = worker->get_session_cache_memcached_dispatcher();
auto &balloc = handler->get_block_allocator();
if (idlen == 0) {
return nullptr;
}
if (conn->tls.cached_session) {
if (LOG_ENABLED(INFO)) {
LOG(INFO) << "Memcached: found cached session, id="
<< util::format_hex(id, idlen);
}
// This is required, without this, memory leak occurs.
*copy = 0;
auto session = conn->tls.cached_session;
conn->tls.cached_session = nullptr;
return session;
}
if (LOG_ENABLED(INFO)) {
LOG(INFO) << "Memcached: get cached session, id="
<< util::format_hex(id, idlen);
}
auto req = make_unique<MemcachedRequest>();
req->op = MEMCACHED_OP_GET;
req->key = MEMCACHED_SESSION_CACHE_KEY_PREFIX.str();
req->key +=
util::format_hex(balloc, StringRef{id, static_cast<size_t>(idlen)});
req->cb = [conn](MemcachedRequest *, MemcachedResult res) {
if (LOG_ENABLED(INFO)) {
LOG(INFO) << "Memcached: returned status code " << res.status_code;
}
// We might stop reading, so start it again
conn->rlimit.startw();
ev_timer_again(conn->loop, &conn->rt);
conn->wlimit.startw();
ev_timer_again(conn->loop, &conn->wt);
conn->tls.cached_session_lookup_req = nullptr;
if (res.status_code != 0) {
conn->tls.handshake_state = TLS_CONN_CANCEL_SESSION_CACHE;
return;
}
const uint8_t *p = res.value.data();
auto session = d2i_SSL_SESSION(nullptr, &p, res.value.size());
if (!session) {
if (LOG_ENABLED(INFO)) {
LOG(INFO) << "cannot materialize session";
}
conn->tls.handshake_state = TLS_CONN_CANCEL_SESSION_CACHE;
return;
}
conn->tls.cached_session = session;
conn->tls.handshake_state = TLS_CONN_GOT_SESSION_CACHE;
};
conn->tls.handshake_state = TLS_CONN_WAIT_FOR_SESSION_CACHE;
conn->tls.cached_session_lookup_req = req.get();
dispatcher->add_request(std::move(req));
return nullptr;
}
} // namespace
namespace {
int ticket_key_cb(SSL *ssl, unsigned char *key_name, unsigned char *iv,
EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int enc) {
auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
auto handler = static_cast<ClientHandler *>(conn->data);
auto worker = handler->get_worker();
auto ticket_keys = worker->get_ticket_keys();
if (!ticket_keys) {
// No ticket keys available.
return -1;
}
auto &keys = ticket_keys->keys;
assert(!keys.empty());
if (enc) {
if (RAND_bytes(iv, EVP_MAX_IV_LENGTH) == 0) {
if (LOG_ENABLED(INFO)) {
CLOG(INFO, handler) << "session ticket key: RAND_bytes failed";
}
return -1;
}
auto &key = keys[0];
if (LOG_ENABLED(INFO)) {
CLOG(INFO, handler) << "encrypt session ticket key: "
<< util::format_hex(key.data.name);
}
std::copy(std::begin(key.data.name), std::end(key.data.name), key_name);
EVP_EncryptInit_ex(ctx, get_config()->tls.ticket.cipher, nullptr,
key.data.enc_key.data(), iv);
HMAC_Init_ex(hctx, key.data.hmac_key.data(), key.hmac_keylen, key.hmac,
nullptr);
return 1;
}
size_t i;
for (i = 0; i < keys.size(); ++i) {
auto &key = keys[i];
if (std::equal(std::begin(key.data.name), std::end(key.data.name),
key_name)) {
break;
}
}
if (i == keys.size()) {
if (LOG_ENABLED(INFO)) {
CLOG(INFO, handler) << "session ticket key "
<< util::format_hex(key_name, 16) << " not found";
}
return 0;
}
if (LOG_ENABLED(INFO)) {
CLOG(INFO, handler) << "decrypt session ticket key: "
<< util::format_hex(key_name, 16);
}
auto &key = keys[i];
HMAC_Init_ex(hctx, key.data.hmac_key.data(), key.hmac_keylen, key.hmac,
nullptr);
EVP_DecryptInit_ex(ctx, key.cipher, nullptr, key.data.enc_key.data(), iv);
return i == 0 ? 1 : 2;
}
} // namespace
namespace {
void info_callback(const SSL *ssl, int where, int ret) {
// To mitigate possible DOS attack using lots of renegotiations, we
// disable renegotiation. Since OpenSSL does not provide an easy way
// to disable it, we check that renegotiation is started in this
// callback.
if (where & SSL_CB_HANDSHAKE_START) {
auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
if (conn && conn->tls.initial_handshake_done) {
auto handler = static_cast<ClientHandler *>(conn->data);
if (LOG_ENABLED(INFO)) {
CLOG(INFO, handler) << "TLS renegotiation started";
}
handler->start_immediate_shutdown();
}
}
}
} // namespace
#if OPENSSL_VERSION_NUMBER >= 0x10002000L
namespace {
int alpn_select_proto_cb(SSL *ssl, const unsigned char **out,
unsigned char *outlen, const unsigned char *in,
unsigned int inlen, void *arg) {
// We assume that get_config()->npn_list contains ALPN protocol
// identifier sorted by preference order. So we just break when we
// found the first overlap.
for (const auto &target_proto_id : get_config()->tls.npn_list) {
for (auto p = in, end = in + inlen; p < end;) {
auto proto_id = p + 1;
auto proto_len = *p;
if (proto_id + proto_len <= end &&
util::streq(target_proto_id, StringRef{proto_id, proto_len})) {
*out = reinterpret_cast<const unsigned char *>(proto_id);
*outlen = proto_len;
return SSL_TLSEXT_ERR_OK;
}
p += 1 + proto_len;
}
}
return SSL_TLSEXT_ERR_NOACK;
}
} // namespace
#endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
#if !LIBRESSL_1_0_API && OPENSSL_VERSION_NUMBER >= 0x10002000L
#ifndef TLSEXT_TYPE_signed_certificate_timestamp
#define TLSEXT_TYPE_signed_certificate_timestamp 18
#endif // !TLSEXT_TYPE_signed_certificate_timestamp
namespace {
int sct_add_cb(SSL *ssl, unsigned int ext_type, unsigned int context,
const unsigned char **out, size_t *outlen, X509 *x,
size_t chainidx, int *al, void *add_arg) {
assert(ext_type == TLSEXT_TYPE_signed_certificate_timestamp);
auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
if (!conn->tls.sct_requested) {
return 0;
}
if (LOG_ENABLED(INFO)) {
LOG(INFO) << "sct_add_cb is called, chainidx=" << chainidx << ", x=" << x
<< ", context=" << std::hex << context;
}
// We only have SCTs for leaf certificate.
if (chainidx != 0) {
return 0;
}
auto ssl_ctx = SSL_get_SSL_CTX(ssl);
auto tls_ctx_data =
static_cast<TLSContextData *>(SSL_CTX_get_app_data(ssl_ctx));
*out = tls_ctx_data->sct_data.data();
*outlen = tls_ctx_data->sct_data.size();
return 1;
}
} // namespace
namespace {
void sct_free_cb(SSL *ssl, unsigned int ext_type, unsigned int context,
const unsigned char *out, void *add_arg) {
assert(ext_type == TLSEXT_TYPE_signed_certificate_timestamp);
}
} // namespace
namespace {
int sct_parse_cb(SSL *ssl, unsigned int ext_type, unsigned int context,
const unsigned char *in, size_t inlen, X509 *x,
size_t chainidx, int *al, void *parse_arg) {
assert(ext_type == TLSEXT_TYPE_signed_certificate_timestamp);
// client SHOULD send 0 length extension_data, but it is still
// SHOULD, and not MUST.
// For TLSv1.3 Certificate message, sct_add_cb is called even if
// client has not sent signed_certificate_timestamp extension in its
// ClientHello. Explicitly remember that client has included it
// here.
auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
conn->tls.sct_requested = true;
return 1;
}
} // namespace
#if !OPENSSL_1_1_1_API
namespace {
int legacy_sct_add_cb(SSL *ssl, unsigned int ext_type,
const unsigned char **out, size_t *outlen, int *al,
void *add_arg) {
return sct_add_cb(ssl, ext_type, 0, out, outlen, nullptr, 0, al, add_arg);
}
} // namespace
namespace {
void legacy_sct_free_cb(SSL *ssl, unsigned int ext_type,
const unsigned char *out, void *add_arg) {
sct_free_cb(ssl, ext_type, 0, out, add_arg);
}
} // namespace
namespace {
int legacy_sct_parse_cb(SSL *ssl, unsigned int ext_type,
const unsigned char *in, size_t inlen, int *al,
void *parse_arg) {
return sct_parse_cb(ssl, ext_type, 0, in, inlen, nullptr, 0, al, parse_arg);
}
} // namespace
#endif // !OPENSSL_1_1_1_API
#endif // !LIBRESSL_1_0_API && OPENSSL_VERSION_NUMBER >= 0x10002000L
#ifndef OPENSSL_NO_PSK
namespace {
unsigned int psk_server_cb(SSL *ssl, const char *identity, unsigned char *psk,
unsigned int max_psk_len) {
auto config = get_config();
auto &tlsconf = config->tls;
auto it = tlsconf.psk_secrets.find(StringRef{identity});
if (it == std::end(tlsconf.psk_secrets)) {
return 0;
}
auto &secret = (*it).second;
if (secret.size() > max_psk_len) {
LOG(ERROR) << "The size of PSK secret is " << secret.size()
<< ", but the acceptable maximum size is" << max_psk_len;
return 0;
}
std::copy(std::begin(secret), std::end(secret), psk);
return static_cast<unsigned int>(secret.size());
}
} // namespace
#endif // OPENSSL_NO_PSK
#if OPENSSL_NO_PSK
namespace {
unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity_out,
unsigned int max_identity_len, unsigned char *psk,
unsigned int max_psk_len) {
auto config = get_config();
auto &tlsconf = config->tls;
auto &identity = tlsconf.client.psk.identity;
auto &secret = tlsconf.client.psk.secret;
if (identity.empty()) {
return 0;
}
if (identity.size() + 1 > max_identity_len) {
LOG(ERROR) << "The size of PSK identity is " << identity.size()
<< ", but the acceptable maximum size is " << max_identity_len;
return 0;
}
if (secret.size() > max_psk_len) {
LOG(ERROR) << "The size of PSK secret is " << secret.size()
<< ", but the acceptable maximum size is " << max_psk_len;
return 0;
}
*std::copy(std::begin(identity), std::end(identity), identity_out) = '\0';
std::copy(std::begin(secret), std::end(secret), psk);
return static_cast<unsigned int>(secret.size());
}
} // namespace
#endif // OPENSSL_NO_PSK
struct TLSProtocol {
StringRef name;
long int mask;
};
constexpr TLSProtocol TLS_PROTOS[] = {
TLSProtocol{StringRef::from_lit("TLSv1.2"), SSL_OP_NO_TLSv1_2},
TLSProtocol{StringRef::from_lit("TLSv1.1"), SSL_OP_NO_TLSv1_1},
TLSProtocol{StringRef::from_lit("TLSv1.0"), SSL_OP_NO_TLSv1}};
long int create_tls_proto_mask(const std::vector<StringRef> &tls_proto_list) {
long int res = 0;
for (auto &supported : TLS_PROTOS) {
auto ok = false;
for (auto &name : tls_proto_list) {
if (util::strieq(supported.name, name)) {
ok = true;
break;
}
}
if (!ok) {
res |= supported.mask;
}
}
return res;
}
SSL_CTX *create_ssl_context(const char *private_key_file, const char *cert_file,
const std::vector<uint8_t> &sct_data
#ifdef HAVE_NEVERBLEED
,
neverbleed_t *nb
#endif // HAVE_NEVERBLEED
) {
auto ssl_ctx = SSL_CTX_new(SSLv23_server_method());
if (!ssl_ctx) {
LOG(FATAL) << ERR_error_string(ERR_get_error(), nullptr);
DIE();
}
constexpr auto ssl_opts =
(SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) | SSL_OP_NO_SSLv2 |
SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION |
SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | SSL_OP_SINGLE_ECDH_USE |
SSL_OP_SINGLE_DH_USE | SSL_OP_CIPHER_SERVER_PREFERENCE;
auto config = mod_config();
auto &tlsconf = config->tls;
SSL_CTX_set_options(ssl_ctx, ssl_opts | tlsconf.tls_proto_mask);
if (nghttp2::tls::ssl_ctx_set_proto_versions(
ssl_ctx, tlsconf.min_proto_version, tlsconf.max_proto_version) != 0) {
LOG(FATAL) << "Could not set TLS protocol version";
DIE();
}
const unsigned char sid_ctx[] = "shrpx";
SSL_CTX_set_session_id_context(ssl_ctx, sid_ctx, sizeof(sid_ctx) - 1);
SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_SERVER);
if (!tlsconf.session_cache.memcached.host.empty()) {
SSL_CTX_sess_set_new_cb(ssl_ctx, tls_session_new_cb);
SSL_CTX_sess_set_get_cb(ssl_ctx, tls_session_get_cb);
}
SSL_CTX_set_timeout(ssl_ctx, tlsconf.session_timeout.count());
if (SSL_CTX_set_cipher_list(ssl_ctx, tlsconf.ciphers.c_str()) == 0) {
LOG(FATAL) << "SSL_CTX_set_cipher_list " << tlsconf.ciphers
<< " failed: " << ERR_error_string(ERR_get_error(), nullptr);
DIE();
}
#ifndef OPENSSL_NO_EC
#if !LIBRESSL_1_0_API && OPENSSL_VERSION_NUMBER >= 0x10002000L
if (SSL_CTX_set1_curves_list(ssl_ctx, tlsconf.ecdh_curves.c_str()) != 1) {
LOG(FATAL) << "SSL_CTX_set1_curves_list " << tlsconf.ecdh_curves
<< " failed";
DIE();
}
#if !defined(OPENSSL_IS_BORINGSSL) && !OPENSSL_1_1_API
// It looks like we need this function call for OpenSSL 1.0.2. This
// function was deprecated in OpenSSL 1.1.0 and BoringSSL.
SSL_CTX_set_ecdh_auto(ssl_ctx, 1);
#endif // !defined(OPENSSL_IS_BORINGSSL) && !OPENSSL_1_1_API
#else // LIBRESSL_1_0_API || OPENSSL_VERSION_NUBMER < 0x10002000L
// Use P-256, which is sufficiently secure at the time of this
// writing.
auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
if (ecdh == nullptr) {
LOG(FATAL) << "EC_KEY_new_by_curv_name failed: "
<< ERR_error_string(ERR_get_error(), nullptr);
DIE();
}
SSL_CTX_set_tmp_ecdh(ssl_ctx, ecdh);
EC_KEY_free(ecdh);
#endif // LIBRESSL_1_0_API || OPENSSL_VERSION_NUBMER < 0x10002000L
#endif // OPENSSL_NO_EC
if (!tlsconf.dh_param_file.empty()) {
// Read DH parameters from file
auto bio = BIO_new_file(tlsconf.dh_param_file.c_str(), "r");
if (bio == nullptr) {
LOG(FATAL) << "BIO_new_file() failed: "
<< ERR_error_string(ERR_get_error(), nullptr);
DIE();
}
auto dh = PEM_read_bio_DHparams(bio, nullptr, nullptr, nullptr);
if (dh == nullptr) {
LOG(FATAL) << "PEM_read_bio_DHparams() failed: "
<< ERR_error_string(ERR_get_error(), nullptr);
DIE();
}
SSL_CTX_set_tmp_dh(ssl_ctx, dh);
DH_free(dh);
BIO_free(bio);
}
SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
if (SSL_CTX_set_default_verify_paths(ssl_ctx) != 1) {
LOG(WARN) << "Could not load system trusted ca certificates: "
<< ERR_error_string(ERR_get_error(), nullptr);
}
if (!tlsconf.cacert.empty()) {
if (SSL_CTX_load_verify_locations(ssl_ctx, tlsconf.cacert.c_str(),
nullptr) != 1) {
LOG(FATAL) << "Could not load trusted ca certificates from "
<< tlsconf.cacert << ": "
<< ERR_error_string(ERR_get_error(), nullptr);
DIE();
}
}
if (!tlsconf.private_key_passwd.empty()) {
SSL_CTX_set_default_passwd_cb(ssl_ctx, ssl_pem_passwd_cb);
SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, config);
}
#ifndef HAVE_NEVERBLEED
if (SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key_file,
SSL_FILETYPE_PEM) != 1) {
LOG(FATAL) << "SSL_CTX_use_PrivateKey_file failed: "
<< ERR_error_string(ERR_get_error(), nullptr);
}
#else // HAVE_NEVERBLEED
std::array<char, NEVERBLEED_ERRBUF_SIZE> errbuf;
if (neverbleed_load_private_key_file(nb, ssl_ctx, private_key_file,
errbuf.data()) != 1) {
LOG(FATAL) << "neverbleed_load_private_key_file failed: " << errbuf.data();
DIE();
}
#endif // HAVE_NEVERBLEED
if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_file) != 1) {
LOG(FATAL) << "SSL_CTX_use_certificate_file failed: "
<< ERR_error_string(ERR_get_error(), nullptr);
DIE();
}
if (SSL_CTX_check_private_key(ssl_ctx) != 1) {
LOG(FATAL) << "SSL_CTX_check_private_key failed: "
<< ERR_error_string(ERR_get_error(), nullptr);
DIE();
}
if (tlsconf.client_verify.enabled) {
if (!tlsconf.client_verify.cacert.empty()) {
if (SSL_CTX_load_verify_locations(
ssl_ctx, tlsconf.client_verify.cacert.c_str(), nullptr) != 1) {
LOG(FATAL) << "Could not load trusted ca certificates from "
<< tlsconf.client_verify.cacert << ": "
<< ERR_error_string(ERR_get_error(), nullptr);
DIE();
}
// It is heard that SSL_CTX_load_verify_locations() may leave
// error even though it returns success. See
// http://forum.nginx.org/read.php?29,242540
ERR_clear_error();
auto list = SSL_load_client_CA_file(tlsconf.client_verify.cacert.c_str());
if (!list) {
LOG(FATAL) << "Could not load ca certificates from "
<< tlsconf.client_verify.cacert << ": "
<< ERR_error_string(ERR_get_error(), nullptr);
DIE();
}
SSL_CTX_set_client_CA_list(ssl_ctx, list);
}
SSL_CTX_set_verify(ssl_ctx,
SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE |
SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
verify_callback);
}
SSL_CTX_set_tlsext_servername_callback(ssl_ctx, servername_callback);
SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx, ticket_key_cb);
#ifndef OPENSSL_IS_BORINGSSL
SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
#endif // OPENSSL_IS_BORINGSSL
SSL_CTX_set_info_callback(ssl_ctx, info_callback);
#ifdef OPENSSL_IS_BORINGSSL
SSL_CTX_set_early_data_enabled(ssl_ctx, 1);
#endif // OPENSSL_IS_BORINGSSL
// NPN advertisement
SSL_CTX_set_next_protos_advertised_cb(ssl_ctx, next_proto_cb, nullptr);
#if OPENSSL_VERSION_NUMBER >= 0x10002000L
// ALPN selection callback
SSL_CTX_set_alpn_select_cb(ssl_ctx, alpn_select_proto_cb, nullptr);
#endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
#if !LIBRESSL_1_0_API && !LIBRESSL_1_1_API && OPENSSL_VERSION_NUMBER >= 0x10002000L
// SSL_extension_supported(TLSEXT_TYPE_signed_certificate_timestamp)
// returns 1, which means OpenSSL internally handles it. But
// OpenSSL handles signed_certificate_timestamp extension specially,
// and it lets custom handler to process the extension.
if (!sct_data.empty()) {
#if OPENSSL_1_1_1_API
// It is not entirely clear to me that SSL_EXT_CLIENT_HELLO is
// required here. sct_parse_cb is called without
// SSL_EXT_CLIENT_HELLO being set. But the passed context value
// is SSL_EXT_CLIENT_HELLO.
if (SSL_CTX_add_custom_ext(
ssl_ctx, TLSEXT_TYPE_signed_certificate_timestamp,
SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO |
SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_IGNORE_ON_RESUMPTION,
sct_add_cb, sct_free_cb, nullptr, sct_parse_cb, nullptr) != 1) {
LOG(FATAL) << "SSL_CTX_add_custom_ext failed: "
<< ERR_error_string(ERR_get_error(), nullptr);
DIE();
}
#else // !OPENSSL_1_1_1_API
if (SSL_CTX_add_server_custom_ext(
ssl_ctx, TLSEXT_TYPE_signed_certificate_timestamp,
legacy_sct_add_cb, legacy_sct_free_cb, nullptr, legacy_sct_parse_cb,
nullptr) != 1) {
LOG(FATAL) << "SSL_CTX_add_server_custom_ext failed: "
<< ERR_error_string(ERR_get_error(), nullptr);
DIE();
}
#endif // !OPENSSL_1_1_1_API
}
#endif // !LIBRESSL_1_0_API && OPENSSL_VERSION_NUMBER >= 0x10002000L
#ifndef OPENSSL_NO_PSK
SSL_CTX_set_psk_server_callback(ssl_ctx, psk_server_cb);
#endif // OPENSSL_NO_PSK
auto tls_ctx_data = new TLSContextData();
tls_ctx_data->cert_file = cert_file;
tls_ctx_data->sct_data = sct_data;
SSL_CTX_set_app_data(ssl_ctx, tls_ctx_data);
return ssl_ctx;
}
namespace {
int select_h2_next_proto_cb(SSL *ssl, unsigned char **out,
unsigned char *outlen, const unsigned char *in,
unsigned int inlen, void *arg) {
if (!util::select_h2(const_cast<const unsigned char **>(out), outlen, in,
inlen)) {
return SSL_TLSEXT_ERR_NOACK;
}
return SSL_TLSEXT_ERR_OK;
}
} // namespace
namespace {
int select_h1_next_proto_cb(SSL *ssl, unsigned char **out,
unsigned char *outlen, const unsigned char *in,
unsigned int inlen, void *arg) {
auto end = in + inlen;
for (; in < end;) {
if (util::streq(NGHTTP2_H1_1_ALPN, StringRef{in, in + (in[0] + 1)})) {
*out = const_cast<unsigned char *>(in) + 1;
*outlen = in[0];
return SSL_TLSEXT_ERR_OK;