Debian Codegraph @

src/tls_openssl.c

raw symbols ◀ ▶
Source reconstructed at patch state 1 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 /*
2 * Copyright (c) 2022 Joris Vink <[email protected]>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
16
17 /*
18 * This TLS backend is the original TLS code used in Kore.
19 */
20
21 #include <sys/types.h>
22
23 #include <openssl/bio.h>
24 #include <openssl/dh.h>
25 #include <openssl/ec.h>
26 #include <openssl/ecdsa.h>
27 #include <openssl/err.h>
28 #include <openssl/ssl.h>
29 #include <openssl/evp.h>
30 #include <openssl/rand.h>
31 #include <openssl/x509.h>
32 #include <openssl/x509v3.h>
33
34 #include <poll.h>
35
36 #include "kore.h"
37 #include "http.h"
38
39 /*
40 * Disable deprecated declaration warnings if we're building against
41 * OpenSSL 3 as they marked all low-level APIs as deprecated.
42 *
43 * Work is being done to replace these, but for now let things build.
44 */
45 #if defined(OPENSSL_VERSION_MAJOR) && OPENSSL_VERSION_MAJOR >= 3
46 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
47 #endif
48
49 #define TLS_SESSION_ID "kore_tls_sessionid"
50
51 static int tls_domain_x509_verify(int, X509_STORE_CTX *);
52 static X509 *tls_domain_load_certificate_chain(SSL_CTX *,
53 const void *, size_t);
54
55 static int tls_sni_cb(SSL *, int *, void *);
56 static void tls_info_callback(const SSL *, int, int);
57
58 #if defined(KORE_USE_ACME)
59 static void tls_acme_challenge_set_cert(SSL *, struct kore_domain *);
60 static int tls_acme_alpn(SSL *, const unsigned char **, unsigned char *,
61 const unsigned char *, unsigned int, void *);
62 #endif
63
64 static void tls_keymgr_await_data(void);
65 static void tls_keymgr_msg_response(struct kore_msg *, const void *);
66
67 static int tls_keymgr_rsa_init(RSA *);
68 static int tls_keymgr_rsa_finish(RSA *);
69 static int tls_keymgr_rsa_privenc(int, const unsigned char *,
70 unsigned char *, RSA *, int);
71
72 static RSA_METHOD *keymgr_rsa_meth = NULL;
73
74 static DH *dh_params = NULL;
75 static int tls_version = KORE_TLS_VERSION_BOTH;
76 static char *tls_cipher_list = KORE_DEFAULT_CIPHER_LIST;
77
78 static u_int8_t keymgr_buf[2048];
79 static size_t keymgr_buflen = 0;
80 static int keymgr_response = 0;
81
82 #if defined(KORE_USE_ACME)
83 static u_int8_t acme_alpn_name[] =
84 { 0xa, 'a', 'c', 'm', 'e', '-', 't', 'l', 's', '/', '1' };
85 #endif
86
87 struct kore_privsep keymgr_privsep;
88 int kore_keymgr_active = 0;
89
90 int
91 kore_tls_supported(void)
92 {
93 return (KORE_RESULT_OK);
94 }
95
96 void
97 kore_tls_init(void)
98 {
99 SSL_library_init();
100 SSL_load_error_strings();
101 ERR_load_crypto_strings();
102
103 if ((keymgr_rsa_meth = RSA_meth_new("kore RSA keymgr method",
104 RSA_METHOD_FLAG_NO_CHECK)) == NULL)
105 fatal("failed to setup RSA method");
106
107 RSA_meth_set_init(keymgr_rsa_meth, tls_keymgr_rsa_init);
108 RSA_meth_set_finish(keymgr_rsa_meth, tls_keymgr_rsa_finish);
109 RSA_meth_set_priv_enc(keymgr_rsa_meth, tls_keymgr_rsa_privenc);
110
111 kore_log(LOG_NOTICE, "TLS backend %s", OPENSSL_VERSION_TEXT);
112 #if !defined(TLS1_3_VERSION)
113 if (!kore_quiet) {
114 kore_log(LOG_NOTICE,
115 "%s has no TLS 1.3 - will only use TLS 1.2",
116 OPENSSL_VERSION_TEXT);
117 }
118 #endif
119 }
120
121 void
122 kore_tls_cleanup(void)
123 {
124 RSA_meth_free(keymgr_rsa_meth);
125 }
126
127 void
128 kore_tls_version_set(int version)
129 {
130 tls_version = version;
131 }
132
133 void
134 kore_tls_dh_check(void)
135 {
136 if (dh_params != NULL)
137 return;
138
139 if (!kore_tls_dh_load(KORE_DHPARAM_PATH))
140 fatal("failed to load default DH parameters");
141 }
142
143 int
144 kore_tls_dh_load(const char *path)
145 {
146 BIO *bio;
147
148 if (dh_params != NULL) {
149 kore_log(LOG_ERR, "tls_dhparam already specified");
150 return (KORE_RESULT_ERROR);
151 }
152
153 if ((bio = BIO_new_file(path, "r")) == NULL) {
154 kore_log(LOG_ERR, "tls_dhparam file '%s' not accessible", path);
155 return (KORE_RESULT_ERROR);
156 }
157
158 dh_params = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
159 BIO_free(bio);
160
161 if (dh_params == NULL) {
162 kore_log(LOG_ERR, "PEM_read_bio_DHparams(): %s", ssl_errno_s);
163 return (KORE_RESULT_ERROR);
164 }
165
166 return (KORE_RESULT_OK);
167 }
168
169 int
170 kore_tls_ciphersuite_set(const char *list)
171 {
172 if (strcmp(tls_cipher_list, KORE_DEFAULT_CIPHER_LIST)) {
173 kore_log(LOG_ERR, "tls_cipher specified twice");
174 return (KORE_RESULT_ERROR);
175 }
176
177 tls_cipher_list = kore_strdup(list);
178
179 return (KORE_RESULT_OK);
180 }
181
182 void
183 kore_tls_keymgr_init(void)
184 {
185 const RSA_METHOD *meth;
186
187 if ((meth = RSA_get_default_method()) == NULL)
188 fatal("failed to obtain RSA method");
189
190 RSA_meth_set_pub_enc(keymgr_rsa_meth, RSA_meth_get_pub_enc(meth));
191 RSA_meth_set_pub_dec(keymgr_rsa_meth, RSA_meth_get_pub_dec(meth));
192 RSA_meth_set_bn_mod_exp(keymgr_rsa_meth, RSA_meth_get_bn_mod_exp(meth));
193
194 kore_msg_register(KORE_MSG_KEYMGR_RESP, tls_keymgr_msg_response);
195 }
196
197 void
198 kore_tls_domain_setup(struct kore_domain *dom, int type,
199 const void *data, size_t datalen)
200 {
201 const u_int8_t *ptr;
202 RSA *rsa;
203 X509 *x509;
204 EVP_PKEY *pkey;
205 STACK_OF(X509_NAME) *certs;
206 const SSL_METHOD *method;
207
208 if (dom->tls_ctx != NULL)
209 SSL_CTX_free(dom->tls_ctx);
210
211 if ((method = TLS_method()) == NULL)
212 fatalx("TLS_method(): %s", ssl_errno_s);
213
214 if ((dom->tls_ctx = SSL_CTX_new(method)) == NULL)
215 fatalx("SSL_ctx_new(): %s", ssl_errno_s);
216
217 if (!SSL_CTX_set_min_proto_version(dom->tls_ctx, TLS1_2_VERSION))
218 fatalx("SSL_CTX_set_min_proto_version: %s", ssl_errno_s);
219
220 #if defined(TLS1_3_VERSION)
221 if (!SSL_CTX_set_max_proto_version(dom->tls_ctx, TLS1_3_VERSION))
222 fatalx("SSL_CTX_set_max_proto_version: %s", ssl_errno_s);
223 #else
224 if (!SSL_CTX_set_max_proto_version(dom->tls_ctx, TLS1_2_VERSION))
225 fatalx("SSL_CTX_set_min_proto_version: %s", ssl_errno_s);
226 #endif
227
228 switch (tls_version) {
229 case KORE_TLS_VERSION_1_3:
230 #if defined(TLS1_3_VERSION)
231 if (!SSL_CTX_set_min_proto_version(dom->tls_ctx,
232 TLS1_3_VERSION)) {
233 fatalx("SSL_CTX_set_min_proto_version: %s",
234 ssl_errno_s);
235 }
236 break;
237 #endif
238 case KORE_TLS_VERSION_1_2:
239 if (!SSL_CTX_set_max_proto_version(dom->tls_ctx,
240 TLS1_2_VERSION)) {
241 fatalx("SSL_CTX_set_min_proto_version: %s",
242 ssl_errno_s);
243 }
244 break;
245 case KORE_TLS_VERSION_BOTH:
246 break;
247 default:
248 fatalx("unknown tls_version: %d", tls_version);
249 return;
250 }
251
252 switch (type) {
253 case KORE_PEM_CERT_CHAIN:
254 x509 = tls_domain_load_certificate_chain(dom->tls_ctx,
255 data, datalen);
256 break;
257 case KORE_DER_CERT_DATA:
258 ptr = data;
259 if ((x509 = d2i_X509(NULL, &ptr, datalen)) == NULL)
260 fatalx("d2i_X509: %s", ssl_errno_s);
261 if (SSL_CTX_use_certificate(dom->tls_ctx, x509) == 0)
262 fatalx("SSL_CTX_use_certificate: %s", ssl_errno_s);
263 break;
264 default:
265 fatalx("%s: unknown type %d", __func__, type);
266 }
267
268 if (x509 == NULL) {
269 kore_log(LOG_NOTICE, "failed to load certificate for '%s': %s",
270 dom->domain, ssl_errno_s);
271 SSL_CTX_free(dom->tls_ctx);
272 dom->tls_ctx = NULL;
273 return;
274 }
275
276 if ((pkey = X509_get_pubkey(x509)) == NULL)
277 fatalx("certificate has no public key");
278
279 switch (EVP_PKEY_id(pkey)) {
280 case EVP_PKEY_RSA:
281 if ((rsa = EVP_PKEY_get1_RSA(pkey)) == NULL)
282 fatalx("no RSA public key present");
283 RSA_set_app_data(rsa, dom);
284 RSA_set_method(rsa, keymgr_rsa_meth);
285 break;
286 default:
287 fatalx("unknown public key in certificate");
288 }
289
290 if (!SSL_CTX_use_PrivateKey(dom->tls_ctx, pkey))
291 fatalx("SSL_CTX_use_PrivateKey(): %s", ssl_errno_s);
292
293 if (!SSL_CTX_check_private_key(dom->tls_ctx)) {
294 fatalx("Public/Private key for %s do not match (%s)",
295 dom->domain, ssl_errno_s);
296 }
297
298 if (dh_params == NULL)
299 fatal("no DH parameters specified");
300
301 SSL_CTX_set_tmp_dh(dom->tls_ctx, dh_params);
302 SSL_CTX_set_options(dom->tls_ctx, SSL_OP_SINGLE_DH_USE);
303
304 if (!SSL_CTX_set_ecdh_auto(dom->tls_ctx, 1))
305 fatalx("SSL_CTX_set_ecdh_auto: %s", ssl_errno_s);
306
307 SSL_CTX_set_options(dom->tls_ctx, SSL_OP_SINGLE_ECDH_USE);
308 SSL_CTX_set_options(dom->tls_ctx, SSL_OP_NO_COMPRESSION);
309
310 if (dom->cafile != NULL) {
311 if ((certs = SSL_load_client_CA_file(dom->cafile)) == NULL) {
312 fatalx("SSL_load_client_CA_file(%s): %s",
313 dom->cafile, ssl_errno_s);
314 }
315
316 SSL_CTX_load_verify_locations(dom->tls_ctx, dom->cafile, NULL);
317 SSL_CTX_set_verify_depth(dom->tls_ctx, dom->x509_verify_depth);
318 SSL_CTX_set_client_CA_list(dom->tls_ctx, certs);
319 SSL_CTX_set_verify(dom->tls_ctx, SSL_VERIFY_PEER |
320 SSL_VERIFY_FAIL_IF_NO_PEER_CERT, tls_domain_x509_verify);
321 }
322
323 SSL_CTX_set_session_id_context(dom->tls_ctx,
324 (unsigned char *)TLS_SESSION_ID, strlen(TLS_SESSION_ID));
325 SSL_CTX_set_mode(dom->tls_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
326
327 if (tls_version == KORE_TLS_VERSION_BOTH) {
328 SSL_CTX_set_options(dom->tls_ctx, SSL_OP_NO_SSLv2);
329 SSL_CTX_set_options(dom->tls_ctx, SSL_OP_NO_SSLv3);
330 SSL_CTX_set_options(dom->tls_ctx, SSL_OP_NO_TLSv1);
331 SSL_CTX_set_options(dom->tls_ctx, SSL_OP_NO_TLSv1_1);
332 }
333
334 SSL_CTX_set_options(dom->tls_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
335 SSL_CTX_set_cipher_list(dom->tls_ctx, tls_cipher_list);
336
337 SSL_CTX_set_info_callback(dom->tls_ctx, tls_info_callback);
338 SSL_CTX_set_tlsext_servername_callback(dom->tls_ctx, tls_sni_cb);
339
340 #if defined(KORE_USE_ACME)
341 SSL_CTX_set_alpn_select_cb(dom->tls_ctx, tls_acme_alpn, dom);
342 #endif
343
344 X509_free(x509);
345 }
346
347 void
348 kore_tls_domain_crl(struct kore_domain *dom, const void *pem, size_t pemlen)
349 {
350 int err;
351 BIO *in;
352 X509_CRL *crl;
353 X509_STORE *store;
354
355 ERR_clear_error();
356 in = BIO_new_mem_buf(pem, pemlen);
357
358 if ((store = SSL_CTX_get_cert_store(dom->tls_ctx)) == NULL) {
359 BIO_free(in);
360 kore_log(LOG_ERR, "SSL_CTX_get_cert_store(): %s", ssl_errno_s);
361 return;
362 }
363
364 for (;;) {
365 crl = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
366 if (crl == NULL) {
367 err = ERR_GET_REASON(ERR_peek_last_error());
368 if (err == PEM_R_NO_START_LINE) {
369 ERR_clear_error();
370 break;
371 }
372
373 kore_log(LOG_WARNING, "failed to read CRL %s: %s",
374 dom->crlfile, ssl_errno_s);
375 continue;
376 }
377
378 if (!X509_STORE_add_crl(store, crl)) {
379 err = ERR_GET_REASON(ERR_peek_last_error());
380 if (err == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
381 X509_CRL_free(crl);
382 continue;
383 }
384
385 kore_log(LOG_WARNING, "failed to add CRL %s: %s",
386 dom->crlfile, ssl_errno_s);
387 X509_CRL_free(crl);
388 continue;
389 }
390 }
391
392 BIO_free(in);
393
394 X509_STORE_set_flags(store,
395 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
396 }
397
398 void
399 kore_tls_domain_cleanup(struct kore_domain *dom)
400 {
401 if (dom->tls_ctx != NULL)
402 SSL_CTX_free(dom->tls_ctx);
403 }
404
405 int
406 kore_tls_connection_accept(struct connection *c)
407 {
408 int r;
409
410 if (primary_dom == NULL) {
411 kore_log(LOG_NOTICE,
412 "TLS handshake but no TLS configured on server");
413 return (KORE_RESULT_ERROR);
414 }
415
416 if (primary_dom->tls_ctx == NULL) {
417 kore_log(LOG_NOTICE,
418 "TLS configuration for %s not yet complete",
419 primary_dom->domain);
420 return (KORE_RESULT_ERROR);
421 }
422
423 if (c->tls == NULL) {
424 c->tls = SSL_new(primary_dom->tls_ctx);
425 if (c->tls == NULL)
426 return (KORE_RESULT_ERROR);
427
428 SSL_set_fd(c->tls, c->fd);
429 SSL_set_accept_state(c->tls);
430
431 if (!SSL_set_ex_data(c->tls, 0, c))
432 return (KORE_RESULT_ERROR);
433
434 if (primary_dom->cafile != NULL)
435 c->flags |= CONN_LOG_TLS_FAILURE;
436 }
437
438 ERR_clear_error();
439 r = SSL_accept(c->tls);
440 if (r <= 0) {
441 r = SSL_get_error(c->tls, r);
442 switch (r) {
443 case SSL_ERROR_WANT_READ:
444 case SSL_ERROR_WANT_WRITE:
445 kore_connection_start_idletimer(c);
446 return (KORE_RESULT_RETRY);
447 default:
448 if (c->flags & CONN_LOG_TLS_FAILURE) {
449 kore_log(LOG_NOTICE,
450 "SSL_accept: %s", ssl_errno_s);
451 }
452 return (KORE_RESULT_ERROR);
453 }
454 }
455
456 #if defined(KORE_USE_ACME)
457 if (c->proto == CONN_PROTO_ACME_ALPN) {
458 kore_log(LOG_INFO, "disconnecting acme client");
459 kore_connection_disconnect(c);
460 return (KORE_RESULT_ERROR);
461 }
462 #endif
463
464 if (SSL_get_verify_mode(c->tls) & SSL_VERIFY_PEER) {
465 c->tls_cert = SSL_get_peer_certificate(c->tls);
466 if (c->tls_cert == NULL) {
467 kore_log(LOG_NOTICE, "no peer certificate");
468 return (KORE_RESULT_ERROR);
469 }
470 } else {
471 c->tls_cert = NULL;
472 }
473
474 return (KORE_RESULT_OK);
475 }
476
477 int
478 kore_tls_read(struct connection *c, size_t *bytes)
479 {
480 int r;
481
482 ERR_clear_error();
483 r = SSL_read(c->tls, (c->rnb->buf + c->rnb->s_off),
484 (c->rnb->b_len - c->rnb->s_off));
485
486 if (c->tls_reneg > 1)
487 return (KORE_RESULT_ERROR);
488
489 if (r <= 0) {
490 r = SSL_get_error(c->tls, r);
491 switch (r) {
492 case SSL_ERROR_WANT_READ:
493 case SSL_ERROR_WANT_WRITE:
494 c->evt.flags &= ~KORE_EVENT_READ;
495 return (KORE_RESULT_OK);
496 case SSL_ERROR_ZERO_RETURN:
497 return (KORE_RESULT_ERROR);
498 case SSL_ERROR_SYSCALL:
499 switch (errno) {
500 case EINTR:
501 *bytes = 0;
502 return (KORE_RESULT_OK);
503 case EAGAIN:
504 c->evt.flags &= ~KORE_EVENT_READ;
505 c->snb->flags |= NETBUF_MUST_RESEND;
506 return (KORE_RESULT_OK);
507 default:
508 break;
509 }
510 /* FALLTHROUGH */
511 default:
512 if (c->flags & CONN_LOG_TLS_FAILURE) {
513 kore_log(LOG_NOTICE,
514 "SSL_read(): %s", ssl_errno_s);
515 }
516 return (KORE_RESULT_ERROR);
517 }
518 }
519
520 *bytes = (size_t)r;
521
522 return (KORE_RESULT_OK);
523 }
524
525 int
526 kore_tls_write(struct connection *c, size_t len, size_t *written)
527 {
528 int r;
529
530 if (len > INT_MAX)
531 return (KORE_RESULT_ERROR);
532
533 ERR_clear_error();
534 r = SSL_write(c->tls, (c->snb->buf + c->snb->s_off), len);
535 if (c->tls_reneg > 1)
536 return (KORE_RESULT_ERROR);
537
538 if (r <= 0) {
539 r = SSL_get_error(c->tls, r);
540 switch (r) {
541 case SSL_ERROR_WANT_READ:
542 case SSL_ERROR_WANT_WRITE:
543 c->evt.flags &= ~KORE_EVENT_WRITE;
544 c->snb->flags |= NETBUF_MUST_RESEND;
545 return (KORE_RESULT_OK);
546 case SSL_ERROR_SYSCALL:
547 switch (errno) {
548 case EINTR:
549 *written = 0;
550 return (KORE_RESULT_OK);
551 case EAGAIN:
552 c->evt.flags &= ~KORE_EVENT_WRITE;
553 c->snb->flags |= NETBUF_MUST_RESEND;
554 return (KORE_RESULT_OK);
555 default:
556 break;
557 }
558 /* FALLTHROUGH */
559 default:
560 if (c->flags & CONN_LOG_TLS_FAILURE) {
561 kore_log(LOG_NOTICE,
562 "SSL_write(): %s", ssl_errno_s);
563 }
564 return (KORE_RESULT_ERROR);
565 }
566 }
567
568 *written = (size_t)r;
569
570 return (KORE_RESULT_OK);
571 }
572
573 void
574 kore_tls_connection_cleanup(struct connection *c)
575 {
576 if (c->tls != NULL) {
577 SSL_shutdown(c->tls);
578 SSL_free(c->tls);
579 }
580
581 if (c->tls_cert != NULL)
582 X509_free(c->tls_cert);
583
584 if (c->tls_sni != NULL)
585 kore_free(c->tls_sni);
586 }
587
588
589 KORE_PRIVATE_KEY *
590 kore_tls_rsakey_load(const char *path)
591 {
592 FILE *fp;
593 KORE_PRIVATE_KEY *pkey;
594
595 if (access(path, R_OK) == -1)
596 return (NULL);
597
598 if ((fp = fopen(path, "r")) == NULL)
599 fatalx("%s(%s): %s", __func__, path, errno_s);
600
601 if ((pkey = PEM_read_PrivateKey(fp, NULL, NULL, NULL)) == NULL)
602 fatalx("PEM_read_PrivateKey: %s", ssl_errno_s);
603
604 fclose(fp);
605
606 return (pkey);
607 }
608
609 KORE_PRIVATE_KEY *
610 kore_tls_rsakey_generate(const char *path)
611 {
612 FILE *fp;
613 EVP_PKEY_CTX *ctx;
614 KORE_PRIVATE_KEY *pkey;
615
616 if ((ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL)) == NULL)
617 fatalx("EVP_PKEY_CTX_new_id: %s", ssl_errno_s);
618
619 if (EVP_PKEY_keygen_init(ctx) <= 0)
620 fatalx("EVP_PKEY_keygen_init: %s", ssl_errno_s);
621
622 if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, KORE_RSAKEY_BITS) <= 0)
623 fatalx("EVP_PKEY_CTX_set_rsa_keygen_bits: %s", ssl_errno_s);
624
625 pkey = NULL;
626 if (EVP_PKEY_keygen(ctx, &pkey) <= 0)
627 fatalx("EVP_PKEY_keygen: %s", ssl_errno_s);
628
629 if (path != NULL) {
630 if ((fp = fopen(path, "w")) == NULL)
631 fatalx("fopen(%s): %s", path, errno_s);
632
633 if (!PEM_write_PrivateKey(fp, pkey, NULL, NULL, 0, NULL, NULL))
634 fatalx("PEM_write_PrivateKey: %s", ssl_errno_s);
635
636 fclose(fp);
637 }
638
639 return (pkey);
640 }
641
642 KORE_X509_NAMES *
643 kore_tls_x509_subject_name(struct connection *c)
644 {
645 X509_NAME *name;
646
647 if ((name = X509_get_subject_name(c->tls_cert)) == NULL)
648 kore_log(LOG_NOTICE, "X509_get_subject_name: %s", ssl_errno_s);
649
650 return (name);
651 }
652
653 KORE_X509_NAMES *
654 kore_tls_x509_issuer_name(struct connection *c)
655 {
656 X509_NAME *name;
657
658 if ((name = X509_get_issuer_name(c->tls_cert)) == NULL)
659 kore_log(LOG_NOTICE, "X509_get_issuer_name: %s", ssl_errno_s);
660
661 return (name);
662 }
663
664 int
665 kore_tls_x509name_foreach(KORE_X509_NAMES *name, int flags, void *udata,
666 int (*cb)(void *, int, int, const char *, const void *, size_t, int))
667 {
668 u_int8_t *data;
669 ASN1_STRING *astr;
670 X509_NAME_ENTRY *entry;
671 const char *field;
672 int islast, ret, idx, namelen, nid, len;
673
674 data = NULL;
675 ret = KORE_RESULT_ERROR;
676
677 if ((namelen = X509_NAME_entry_count(name)) == 0)
678 goto cleanup;
679
680 for (idx = 0; idx < namelen; idx++) {
681 if ((entry = X509_NAME_get_entry(name, idx)) == NULL)
682 goto cleanup;
683
684 nid = OBJ_obj2nid(X509_NAME_ENTRY_get_object(entry));
685 if ((field = OBJ_nid2sn(nid)) == NULL)
686 goto cleanup;
687
688 switch (nid) {
689 case NID_commonName:
690 nid = KORE_X509_NAME_COMMON_NAME;
691 break;
692 default:
693 nid = -1;
694 break;
695 }
696
697 if ((astr = X509_NAME_ENTRY_get_data(entry)) == NULL)
698 goto cleanup;
699
700 data = NULL;
701 if ((len = ASN1_STRING_to_UTF8(&data, astr)) < 0)
702 goto cleanup;
703
704 if (idx != (namelen - 1))
705 islast = 0;
706 else
707 islast = 1;
708
709 if (!cb(udata, islast, nid, field, data, len, flags))
710 goto cleanup;
711
712 OPENSSL_free(data);
713 data = NULL;
714 }
715
716 ret = KORE_RESULT_OK;
717
718 cleanup:
719 if (data != NULL)
720 OPENSSL_free(data);
721
722 return (ret);
723 }
724
725 int
726 kore_tls_x509_data(struct connection *c, u_int8_t **ptr, size_t *olen)
727 {
728 int len;
729 u_int8_t *der, *pp;
730
731 if ((len = i2d_X509(c->tls_cert, NULL)) <= 0) {
732 kore_log(LOG_NOTICE, "i2d_X509: %s", ssl_errno_s);
733 return (KORE_RESULT_ERROR);
734 }
735
736 der = kore_calloc(1, len);
737 pp = der;
738
739 if (i2d_X509(c->tls_cert, &pp) <= 0) {
740 kore_free(der);
741 kore_log(LOG_NOTICE, "i2d_X509: %s", ssl_errno_s);
742 return (KORE_RESULT_ERROR);
743 }
744
745 *ptr = der;
746 *olen = len;
747
748 return (KORE_RESULT_OK);
749 }
750
751 void
752 kore_tls_seed(const void *data, size_t len)
753 {
754 RAND_poll();
755 RAND_seed(data, len);
756 }
757
758 static void
759 tls_info_callback(const SSL *ssl, int flags, int ret)
760 {
761 struct connection *c;
762
763 if (flags & SSL_CB_HANDSHAKE_START) {
764 if ((c = SSL_get_app_data(ssl)) == NULL)
765 fatal("no SSL_get_app_data");
766
767 #if defined(TLS1_3_VERSION)
768 if (SSL_version(ssl) != TLS1_3_VERSION)
769 #endif
770 c->tls_reneg++;
771 }
772 }
773
774 static int
775 tls_sni_cb(SSL *ssl, int *ad, void *arg)
776 {
777 struct connection *c;
778 struct kore_domain *dom;
779 const char *sname;
780
781 if ((c = SSL_get_ex_data(ssl, 0)) == NULL)
782 fatal("no connection data in %s", __func__);
783
784 sname = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
785
786 if (sname != NULL)
787 c->tls_sni = kore_strdup(sname);
788
789 if (sname != NULL &&
790 (dom = kore_domain_lookup(c->owner->server, sname)) != NULL) {
791 if (dom->tls_ctx == NULL) {
792 kore_log(LOG_NOTICE,
793 "TLS configuration for %s not complete",
794 dom->domain);
795 return (SSL_TLSEXT_ERR_NOACK);
796 }
797
798 SSL_set_SSL_CTX(ssl, dom->tls_ctx);
799
800 if (dom->cafile != NULL) {
801 SSL_set_verify(ssl, SSL_VERIFY_PEER |
802 SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
803 c->flags |= CONN_LOG_TLS_FAILURE;
804 } else {
805 SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
806 }
807
808 #if defined(KORE_USE_ACME)
809 /*
810 * If ALPN callback was called before SNI was parsed we
811 * must make sure we swap to the correct certificate now.
812 */
813 if (c->flags & CONN_TLS_ALPN_ACME_SEEN)
814 tls_acme_challenge_set_cert(ssl, dom);
815
816 c->flags |= CONN_TLS_SNI_SEEN;
817 #endif
818 return (SSL_TLSEXT_ERR_OK);
819 }
820
821 return (SSL_TLSEXT_ERR_NOACK);
822 }
823
824 static int
825 tls_keymgr_rsa_init(RSA *rsa)
826 {
827 if (rsa != NULL) {
828 RSA_set_flags(rsa, RSA_flags(rsa) |
829 RSA_FLAG_EXT_PKEY | RSA_METHOD_FLAG_NO_CHECK);
830 return (1);
831 }
832
833 return (0);
834 }
835
836 static int
837 tls_keymgr_rsa_privenc(int flen, const unsigned char *from, unsigned char *to,
838 RSA *rsa, int padding)
839 {
840 int ret;
841 size_t len;
842 struct kore_keyreq *req;
843 struct kore_domain *dom;
844
845 len = sizeof(*req) + flen;
846 if (len > sizeof(keymgr_buf))
847 fatal("keymgr_buf too small");
848
849 if ((dom = RSA_get_app_data(rsa)) == NULL)
850 fatal("RSA key has no domain attached");
851
852 memset(keymgr_buf, 0, sizeof(keymgr_buf));
853
854 req = (struct kore_keyreq *)keymgr_buf;
855
856 if (kore_strlcpy(req->domain, dom->domain, sizeof(req->domain)) >=
857 sizeof(req->domain))
858 fatal("%s: domain truncated", __func__);
859
860 req->data_len = flen;
861 req->padding = padding;
862 memcpy(&req->data[0], from, req->data_len);
863
864 kore_msg_send(KORE_WORKER_KEYMGR, KORE_MSG_KEYMGR_REQ, keymgr_buf, len);
865 tls_keymgr_await_data();
866
867 ret = -1;
868 if (keymgr_response) {
869 if (keymgr_buflen < INT_MAX &&
870 (int)keymgr_buflen == RSA_size(rsa)) {
871 ret = RSA_size(rsa);
872 memcpy(to, keymgr_buf, RSA_size(rsa));
873 }
874 }
875
876 keymgr_buflen = 0;
877 keymgr_response = 0;
878 kore_platform_event_all(worker->msg[1]->fd, worker->msg[1]);
879
880 return (ret);
881 }
882
883 static int
884 tls_keymgr_rsa_finish(RSA *rsa)
885 {
886 return (1);
887 }
888
889 static void
890 tls_keymgr_await_data(void)
891 {
892 int ret;
893 struct pollfd pfd[1];
894 u_int64_t start, cur;
895 #if !defined(KORE_NO_HTTP)
896 int process_requests;
897 #endif
898
899 /*
900 * We need to wait until the keymgr responds to us, so keep doing
901 * net_recv_flush() until our callback for KORE_MSG_KEYMGR_RESP
902 * tells us that we have obtained the response.
903 *
904 * This means other internal messages can still be delivered by
905 * this worker process to the appropriate callbacks but we do not
906 * drop out until we've either received an answer from the keymgr
907 * or until the timeout has been reached (1 second currently).
908 *
909 * If we end up waiting for the keymgr process we will call
910 * http_process (if not built with NOHTTP=1) to further existing
911 * requests so those do not block too much.
912 *
913 * This means that all incoming data will stop being processed
914 * while existing requests will get processed until we return
915 * from this call.
916 */
917 start = kore_time_ms();
918 kore_platform_disable_read(worker->msg[1]->fd);
919
920 keymgr_response = 0;
921 memset(keymgr_buf, 0, sizeof(keymgr_buf));
922
923 #if !defined(KORE_NO_HTTP)
924 process_requests = 0;
925 #endif
926
927 for (;;) {
928 #if !defined(KORE_NO_HTTP)
929 if (process_requests) {
930 http_process();
931 process_requests = 0;
932 }
933 #endif
934 pfd[0].fd = worker->msg[1]->fd;
935 pfd[0].events = POLLIN;
936 pfd[0].revents = 0;
937
938 ret = poll(pfd, 1, 100);
939 if (ret == -1) {
940 if (errno == EINTR)
941 continue;
942 fatal("poll: %s", errno_s);
943 }
944
945 cur = kore_time_ms();
946 if ((cur - start) > 1000)
947 break;
948 if (ret == 0) {
949 #if !defined(KORE_NO_HTTP)
950 /* No activity on channel, process HTTP requests. */
951 process_requests = 1;
952 #endif
953 continue;
954 }
955
956 if (pfd[0].revents & (POLLERR | POLLHUP))
957 break;
958 if (!(pfd[0].revents & POLLIN))
959 break;
960
961 worker->msg[1]->evt.flags |= KORE_EVENT_READ;
962 if (!net_recv_flush(worker->msg[1]))
963 break;
964
965 if (keymgr_response)
966 break;
967
968 #if !defined(KORE_NO_HTTP)
969 /* If we've spent 100ms already, process HTTP requests. */
970 if ((cur - start) > 100) {
971 process_requests = 1;
972 }
973 #endif
974 }
975 }
976
977 static void
978 tls_keymgr_msg_response(struct kore_msg *msg, const void *data)
979 {
980 keymgr_response = 1;
981 keymgr_buflen = msg->length;
982
983 if (keymgr_buflen > sizeof(keymgr_buf))
984 return;
985
986 memcpy(keymgr_buf, data, keymgr_buflen);
987 }
988
989 static int
990 tls_domain_x509_verify(int ok, X509_STORE_CTX *ctx)
991 {
992 X509 *cert;
993 const char *text;
994 int error, depth;
995
996 error = X509_STORE_CTX_get_error(ctx);
997 cert = X509_STORE_CTX_get_current_cert(ctx);
998
999 if (ok == 0 && cert != NULL) {
1000 text = X509_verify_cert_error_string(error);
1001 depth = X509_STORE_CTX_get_error_depth(ctx);
1002
1003 kore_log(LOG_WARNING, "X509 verification error depth:%d - %s",
1004 depth, text);
1005
1006 /* Continue on CRL validity errors. */
1007 switch (error) {
1008 case X509_V_ERR_CRL_HAS_EXPIRED:
1009 case X509_V_ERR_CRL_NOT_YET_VALID:
1010 case X509_V_ERR_UNABLE_TO_GET_CRL:
1011 ok = 1;
1012 break;
1013 }
1014 }
1015
1016 return (ok);
1017 }
1018
1019 /*
1020 * What follows is basically a reimplementation of
1021 * SSL_CTX_use_certificate_chain_file() from OpenSSL but with our
1022 * BIO set to the pem data that we received.
1023 */
1024 static X509 *
1025 tls_domain_load_certificate_chain(SSL_CTX *ctx, const void *data, size_t len)
1026 {
1027 unsigned long err;
1028 BIO *in;
1029 X509 *x, *ca;
1030
1031 ERR_clear_error();
1032 in = BIO_new_mem_buf(data, len);
1033
1034 if ((x = PEM_read_bio_X509_AUX(in, NULL, NULL, NULL)) == NULL)
1035 return (NULL);
1036
1037 /* refcount for x509 will go up one. */
1038 if (SSL_CTX_use_certificate(ctx, x) == 0)
1039 return (NULL);
1040
1041 SSL_CTX_clear_chain_certs(ctx);
1042
1043 ERR_clear_error();
1044 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL)) != NULL) {
1045 /* ca its reference count won't be increased. */
1046 if (SSL_CTX_add0_chain_cert(ctx, ca) == 0)
1047 return (NULL);
1048 }
1049
1050 err = ERR_peek_last_error();
1051
1052 if (ERR_GET_LIB(err) != ERR_LIB_PEM ||
1053 ERR_GET_REASON(err) != PEM_R_NO_START_LINE)
1054 return (NULL);
1055
1056 BIO_free(in);
1057
1058 return (x);
1059 }
1060
1061 #if defined(KORE_USE_ACME)
1062 static int
1063 tls_acme_alpn(SSL *ssl, const unsigned char **out, unsigned char *outlen,
1064 const unsigned char *in, unsigned int inlen, void *udata)
1065 {
1066 struct connection *c;
1067
1068 if ((c = SSL_get_ex_data(ssl, 0)) == NULL)
1069 fatal("%s: no connection data present", __func__);
1070
1071 if (inlen != sizeof(acme_alpn_name))
1072 return (SSL_TLSEXT_ERR_NOACK);
1073
1074 if (memcmp(acme_alpn_name, in, sizeof(acme_alpn_name)))
1075 return (SSL_TLSEXT_ERR_NOACK);
1076
1077 *out = in + 1;
1078 *outlen = inlen - 1;
1079
1080 c->flags |= CONN_TLS_ALPN_ACME_SEEN;
1081
1082 /*
1083 * If SNI was already done, we can continue, otherwise we mark
1084 * that we saw the right ALPN negotiation on this connection
1085 * and wait for the SNI extension to be parsed.
1086 */
1087 if (c->flags & CONN_TLS_SNI_SEEN) {
1088 /* SNI was seen, we are on the right domain. */
1089 tls_acme_challenge_set_cert(ssl, udata);
1090 }
1091
1092 return (SSL_TLSEXT_ERR_OK);
1093 }
1094
1095 static void
1096 tls_acme_challenge_set_cert(SSL *ssl, struct kore_domain *dom)
1097 {
1098 struct connection *c;
1099 const unsigned char *ptr;
1100 X509 *x509;
1101
1102 if (dom->acme == 0) {
1103 kore_log(LOG_NOTICE, "[%s] ACME not active", dom->domain);
1104 return;
1105 }
1106
1107 if (dom->acme_challenge == 0) {
1108 kore_log(LOG_NOTICE,
1109 "[%s] ACME auth challenge not active", dom->domain);
1110 return;
1111 }
1112
1113 kore_log(LOG_INFO, "[%s] acme-tls/1 challenge requested",
1114 dom->domain);
1115
1116 if ((c = SSL_get_ex_data(ssl, 0)) == NULL)
1117 fatal("%s: no connection data present", __func__);
1118
1119 ptr = dom->acme_cert;
1120 if ((x509 = d2i_X509(NULL, &ptr, dom->acme_cert_len)) == NULL)
1121 fatal("d2i_X509: %s", ssl_errno_s);
1122
1123 if (SSL_use_certificate(ssl, x509) == 0)
1124 fatal("SSL_use_certificate: %s", ssl_errno_s);
1125
1126 SSL_clear_chain_certs(ssl);
1127 SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
1128
1129 c->proto = CONN_PROTO_ACME_ALPN;
1130 }
1131 #endif /* KORE_USE_ACME */