forked from scylladb/seastar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtls.cc
2224 lines (2016 loc) · 83.1 KB
/
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
/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright 2015 Cloudius Systems
*/
#ifdef SEASTAR_MODULE
module;
#endif
#include <any>
#include <filesystem>
#include <stdexcept>
#include <system_error>
#include <memory>
#include <chrono>
#include <span>
#include <unordered_set>
#include <seastar/util/assert.hh>
#include <netinet/in.h>
#include <sys/stat.h>
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#include <boost/any.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/range/adaptor/map.hpp>
#include <fmt/core.h>
#include <fmt/ostream.h>
#ifdef SEASTAR_MODULE
module seastar;
#else
#include <seastar/core/loop.hh>
#include <seastar/core/reactor.hh>
#include <seastar/core/seastar.hh>
#include <seastar/core/file.hh>
#include <seastar/core/thread.hh>
#include <seastar/core/sstring.hh>
#include <seastar/core/semaphore.hh>
#include <seastar/core/timer.hh>
#include <seastar/core/print.hh>
#include <seastar/core/with_timeout.hh>
#include <seastar/net/tls.hh>
#include <seastar/net/stack.hh>
#include <seastar/util/std-compat.hh>
#include <seastar/util/variant_utils.hh>
#include <seastar/core/fsnotify.hh>
#endif
namespace seastar {
class net::get_impl {
public:
static std::unique_ptr<connected_socket_impl> get(connected_socket s) {
return std::move(s._csi);
}
static connected_socket_impl* maybe_get_ptr(connected_socket& s) {
if (s._csi) {
return s._csi.get();
}
return nullptr;
}
};
class blob_wrapper: public gnutls_datum_t {
public:
blob_wrapper(const tls::blob& in)
: gnutls_datum_t {
reinterpret_cast<uint8_t *>(const_cast<char *>(in.data())),
unsigned(in.size()) } {
}
};
class gnutlsinit {
public:
gnutlsinit() {
gnutls_global_init();
}
~gnutlsinit() {
gnutls_global_deinit();
}
};
// Helper to ensure gnutls legacy init
// is handled properly with regards to
// object life spans. Could be better,
// this version will not destroy the
// gnutls stack until process exit.
class gnutlsobj {
public:
gnutlsobj() {
static gnutlsinit init;
}
};
// Helper
struct file_info {
sstring filename;
std::chrono::system_clock::time_point modified;
};
struct file_result {
temporary_buffer<char> buf;
file_info file;
operator temporary_buffer<char>&&() && {
return std::move(buf);
}
};
static future<file_result> read_fully(const sstring& name, const sstring& what) {
return open_file_dma(name, open_flags::ro).then([name = name](file f) mutable {
return do_with(std::move(f), [name = std::move(name)](file& f) mutable {
return f.stat().then([&f, name = std::move(name)](struct stat s) mutable {
return f.dma_read_bulk<char>(0, s.st_size).then([s, name = std::move(name)](temporary_buffer<char> buf) mutable {
return file_result{ std::move(buf), file_info{
std::move(name), std::chrono::system_clock::from_time_t(s.st_mtim.tv_sec) +
std::chrono::duration_cast<std::chrono::system_clock::duration>(std::chrono::nanoseconds(s.st_mtim.tv_nsec))
} };
});
}).finally([&f]() {
return f.close();
});
});
}).handle_exception([name = name, what = what](std::exception_ptr ep) -> future<file_result> {
try {
std::rethrow_exception(std::move(ep));
} catch (...) {
std::throw_with_nested(std::runtime_error(sstring("Could not read ") + what + " " + name));
}
});
}
// Note: we are not using gnutls++ interfaces, mainly because we
// want to keep _our_ interface reasonably non-gnutls (well...)
// and once we get to this level, their abstractions don't help
// that much anyway. And they are sooo c++98...
class gnutls_error_category : public std::error_category {
public:
constexpr gnutls_error_category() noexcept : std::error_category{} {}
const char * name() const noexcept override {
return "GnuTLS";
}
std::string message(int error) const override {
return gnutls_strerror(error);
}
};
const std::error_category& tls::error_category() {
static const gnutls_error_category ec;
return ec;
}
// Checks a gnutls return value.
// < 0 -> error.
static void gtls_chk(int res) {
if (res < 0) {
throw std::system_error(res, tls::error_category());
}
}
namespace {
// helper for gnutls-functions for receiving a string
// arguments
// func - the gnutls function that is returning a string (e.g. gnutls_x509_crt_get_issuer_dn)
// args - the arguments to func that come before the char array's ptr and size args
// returns
// pair<int, string> - [gnutls error code, extracted string],
// in case of no errors, the error code is zero
static auto get_gtls_string = [](auto func, auto... args) noexcept {
size_t size = 0;
int ret = func(args..., nullptr, &size);
// by construction, we expect the SHORT_MEMORY_BUFFER error code here
if (ret != GNUTLS_E_SHORT_MEMORY_BUFFER) {
return std::make_pair(ret, sstring{});
}
SEASTAR_ASSERT(size != 0);
sstring res(sstring::initialized_later{}, size - 1);
ret = func(args..., res.data(), &size);
return std::make_pair(ret, res);
};
}
class tls::dh_params::impl : gnutlsobj {
static gnutls_sec_param_t to_gnutls_level(level l) {
switch (l) {
case level::LEGACY: return GNUTLS_SEC_PARAM_LEGACY;
#if GNUTLS_VERSION_NUMBER >= 0x030300
case level::MEDIUM: return GNUTLS_SEC_PARAM_MEDIUM;
#else
case level::MEDIUM: return GNUTLS_SEC_PARAM_NORMAL;
#endif
case level::HIGH: return GNUTLS_SEC_PARAM_HIGH;
case level::ULTRA: return GNUTLS_SEC_PARAM_ULTRA;
default:
throw std::runtime_error(format("Unknown value of dh_params::level: {:d}", static_cast<std::underlying_type_t<level>>(l)));
}
}
using dh_ptr = std::unique_ptr<std::remove_pointer_t<gnutls_dh_params_t>, void(*)(gnutls_dh_params_t)>;
static dh_ptr new_dh_params() {
gnutls_dh_params_t params;
gtls_chk(gnutls_dh_params_init(¶ms));
return dh_ptr(params, &gnutls_dh_params_deinit);
}
public:
impl(dh_ptr p)
: _params(std::move(p))
{}
impl(level lvl)
#if GNUTLS_VERSION_NUMBER >= 0x030506
: _params(nullptr, &gnutls_dh_params_deinit)
, _sec_param(to_gnutls_level(lvl))
#else
: impl([&] {
auto bits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, to_gnutls_level(lvl));
auto ptr = new_dh_params();
gtls_chk(gnutls_dh_params_generate2(ptr.get(), bits));
return ptr;
}())
#endif
{}
impl(const blob& pkcs3, x509_crt_format fmt)
: impl([&] {
auto ptr = new_dh_params();
blob_wrapper w(pkcs3);
gtls_chk(gnutls_dh_params_import_pkcs3(ptr.get(), &w, gnutls_x509_crt_fmt_t(fmt)));
return ptr;
}())
{}
impl(const impl& v)
: impl([&v] {
auto ptr = new_dh_params();
gtls_chk(gnutls_dh_params_cpy(ptr.get(), v));
return ptr;
}())
{}
~impl() = default;
operator gnutls_dh_params_t() const {
return _params.get();
}
#if GNUTLS_VERSION_NUMBER >= 0x030506
std::optional<gnutls_sec_param_t> sec_param() const {
return _sec_param;
}
#endif
private:
dh_ptr _params;
#if GNUTLS_VERSION_NUMBER >= 0x030506
std::optional<gnutls_sec_param_t> _sec_param;
#endif
};
tls::dh_params::dh_params(level lvl) : _impl(std::make_unique<impl>(lvl))
{}
tls::dh_params::dh_params(const blob& b, x509_crt_format fmt)
: _impl(std::make_unique<impl>(b, fmt)) {
}
tls::dh_params::~dh_params() {
}
tls::dh_params::dh_params(dh_params&&) noexcept = default;
tls::dh_params& tls::dh_params::operator=(dh_params&&) noexcept = default;
future<tls::dh_params> tls::dh_params::from_file(
const sstring& filename, x509_crt_format fmt) {
return read_fully(filename, "dh parameters").then([fmt](temporary_buffer<char> buf) {
return make_ready_future<dh_params>(dh_params(blob(buf.get()), fmt));
});
}
class tls::x509_cert::impl : gnutlsobj {
public:
impl()
: _cert([] {
gnutls_x509_crt_t cert;
gtls_chk(gnutls_x509_crt_init(&cert));
return cert;
}()) {
}
impl(const blob& b, x509_crt_format fmt)
: impl()
{
blob_wrapper w(b);
gtls_chk(gnutls_x509_crt_import(*this, &w, gnutls_x509_crt_fmt_t(fmt)));
}
~impl() {
if (_cert != nullptr) {
gnutls_x509_crt_deinit(_cert);
}
}
operator gnutls_x509_crt_t() const {
return _cert;
}
private:
gnutls_x509_crt_t _cert;
};
tls::x509_cert::x509_cert(shared_ptr<impl> impl)
: _impl(std::move(impl)) {
}
tls::x509_cert::x509_cert(const blob& b, x509_crt_format fmt)
: x509_cert(::seastar::make_shared<impl>(b, fmt)) {
}
future<tls::x509_cert> tls::x509_cert::from_file(
const sstring& filename, x509_crt_format fmt) {
return read_fully(filename, "x509 certificate").then([fmt](temporary_buffer<char> buf) {
return make_ready_future<x509_cert>(x509_cert(blob(buf.get()), fmt));
});
}
// wrapper for gnutls_datum, with raii free
struct gnutls_datum : public gnutls_datum_t {
gnutls_datum(size_t s) {
data = reinterpret_cast<unsigned char*>(gnutls_malloc(s));
if (data == nullptr) {
throw std::bad_alloc();
}
size = s;
}
gnutls_datum() {
data = nullptr;
size = 0;
}
gnutls_datum(const gnutls_datum&) = delete;
gnutls_datum& operator=(gnutls_datum&& other) {
if (this == &other) {
return *this;
}
if (data != nullptr) {
::gnutls_memset(data, 0, size);
::gnutls_free(data);
}
data = std::exchange(other.data, nullptr);
size = std::exchange(other.size, 0);
return *this;
}
~gnutls_datum() {
if (data != nullptr) {
::gnutls_memset(data, 0, size);
::gnutls_free(data);
}
}
};
class tls::certificate_credentials::impl: public gnutlsobj {
public:
impl()
: _creds([] {
gnutls_certificate_credentials_t xcred;
gnutls_certificate_allocate_credentials(&xcred);
if (xcred == nullptr) {
throw std::bad_alloc();
}
return xcred;
}()), _priority(nullptr, &gnutls_priority_deinit)
{}
~impl() {
if (_creds != nullptr) {
gnutls_certificate_free_credentials (_creds);
}
}
operator gnutls_certificate_credentials_t() const {
return _creds;
}
void set_x509_trust(const blob& b, x509_crt_format fmt) {
blob_wrapper w(b);
gtls_chk(
gnutls_certificate_set_x509_trust_mem(_creds, &w,
gnutls_x509_crt_fmt_t(fmt)));
}
void set_x509_crl(const blob& b, x509_crt_format fmt) {
blob_wrapper w(b);
gtls_chk(
gnutls_certificate_set_x509_crl_mem(_creds, &w,
gnutls_x509_crt_fmt_t(fmt)));
}
void set_x509_key(const blob& cert, const blob& key, x509_crt_format fmt) {
blob_wrapper w1(cert);
blob_wrapper w2(key);
gtls_chk(
gnutls_certificate_set_x509_key_mem(_creds, &w1, &w2,
gnutls_x509_crt_fmt_t(fmt)));
}
void set_simple_pkcs12(const blob& b, x509_crt_format fmt,
const sstring& password) {
blob_wrapper w(b);
gtls_chk(
gnutls_certificate_set_x509_simple_pkcs12_mem(_creds, &w,
gnutls_x509_crt_fmt_t(fmt), password.c_str()));
}
void dh_params(const tls::dh_params& dh) {
#if GNUTLS_VERSION_NUMBER >= 0x030506
auto sec_param = dh._impl->sec_param();
if (sec_param) {
gnutls_certificate_set_known_dh_params(*this, *sec_param);
return;
}
#endif
auto cpy = std::make_unique<tls::dh_params::impl>(*dh._impl);
gnutls_certificate_set_dh_params(*this, *cpy);
_dh_params = std::move(cpy);
}
future<> set_system_trust() {
return async([this] {
gtls_chk(gnutls_certificate_set_x509_system_trust(_creds));
_load_system_trust = false; // should only do once, for whatever reason
});
}
void set_client_auth(client_auth ca) {
_client_auth = ca;
}
client_auth get_client_auth() const {
return _client_auth;
}
void set_session_resume_mode(session_resume_mode m, std::span<const uint8_t> key = {}) {
_session_resume_mode = m;
// (re-)generate session key
if (m != session_resume_mode::NONE) {
_session_resume_key = {};
if (key.empty()) {
gtls_chk(gnutls_session_ticket_key_generate(&_session_resume_key));
} else {
_session_resume_key = gnutls_datum(key.size());
std::copy(key.begin(), key.end(), _session_resume_key.data);
}
}
}
session_resume_mode get_session_resume_mode() const {
return _session_resume_mode;
}
const gnutls_datum_t* get_session_resume_key() const {
return &_session_resume_key;
}
void set_priority_string(const sstring& prio) {
const char * err = prio.c_str();
try {
gnutls_priority_t p;
gtls_chk(gnutls_priority_init(&p, prio.c_str(), &err));
_priority.reset(p);
} catch (...) {
std::throw_with_nested(std::invalid_argument(std::string("Could not set priority: ") + err));
}
}
gnutls_priority_t get_priority() const {
return _priority.get();
}
void set_dn_verification_callback(dn_callback cb) {
_dn_callback = std::move(cb);
}
void set_enable_certificate_verification(bool enable) {
_enable_certificate_verification = enable;
}
private:
friend class credentials_builder;
friend class session;
bool need_load_system_trust() const {
return _load_system_trust;
}
future<> maybe_load_system_trust() {
return with_semaphore(_system_trust_sem, 1, [this] {
if (!_load_system_trust) {
return make_ready_future();
}
return set_system_trust();
});
}
gnutls_certificate_credentials_t _creds;
std::unique_ptr<tls::dh_params::impl> _dh_params;
std::unique_ptr<std::remove_pointer_t<gnutls_priority_t>, void(*)(gnutls_priority_t)> _priority;
client_auth _client_auth = client_auth::NONE;
session_resume_mode _session_resume_mode = session_resume_mode::NONE;
bool _load_system_trust = false;
semaphore _system_trust_sem {1};
dn_callback _dn_callback;
bool _enable_certificate_verification = true;
gnutls_datum _session_resume_key;
};
tls::certificate_credentials::certificate_credentials()
: _impl(make_shared<impl>()) {
}
tls::certificate_credentials::~certificate_credentials() {
}
tls::certificate_credentials::certificate_credentials(
certificate_credentials&&) noexcept = default;
tls::certificate_credentials& tls::certificate_credentials::operator=(
certificate_credentials&&) noexcept = default;
void tls::certificate_credentials::set_x509_trust(const blob& b,
x509_crt_format fmt) {
_impl->set_x509_trust(b, fmt);
}
void tls::certificate_credentials::set_x509_crl(const blob& b,
x509_crt_format fmt) {
_impl->set_x509_crl(b, fmt);
}
void tls::certificate_credentials::set_x509_key(const blob& cert,
const blob& key, x509_crt_format fmt) {
_impl->set_x509_key(cert, key, fmt);
}
void tls::certificate_credentials::set_simple_pkcs12(const blob& b,
x509_crt_format fmt, const sstring& password) {
_impl->set_simple_pkcs12(b, fmt, password);
}
future<> tls::abstract_credentials::set_x509_trust_file(
const sstring& cafile, x509_crt_format fmt) {
return read_fully(cafile, "trust file").then([this, fmt](temporary_buffer<char> buf) {
set_x509_trust(blob(buf.get(), buf.size()), fmt);
});
}
future<> tls::abstract_credentials::set_x509_crl_file(
const sstring& crlfile, x509_crt_format fmt) {
return read_fully(crlfile, "crl file").then([this, fmt](temporary_buffer<char> buf) {
set_x509_crl(blob(buf.get(), buf.size()), fmt);
});
}
future<> tls::abstract_credentials::set_x509_key_file(
const sstring& cf, const sstring& kf, x509_crt_format fmt) {
return read_fully(cf, "certificate file").then([this, fmt, kf = kf](temporary_buffer<char> buf) {
return read_fully(kf, "key file").then([this, fmt, buf = std::move(buf)](temporary_buffer<char> buf2) {
set_x509_key(blob(buf.get(), buf.size()), blob(buf2.get(), buf2.size()), fmt);
});
});
}
future<> tls::abstract_credentials::set_simple_pkcs12_file(
const sstring& pkcs12file, x509_crt_format fmt,
const sstring& password) {
return read_fully(pkcs12file, "pkcs12 file").then([this, fmt, password = password](temporary_buffer<char> buf) {
set_simple_pkcs12(blob(buf.get(), buf.size()), fmt, password);
});
}
future<> tls::certificate_credentials::set_system_trust() {
return _impl->set_system_trust();
}
void tls::certificate_credentials::set_priority_string(const sstring& prio) {
_impl->set_priority_string(prio);
}
void tls::certificate_credentials::set_dn_verification_callback(dn_callback cb) {
_impl->set_dn_verification_callback(std::move(cb));
}
void tls::certificate_credentials::set_enable_certificate_verification(bool enable) {
_impl->set_enable_certificate_verification(enable);
}
tls::server_credentials::server_credentials()
#if GNUTLS_VERSION_NUMBER < 0x030600
: server_credentials(dh_params{})
#endif
{}
tls::server_credentials::server_credentials(shared_ptr<dh_params> dh)
: server_credentials(*dh)
{}
tls::server_credentials::server_credentials(const dh_params& dh) {
_impl->dh_params(dh);
}
tls::server_credentials::server_credentials(server_credentials&&) noexcept = default;
tls::server_credentials& tls::server_credentials::operator=(
server_credentials&&) noexcept = default;
void tls::server_credentials::set_client_auth(client_auth ca) {
_impl->set_client_auth(ca);
}
void tls::server_credentials::set_session_resume_mode(session_resume_mode m) {
_impl->set_session_resume_mode(m);
}
static const sstring dh_level_key = "dh_level";
static const sstring x509_trust_key = "x509_trust";
static const sstring x509_crl_key = "x509_crl";
static const sstring x509_key_key = "x509_key";
static const sstring pkcs12_key = "pkcs12";
static const sstring system_trust = "system_trust";
using buffer_type = std::basic_string<tls::blob::value_type, tls::blob::traits_type, std::allocator<tls::blob::value_type>>;
struct x509_simple {
buffer_type data;
tls::x509_crt_format format;
file_info file;
};
struct x509_key {
buffer_type cert;
buffer_type key;
tls::x509_crt_format format;
file_info cert_file;
file_info key_file;
};
struct pkcs12_simple {
buffer_type data;
tls::x509_crt_format format;
sstring password;
file_info file;
};
void tls::credentials_builder::set_dh_level(dh_params::level level) {
_blobs.emplace(dh_level_key, level);
}
void tls::credentials_builder::set_x509_trust(const blob& b, x509_crt_format fmt) {
_blobs.emplace(x509_trust_key, x509_simple{ std::string(b), fmt });
}
void tls::credentials_builder::set_x509_crl(const blob& b, x509_crt_format fmt) {
_blobs.emplace(x509_crl_key, x509_simple{ std::string(b), fmt });
}
void tls::credentials_builder::set_x509_key(const blob& cert, const blob& key, x509_crt_format fmt) {
_blobs.emplace(x509_key_key, x509_key { std::string(cert), std::string(key), fmt });
}
void tls::credentials_builder::set_simple_pkcs12(const blob& b, x509_crt_format fmt, const sstring& password) {
_blobs.emplace(pkcs12_key, pkcs12_simple{std::string(b), fmt, password });
}
static buffer_type to_buffer(const temporary_buffer<char>& buf) {
return buffer_type(buf.get(), buf.get() + buf.size());
}
future<> tls::credentials_builder::set_x509_trust_file(const sstring& cafile, x509_crt_format fmt) {
return read_fully(cafile, "trust file").then([this, fmt](file_result f) {
_blobs.emplace(x509_trust_key, x509_simple{ to_buffer(f.buf), fmt, std::move(f.file) });
});
}
future<> tls::credentials_builder::set_x509_crl_file(const sstring& crlfile, x509_crt_format fmt) {
return read_fully(crlfile, "crl file").then([this, fmt](file_result f) {
_blobs.emplace(x509_crl_key, x509_simple{ to_buffer(f.buf), fmt, std::move(f.file) });
});
}
future<> tls::credentials_builder::set_x509_key_file(const sstring& cf, const sstring& kf, x509_crt_format fmt) {
return read_fully(cf, "certificate file").then([this, fmt, kf = kf](file_result cf) {
return read_fully(kf, "key file").then([this, fmt, cf = std::move(cf)](file_result kf) {
_blobs.emplace(x509_key_key, x509_key{ to_buffer(cf.buf), to_buffer(kf.buf), fmt, std::move(cf.file), std::move(kf.file) });
});
});
}
future<> tls::credentials_builder::set_simple_pkcs12_file(const sstring& pkcs12file, x509_crt_format fmt, const sstring& password) {
return read_fully(pkcs12file, "pkcs12 file").then([this, fmt, password = password](file_result f) {
_blobs.emplace(pkcs12_key, pkcs12_simple{ to_buffer(f.buf), fmt, password, std::move(f.file) });
});
}
future<> tls::credentials_builder::set_system_trust() {
// TODO / Caveat:
// We cannot actually issue a loading of system trust here,
// because we have no actual tls context.
// And we probably _don't want to get into the guessing game
// of where the system trust cert chains are, since this is
// super distro dependent, and usually compiled into the library.
// Pretent it is raining, and just set a flag.
// Leave the function returning future, so if we change our
// minds and want to do explicit loading, we can...
_blobs.emplace(system_trust, true);
return make_ready_future();
}
void tls::credentials_builder::set_client_auth(client_auth auth) {
_client_auth = auth;
}
void tls::credentials_builder::set_priority_string(const sstring& prio) {
_priority = prio;
}
void tls::credentials_builder::set_session_resume_mode(session_resume_mode m) {
_session_resume_mode = m;
if (m != session_resume_mode::NONE) {
gnutls_datum key;
gtls_chk(gnutls_session_ticket_key_generate(&key));
_session_resume_key.assign(key.data, key.data + key.size);
}
}
template<typename Blobs, typename Visitor>
static void visit_blobs(Blobs& blobs, Visitor&& visitor) {
auto visit = [&](const sstring& key, auto* vt) {
auto tr = blobs.equal_range(key);
for (auto& p : boost::make_iterator_range(tr.first, tr.second)) {
auto* v = std::any_cast<std::decay_t<decltype(*vt)>>(&p.second);
visitor(key, *v);
}
};
visit(x509_trust_key, static_cast<x509_simple*>(nullptr));
visit(x509_crl_key, static_cast<x509_simple*>(nullptr));
visit(x509_key_key, static_cast<x509_key*>(nullptr));
visit(pkcs12_key, static_cast<pkcs12_simple*>(nullptr));
}
void tls::credentials_builder::apply_to(certificate_credentials& creds) const {
// Could potentially be templated down, but why bother...
visit_blobs(_blobs, make_visitor(
[&](const sstring& key, const x509_simple& info) {
if (key == x509_trust_key) {
creds.set_x509_trust(info.data, info.format);
} else if (key == x509_crl_key) {
creds.set_x509_crl(info.data, info.format);
}
},
[&](const sstring&, const x509_key& info) {
creds.set_x509_key(info.cert, info.key, info.format);
},
[&](const sstring&, const pkcs12_simple& info) {
creds.set_simple_pkcs12(info.data, info.format, info.password);
}
));
// TODO / Caveat:
// We cannot do this immediately, because we are not a continuation, and
// potentially blocking calls are a no-no.
// Doing this detached would be indeterministic, so set a flag in
// credentials, and do actual loading in first handshake (see session)
if (_blobs.count(system_trust)) {
creds._impl->_load_system_trust = true;
}
if (!_priority.empty()) {
creds.set_priority_string(_priority);
}
creds._impl->set_client_auth(_client_auth);
// Note: this causes server session key rotation on cert reload
creds._impl->set_session_resume_mode(_session_resume_mode, std::span{_session_resume_key.begin(), _session_resume_key.end()});
}
shared_ptr<tls::certificate_credentials> tls::credentials_builder::build_certificate_credentials() const {
auto creds = make_shared<certificate_credentials>();
apply_to(*creds);
return creds;
}
shared_ptr<tls::server_credentials> tls::credentials_builder::build_server_credentials() const {
auto i = _blobs.find(dh_level_key);
if (i == _blobs.end()) {
#if GNUTLS_VERSION_NUMBER < 0x030600
throw std::invalid_argument("No DH level set");
#else
auto creds = make_shared<server_credentials>();
apply_to(*creds);
return creds;
#endif
}
auto creds = make_shared<server_credentials>(dh_params(std::any_cast<dh_params::level>(i->second)));
apply_to(*creds);
return creds;
}
using namespace std::chrono_literals;
class tls::reloadable_credentials_base {
public:
using delay_type = std::chrono::milliseconds;
static inline constexpr delay_type default_tolerance = 500ms;
class reloading_builder
: public credentials_builder
, public enable_shared_from_this<reloading_builder>
{
public:
using time_point = std::chrono::system_clock::time_point;
reloading_builder(credentials_builder b, reload_callback_ex cb, reloadable_credentials_base* creds, delay_type delay)
: credentials_builder(std::move(b))
, _cb(std::move(cb))
, _creds(creds)
, _delay(delay)
{}
future<> init() {
std::vector<future<>> futures;
visit_blobs(_blobs, make_visitor(
[&](const sstring&, const x509_simple& info) {
_all_files.emplace(info.file.filename);
},
[&](const sstring&, const x509_key& info) {
_all_files.emplace(info.cert_file.filename);
_all_files.emplace(info.key_file.filename);
},
[&](const sstring&, const pkcs12_simple& info) {
_all_files.emplace(info.file.filename);
}
));
return parallel_for_each(_all_files, [this](auto& f) {
if (!f.empty()) {
return add_watch(f).discard_result();
}
return make_ready_future<>();
}).finally([me = shared_from_this()] {});
}
void start() {
// run the loop in a thread. makes code almost readable.
(void)async(std::bind(&reloading_builder::run, this)).finally([me = shared_from_this()] {});
}
void run() {
while (_creds) {
try {
auto events = _fsn.wait().get();
if (events.empty() && _creds == nullptr) {
return;
}
rebuild(events);
_timer.cancel();
} catch (...) {
if (!_timer.armed()) {
_timer.set_callback([this, ep = std::current_exception()]() mutable {
do_callback(std::move(ep));
});
_timer.arm(_delay);
}
}
}
}
void detach() {
_creds = nullptr;
_cb = {};
_fsn.shutdown();
_timer.cancel();
}
private:
using fsnotifier = experimental::fsnotifier;
// called from seastar::thread
void rebuild(const std::vector<fsnotifier::event>& events) {
for (auto& e : events) {
// don't use at. We could be getting two events for
// same watch (mod + delete), but we only need to care
// about one...
auto i = _watches.find(e.id);
if (i != _watches.end()) {
auto& filename = i->second.second;
// only add actual file watches to
// query set. If this was a directory
// watch, the file should already be
// in there.
if (_all_files.count(filename)) {
_files[filename] = e.mask;
}
_watches.erase(i);
}
}
auto num_changed = 0;
auto maybe_reload = [&](const sstring& filename, buffer_type& dst) {
if (filename.empty() || !_files.count(filename)) {
return;
}
// #756
// first, add a watch to nearest parent dir we
// can find. If user deleted folders, we could end
// up looking at modifications to root.
// The idea is that should adding a watch to actual file
// fail (deleted file/folder), we wait for changes to closest
// parent. When this happens, we will retry all files
// that have not been successfully replaced (and maybe more),
// repeating the process. At some point, we hopefully
// get new, current data.
add_dir_watch(filename);
// #756 add watch _first_. File could change while we are
// reading this.
try {
add_watch(filename).get();
} catch (...) {
// let's just assume if this happens, it's because the file or folder was deleted.
// just ignore for now, and hope the dir watch will tell us when it is back...
return;
}
temporary_buffer<char> buf = read_fully(filename, "reloading").get();
dst = to_buffer(buf);
++num_changed;
};
visit_blobs(_blobs, make_visitor(
[&](const sstring&, x509_simple& info) {
maybe_reload(info.file.filename, info.data);
},
[&](const sstring&, x509_key& info) {
maybe_reload(info.cert_file.filename, info.cert);
maybe_reload(info.key_file.filename, info.key);
},
[&](const sstring&, pkcs12_simple& info) {
maybe_reload(info.file.filename, info.data);
}
));
// only try this if anything was in fact successfully loaded.
// if files were missing, or pairs incomplete, we can just skip.
if (num_changed == 0) {
return;
}
try {
// force rebuilding session resume mode key if
// enabled. should not reuse sessions across certificate
// change (should not work anyway)
set_session_resume_mode(_session_resume_mode);
if (_creds) {
_creds->rebuild(*this);
}
} catch (...) {
if (std::any_of(_files.begin(), _files.end(), [](auto& p) { return p.second == fsnotifier::flags::ignored; })) {
// if any file in the reload set was deleted - i.e. we have not seen a "closed" yet - assume
// this is a spurious reload and we'd better wait for next event - hopefully a "closed" -
// and try again
return;
}
throw;
}
// if we got here, all files loaded, all watches were created,
// and gnutls was ok with the content. success.
do_callback();
on_success();
}
void on_success() {
_files.clear();
// remove all directory watches, since we've successfully
// reloaded -> the file watches themselves should suffice now
auto i = _watches.begin();
auto e = _watches.end();
while (i != e) {
if (!_all_files.count(i->second.second)) {
i = _watches.erase(i);
continue;
}
++i;
}
}
void do_callback(std::exception_ptr ep = {}) {
if (_cb && !_files.empty()) {
_cb(*this, boost::copy_range<std::unordered_set<sstring>>(_files | boost::adaptors::map_keys), std::move(ep)).get();
}
}
// called from seastar::thread
fsnotifier::watch_token add_dir_watch(const sstring& filename) {
auto dir = std::filesystem::path(filename).parent_path();
for (;;) {
try {
return add_watch(dir.native(), fsnotifier::flags::create_child | fsnotifier::flags::move).get();
} catch (...) {
auto parent = dir.parent_path();
if (parent.empty() || dir == parent) {
throw;
}
dir = std::move(parent);
continue;
}
}
}