-
Notifications
You must be signed in to change notification settings - Fork 40
/
neverbleed.c
2274 lines (1960 loc) · 67.4 KB
/
neverbleed.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2015 Kazuho Oku, DeNA Co., Ltd.
*
* 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 <assert.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <limits.h>
#include <pthread.h>
#include <pwd.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <signal.h>
#if defined(__linux__)
#include <sys/epoll.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#elif defined(__APPLE__)
#include <sys/ptrace.h>
#elif defined(__FreeBSD__)
#include <sys/procctl.h>
#elif defined(__sun)
#include <priv.h>
#endif
/* to maximize code-reuse between different stacks, we intentionally use API declared by OpenSSL as legacy */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <openssl/opensslconf.h>
#include <openssl/opensslv.h>
#if defined(LIBRESSL_VERSION_NUMBER) ? LIBRESSL_VERSION_NUMBER >= 0x3050000fL : OPENSSL_VERSION_NUMBER >= 0x1010000fL
/* RSA_METHOD is opaque, so RSA_meth* are used. */
#define NEVERBLEED_OPAQUE_RSA_METHOD
#endif
#if OPENSSL_VERSION_NUMBER >= 0x1010000fL && !defined(OPENSSL_NO_EC) && \
(!defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER >= 0x2090100fL)
/* EC_KEY_METHOD and related APIs are avaliable, so ECDSA is enabled. */
#define NEVERBLEED_ECDSA
#endif
#include <openssl/bn.h>
#ifdef NEVERBLEED_ECDSA
#include <openssl/ec.h>
#endif
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/ssl.h>
#ifdef __linux
#if OPENSSL_VERSION_NUMBER >= 0x1010000fL && !defined(LIBRESSL_VERSION_NUMBER) && !defined(OPENSSL_IS_BORINGSSL)
#define USE_OFFLOAD 1
#endif
#if defined(OPENSSL_IS_BORINGSSL) && defined(NEVERBLEED_BORINGSSL_USE_QAT)
#include "qat_bssl.h"
/* the mapping seems to be missing */
#ifndef ASYNC_WAIT_CTX_get_all_fds
extern int bssl_async_wait_ctx_get_all_fds(ASYNC_WAIT_CTX *ctx, OSSL_ASYNC_FD *fd, size_t *numfds);
#define ASYNC_WAIT_CTX_get_all_fds bssl_async_wait_ctx_get_all_fds
#endif
#define USE_OFFLOAD 1
#endif
#endif
#if OPENSSL_VERSION_NUMBER < 0x1010000fL || (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL)
static void RSA_get0_key(const RSA *rsa, const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
{
if (n) {
*n = rsa->n;
}
if (e) {
*e = rsa->e;
}
if (d) {
*d = rsa->d;
}
}
static int RSA_set0_key(RSA *rsa, BIGNUM *n, BIGNUM *e, BIGNUM *d)
{
if (n == NULL || e == NULL) {
return 0;
}
BN_free(rsa->n);
BN_free(rsa->e);
BN_free(rsa->d);
rsa->n = n;
rsa->e = e;
rsa->d = d;
return 1;
}
static void RSA_set_flags(RSA *r, int flags)
{
r->flags |= flags;
}
#define EVP_PKEY_up_ref(p) CRYPTO_add(&(p)->references, 1, CRYPTO_LOCK_EVP_PKEY)
#endif
#include "neverbleed.h"
enum neverbleed_type { NEVERBLEED_TYPE_ERROR, NEVERBLEED_TYPE_RSA, NEVERBLEED_TYPE_ECDSA };
struct st_neverbleed_rsa_exdata_t {
neverbleed_t *nb;
size_t key_index;
};
struct st_neverbleed_thread_data_t {
pid_t self_pid;
int fd;
};
/**
* a variant of pthread_once, that does not require you to declare a callback, nor have a global variable
*/
#define NEVERBLEED_MULTITHREAD_ONCE(block) \
do { \
static volatile int lock = 0; \
int lock_loaded = lock; \
__sync_synchronize(); \
if (!lock_loaded) { \
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; \
pthread_mutex_lock(&mutex); \
if (!lock) { \
do { \
block \
} while (0); \
__sync_synchronize(); \
lock = 1; \
} \
pthread_mutex_unlock(&mutex); \
} \
} while (0)
static void warnvf(const char *fmt, va_list args)
{
char errbuf[256];
if (errno != 0) {
strerror_r(errno, errbuf, sizeof(errbuf));
} else {
errbuf[0] = '\0';
}
fprintf(stderr, "[openssl-privsep] ");
vfprintf(stderr, fmt, args);
if (errbuf[0] != '\0')
fputs(errbuf, stderr);
fputc('\n', stderr);
}
__attribute__((format(printf, 1, 2))) static void warnf(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
warnvf(fmt, args);
va_end(args);
}
__attribute__((format(printf, 1, 2), noreturn)) static void dief(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
warnvf(fmt, args);
va_end(args);
abort();
}
static char *dirname(const char *path)
{
const char *last_slash = strrchr(path, '/');
char *ret;
if (last_slash == NULL) {
errno = 0;
dief("dirname: no slash in given path:%s", path);
}
if ((ret = malloc(last_slash + 1 - path)) == NULL)
dief("no memory");
memcpy(ret, path, last_slash - path);
ret[last_slash - path] = '\0';
return ret;
}
static void set_cloexec(int fd)
{
if (fcntl(fd, F_SETFD, O_CLOEXEC) == -1)
dief("failed to set O_CLOEXEC to fd %d", fd);
}
static int read_nbytes(int fd, void *p, size_t sz)
{
while (sz != 0) {
ssize_t r;
while ((r = read(fd, p, sz)) == -1 && errno == EINTR)
;
if (r == -1) {
return -1;
} else if (r == 0) {
errno = 0;
return -1;
}
p = (char *)p + r;
sz -= r;
}
return 0;
}
/**
* This function disposes of the memory allocated for `neverbleed_iobuf_t`, but retains the value of `next` and `processing` so that
* the buffer can be "cleared" while in use by worker threads.
*/
static void iobuf_dispose(neverbleed_iobuf_t *buf)
{
if (buf->capacity != 0)
OPENSSL_cleanse(buf->buf, buf->capacity);
free(buf->buf);
buf->buf = NULL;
buf->start = NULL;
buf->end = NULL;
buf->capacity = 0;
}
static void iobuf_reserve(neverbleed_iobuf_t *buf, size_t extra)
{
size_t start_off, end_off;
if (extra <= buf->buf - buf->end + buf->capacity)
return;
if (buf->capacity == 0)
buf->capacity = 4096;
while (buf->buf - buf->end + buf->capacity < extra)
buf->capacity *= 2;
if (buf->buf != NULL) {
start_off = buf->start - buf->buf;
end_off = buf->end - buf->buf;
} else {
/* C99 forbids us doing `buf->start - buf->buf` when both are NULL (undefined behavior) */
start_off = 0;
end_off = 0;
}
if ((buf->buf = realloc(buf->buf, buf->capacity)) == NULL)
dief("realloc failed");
buf->start = buf->buf + start_off;
buf->end = buf->buf + end_off;
}
static void iobuf_push_num(neverbleed_iobuf_t *buf, size_t v)
{
iobuf_reserve(buf, sizeof(v));
memcpy(buf->end, &v, sizeof(v));
buf->end += sizeof(v);
}
static void iobuf_push_str(neverbleed_iobuf_t *buf, const char *s)
{
size_t l = strlen(s) + 1;
iobuf_reserve(buf, l);
memcpy(buf->end, s, l);
buf->end += l;
}
static void iobuf_push_bytes(neverbleed_iobuf_t *buf, const void *p, size_t l)
{
iobuf_push_num(buf, l);
iobuf_reserve(buf, l);
memcpy(buf->end, p, l);
buf->end += l;
}
static int iobuf_shift_num(neverbleed_iobuf_t *buf, size_t *v)
{
if (neverbleed_iobuf_size(buf) < sizeof(*v))
return -1;
memcpy(v, buf->start, sizeof(*v));
buf->start += sizeof(*v);
return 0;
}
static char *iobuf_shift_str(neverbleed_iobuf_t *buf)
{
char *nul = memchr(buf->start, '\0', neverbleed_iobuf_size(buf)), *ret;
if (nul == NULL)
return NULL;
ret = buf->start;
buf->start = nul + 1;
return ret;
}
static void *iobuf_shift_bytes(neverbleed_iobuf_t *buf, size_t *l)
{
void *ret;
if (iobuf_shift_num(buf, l) != 0)
return NULL;
if (neverbleed_iobuf_size(buf) < *l)
return NULL;
ret = buf->start;
buf->start += *l;
return ret;
}
static int iobuf_write(neverbleed_iobuf_t *buf, int fd)
{
struct iovec vecs[2] = {{NULL}};
size_t bufsz = neverbleed_iobuf_size(buf);
int vecindex;
ssize_t r;
vecs[0].iov_base = &bufsz;
vecs[0].iov_len = sizeof(bufsz);
vecs[1].iov_base = buf->start;
vecs[1].iov_len = bufsz;
for (vecindex = 0; vecindex != sizeof(vecs) / sizeof(vecs[0]);) {
while ((r = writev(fd, vecs + vecindex, sizeof(vecs) / sizeof(vecs[0]) - vecindex)) == -1 && errno == EINTR)
;
if (r == -1)
return -1;
assert(r != 0);
while (r != 0 && r >= vecs[vecindex].iov_len) {
r -= vecs[vecindex].iov_len;
++vecindex;
}
if (r != 0) {
vecs[vecindex].iov_base = (char *)vecs[vecindex].iov_base + r;
vecs[vecindex].iov_len -= r;
}
}
return 0;
}
static int iobuf_read(neverbleed_iobuf_t *buf, int fd)
{
size_t sz;
if (read_nbytes(fd, &sz, sizeof(sz)) != 0)
return -1;
iobuf_reserve(buf, sz);
if (read_nbytes(fd, buf->end, sz) != 0)
return -1;
buf->end += sz;
return 0;
}
void neverbleed_iobuf_dispose(neverbleed_iobuf_t *buf)
{
iobuf_dispose(buf);
}
static void iobuf_transaction_write(neverbleed_iobuf_t *buf, struct st_neverbleed_thread_data_t *thdata)
{
if (iobuf_write(buf, thdata->fd) == -1) {
if (errno != 0) {
dief("write error (%d) %s", errno, strerror(errno));
} else {
dief("connection closed by daemon");
}
}
}
static void iobuf_transaction_read(neverbleed_iobuf_t *buf, struct st_neverbleed_thread_data_t *thdata)
{
iobuf_dispose(buf);
if (iobuf_read(buf, thdata->fd) == -1) {
if (errno != 0) {
dief("read error (%d) %s", errno, strerror(errno));
} else {
dief("connection closed by daemon");
}
}
}
/**
* Only sends a request, does not read a response
*/
static void iobuf_transaction_no_response(neverbleed_iobuf_t *buf, struct st_neverbleed_thread_data_t *thdata)
{
if (neverbleed_transaction_cb != NULL) {
neverbleed_transaction_cb(buf, 1);
} else {
iobuf_transaction_write(buf, thdata);
iobuf_dispose(buf);
}
}
/**
* Sends a request and reads a response.
*/
static void iobuf_transaction(neverbleed_iobuf_t *buf, struct st_neverbleed_thread_data_t *thdata)
{
if (neverbleed_transaction_cb != NULL) {
neverbleed_transaction_cb(buf, 0);
} else {
iobuf_transaction_write(buf, thdata);
iobuf_transaction_read(buf, thdata);
}
}
#if !defined(NAME_MAX) || defined(__linux__)
/* readdir(3) is known to be thread-safe on Linux and should be thread-safe on a platform that does not have a predefined value for
NAME_MAX */
#define FOREACH_DIRENT(dp, dent) \
struct dirent *dent; \
while ((dent = readdir(dp)) != NULL)
#else
#define FOREACH_DIRENT(dp, dent) \
struct { \
struct dirent d; \
char s[NAME_MAX + 1]; \
} dent_; \
struct dirent *dentp, *dent = &dent_.d; \
int ret; \
while ((ret = readdir_r(dp, dent, &dentp)) == 0 && dentp != NULL)
#endif /* FOREACH_DIRENT */
static void unlink_dir(const char *path)
{
DIR *dp;
char buf[PATH_MAX];
if ((dp = opendir(path)) != NULL) {
FOREACH_DIRENT(dp, entp)
{
if (strcmp(entp->d_name, ".") == 0 || strcmp(entp->d_name, "..") == 0)
continue;
snprintf(buf, sizeof(buf), "%s/%s", path, entp->d_name);
unlink_dir(buf);
}
closedir(dp);
}
unlink(path);
rmdir(path);
}
static void dispose_thread_data(void *_thdata)
{
struct st_neverbleed_thread_data_t *thdata = _thdata;
assert(thdata->fd >= 0);
close(thdata->fd);
thdata->fd = -1;
free(thdata);
}
static struct st_neverbleed_thread_data_t *get_thread_data(neverbleed_t *nb)
{
struct st_neverbleed_thread_data_t *thdata;
pid_t self_pid = getpid();
ssize_t r;
if ((thdata = pthread_getspecific(nb->thread_key)) != NULL) {
if (thdata->self_pid == self_pid)
return thdata;
/* we have been forked! */
close(thdata->fd);
} else {
if ((thdata = malloc(sizeof(*thdata))) == NULL)
dief("malloc failed");
}
thdata->self_pid = self_pid;
#ifdef SOCK_CLOEXEC
if ((thdata->fd = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) == -1)
dief("socket(2) failed");
#else
if ((thdata->fd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
dief("socket(2) failed");
set_cloexec(thdata->fd);
#endif
while (connect(thdata->fd, (void *)&nb->sun_, sizeof(nb->sun_)) != 0)
if (errno != EINTR)
dief("failed to connect to privsep daemon");
while ((r = write(thdata->fd, nb->auth_token, sizeof(nb->auth_token))) == -1 && errno == EINTR)
;
if (r != sizeof(nb->auth_token))
dief("failed to send authentication token");
pthread_setspecific(nb->thread_key, thdata);
return thdata;
}
int neverbleed_get_fd(neverbleed_t *nb)
{
struct st_neverbleed_thread_data_t *thdata = get_thread_data(nb);
return thdata->fd;
}
void neverbleed_transaction_read(neverbleed_t *nb, neverbleed_iobuf_t *buf)
{
struct st_neverbleed_thread_data_t *thdata = get_thread_data(nb);
iobuf_transaction_read(buf, thdata);
}
void neverbleed_transaction_write(neverbleed_t *nb, neverbleed_iobuf_t *buf)
{
struct st_neverbleed_thread_data_t *thdata = get_thread_data(nb);
iobuf_transaction_write(buf, thdata);
}
static void do_exdata_free_callback(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
{
/* when other engines are used, this callback gets called without neverbleed data */
if (ptr == NULL)
return;
struct st_neverbleed_rsa_exdata_t *exdata = ptr;
struct st_neverbleed_thread_data_t *thdata = get_thread_data(exdata->nb);
neverbleed_iobuf_t buf = {NULL};
iobuf_push_str(&buf, "del_pkey");
iobuf_push_num(&buf, exdata->key_index);
// "del_pkey" command is fire-and-forget, it cannot fail, so doesn't have a response
iobuf_transaction_no_response(&buf, thdata);
free(exdata);
}
static int get_rsa_exdata_idx(void);
static void rsa_exdata_free_callback(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
{
assert(idx == get_rsa_exdata_idx());
do_exdata_free_callback(parent, ptr, ad, idx, argl, argp);
}
static int get_rsa_exdata_idx(void)
{
static volatile int index;
NEVERBLEED_MULTITHREAD_ONCE({
index = RSA_get_ex_new_index(0, NULL, NULL, NULL, rsa_exdata_free_callback);
});
return index;
}
static void get_privsep_data(const RSA *rsa, struct st_neverbleed_rsa_exdata_t **exdata,
struct st_neverbleed_thread_data_t **thdata)
{
*exdata = RSA_get_ex_data(rsa, get_rsa_exdata_idx());
if (*exdata == NULL) {
errno = 0;
dief("invalid internal ref");
}
*thdata = get_thread_data((*exdata)->nb);
}
static struct {
struct {
pthread_mutex_t lock;
/**
* if the slot is use contains a non-NULL key; if not in use, contains the index of the next empty slot or SIZE_MAX if there
* are no more empty slots
*/
union {
EVP_PKEY *pkey;
size_t next_empty;
} *slots;
size_t num_slots;
size_t first_empty;
} keys;
neverbleed_t *nb;
} daemon_vars = {{.lock = PTHREAD_MUTEX_INITIALIZER, .first_empty = SIZE_MAX}};
static __thread struct {
int sockfd;
#ifdef __linux
int epollfd;
#endif
struct {
neverbleed_iobuf_t *first, **next;
} responses;
} conn_ctx;
static int use_offload = 0;
#if USE_OFFLOAD
struct engine_request {
neverbleed_iobuf_t *buf;
int async_fd;
#ifdef OPENSSL_IS_BORINGSSL
struct {
RSA *rsa;
uint8_t output[512];
union {
struct {
uint8_t padded[512];
} digestsign;
};
} data;
async_ctx *async_ctx;
#else
int (*stub)(neverbleed_iobuf_t *);
struct {
ASYNC_WAIT_CTX *ctx;
ASYNC_JOB *job;
} async;
#endif
};
static void offload_free_request(struct engine_request *req)
{
#ifdef OPENSSL_IS_BORINGSSL
bssl_qat_async_finish_job(req->async_ctx);
RSA_free(req->data.rsa);
#else
ASYNC_WAIT_CTX_free(req->async.ctx);
#endif
OPENSSL_cleanse(req, sizeof(*req));
free(req);
}
static int do_epoll_ctl(int epollfd, int op, int fd, struct epoll_event *event)
{
int ret;
while ((ret = epoll_ctl(epollfd, op, fd, event) != 0) && errno == EINTR)
;
return ret;
}
static void register_wait_fd(struct engine_request *req)
{
#ifdef OPENSSL_IS_BORINGSSL
ASYNC_WAIT_CTX *ctx = req->async_ctx->currjob->waitctx;
#else
ASYNC_WAIT_CTX *ctx = req->async.ctx;
#endif
size_t numfds;
if (!ASYNC_WAIT_CTX_get_all_fds(ctx, NULL, &numfds) || numfds != 1)
dief("unexpected number of fds (%zu) requested in async mode\n", numfds);
if (!ASYNC_WAIT_CTX_get_all_fds(ctx, &req->async_fd, &numfds))
dief("ASYNC_WAIT_CTX_get_all_fds failed\n");
struct epoll_event ev = {.events = EPOLLIN, .data.ptr = req};
if (do_epoll_ctl(conn_ctx.epollfd, EPOLL_CTL_ADD, req->async_fd, &ev) != 0)
dief("epoll_ctl failed:%d\n", errno);
}
#endif
static int send_responses(int cleanup)
{
neverbleed_iobuf_t *buf;
int result = 0;
/* Send all buffers that have data being filled. The lock is held until everything is being done, as this function can be called
* from multiple threads simultaneously. */
while ((buf = conn_ctx.responses.first) != NULL && !buf->processing) {
if ((conn_ctx.responses.first = buf->next) == NULL)
conn_ctx.responses.next = &conn_ctx.responses.first;
if (!cleanup && iobuf_write(buf, conn_ctx.sockfd) != 0) {
warnf(errno != 0 ? "write error" : "connection closed by client");
result = -1;
}
iobuf_dispose(buf);
free(buf);
if (result != 0)
break;
}
return result;
}
static RSA *daemon_get_rsa(size_t key_index)
{
RSA *rsa = NULL;
pthread_mutex_lock(&daemon_vars.keys.lock);
if (key_index < daemon_vars.keys.num_slots)
rsa = EVP_PKEY_get1_RSA(daemon_vars.keys.slots[key_index].pkey);
pthread_mutex_unlock(&daemon_vars.keys.lock);
return rsa;
}
size_t allocate_slot(void)
{
/* expand if all slots are in use */
if (daemon_vars.keys.first_empty == SIZE_MAX) {
size_t new_capacity = (daemon_vars.keys.num_slots < 4 ? 4 : daemon_vars.keys.num_slots) * 2;
if ((daemon_vars.keys.slots = realloc(daemon_vars.keys.slots, sizeof(daemon_vars.keys.slots[0]) * new_capacity)) == NULL)
dief("no memory");
daemon_vars.keys.first_empty = daemon_vars.keys.num_slots;
for (size_t i = daemon_vars.keys.num_slots; i < new_capacity - 1; ++i)
daemon_vars.keys.slots[i].next_empty = i + 1;
daemon_vars.keys.slots[new_capacity - 1].next_empty = SIZE_MAX;
daemon_vars.keys.num_slots = new_capacity;
}
/* detach the first empty slot from the empty list */
size_t slot_index = daemon_vars.keys.first_empty;
daemon_vars.keys.first_empty = daemon_vars.keys.slots[slot_index].next_empty;
/* set bogus value in the allocated slot to help figure out what happened upon crash */
daemon_vars.keys.slots[slot_index].next_empty = SIZE_MAX - 1;
return slot_index;
}
static size_t daemon_set_pkey(EVP_PKEY *pkey)
{
assert(pkey != NULL);
pthread_mutex_lock(&daemon_vars.keys.lock);
size_t index = allocate_slot();
daemon_vars.keys.slots[index].pkey = pkey;
EVP_PKEY_up_ref(pkey);
pthread_mutex_unlock(&daemon_vars.keys.lock);
return index;
}
static int priv_encdec_proxy(const char *cmd, int flen, const unsigned char *from, unsigned char *_to, RSA *rsa, int padding)
{
struct st_neverbleed_rsa_exdata_t *exdata;
struct st_neverbleed_thread_data_t *thdata;
neverbleed_iobuf_t buf = {NULL};
size_t ret;
unsigned char *to;
size_t tolen;
get_privsep_data(rsa, &exdata, &thdata);
iobuf_push_str(&buf, cmd);
iobuf_push_bytes(&buf, from, flen);
iobuf_push_num(&buf, exdata->key_index);
iobuf_push_num(&buf, padding);
iobuf_transaction(&buf, thdata);
if (iobuf_shift_num(&buf, &ret) != 0 || (to = iobuf_shift_bytes(&buf, &tolen)) == NULL) {
errno = 0;
dief("failed to parse response");
}
memcpy(_to, to, tolen);
iobuf_dispose(&buf);
return (int)ret;
}
static int priv_encdec_stub(const char *name,
int (*func)(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding),
neverbleed_iobuf_t *buf)
{
unsigned char *from, to[4096];
size_t flen;
size_t key_index, padding;
RSA *rsa;
int ret;
if ((from = iobuf_shift_bytes(buf, &flen)) == NULL || iobuf_shift_num(buf, &key_index) != 0 ||
iobuf_shift_num(buf, &padding) != 0) {
errno = 0;
warnf("%s: failed to parse request", name);
return -1;
}
if ((rsa = daemon_get_rsa(key_index)) == NULL) {
errno = 0;
warnf("%s: invalid key index:%zu\n", name, key_index);
return -1;
}
ret = func((int)flen, from, to, rsa, (int)padding);
iobuf_dispose(buf);
RSA_free(rsa);
iobuf_push_num(buf, ret);
iobuf_push_bytes(buf, to, ret > 0 ? ret : 0);
return 0;
}
#if !defined(OPENSSL_IS_BORINGSSL)
static int priv_enc_proxy(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
{
return priv_encdec_proxy("priv_enc", flen, from, to, rsa, padding);
}
static int priv_enc_stub(neverbleed_iobuf_t *buf)
{
return priv_encdec_stub(__FUNCTION__, RSA_private_encrypt, buf);
}
static int priv_dec_proxy(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
{
return priv_encdec_proxy("priv_dec", flen, from, to, rsa, padding);
}
static int priv_dec_stub(neverbleed_iobuf_t *buf)
{
return priv_encdec_stub(__FUNCTION__, RSA_private_decrypt, buf);
}
static int sign_proxy(int type, const unsigned char *m, unsigned int m_len, unsigned char *_sigret, unsigned *_siglen,
const RSA *rsa)
{
struct st_neverbleed_rsa_exdata_t *exdata;
struct st_neverbleed_thread_data_t *thdata;
neverbleed_iobuf_t buf = {NULL};
size_t ret, siglen;
unsigned char *sigret;
get_privsep_data(rsa, &exdata, &thdata);
iobuf_push_str(&buf, "sign");
iobuf_push_num(&buf, type);
iobuf_push_bytes(&buf, m, m_len);
iobuf_push_num(&buf, exdata->key_index);
iobuf_transaction(&buf, thdata);
if (iobuf_shift_num(&buf, &ret) != 0 || (sigret = iobuf_shift_bytes(&buf, &siglen)) == NULL) {
errno = 0;
dief("failed to parse response");
}
memcpy(_sigret, sigret, siglen);
*_siglen = (unsigned)siglen;
iobuf_dispose(&buf);
return (int)ret;
}
static int sign_stub(neverbleed_iobuf_t *buf)
{
unsigned char *m, sigret[4096];
size_t type, m_len, key_index;
RSA *rsa;
unsigned siglen = 0;
int ret;
if (iobuf_shift_num(buf, &type) != 0 || (m = iobuf_shift_bytes(buf, &m_len)) == NULL || iobuf_shift_num(buf, &key_index) != 0) {
errno = 0;
warnf("%s: failed to parse request", __FUNCTION__);
return -1;
}
if ((rsa = daemon_get_rsa(key_index)) == NULL) {
errno = 0;
warnf("%s: invalid key index:%zu", __FUNCTION__, key_index);
return -1;
}
ret = RSA_sign((int)type, m, (unsigned)m_len, sigret, &siglen, rsa);
iobuf_dispose(buf);
RSA_free(rsa);
iobuf_push_num(buf, ret);
iobuf_push_bytes(buf, sigret, ret == 1 ? siglen : 0);
return 0;
}
#endif
static EVP_PKEY *create_pkey(neverbleed_t *nb, size_t key_index, const char *ebuf, const char *nbuf)
{
struct st_neverbleed_rsa_exdata_t *exdata;
RSA *rsa;
EVP_PKEY *pkey;
BIGNUM *e = NULL, *n = NULL;
if ((exdata = malloc(sizeof(*exdata))) == NULL) {
fprintf(stderr, "no memory\n");
abort();
}
exdata->nb = nb;
exdata->key_index = key_index;
rsa = RSA_new_method(nb->engine);
RSA_set_ex_data(rsa, get_rsa_exdata_idx(), exdata);
if (BN_hex2bn(&e, ebuf) == 0) {
fprintf(stderr, "failed to parse e:%s\n", ebuf);
abort();
}
if (BN_hex2bn(&n, nbuf) == 0) {
fprintf(stderr, "failed to parse n:%s\n", nbuf);
abort();
}
RSA_set0_key(rsa, n, e, NULL);
#if !defined(OPENSSL_IS_BORINGSSL)
RSA_set_flags(rsa, RSA_FLAG_EXT_PKEY);
#endif
pkey = EVP_PKEY_new();
EVP_PKEY_set1_RSA(pkey, rsa);
RSA_free(rsa);
return pkey;
}
#ifdef NEVERBLEED_ECDSA
static EC_KEY *daemon_get_ecdsa(size_t key_index)
{
EC_KEY *ec_key = NULL;
pthread_mutex_lock(&daemon_vars.keys.lock);
if (key_index < daemon_vars.keys.num_slots)
ec_key = EVP_PKEY_get1_EC_KEY(daemon_vars.keys.slots[key_index].pkey);
pthread_mutex_unlock(&daemon_vars.keys.lock);
return ec_key;
}
static int ecdsa_sign_stub(neverbleed_iobuf_t *buf)
{
unsigned char *m, sigret[4096];
size_t type, m_len, key_index;
EC_KEY *ec_key;
unsigned siglen = 0;
int ret;
if (iobuf_shift_num(buf, &type) != 0 || (m = iobuf_shift_bytes(buf, &m_len)) == NULL || iobuf_shift_num(buf, &key_index) != 0) {
errno = 0;
warnf("%s: failed to parse request", __FUNCTION__);
return -1;
}
if ((ec_key = daemon_get_ecdsa(key_index)) == NULL) {
errno = 0;
warnf("%s: invalid key index:%zu", __FUNCTION__, key_index);
return -1;
}
ret = ECDSA_sign((int)type, m, (unsigned)m_len, sigret, &siglen, ec_key);
iobuf_dispose(buf);
EC_KEY_free(ec_key);
iobuf_push_num(buf, ret);
iobuf_push_bytes(buf, sigret, ret == 1 ? siglen : 0);
return 0;
}
static int get_ecdsa_exdata_idx(void);
static void ecdsa_exdata_free_callback(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
{
assert(idx == get_ecdsa_exdata_idx());
do_exdata_free_callback(parent, ptr, ad, idx, argl, argp);
}
static int get_ecdsa_exdata_idx(void)
{
static volatile int index;
NEVERBLEED_MULTITHREAD_ONCE({
index = EC_KEY_get_ex_new_index(0, NULL, NULL, NULL, ecdsa_exdata_free_callback);
});
return index;
}
static void ecdsa_get_privsep_data(const EC_KEY *ec_key, struct st_neverbleed_rsa_exdata_t **exdata,
struct st_neverbleed_thread_data_t **thdata)
{
*exdata = EC_KEY_get_ex_data(ec_key, get_ecdsa_exdata_idx());
if (*exdata == NULL) {
errno = 0;
dief("invalid internal ref");
}
*thdata = get_thread_data((*exdata)->nb);
}
static int ecdsa_sign_proxy(int type, const unsigned char *m, int m_len, unsigned char *_sigret, unsigned int *_siglen,
const BIGNUM *kinv, const BIGNUM *rp, EC_KEY *ec_key)