-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathservice.cpp
3570 lines (2863 loc) · 177 KB
/
service.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
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
// KMS: A simple Keys management service
// (C) Phaistos Networks, S.A.
#include "sss/sss.h"
#include <base64.h>
#include <data.h>
#include <ext/tl/optional.hpp>
#include <network.h>
#include <switch.h>
#include <switch_security.h>
#include <sys/mman.h>
#ifndef SWITCH_MIN
#include <overseer_client.h>
#include <switch_rpc.h>
#include <switch_url.h>
#include <tls.h>
#else
#include <compress.h>
#include <ext/json.hpp>
#include <network.h>
#include <openssl/bio.h>
#include <openssl/engine.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/opensslconf.h>
#include <openssl/rand.h>
#include <openssl/ssl.h>
#include <signal.h>
#include <switch_hash.h>
#include <switch_mallocators.h>
#include <text.h>
#endif
#include <net/if.h>
#include <sys/ioctl.h>
#include <system_error>
#include <unordered_map>
static constexpr bool dev_mode{false}; // enable it for development
static constexpr std::size_t max_masterkey_shares{16};
struct authenticated_session final {
uint32_t account_id;
uint32_t lease_exp_ts;
uint32_t token_exp_ts;
};
struct connection final {
int fd; // must be first field in the struct
IOBuffer *inb{nullptr}, *outb{nullptr};
SSL * ssl{nullptr};
time_t last_activity;
~connection() {
if (ssl)
SSL_free(ssl);
}
struct
{
struct iovec data[128];
uint16_t size{0};
uint16_t idx{0};
bool need_patch{false};
auto reserve() {
require(size != sizeof_array(data));
return data + (size++);
}
auto append(const char *p, const std::size_t len) {
require(size != sizeof_array(data));
data[size] = iovec{(void *)p, len};
return data + (size++);
}
auto append(const str_view32 s) {
return append(s.data(), s.size());
}
void set_range(const range32_t range, struct iovec *iv) {
need_patch = true;
iv->iov_base = (void *)uintptr_t(range.offset);
iv->iov_len = range.size() | (1u << 30);
}
auto append_range(const range32_t range) {
require(size != sizeof_array(data));
set_range(range, data + size);
return data + (size++);
}
} iov;
enum class Flags : uint8_t {
need_outavail = 1,
state_have_headers = 1 << 1,
shutdown_onflush = 1 << 2,
tls_want_read = 1 << 3,
tls_want_write = 1 << 4,
tls_want_accept = 1 << 5,
tls_accept_ok = 1 << 6,
};
uint32_t flags{0};
struct
{
struct
{
uint32_t content_length;
str_view32 method, path;
bool expect_connection_close;
tl::optional<authenticated_session> auth;
} cur_req;
} state;
inline bool is_root() const noexcept {
return state.cur_req.auth && state.cur_req.auth.value().account_id == 0;
}
connection(int fd_)
: fd{fd_} {
}
};
static void wrapping_key_from_master_key(const uint8_t master_key[sss_MLEN], uint8_t wrapping_key[32]) {
// switch_security::hmac with EVP_sha256 is suitable(because it produces a 256-bit digest, and our wrapping key must be 256-bits)
// Or maybe, for the extra effort, switch_security::hmac::PBKDF2 should be used instad
// where salt is something reasonable.
//
// For now, we 'll use an HMAC
// XXX: what are we going to use for the key of this hmac? whatever it is, it needs to be
// non-legible so that e.g someone won't just use strings(1) to extract all strings from the binary
// (although the binary should only be readable by root anyway)
switch_security::hmac hmac(EVP_sha256(), _S("foo.key"));
hmac.update(master_key, sss_MLEN);
hmac.finalize(wrapping_key);
}
static bool verify_secret_prop_name(const str_view32 prop) noexcept {
if (!prop.size() || prop.size() > 64)
return false;
for (const auto *p = prop.data(), *const e = p + prop.size(); p != e; ++p) {
if ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || (*p >= '0' && *p <= '9') || *p == '_') {
// accept
} else
return false;
}
return true;
}
// Verifies a key name, or otherwise known as an object id
// root/sub/sub/sub...
static bool verify_objid(const str_view32 s) noexcept {
static constexpr bool trace{false};
if (s.size() < 2 || s.size() > 128 || s.front() == '/' || s.back() == '/') {
if (trace)
SLog("Invalid key name[", s, "]\n");
return false;
}
std::size_t components{0};
for (const auto *p = s.data(), *const e = p + s.size(); p != e; ++p) {
if (*p == '/') {
if (p[-1] == '/') {
if (trace)
SLog("Invalid key name[", s, "]\n");
return false;
} else
++components;
} else if ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || (*p >= '0' && *p <= '9') || *p == '_') {
// accept
} else {
if (trace)
SLog("Invalid key name[", s, "]\n");
return false;
}
}
return components && components < 16;
}
namespace {
// The IV we use for encrypting/decrypting keys we manage is based on their key name
// This is the iv[] we will use for encrypting/decrypting managed keys(i.e key => manged key) -- the encrypted keys
// are stored in the backing store
//
// We use the same iv[] for encrypting/decrypting arbitrary (plaintext or ciphertext) content
// and by extension, for wrap/unwrap operations, for the provided *wrapped* key
void build_iv(const str_view32 keyname, uint64_t iv[]) {
iv[0] = FNVHash64(reinterpret_cast<const uint8_t *>(keyname.data()), keyname.size());
iv[1] = XXH64(keyname.data(), keyname.size(), 1151);
}
void build_iv(const str_view32 keyname, uint8_t iv[16]) {
build_iv(keyname, reinterpret_cast<uint64_t *>(iv));
}
} // namespace
int main(int argc, char *argv[]) {
[[maybe_unused]] const auto verify_ownership = [](const auto path) {
struct stat64 s;
if (-1 == stat64(path, &s)) {
Print("Failed to authorize user: unable to stat file:", strerror(errno), "\n");
return false;
}
if (s.st_uid) {
Print("Failed to authorize user. ", path, " owner is not root\n");
return false;
}
if (s.st_mode & S_IRWXO) {
// Others cannot possibly read, write, or execute this binary
Print("Failed to authorize user. Unexpected file permissions for ", path, "\n");
return false;
}
return true;
};
// Select an ip4 address from one of the network interaces.
// Choose based on a simple heuristic
[[maybe_unused]] const auto main_if_ipaddr4 = []() -> uint32_t {
struct ifconf ifc;
struct ifreq ifreqs[128];
const struct ifreq *sel{nullptr};
int sel_idx;
memset(&ifc, 0, sizeof(ifc));
ifc.ifc_len = sizeof(ifreqs);
ifc.ifc_buf = reinterpret_cast<char *>(&ifreqs);
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1)
throw std::system_error(errno, std::system_category());
if (ioctl(fd, SIOCGIFCONF, &ifc) == -1) {
close(fd);
throw std::system_error(errno, std::system_category());
}
for (const auto *it = ifreqs, *const e = it + ifc.ifc_len / sizeof(ifreq); it != e; ++it) {
if (ioctl(fd, SIOCGIFFLAGS, it) == -1)
continue;
if ((it->ifr_flags & (IFF_UP | IFF_LOOPBACK)) == IFF_UP) {
if (ioctl(fd, SIOCGIFBRDADDR, it) == -1)
continue;
const auto s = reinterpret_cast<const sockaddr_in *>(&it->ifr_addr);
const auto broadcast_ip4 = *reinterpret_cast<const uint32_t *>(&s->sin_addr.s_addr);
if (broadcast_ip4 == INADDR_ANY)
continue;
if (ioctl(fd, SIOCGIFINDEX, it) == -1)
continue;
if (!sel || (it->ifr_ifindex < sel_idx || strlen(it->ifr_name) < strlen(sel->ifr_name))) {
sel_idx = it->ifr_ifindex;
sel = it;
}
}
}
if (sel) {
if (ioctl(fd, SIOCGIFADDR, sel) == -1) {
close(fd);
throw std::system_error(errno, std::system_category());
}
close(fd);
const auto s = reinterpret_cast<const sockaddr_in *>(&sel->ifr_addr);
const auto addr_ip4 = *reinterpret_cast<const uint32_t *>(&s->sin_addr.s_addr);
return addr_ip4;
} else {
close(fd);
return 0;
}
};
[[maybe_unused]] const auto verify_ownership_with_fd = [](const auto path, auto fd) {
struct stat s;
if (-1 == fstat(fd, &s)) {
Print("Failed to authorize user: unable to stat file:", strerror(errno), "\n");
return false;
}
if (s.st_uid) {
Print("Failed to authorize user. ", path, " owner is not root\n");
return false;
}
if (s.st_mode & S_IRWXO) {
Print("Failed to authorize user. Unexpected file permissions for ", path, "\n");
return false;
}
return true;
};
if (false == dev_mode) {
const auto uid = geteuid();
if (0 != uid) {
Print("Unauthorized execution not allowed. KMS requires root access.\n");
return 1;
}
#ifdef MLOCK_ONFAULT
if (-1 == mlockall(MLOCK_ONFAULT))
#else
if (-1 == mlockall(MCL_CURRENT | MCL_FUTURE))
#endif
{
Print("System Error: cannot guarantee safety. Cowardly aborting: ", strerror(errno), "\n");
return 1;
}
// verify that we have the right to do this
char b[8192];
if (auto fh = fopen("/proc/self/cmdline", "r"); nullptr == fh) {
Print("Failed to authorize user: unable to access /proc/self/cmdline\n");
return 1;
} else if (nullptr == fgets(b, sizeof(b), fh)) {
fclose(fh);
Print("Failed to authorize user: unable to read /proc/self/cmdline\n");
return 1;
} else {
if (!verify_ownership(b /* this works, because command is \0 terminated */))
return 1;
}
}
MysqlClient mysql_client;
Switch::endpoint e;
int r;
uint32_t now = time(nullptr);
IOBuffer base64_buf, tbuf;
static const str_view32 server_name("Phaistos KMS");
struct
{
struct
{
std::size_t create_keys;
std::size_t delete_keys;
std::size_t set_keys;
std::size_t encrypt;
std::size_t decrypt;
std::size_t get_keys;
std::size_t unwrap;
std::size_t get_secrets;
std::size_t set_secrets;
} reqs;
uint32_t if_addr4;
} runtime_metrics;
time_t past{0};
struct Enclave final {
simple_allocator allocator;
// it's important that we get the tokens generation right
// for now, this will just be unix epoch time
// but even if someone is messing with the data in an attempt to fool KMS, we will likely still be fine (see build_new_token() impl.)
uint32_t tokens_sequencer_gen{0};
uint32_t tokens_sequencer{0};
uint8_t enc_key[256 / 8]; // AES-256, 8-bytes key
bool locked{true};
struct
{
// used for tokens generation
// initialized on startup and is hopefully unique
uint64_t session_id;
} cur_sess;
struct
{
uint8_t shares_cnt{0};
uint8_t master_key_shares_threshold;
uint8_t collected{0};
Buffer shares[max_masterkey_shares];
// used for encrypting all provided shares
// we reset when we get the first share
uint8_t enc_key[32] = {0};
uint8_t enc_iv[16];
struct
{
} root_token;
void reset() {
collected = 0;
memset(enc_key, 0, sizeof(enc_key));
memset(enc_iv, 0, sizeof(enc_iv));
}
} mk_unlock_ctx;
// a token encodes:
// - account id:u32
// - lease expiration:u32
// - token expiration:u32
// - seq:u32
// - gen:u32
// - hash of KMS instance session digest:u64
// - digest hash:u64
//
// - the digest hash is the hash of (lease expiration, token expiration, seq, gen, KMS enc.key, hash of KMS instance session digest)
// - instance session digest:u8[16] is initialized once on startup via switch_security::gen_rnd()
// - we have two different expiration timestamps(lease and token), because when the lease
// expires, that's when we check if the token has been revoked, and if not, we create another
// token with a new lease time. By setting short lease times (e.g 1 minute), we can revoke within 1 minute
// - gen is reset to time(null) on startup, and (gen, seq) are useful because we can rely on them and
// on the hash instance session digest
//
// For representation, we 'll just concatenate the fields, then encrypt it using our kms.enc key and will use a base64 representation for it
void build_token(uint64_t data[7], const uint32_t account_id, const uint32_t lease_exp_ts, const uint32_t token_exp_ts) {
const auto seq = ++tokens_sequencer;
data[0] = account_id;
data[1] = lease_exp_ts;
data[2] = token_exp_ts;
data[3] = seq;
data[4] = tokens_sequencer_gen;
data[5] = cur_sess.session_id;
uint64_t h = BeginFNVHash64();
for (size_t i{0}; i != 6; ++i)
h = FNVHash64(h, reinterpret_cast<const uint8_t *>(data + i), sizeof(uint64_t));
h = FNVHash64(h, enc_key, 32);
data[6] = h;
}
tl::optional<authenticated_session> parse_token(const str_view32 repr, const uint32_t now) const {
static constexpr bool trace{false};
uint64_t input[8];
uint8_t n{0};
if (trace)
SLog("Parsing [", repr, "]\n");
for (const auto it : repr.Split('-')) {
if (it.empty() || it.size() > 64) {
if (trace)
SLog("Unexpected input\n");
return tl::nullopt;
} else
input[n++] = Text::FromBase(it.data(), it.size(), 60);
}
if (n != 7) {
if (trace)
SLog("Expected ", n, " segments\n");
return tl::nullopt;
}
if (const auto exp_ts = input[2]; exp_ts && exp_ts < now) {
// Expired
// TODO: delete from tokens
if (trace)
SLog("Expired already (now = ", now, ", exp_ts = ", exp_ts, ")\n");
return tl::nullopt;
}
uint64_t h = BeginFNVHash64();
for (size_t i{0}; i != 6; ++i)
h = FNVHash64(h, reinterpret_cast<const uint8_t *>(input + i), sizeof(uint64_t));
h = FNVHash64(h, enc_key, 32);
if (h != input[6]) {
if (trace)
SLog("Failed to verify hash ", h, " ", input[6], "\n");
return tl::nullopt;
}
if (const auto lease_exp_ts = input[1]; now > lease_exp_ts) {
[[maybe_unused]] const auto account_id = input[0];
// TODO: check if account_id is in our revoked tokens list
// If it is not, see if it's in our database
// if it is, make room for it in the in-memory revoked tokens list and reny access
// if not, we need to create a new token
// with a proper lease. Short leases faciliate frequent checks for revoked tokens
}
if (trace)
SLog("Auth token repr OK\n");
return authenticated_session{uint32_t(input[0]), uint32_t(input[1]), uint32_t(input[2])};
}
// aa-bb-cc-dd-ee-ff
static std::size_t token_repr(const uint64_t token[7], char *out) {
const auto base{out};
out += Text::ToBase(token[0], 60, out);
for (size_t i{1}; i != 7; ++i) {
*out++ = '-';
const auto c{out};
out += Text::ToBase(token[i], 60, out);
// sanity check
require(Text::FromBase(c, std::distance(c, out), 60) == token[i]);
}
return std::distance(base, out);
}
} secure_enclave;
struct token_props final {
uint8_t domains_cnt{0};
std::pair<str_view8, uint32_t> *domains;
uint32_t last_update{0};
~token_props() {
while (domains_cnt)
std::free((void *)(domains[--domains_cnt].first.data()));
}
};
std::unordered_map<uint32_t, std::unique_ptr<token_props>> tokens_map;
Buffer _mc;
bool use_http{false};
if (dev_mode)
Print("KMS is running in DEVELOPMENT MODE. Please make sure you acknowledge that\n");
e.unset();
while ((r = getopt(argc, argv, dev_mode ? "l:M:f:P" : "l:f:P")) != -1) {
switch (r) {
case 'P':
use_http = true;
break;
case 'f': {
int fd = open(optarg, O_RDONLY | O_CLOEXEC);
if (fd == -1) {
Print("Unable to access ", optarg, ": ", strerror(errno), "\n");
return 1;
}
if (!dev_mode && !verify_ownership_with_fd(optarg, fd))
return 1;
struct vma_dtor {
const off_t size_;
vma_dtor(const off_t size)
: size_{size} {
}
void operator()(void *ptr) {
if (ptr != MAP_FAILED)
munmap(ptr, size_);
}
};
const auto file_size = lseek(fd, 0, SEEK_END);
std::unique_ptr<void, vma_dtor> vma(mmap(nullptr, file_size, PROT_READ, MAP_SHARED, fd, 0), vma_dtor(file_size));
close(fd);
if (vma.get() == MAP_FAILED) {
Print("System Error:", strerror(errno), "\n");
return 1;
}
madvise(vma.get(), file_size, MADV_SEQUENTIAL | MADV_DONTDUMP);
for (const auto s : str_view32(reinterpret_cast<const char *>(vma.get()), file_size).Split('\n')) {
// no longer treating '#' as a comment, because it may be used in a password
if (const auto l = s.ws_trimmed()) {
//if (const auto l = s.Divided('#').first.ws_trimmed()) {
const auto[n, v] = l.Divided('=');
const auto name = n.ws_trimmed();
const auto value = v.ws_trimmed();
if (name.Eq(_S("persist.mysql.endpoint"))) {
_mc.clear();
_mc.append(value);
} else
Print("Unsupported configuration option '", name, "'\n");
}
}
} break;
case 'M':
if (!dev_mode) {
Print("Not Supported Option\n");
return 1;
} else {
// not supposed to use this
// this is for development puproses really
_mc.append(optarg);
break;
}
case 'l': {
const str_view32 repr(optarg);
try {
e = Switch::ParseSrvEndpoint(repr, "http"_s8, 80);
} catch (...) {
e.unset();
}
if (!e) {
Print("Unable to parse endpoint from ", repr, "\n");
return 1;
}
} break;
default:
return 1;
}
}
argc -= optind;
argv += optind;
if (_mc.empty()) {
char input[512];
fprintf(stderr, "mySQL endpoint (username:password@host[:port]/databasename): ");
fgets(input, sizeof(input), stdin);
_mc.append(input);
#ifndef SWITCH_MIN
_mc.TrimWS();
#endif
}
{
if (_mc.size() > 255) {
Print("Invalid mySQL endpoint: ", _mc, "\n");
return 1;
}
// user[:password]@endpoint[/database_name]
const auto[auth, r] = _mc.as_s32().Divided('@');
if (!auth || !r) {
Print("Invalid mySQL endpoint \"", _mc.as_s32(), "\". Expected authentication\n");
return 1;
}
const auto[endpoint, dbname] = r.Divided('/');
if (!endpoint || !dbname) {
Print("Invalid mySQL endpoint. Expecte database name\n");
return 1;
}
const auto[hostname, port_repr] = endpoint.Divided(':');
const uint32_t port = port_repr ? port_repr.as_uint32() : 3306;
const auto[username, password] = auth.Divided(':');
if (!username) {
Print("Invalid mySQL endpoint. Username not specified\n");
return 1;
}
char hostname_data[0xff], username_data[0xff], password_data[0xff], dbname_data[0xff];
hostname.ToCString(hostname_data, sizeof(hostname_data));
username.ToCString(username_data, sizeof(username_data));
password.ToCString(password_data, sizeof(password_data));
dbname.ToCString(dbname_data, sizeof(dbname_data));
try {
mysql_client.enable_ssl();
mysql_client.connect(hostname_data, username_data, password_data, dbname_data, port, nullptr, 0);
} catch (...) {
Print("Unable to establish secure connection. Aborting\n");
return 1;
}
mysql_client.exec(R"stmt(CREATE TABLE IF NOT EXISTS `kms_runtime_metrics` ( `ip_addr4` int unsigned not null, `op_create_keys` bigint(20) unsigned NOT NULL, `op_delete_keys` bigint(20) unsigned NOT NULL, `op_set_keys` bigint(20) unsigned NOT NULL, `op_encrypt` bigint(20) unsigned NOT NULL, `op_decrypt` bigint(20) unsigned NOT NULL, `op_get_keys` bigint(20) unsigned NOT NULL, `op_unwrap` bigint(20) unsigned NOT NULL, `op_get_secrets` bigint(20) unsigned NOT NULL, `op_set_secrets` bigint(20) unsigned NOT NULL, PRIMARY KEY(ip_addr4)))stmt"_s32);
runtime_metrics.if_addr4 = main_if_ipaddr4();
if (runtime_metrics.if_addr4) {
if (auto &&rows = mysql_client.select("SELECT * FROM kms_runtime_metrics WHERE ip_addr4 = "_s32, runtime_metrics.if_addr4); auto &&row = rows.next()) {
auto &r{runtime_metrics.reqs};
r.create_keys = row[1].as_uint64();
r.delete_keys = row[2].as_uint64();
r.set_keys = row[3].as_uint64();
r.encrypt = row[4].as_uint64();
r.decrypt = row[5].as_uint64();
r.get_keys = row[6].as_uint64();
r.unwrap = row[7].as_uint64();
r.get_secrets = row[8].as_uint64();
r.set_secrets = row[9].as_uint64();
} else
memset(&runtime_metrics.reqs, 0, sizeof(runtime_metrics.reqs));
} else {
Print("Unable to select a hardware network interface IP4 address for metrics. Will not track metrics\n");
}
}
const auto set_response_connection_header = [](auto c) {
// TODO: if (c->inb->offset() == c->inb->size()), we have more requests to processs, so maybe we should shutdown the connection
if ((c->flags & unsigned(connection::Flags::shutdown_onflush)) || c->state.cur_req.expect_connection_close) {
c->iov.append("Connection: close\r\n"_s32);
c->flags |= unsigned(connection::Flags::shutdown_onflush);
} else
c->iov.append("Connection: keep-alive\r\n"_s32);
};
std::vector<IOBuffer *> reusable_bufs;
const auto new_buf = [&reusable_bufs]() {
if (reusable_bufs.empty())
return new IOBuffer();
auto res = reusable_bufs.back();
reusable_bufs.pop_back();
return res;
};
const auto renew_token = [&](auto c, const uint32_t lease_exp_ts, const uint32_t token_exp_ts) {
require(c->state.cur_req.auth);
if (lease_exp_ts >= token_exp_ts) {
c->iov.append("X-KMS-SetAuth: \r\n"_s32);
} else {
const auto sess = c->state.cur_req.auth.value();
uint64_t new_auth_token[7];
char token_repr[128];
uint8_t token_iv[16];
build_iv("**"_s32, token_iv);
secure_enclave.build_token(new_auth_token, sess.account_id, lease_exp_ts, token_exp_ts);
const uint32_t token_repr_size = Enclave::token_repr(new_auth_token, token_repr);
const auto wrapped_token = switch_security::ciphers::aes256{{secure_enclave.enc_key, 32}, {token_iv, 16}}.encrypt({token_repr, token_repr_size});
auto outb = c->outb ?: (c->outb = new_buf());
const auto o = outb->size();
c->iov.append("X-KMS-SetAuth: "_s32);
Base64::Encode(reinterpret_cast<const uint8_t *>(wrapped_token.data()), wrapped_token.size(), outb);
c->iov.append_range({o, outb->size() - o});
c->iov.append("\r\n"_s32);
}
};
[[maybe_unused]] const auto extend_lease = [&](auto c, const uint32_t extension) {
require(c->state.cur_req.auth);
const auto sess = c->state.cur_req.auth.value();
renew_token(c, std::min<uint32_t>(now + extension, sess.token_exp_ts), sess.token_exp_ts);
};
[[maybe_unused]] const auto maybe_extend_lease = [&](auto c) {
if (c->state.cur_req.auth && !c->is_root()) {
if (const auto lease_exp_ts = c->state.cur_req.auth.value().lease_exp_ts; lease_exp_ts < now) {
// a minute later
extend_lease(c, 60);
}
}
};
const auto build_response = [&new_buf, &set_response_connection_header](auto c, const str_view32 resp, const str_view32 msg = {}) {
if (!msg) {
c->iov.append("HTTP/1.1 "_s32);
c->iov.append(resp);
c->iov.append("\r\nContent-Length: 0\r\nServer: "_s32);
c->iov.append(server_name);
c->iov.append("\r\n");
set_response_connection_header(c);
c->iov.append("\r\n"_s32);
} else {
auto outb = c->outb ?: (c->outb = new_buf());
c->iov.append("HTTP/1.1 "_s32);
c->iov.append(resp);
c->iov.append("\r\nContent-Length: "_s32);
const auto o{outb->size()};
outb->append(msg.size());
c->iov.append_range({o, outb->size() - o});
c->iov.append("\r\nServer: "_s32);
c->iov.append(server_name);
c->iov.append("\r\n"_s32);
set_response_connection_header(c);
c->iov.append("\r\n"_s32);
if (IsConstant(msg.data())) {
c->iov.append(msg);
} else {
const auto o2{outb->size()};
outb->append(msg);
c->iov.append_range({o2, outb->size() - o2});
}
}
};
const auto try_unlock = [&](const sss_Share *shares, const std::size_t cnt) {
uint8_t restored_master_key[sss_MLEN];
uint8_t wrapping_key[32];
const auto res = sss_combine_shares(restored_master_key, shares, cnt);
if (0 != res) {
Print("Failed to reconstruct master key\n");
return false;
}
// great, we can now derive a wrapping key
// from the restored master key, and use that to unwrap the KMS enc.key
wrapping_key_from_master_key(restored_master_key, wrapping_key);
// Fetch the wrapped key from the backing store
try {
if (auto rows = mysql_client.select("SELECT k FROM keyring WHERE id = '*'"_s32); auto &&row = rows.next()) {
if (row[0].size() < 8) {
// Sanity check
return false;
}
const auto wrapped_key = row[0].SuffixFrom(2); // skip encoded (total shares, required shares)
try {
// decrypt wrapped key using the wrapping key to produce the plaintext(which will be the enc_key)
// the iv is derived from the master key
const uint64_t iv[2]{
FNVHash64(restored_master_key, sss_MLEN),
XXH64(restored_master_key, sss_MLEN, 5022)};
const auto plaintext = switch_security::ciphers::aes256{{wrapping_key, 32}, {reinterpret_cast<const uint8_t *>(iv), 16}}.decrypt(wrapped_key);
if (plaintext.size() != 32) {
Print("Unexpected state: Cowardly rejecting unlock operation (#2)\n");
return false;
}
memcpy(secure_enclave.enc_key, plaintext.data(), plaintext.size());
secure_enclave.locked = false;
Print(ansifmt::bold, ansifmt::color_green, "KMS unlocked", ansifmt::reset, "\n");
return true;
} catch (...) {
Print("FAILED to unlock KMS. Unexpected state\n");
return false;
}
} else {
Print("Not initialized yet?\n");
return false;
}
} catch (...) {
Print("Failed to access `keyring` table. Please make sure you have initialised the mySQL databased used by KMS first.\n");
return false;
}
};
secure_enclave.tokens_sequencer_gen = time(nullptr);
if (argc == 3 && !strcmp(argv[0], "init")) {
const auto cnt = str_view32(argv[1]).as_uint32();
if (cnt > max_masterkey_shares || cnt < 1) {
Print("Unexpected number of shares requested\n");
return 1;
} else {
const auto threshold = str_view32(argv[2]).as_uint32();
if (threshold > cnt) {
Print("Invalid number of shares required to reconstruct key\n");
return 1;
} else {
if (false == dev_mode) {
if (mysql_client.select("SELECT 1 FROM keyring WHERE id = '*'"_s32).size()) {
Print("Already initialized. Cowardingly aborting\n");
return 1;
}
}
uint8_t master_key[sss_MLEN];
uint8_t wrapping_key[32], enc_key[32];
uint64_t enc_key_iv[2];
sss_Share shares[cnt]; // this is uint8_t[sss_SHARE_LEN]
Buffer repr;
// Let's create the enc.key
// This is the key that we will use to encrypt and ecrypt everything in the backing store, except
// for the objid identified by '*'
switch_security::gen_rnd(32, enc_key);
// We will need a root token
// create one here, one that never expires
char root_token_repr[256];
uint64_t root_token[7];
memcpy(secure_enclave.enc_key, enc_key, 32); // because secure_enclave::build_token() requires enc_key
secure_enclave.build_token(root_token, 0, 0, 0);
const uint32_t root_token_repr_size = Enclave::token_repr(root_token, root_token_repr);
// The master key is specifically used to build a wrapping key, which will be used, once, for
// encrypting the KMS enc.key
// It will be used hence forth for unlocking KMS. That is, we will again derive a wrapping key from
// the master key, and we will use that to unwrap the KMS enc.key
switch_security::gen_rnd(sss_MLEN, master_key);
// We will derive the wrapping key from master key
// Because we need a 32-bytes key, we will use salt/digests to get from the sss_MLEN-bytes master key
// to a wrapping key.
wrapping_key_from_master_key(master_key, wrapping_key);
// Encrypt the enc.key with the wrapping key, and *store* the wrapped KMS enc.key somewhere
// the iv depends on the master_key.
enc_key_iv[0] = FNVHash64(master_key, sss_MLEN);
enc_key_iv[1] = XXH64(master_key, sss_MLEN, 5022);
const auto wrapped_enc_key = switch_security::ciphers::aes256{{wrapping_key, 32}, {reinterpret_cast<uint8_t *>(enc_key_iv), 16}}
.encrypt(str_view32(reinterpret_cast<const char *>(enc_key), 32));
// we also include (cnt, threshold)
// encoded as the first characters of the row
// it's fine if someone accesses it anyway, because that's just two numbers
// TODO: consider alternative ways to store those
mysql_client.begin();
mysql_client.exec("REPLACE INTO keyring VALUES ('*', '", char('a' + cnt), char('a' + threshold), escaped_repr(wrapped_enc_key.as_s32()), "')");
// Another for the root token
// We will encrypt it using our KMS enc.key
// and the IV[] just depends on the key name which is "**"
// we will encrypt it, and then base64 encode it
uint8_t root_token_iv[16];
Buffer wrapped_root_token_base64;
build_iv("**"_s32, root_token_iv);
const auto wrapped_root_token = switch_security::ciphers::aes256{{enc_key, 32}, {root_token_iv, 16}}.encrypt({root_token_repr, root_token_repr_size});
Base64::Encode(reinterpret_cast<const uint8_t *>(wrapped_root_token.data()), wrapped_root_token.size(), &wrapped_root_token_base64);
// We will split the master key into shares pieces and will require threshold parts
// to reconstruct the master key.
// So, to unwrap the wrapped KMS enc.key, the master key is required
sss_create_shares(shares, master_key, cnt, threshold);
Base64::Encode(master_key, sss_MLEN, &repr);
// There is no need to display the Master Key here
// It should't be stored anywhere, TODO: UNLESS you have a trusted environment, and you want to store it somewhere
// so that when you unlock it later, you can somehow use the master key instead of requiring shares
// This is so that it can be automated to some extent (no need for someone to physically paste/type their shares)
//
// TODO: maybe we should salt, and encrypt each share, so that the base64 representation will be less uniform and
// will be harder for someone to - in theory - guess a share.
Print("Root Token: ", wrapped_root_token_base64, "\n");
for (size_t i{0}; i != cnt; ++i) {
repr.clear();
Base64::Encode(reinterpret_cast<const uint8_t *>(shares + i), sss_SHARE_LEN, &repr);
Print("Share ", i, ": ", ansifmt::bold, repr.as_s32(), ansifmt::reset, "\n");
}
Print("Trusted operators should own those shares. A minimum of ", threshold, " shares are required to reconstruct the Master Key, and unseal KMS.\n");
Print("If you can't reconstruct the Master Key, you are toast. Backup often.\n");
mysql_client.commit();
return 0;
}
}
} else if (argc > 1 && !strcmp(argv[0], "rotate")) {
// we will unlock, see try_unlock()
// enc.key, and then we will create a new master key, etc (see "init" impl.)
//
// This is useful when you want to alter the number of trusted parties, or number of required shares, etc.