kore

An easy to use, scalable and secure web application framework for writing web APIs in C.
Commits | Files | Refs | README | LICENSE | git clone https://git.kore.io/kore.git

keymgr_openssl.c (33256B)



      1 /*
      2  * Copyright (c) 2017-2022 Joris Vink <joris@coders.se>
      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  * The kore keymgr process is responsible for managing certificates
     19  * and their matching private keys.
     20  *
     21  * It is the only process in Kore that holds the private keys (the workers
     22  * do not have a copy of them in memory).
     23  *
     24  * When a worker requires the private key for signing it will send a message
     25  * to the keymgr with the to-be-signed data (KORE_MSG_KEYMGR_REQ). The keymgr
     26  * will perform the signing and respond with a KORE_MSG_KEYMGR_RESP message.
     27  *
     28  * The keymgr can transparently reload the private keys and certificates
     29  * for a configured domain when it receives a SIGUSR1. It it reloads them
     30  * it will send the newly loaded certificate chains to the worker processes
     31  * which will update their TLS contexts accordingly.
     32  *
     33  * If ACME is turned on the keymgr will also hold all account and domain
     34  * keys and will initiate the process of acquiring new certificates against
     35  * the ACME provider that is configured if those certificates do not exist
     36  * or are expired (or are expiring soon).
     37  */
     38 
     39 #include <sys/types.h>
     40 #include <sys/mman.h>
     41 #include <sys/stat.h>
     42 
     43 #include <openssl/err.h>
     44 #include <openssl/evp.h>
     45 #include <openssl/rsa.h>
     46 #include <openssl/rand.h>
     47 #include <openssl/pem.h>
     48 #include <openssl/sha.h>
     49 #include <openssl/x509.h>
     50 #include <openssl/x509v3.h>
     51 
     52 #include <ctype.h>
     53 #include <fcntl.h>
     54 #include <stdio.h>
     55 #include <stdlib.h>
     56 #include <stdint.h>
     57 #include <signal.h>
     58 #include <unistd.h>
     59 
     60 #include "kore.h"
     61 
     62 #if defined(KORE_USE_ACME)
     63 #include "acme.h"
     64 #endif
     65 
     66 #define RAND_TMP_FILE		"rnd.tmp"
     67 #define RAND_POLL_INTERVAL	(1800 * 1000)
     68 #define RAND_FILE_SIZE		1024
     69 
     70 #if defined(__linux__)
     71 #include "seccomp.h"
     72 
     73 /* The syscalls our keymgr is allowed to perform, only. */
     74 static struct sock_filter filter_keymgr[] = {
     75 	/* Deny these, but with EACCESS instead of dying. */
     76 	KORE_SYSCALL_DENY(ioctl, EACCES),
     77 
     78 	/* Required to deal with private keys and certs. */
     79 #if defined(SYS_open)
     80 	KORE_SYSCALL_ALLOW(open),
     81 #endif
     82 	KORE_SYSCALL_ALLOW(read),
     83 	KORE_SYSCALL_ALLOW(lseek),
     84 	KORE_SYSCALL_ALLOW(write),
     85 	KORE_SYSCALL_ALLOW(close),
     86 #if defined(SYS_stat)
     87 	KORE_SYSCALL_ALLOW(stat),
     88 #endif
     89 	KORE_SYSCALL_ALLOW(fstat),
     90 #if defined(SYS_fstat64)
     91 	KORE_SYSCALL_ALLOW(fstat64),
     92 #endif
     93 #if defined(SYS_newfstatat)
     94 	KORE_SYSCALL_ALLOW(newfstatat),
     95 #endif
     96 	KORE_SYSCALL_ALLOW(futex),
     97 	KORE_SYSCALL_ALLOW(writev),
     98 	KORE_SYSCALL_ALLOW(openat),
     99 #if defined(SYS_access)
    100 	KORE_SYSCALL_ALLOW(access),
    101 #endif
    102 	KORE_SYSCALL_ALLOW(faccessat),
    103 
    104 	/* Net related. */
    105 #if defined(SYS_poll)
    106 	KORE_SYSCALL_ALLOW(poll),
    107 #endif
    108 #if defined(SYS_send)
    109 	KORE_SYSCALL_ALLOW(send),
    110 #endif
    111 	KORE_SYSCALL_ALLOW(sendto),
    112 #if defined(SYS_recv)
    113 	KORE_SYSCALL_ALLOW(recv),
    114 #endif
    115 	KORE_SYSCALL_ALLOW(recvfrom),
    116 #if defined(SYS_epoll_wait)
    117 	KORE_SYSCALL_ALLOW(epoll_wait),
    118 #endif
    119 	KORE_SYSCALL_ALLOW(epoll_pwait),
    120 
    121 	/* Process things. */
    122 	KORE_SYSCALL_ALLOW(exit),
    123 	KORE_SYSCALL_ALLOW(kill),
    124 	KORE_SYSCALL_ALLOW(getuid),
    125 	KORE_SYSCALL_ALLOW(getpid),
    126 #if defined(SYS_arch_prctl)
    127 	KORE_SYSCALL_ALLOW(arch_prctl),
    128 #endif
    129 	KORE_SYSCALL_ALLOW(exit_group),
    130 	KORE_SYSCALL_ALLOW(sigaltstack),
    131 #if defined(SYS_sigreturn)
    132 	KORE_SYSCALL_ALLOW(sigreturn),
    133 #endif
    134 	KORE_SYSCALL_ALLOW(rt_sigreturn),
    135 	KORE_SYSCALL_ALLOW(rt_sigaction),
    136 	KORE_SYSCALL_ALLOW(rt_sigprocmask),
    137 
    138 	/* Other things. */
    139 	KORE_SYSCALL_ALLOW(brk),
    140 #if defined(SYS_mmap)
    141 	KORE_SYSCALL_ALLOW(mmap),
    142 #endif
    143 #if defined(SYS_mmap2)
    144 	KORE_SYSCALL_ALLOW(mmap2),
    145 #endif
    146 #if defined(SYS_madvise)
    147 	KORE_SYSCALL_ALLOW(madvise),
    148 #endif
    149 	KORE_SYSCALL_ALLOW(munmap),
    150 	KORE_SYSCALL_ALLOW(clock_gettime),
    151 #if defined(__NR_getrandom)
    152 	KORE_SYSCALL_ALLOW(getrandom),
    153 #endif
    154 
    155 #if defined(KORE_USE_ACME)
    156 #if defined(SYS_mkdir)
    157 	KORE_SYSCALL_ALLOW(mkdir),
    158 #endif
    159 	KORE_SYSCALL_ALLOW(mkdirat),
    160 	KORE_SYSCALL_ALLOW(umask),
    161 #endif
    162 };
    163 #endif
    164 
    165 struct key {
    166 	KORE_PRIVATE_KEY	*pkey;
    167 	struct kore_domain	*dom;
    168 	TAILQ_ENTRY(key)	list;
    169 };
    170 
    171 char				*kore_rand_file = NULL;
    172 
    173 static TAILQ_HEAD(, key)	keys;
    174 static int			initialized = 0;
    175 
    176 #if defined(KORE_USE_ACME)
    177 
    178 #define ACME_ORDER_STATE_INIT		1
    179 #define ACME_ORDER_STATE_SUBMIT		2
    180 
    181 #define ACME_X509_EXPIRATION		120
    182 #define ACME_TLS_ALPN_01_OID		"1.3.6.1.5.5.7.1.31"
    183 
    184 #define ACME_RENEWAL_THRESHOLD		5
    185 #define ACME_RENEWAL_TIMER		(3600 * 1000)
    186 
    187 /* UTCTIME in format of YYMMDDHHMMSSZ */
    188 #define ASN1_UTCTIME_LEN		13
    189 
    190 /* GENERALIZEDTIME in format of YYYYMMDDHHMMSSZ */
    191 #define ASN1_GENERALIZEDTIME_LEN	15
    192 
    193 /* Set to 1 when we receive KORE_ACME_PROC_READY. */
    194 static int			acmeproc_ready = 0;
    195 
    196 /* Renewal timer for all domains under acme control. */
    197 static struct kore_timer	*acme_renewal = NULL;
    198 
    199 /* oid for acme extension. */
    200 static int			acme_oid = -1;
    201 
    202 struct acme_order {
    203 	int			state;
    204 	struct kore_timer	*timer;
    205 	char			*domain;
    206 };
    207 
    208 static char	*keymgr_bignum_base64(const BIGNUM *);
    209 
    210 static void	keymgr_acme_init(void);
    211 static void	keymgr_acme_renewal(void *, u_int64_t);
    212 static void	keymgr_acme_check(struct kore_domain *);
    213 static void	keymgr_acme_sign(struct kore_msg *, const void *);
    214 static void	keymgr_acme_ready(struct kore_msg *, const void *);
    215 static void	keymgr_acme_domainkey(struct kore_domain *, struct key *);
    216 
    217 static void	keymgr_acme_order_create(const char *);
    218 static void	keymgr_acme_order_redo(void *, u_int64_t);
    219 static void	keymgr_acme_order_start(void *, u_int64_t);
    220 
    221 static void	keymgr_x509_ext(STACK_OF(X509_EXTENSION) *,
    222 		    int, const char *, ...)
    223 		    __attribute__((format (printf, 3, 4)));
    224 
    225 static void	keymgr_acme_csr(const struct kore_keyreq *, struct key *);
    226 static void	keymgr_acme_install_cert(const void *, size_t, struct key *);
    227 static void	keymgr_acme_order_failed(const void *, size_t, struct key *);
    228 static void	keymgr_acme_challenge_cert(const void *, size_t, struct key *);
    229 
    230 static int	keymgr_x509_not_after(X509 *, time_t *);
    231 static int	keymgr_asn1_convert_utctime(const ASN1_TIME *, time_t *);
    232 static int	keymgr_asn1_convert_generalizedtime(const void *,
    233 		    size_t, time_t *);
    234 
    235 #endif /* KORE_USE_ACME */
    236 
    237 static void	keymgr_reload(void);
    238 static void	keymgr_load_randfile(void);
    239 static void	keymgr_save_randfile(void);
    240 
    241 static struct key	*keymgr_load_privatekey(const char *);
    242 static void		keymgr_load_domain_privatekey(struct kore_domain *);
    243 
    244 static void	keymgr_msg_recv(struct kore_msg *, const void *);
    245 static void	keymgr_entropy_request(struct kore_msg *, const void *);
    246 static void	keymgr_certificate_request(struct kore_msg *, const void *);
    247 static void	keymgr_submit_certificates(struct kore_domain *, u_int16_t);
    248 static void	keymgr_submit_file(u_int8_t, struct kore_domain *,
    249 		    const char *, u_int16_t, int);
    250 static void	keymgr_x509_msg(const char *, const void *, size_t, int, int);
    251 
    252 static void	keymgr_rsa_encrypt(struct kore_msg *, const void *,
    253 		    struct key *);
    254 static void	keymgr_ecdsa_sign(struct kore_msg *, const void *,
    255 		    struct key *);
    256 
    257 #if defined(__OpenBSD__)
    258 #if defined(KORE_USE_ACME)
    259 static const char *keymgr_pledges = "stdio rpath wpath cpath";
    260 #else
    261 static const char *keymgr_pledges = "stdio rpath";
    262 #endif
    263 #endif
    264 
    265 void
    266 kore_keymgr_run(void)
    267 {
    268 	int		quit;
    269 	u_int64_t	now, netwait, last_seed;
    270 
    271 	if (kore_keymgr_active == 0)
    272 		fatalx("%s: called with kore_keymgr_active == 0", __func__);
    273 
    274 	quit = 0;
    275 
    276 	kore_server_closeall();
    277 	kore_module_cleanup();
    278 
    279 	net_init();
    280 	kore_timer_init();
    281 	kore_connection_init();
    282 	kore_platform_event_init();
    283 
    284 	kore_msg_worker_init();
    285 	kore_msg_register(KORE_MSG_KEYMGR_REQ, keymgr_msg_recv);
    286 	kore_msg_register(KORE_MSG_ENTROPY_REQ, keymgr_entropy_request);
    287 	kore_msg_register(KORE_MSG_CERTIFICATE_REQ, keymgr_certificate_request);
    288 
    289 #if defined(__linux__)
    290 	/* Drop all enabled seccomp filters, and add only ours. */
    291 	kore_seccomp_drop();
    292 	kore_seccomp_filter("keymgr", filter_keymgr,
    293 	    KORE_FILTER_LEN(filter_keymgr));
    294 #endif
    295 #if defined(KORE_USE_PYTHON)
    296 	kore_msg_unregister(KORE_PYTHON_SEND_OBJ);
    297 #endif
    298 	kore_worker_privsep();
    299 
    300 	if (kore_rand_file != NULL) {
    301 		keymgr_load_randfile();
    302 		keymgr_save_randfile();
    303 	} else if (!kore_quiet) {
    304 		kore_log(LOG_WARNING, "no rand_file location specified");
    305 	}
    306 
    307 	RAND_poll();
    308 	last_seed = 0;
    309 
    310 	initialized = 1;
    311 	keymgr_reload();
    312 
    313 #if defined(__OpenBSD__)
    314 	if (pledge(keymgr_pledges, NULL) == -1)
    315 		fatalx("failed to pledge keymgr process");
    316 #endif
    317 
    318 #if defined(KORE_USE_ACME)
    319 	acme_oid = OBJ_create(ACME_TLS_ALPN_01_OID, "acme", "acmeIdentifier");
    320 	X509V3_EXT_add_alias(acme_oid, NID_subject_key_identifier);
    321 #endif
    322 
    323 	kore_worker_started();
    324 
    325 	while (quit != 1) {
    326 		now = kore_time_ms();
    327 		if ((now - last_seed) > RAND_POLL_INTERVAL) {
    328 			RAND_poll();
    329 			last_seed = now;
    330 		}
    331 
    332 		netwait = kore_timer_next_run(now);
    333 		kore_platform_event_wait(netwait);
    334 
    335 		if (sig_recv != 0) {
    336 			switch (sig_recv) {
    337 			case SIGQUIT:
    338 			case SIGINT:
    339 			case SIGTERM:
    340 				quit = 1;
    341 				break;
    342 			case SIGUSR1:
    343 				keymgr_reload();
    344 				break;
    345 			default:
    346 				break;
    347 			}
    348 			sig_recv = 0;
    349 		}
    350 
    351 		if (quit)
    352 			break;
    353 
    354 		now = kore_time_ms();
    355 		kore_timer_run(now);
    356 		kore_connection_prune(KORE_CONNECTION_PRUNE_DISCONNECT);
    357 	}
    358 
    359 	kore_keymgr_cleanup(1);
    360 	kore_platform_event_cleanup();
    361 	kore_connection_cleanup();
    362 	net_cleanup();
    363 }
    364 
    365 void
    366 kore_keymgr_cleanup(int final)
    367 {
    368 	struct key		*key, *next;
    369 
    370 	if (initialized == 0)
    371 		return;
    372 
    373 	for (key = TAILQ_FIRST(&keys); key != NULL; key = next) {
    374 		next = TAILQ_NEXT(key, list);
    375 		TAILQ_REMOVE(&keys, key, list);
    376 
    377 		EVP_PKEY_free(key->pkey);
    378 		kore_free(key);
    379 	}
    380 }
    381 
    382 static void
    383 keymgr_reload(void)
    384 {
    385 	struct kore_server	*srv;
    386 	struct kore_domain	*dom;
    387 
    388 	if (!kore_quiet)
    389 		kore_log(LOG_INFO, "(re)loading certificates, keys and CRLs");
    390 
    391 	kore_keymgr_cleanup(0);
    392 	TAILQ_INIT(&keys);
    393 
    394 #if defined(KORE_USE_ACME)
    395 	keymgr_acme_init();
    396 #endif
    397 
    398 	kore_domain_callback(keymgr_load_domain_privatekey);
    399 
    400 	/* can't use kore_domain_callback() due to dst parameter. */
    401 	LIST_FOREACH(srv, &kore_servers, list) {
    402 		if (srv->tls == 0)
    403 			continue;
    404 		TAILQ_FOREACH(dom, &srv->domains, list)
    405 			keymgr_submit_certificates(dom, KORE_MSG_WORKER_ALL);
    406 	}
    407 }
    408 
    409 static void
    410 keymgr_submit_certificates(struct kore_domain *dom, u_int16_t dst)
    411 {
    412 	if (access(dom->certfile, R_OK) == -1) {
    413 #if defined(KORE_USE_ACME)
    414 		if (dom->acme && errno == ENOENT)
    415 			return;
    416 #endif
    417 		fatalx("cannot read '%s' for %s: %s",
    418 		    dom->certfile, dom->domain, errno_s);
    419 	}
    420 
    421 	keymgr_submit_file(KORE_MSG_CERTIFICATE, dom, dom->certfile, dst, 0);
    422 
    423 	if (dom->crlfile != NULL)
    424 		keymgr_submit_file(KORE_MSG_CRL, dom, dom->crlfile, dst, 1);
    425 }
    426 
    427 static void
    428 keymgr_submit_file(u_int8_t id, struct kore_domain *dom,
    429     const char *file, u_int16_t dst, int can_fail)
    430 {
    431 	int				fd;
    432 	struct stat			st;
    433 	u_int8_t			*payload;
    434 
    435 	if ((fd = open(file, O_RDONLY)) == -1) {
    436 		if (errno == ENOENT && can_fail)
    437 			return;
    438 		fatalx("open(%s): %s", file, errno_s);
    439 	}
    440 
    441 	if (fstat(fd, &st) == -1)
    442 		fatalx("stat(%s): %s", file, errno_s);
    443 
    444 	if (!S_ISREG(st.st_mode))
    445 		fatalx("%s is not a file", file);
    446 
    447 	payload = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
    448 	if (payload == MAP_FAILED)
    449 		fatalx("mmap(): %s", errno_s);
    450 
    451 	keymgr_x509_msg(dom->domain, payload, st.st_size, dst, id);
    452 
    453 	(void)munmap(payload, st.st_size);
    454 	close(fd);
    455 }
    456 
    457 static void
    458 keymgr_load_randfile(void)
    459 {
    460 	int		fd;
    461 	struct stat	st;
    462 	ssize_t		ret;
    463 	size_t		total;
    464 	u_int8_t	buf[RAND_FILE_SIZE];
    465 
    466 	if (kore_rand_file == NULL)
    467 		return;
    468 
    469 	if ((fd = open(kore_rand_file, O_RDONLY)) == -1)
    470 		fatalx("open(%s): %s", kore_rand_file, errno_s);
    471 
    472 	if (fstat(fd, &st) == -1)
    473 		fatalx("stat(%s): %s", kore_rand_file, errno_s);
    474 	if (!S_ISREG(st.st_mode))
    475 		fatalx("%s is not a file", kore_rand_file);
    476 	if (st.st_size != RAND_FILE_SIZE)
    477 		fatalx("%s has an invalid size", kore_rand_file);
    478 
    479 	total = 0;
    480 
    481 	while (total != RAND_FILE_SIZE) {
    482 		ret = read(fd, buf, sizeof(buf));
    483 		if (ret == 0)
    484 			fatalx("EOF on %s", kore_rand_file);
    485 
    486 		if (ret == -1) {
    487 			if (errno == EINTR)
    488 				continue;
    489 			fatalx("read(%s): %s", kore_rand_file, errno_s);
    490 		}
    491 
    492 		total += (size_t)ret;
    493 		RAND_seed(buf, (int)ret);
    494 		OPENSSL_cleanse(buf, sizeof(buf));
    495 	}
    496 
    497 	(void)close(fd);
    498 	if (unlink(kore_rand_file) == -1) {
    499 		kore_log(LOG_WARNING, "failed to unlink %s: %s",
    500 		    kore_rand_file, errno_s);
    501 	}
    502 }
    503 
    504 static void
    505 keymgr_save_randfile(void)
    506 {
    507 	int		fd;
    508 	struct stat	st;
    509 	ssize_t		ret;
    510 	u_int8_t	buf[RAND_FILE_SIZE];
    511 
    512 	if (kore_rand_file == NULL)
    513 		return;
    514 
    515 	if (stat(RAND_TMP_FILE, &st) != -1) {
    516 		kore_log(LOG_WARNING, "removing stale %s file", RAND_TMP_FILE);
    517 		(void)unlink(RAND_TMP_FILE);
    518 	}
    519 
    520 	if (RAND_bytes(buf, sizeof(buf)) != 1) {
    521 		kore_log(LOG_WARNING, "RAND_bytes: %s", ssl_errno_s);
    522 		goto cleanup;
    523 	}
    524 
    525 	if ((fd = open(RAND_TMP_FILE,
    526 	    O_CREAT | O_TRUNC | O_WRONLY, 0400)) == -1) {
    527 		kore_log(LOG_WARNING,
    528 		    "failed to open %s: %s - random data not written",
    529 		    RAND_TMP_FILE, errno_s);
    530 		goto cleanup;
    531 	}
    532 
    533 	ret = write(fd, buf, sizeof(buf));
    534 	if (ret == -1 || (size_t)ret != sizeof(buf)) {
    535 		kore_log(LOG_WARNING, "failed to write random data");
    536 		(void)close(fd);
    537 		(void)unlink(RAND_TMP_FILE);
    538 		goto cleanup;
    539 	}
    540 
    541 	if (close(fd) == -1)
    542 		kore_log(LOG_WARNING, "close(%s): %s", RAND_TMP_FILE, errno_s);
    543 
    544 	if (rename(RAND_TMP_FILE, kore_rand_file) == -1) {
    545 		kore_log(LOG_WARNING, "rename(%s, %s): %s",
    546 		    RAND_TMP_FILE, kore_rand_file, errno_s);
    547 		(void)unlink(kore_rand_file);
    548 		(void)unlink(RAND_TMP_FILE);
    549 	}
    550 
    551 cleanup:
    552 	OPENSSL_cleanse(buf, sizeof(buf));
    553 }
    554 
    555 static void
    556 keymgr_load_domain_privatekey(struct kore_domain *dom)
    557 {
    558 	struct key	*key;
    559 
    560 	if (dom->server->tls == 0)
    561 		return;
    562 
    563 	key = keymgr_load_privatekey(dom->certkey);
    564 
    565 	if (key->pkey == NULL) {
    566 #if defined(KORE_USE_ACME)
    567 		if (dom->acme)
    568 			keymgr_acme_domainkey(dom, key);
    569 #endif
    570 		if (key->pkey == NULL) {
    571 			fatalx("failed to load private key for '%s' (%s)",
    572 			    dom->domain, errno_s);
    573 		}
    574 	}
    575 
    576 	key->dom = dom;
    577 
    578 	if (!kore_quiet)
    579 		kore_log(LOG_INFO, "loaded private key for '%s'", dom->domain);
    580 }
    581 
    582 static struct key *
    583 keymgr_load_privatekey(const char *path)
    584 {
    585 	struct key		*key;
    586 
    587 	key = kore_calloc(1, sizeof(*key));
    588 	TAILQ_INSERT_TAIL(&keys, key, list);
    589 
    590 	/* Caller should check if pkey was loaded. */
    591 	if (path)
    592 		key->pkey = kore_tls_rsakey_load(path);
    593 
    594 	return (key);
    595 }
    596 
    597 static void
    598 keymgr_certificate_request(struct kore_msg *msg, const void *data)
    599 {
    600 	struct kore_server	*srv;
    601 	struct kore_domain	*dom;
    602 
    603 	LIST_FOREACH(srv, &kore_servers, list) {
    604 		if (srv->tls == 0)
    605 			continue;
    606 		TAILQ_FOREACH(dom, &srv->domains, list)
    607 			keymgr_submit_certificates(dom, msg->src);
    608 	}
    609 }
    610 
    611 static void
    612 keymgr_entropy_request(struct kore_msg *msg, const void *data)
    613 {
    614 	u_int8_t	buf[RAND_FILE_SIZE];
    615 
    616 	if (RAND_bytes(buf, sizeof(buf)) != 1) {
    617 		kore_log(LOG_WARNING,
    618 		    "failed to generate entropy for worker %u: %s",
    619 		    msg->src, ssl_errno_s);
    620 		return;
    621 	}
    622 
    623 	/* No cleanse, this stuff is leaked in the kernel path anyway. */
    624 	kore_msg_send(msg->src, KORE_MSG_ENTROPY_RESP, buf, sizeof(buf));
    625 }
    626 
    627 static void
    628 keymgr_msg_recv(struct kore_msg *msg, const void *data)
    629 {
    630 	const struct kore_keyreq	*req;
    631 	struct key			*key;
    632 
    633 	if (msg->length < sizeof(*req))
    634 		return;
    635 
    636 	req = (const struct kore_keyreq *)data;
    637 
    638 	if (msg->length != (sizeof(*req) + req->data_len))
    639 		return;
    640 
    641 	if (req->domain[KORE_DOMAINNAME_LEN] != '\0')
    642 		return;
    643 
    644 	key = NULL;
    645 	TAILQ_FOREACH(key, &keys, list) {
    646 		if (key->dom == NULL)
    647 			continue;
    648 		if (!strcmp(key->dom->domain, req->domain))
    649 			break;
    650 	}
    651 
    652 	if (key == NULL)
    653 		return;
    654 
    655 	switch (msg->id) {
    656 	case KORE_MSG_KEYMGR_REQ:
    657 		switch (EVP_PKEY_id(key->pkey)) {
    658 		case EVP_PKEY_RSA:
    659 			keymgr_rsa_encrypt(msg, data, key);
    660 			break;
    661 		case EVP_PKEY_EC:
    662 			keymgr_ecdsa_sign(msg, data, key);
    663 			break;
    664 		default:
    665 			break;
    666 		}
    667 		break;
    668 #if defined(KORE_USE_ACME)
    669 	case KORE_ACME_CSR_REQUEST:
    670 		keymgr_acme_csr(req, key);
    671 		break;
    672 	case KORE_ACME_ORDER_FAILED:
    673 		keymgr_acme_order_failed(req->data, req->data_len, key);
    674 		break;
    675 	case KORE_ACME_CHALLENGE_CERT:
    676 		keymgr_acme_challenge_cert(req->data, req->data_len, key);
    677 		break;
    678 	case KORE_ACME_INSTALL_CERT:
    679 		keymgr_acme_install_cert(req->data, req->data_len, key);
    680 		break;
    681 #endif
    682 	}
    683 }
    684 
    685 static void
    686 keymgr_rsa_encrypt(struct kore_msg *msg, const void *data, struct key *key)
    687 {
    688 	int				ret;
    689 	RSA				*rsa;
    690 	const struct kore_keyreq	*req;
    691 	size_t				keylen;
    692 	u_int8_t			buf[1024];
    693 
    694 	req = (const struct kore_keyreq *)data;
    695 	rsa = EVP_PKEY_get0_RSA(key->pkey);
    696 
    697 	keylen = RSA_size(rsa);
    698 	if (req->data_len > keylen || keylen > sizeof(buf))
    699 		return;
    700 
    701 	ret = RSA_private_encrypt(req->data_len, req->data,
    702 	    buf, rsa, req->padding);
    703 	if (ret != RSA_size(rsa))
    704 		return;
    705 
    706 	kore_msg_send(msg->src, KORE_MSG_KEYMGR_RESP, buf, ret);
    707 }
    708 
    709 static void
    710 keymgr_ecdsa_sign(struct kore_msg *msg, const void *data, struct key *key)
    711 {
    712 	size_t				len;
    713 	EC_KEY				*ec;
    714 	const struct kore_keyreq	*req;
    715 	unsigned int			siglen;
    716 	u_int8_t			sig[1024];
    717 
    718 	req = (const struct kore_keyreq *)data;
    719 	ec = EVP_PKEY_get0_EC_KEY(key->pkey);
    720 
    721 	len = ECDSA_size(ec);
    722 	if (req->data_len > len || len > sizeof(sig))
    723 		return;
    724 
    725 	if (ECDSA_sign(EVP_PKEY_NONE, req->data, req->data_len,
    726 	    sig, &siglen, ec) == 0)
    727 		return;
    728 
    729 	if (siglen > sizeof(sig))
    730 		return;
    731 
    732 	kore_msg_send(msg->src, KORE_MSG_KEYMGR_RESP, sig, siglen);
    733 }
    734 
    735 static void
    736 keymgr_x509_msg(const char *domain, const void *data, size_t len,
    737     int target, int msg)
    738 {
    739 	struct kore_buf			buf;
    740 	struct kore_x509_msg		hdr;
    741 
    742 	memset(&hdr, 0, sizeof(hdr));
    743 
    744 	hdr.data_len = len;
    745 
    746 	if (kore_strlcpy(hdr.domain, domain, sizeof(hdr.domain)) >=
    747 	    sizeof(hdr.domain))
    748 		fatalx("%s: domain truncated", __func__);
    749 
    750 	kore_buf_init(&buf, sizeof(hdr) + len);
    751 	kore_buf_append(&buf, &hdr, sizeof(hdr));
    752 	kore_buf_append(&buf, data, len);
    753 
    754 	kore_msg_send(target, msg, buf.data, buf.offset);
    755 	kore_buf_cleanup(&buf);
    756 }
    757 
    758 #if defined(KORE_USE_ACME)
    759 static void
    760 keymgr_acme_init(void)
    761 {
    762 	RSA		*rsa;
    763 	struct key	*key;
    764 	char		*e, *n;
    765 	int		needsreg;
    766 	const BIGNUM	*be, *bn;
    767 
    768 	if (acme_provider == NULL)
    769 		return;
    770 
    771 	if (mkdir(KORE_ACME_CERTDIR, 0700) == -1) {
    772 		if (errno != EEXIST)
    773 			fatalx("mkdir(%s): %s", KORE_ACME_CERTDIR, errno_s);
    774 	}
    775 
    776 	umask(S_IWGRP | S_IWOTH | S_IRGRP | S_IROTH);
    777 
    778 	needsreg = 0;
    779 	acmeproc_ready = 0;
    780 	key = keymgr_load_privatekey(KORE_ACME_ACCOUNT_KEY);
    781 
    782 	if (acme_renewal != NULL)
    783 		kore_timer_remove(acme_renewal);
    784 
    785 	acme_renewal = kore_timer_add(keymgr_acme_renewal,
    786 	    ACME_RENEWAL_TIMER, NULL, 0);
    787 
    788 	if (key->pkey == NULL) {
    789 		kore_log(LOG_INFO, "generating new ACME account key");
    790 		key->pkey = kore_tls_rsakey_generate(KORE_ACME_ACCOUNT_KEY);
    791 		needsreg = 1;
    792 	} else {
    793 		kore_log(LOG_INFO, "loaded existing ACME account key");
    794 	}
    795 
    796 	rsa = EVP_PKEY_get0_RSA(key->pkey);
    797 	RSA_get0_key(rsa, &bn, &be, NULL);
    798 
    799 	e = keymgr_bignum_base64(be);
    800 	n = keymgr_bignum_base64(bn);
    801 
    802 	kore_msg_send(KORE_WORKER_ACME, KORE_ACME_RSAKEY_E, e, strlen(e));
    803 	kore_msg_send(KORE_WORKER_ACME, KORE_ACME_RSAKEY_N, n, strlen(n));
    804 
    805 	kore_free(e);
    806 	kore_free(n);
    807 
    808 	if (needsreg) {
    809 		kore_msg_send(KORE_WORKER_ACME,
    810 		    KORE_ACME_ACCOUNT_CREATE, NULL, 0);
    811 	} else {
    812 		kore_msg_send(KORE_WORKER_ACME,
    813 		    KORE_ACME_ACCOUNT_RESOLVE, NULL, 0);
    814 	}
    815 
    816 	kore_msg_register(KORE_ACME_SIGN, keymgr_acme_sign);
    817 	kore_msg_register(KORE_ACME_CSR_REQUEST, keymgr_msg_recv);
    818 	kore_msg_register(KORE_ACME_PROC_READY, keymgr_acme_ready);
    819 	kore_msg_register(KORE_ACME_ORDER_FAILED, keymgr_msg_recv);
    820 	kore_msg_register(KORE_ACME_INSTALL_CERT, keymgr_msg_recv);
    821 	kore_msg_register(KORE_ACME_CHALLENGE_CERT, keymgr_msg_recv);
    822 }
    823 
    824 static void
    825 keymgr_acme_domainkey(struct kore_domain *dom, struct key *key)
    826 {
    827 	char		*p;
    828 
    829 	kore_log(LOG_INFO, "generated new domain key for %s", dom->domain);
    830 
    831 	if ((p = strrchr(dom->certkey, '/')) == NULL)
    832 		fatalx("invalid certkey path '%s'", dom->certkey);
    833 
    834 	*p = '\0';
    835 
    836 	if (mkdir(dom->certkey, 0700) == -1) {
    837 		if (errno != EEXIST)
    838 			fatalx("mkdir(%s): %s", dom->certkey, errno_s);
    839 	}
    840 
    841 	*p = '/';
    842 	key->pkey = kore_tls_rsakey_generate(dom->certkey);
    843 }
    844 
    845 static void
    846 keymgr_acme_order_create(const char *domain)
    847 {
    848 	struct acme_order	*order;
    849 
    850 	order = kore_calloc(1, sizeof(*order));
    851 
    852 	order->state = ACME_ORDER_STATE_INIT;
    853 	order->domain = kore_strdup(domain);
    854 	order->timer = kore_timer_add(keymgr_acme_order_start,
    855 	    1000, order, KORE_TIMER_ONESHOT);
    856 }
    857 
    858 static void
    859 keymgr_acme_order_redo(void *udata, u_int64_t now)
    860 {
    861 	struct kore_domain	*dom = udata;
    862 
    863 	kore_log(LOG_INFO, "[%s] redoing order", dom->domain);
    864 	keymgr_acme_order_create(dom->domain);
    865 }
    866 
    867 static void
    868 keymgr_acme_order_start(void *udata, u_int64_t now)
    869 {
    870 	struct acme_order	*order = udata;
    871 
    872 	switch (order->state) {
    873 	case ACME_ORDER_STATE_INIT:
    874 		if (acmeproc_ready == 0)
    875 			break;
    876 		order->state = ACME_ORDER_STATE_SUBMIT;
    877 		/* fallthrough */
    878 	case ACME_ORDER_STATE_SUBMIT:
    879 		kore_msg_send(KORE_WORKER_ACME, KORE_ACME_ORDER_CREATE,
    880 		    order->domain, strlen(order->domain));
    881 		kore_free(order->domain);
    882 		kore_free(order);
    883 		order = NULL;
    884 		break;
    885 	default:
    886 		fatalx("%s: unknown order state %d", __func__, order->state);
    887 	}
    888 
    889 	if (order != NULL) {
    890 		order->timer = kore_timer_add(keymgr_acme_order_start,
    891 		    5000, order, KORE_TIMER_ONESHOT);
    892 	}
    893 }
    894 
    895 static void
    896 keymgr_acme_ready(struct kore_msg *msg, const void *data)
    897 {
    898 	acmeproc_ready = 1;
    899 	kore_log(LOG_INFO, "acme process ready to receive orders");
    900 
    901 	keymgr_acme_renewal(NULL, kore_time_ms());
    902 }
    903 
    904 static void
    905 keymgr_acme_check(struct kore_domain *dom)
    906 {
    907 	FILE			*fp;
    908 	int			days;
    909 	X509			*x509;
    910 	time_t			expires, now;
    911 
    912 	if (dom->acme == 0)
    913 		return;
    914 
    915 	if (access(dom->certfile, R_OK) == -1) {
    916 		if (errno == ENOENT) {
    917 			keymgr_acme_order_create(dom->domain);
    918 			return;
    919 		}
    920 		kore_log(LOG_ERR, "access(%s): %s", dom->certfile, errno_s);
    921 		return;
    922 	}
    923 
    924 	if ((fp = fopen(dom->certfile, "r")) == NULL) {
    925 		kore_log(LOG_ERR, "fopen(%s): %s", dom->certfile, errno_s);
    926 		return;
    927 	}
    928 
    929 	if ((x509 = PEM_read_X509(fp, NULL, NULL, NULL)) == NULL) {
    930 		fclose(fp);
    931 		kore_log(LOG_ERR, "PEM_read_X509: %s", ssl_errno_s);
    932 		return;
    933 	}
    934 
    935 	fclose(fp);
    936 
    937 	if (!keymgr_x509_not_after(x509, &expires)) {
    938 		X509_free(x509);
    939 		return;
    940 	}
    941 
    942 	time(&now);
    943 	days = (expires - now) / 86400;
    944 
    945 	kore_log(LOG_INFO, "%s certificate expires in %d days",
    946 	    dom->domain, days);
    947 
    948 	if (days <= ACME_RENEWAL_THRESHOLD) {
    949 		kore_log(LOG_INFO, "%s renewing certificate", dom->domain);
    950 		keymgr_acme_order_create(dom->domain);
    951 	}
    952 
    953 	X509_free(x509);
    954 }
    955 
    956 static void
    957 keymgr_acme_renewal(void *udata, u_int64_t now)
    958 {
    959 	kore_domain_callback(keymgr_acme_check);
    960 }
    961 
    962 static void
    963 keymgr_acme_sign(struct kore_msg *msg, const void *data)
    964 {
    965 	u_int32_t		id;
    966 	struct kore_buf		buf;
    967 	const u_int8_t		*ptr;
    968 	u_int8_t		*sig;
    969 	EVP_MD_CTX		*ctx;
    970 	struct key		*key;
    971 	char			*b64;
    972 	unsigned int		siglen;
    973 
    974 	TAILQ_FOREACH(key, &keys, list) {
    975 		if (key->dom == NULL)
    976 			break;
    977 	}
    978 
    979 	if (key == NULL)
    980 		fatalx("%s: missing key", __func__);
    981 
    982 	if (msg->length < sizeof(id))
    983 		fatalx("%s: invalid length (%zu)", __func__, msg->length);
    984 
    985 	ptr = data;
    986 	memcpy(&id, ptr, sizeof(id));
    987 
    988 	ptr += sizeof(id);
    989 	msg->length -= sizeof(id);
    990 
    991 	sig = kore_calloc(1, EVP_PKEY_size(key->pkey));
    992 
    993 	if ((ctx = EVP_MD_CTX_create()) == NULL)
    994 		fatalx("EVP_MD_CTX_create: %s", ssl_errno_s);
    995 
    996 	if (!EVP_SignInit_ex(ctx, EVP_sha256(), NULL))
    997 		fatalx("EVP_SignInit_ex: %s", ssl_errno_s);
    998 
    999 	if (!EVP_SignUpdate(ctx, ptr, msg->length))
   1000 		fatalx("EVP_SignUpdate: %s", ssl_errno_s);
   1001 
   1002 	if (!EVP_SignFinal(ctx, sig, &siglen, key->pkey))
   1003 		fatalx("EVP_SignFinal: %s", ssl_errno_s);
   1004 
   1005 	if (!kore_base64url_encode(sig, siglen, &b64, KORE_BASE64_RAW))
   1006 		fatalx("%s: failed to b64url encode signed data", __func__);
   1007 
   1008 	kore_buf_init(&buf, siglen + sizeof(id));
   1009 	kore_buf_append(&buf, &id, sizeof(id));
   1010 	kore_buf_append(&buf, b64, strlen(b64));
   1011 
   1012 	kore_msg_send(KORE_WORKER_ACME,
   1013 	    KORE_ACME_SIGN_RESULT, buf.data, buf.offset);
   1014 
   1015 	EVP_MD_CTX_destroy(ctx);
   1016 
   1017 	kore_free(sig);
   1018 	kore_free(b64);
   1019 	kore_buf_cleanup(&buf);
   1020 }
   1021 
   1022 static void
   1023 keymgr_acme_install_cert(const void *data, size_t len, struct key *key)
   1024 {
   1025 	int		fd;
   1026 	ssize_t		ret;
   1027 
   1028 	fd = open(key->dom->certfile, O_CREAT | O_TRUNC | O_WRONLY, 0700);
   1029 	if (fd == -1)
   1030 		fatalx("open(%s): %s", key->dom->certfile, errno_s);
   1031 
   1032 	kore_log(LOG_INFO, "writing %zu bytes of data", len);
   1033 
   1034 	for (;;) {
   1035 		ret = write(fd, data, len);
   1036 		if (ret == -1) {
   1037 			if (errno == EINTR)
   1038 				continue;
   1039 			fatalx("write(%s): %s", key->dom->certfile, errno_s);
   1040 		}
   1041 
   1042 		break;
   1043 	}
   1044 
   1045 	if ((size_t)ret != len) {
   1046 		fatalx("incorrect write on %s (%zd/%zu)",
   1047 		    key->dom->certfile, ret, len);
   1048 	}
   1049 
   1050 	if (close(fd) == -1) {
   1051 		kore_log(LOG_NOTICE,
   1052 		    "close error on '%s' (%s)", key->dom->certfile, errno_s);
   1053 	}
   1054 
   1055 	keymgr_submit_certificates(key->dom, KORE_MSG_WORKER_ALL);
   1056 
   1057 	keymgr_x509_msg(key->dom->domain, NULL, 0,
   1058 	    KORE_MSG_WORKER_ALL, KORE_ACME_CHALLENGE_CLEAR_CERT);
   1059 }
   1060 
   1061 static void
   1062 keymgr_acme_order_failed(const void *data, size_t len, struct key *key)
   1063 {
   1064 	u_int32_t	retry;
   1065 
   1066 	if (len != sizeof(retry)) {
   1067 		kore_log(LOG_ERR, "%s: invalid payload (%zu)", __func__, len);
   1068 		return;
   1069 	}
   1070 
   1071 	memcpy(&retry, data, len);
   1072 
   1073 	kore_timer_add(keymgr_acme_order_redo, retry, key->dom,
   1074 	    KORE_TIMER_ONESHOT);
   1075 }
   1076 
   1077 static void
   1078 keymgr_acme_challenge_cert(const void *data, size_t len, struct key *key)
   1079 {
   1080 	STACK_OF(X509_EXTENSION)	*sk;
   1081 	size_t				idx;
   1082 	time_t				now;
   1083 	X509_EXTENSION			*ext;
   1084 	X509_NAME			*name;
   1085 	X509				*x509;
   1086 	const u_int8_t			*digest;
   1087 	int				slen, i;
   1088 	u_int8_t			*cert, *uptr;
   1089 	char				hex[(SHA256_DIGEST_LENGTH * 2) + 1];
   1090 
   1091 	kore_log(LOG_INFO, "[%s] generating tls-alpn-01 challenge cert",
   1092 	    key->dom->domain);
   1093 
   1094 	if (len != SHA256_DIGEST_LENGTH)
   1095 		fatalx("invalid digest length of %zu bytes", len);
   1096 
   1097 	digest = data;
   1098 
   1099 	for (idx = 0; idx < SHA256_DIGEST_LENGTH; idx++) {
   1100 		slen = snprintf(hex + (idx * 2), sizeof(hex) - (idx * 2),
   1101 		    "%02x", digest[idx]);
   1102 		if (slen == -1 || (size_t)slen >= sizeof(hex))
   1103 			fatalx("failed to convert digest to hex");
   1104 	}
   1105 
   1106 	if ((x509 = X509_new()) == NULL)
   1107 		fatalx("X509_new(): %s", ssl_errno_s);
   1108 
   1109 	if (!X509_set_version(x509, 2))
   1110 		fatalx("X509_set_version(): %s", ssl_errno_s);
   1111 
   1112 	time(&now);
   1113 	if (!ASN1_INTEGER_set(X509_get_serialNumber(x509), now))
   1114 		fatalx("ASN1_INTEGER_set(): %s", ssl_errno_s);
   1115 
   1116 	if (!X509_gmtime_adj(X509_get_notBefore(x509), 0))
   1117 		fatalx("X509_gmtime_adj(): %s", ssl_errno_s);
   1118 
   1119 	if (!X509_gmtime_adj(X509_get_notAfter(x509), ACME_X509_EXPIRATION))
   1120 		fatalx("X509_gmtime_adj(): %s", ssl_errno_s);
   1121 
   1122 	if (!X509_set_pubkey(x509, key->pkey))
   1123 		fatalx("X509_set_pubkey(): %s", ssl_errno_s);
   1124 
   1125 	if ((name = X509_get_subject_name(x509)) == NULL)
   1126 		fatalx("X509_get_subject_name(): %s", ssl_errno_s);
   1127 
   1128 	if (!X509_NAME_add_entry_by_txt(name, "CN",
   1129 	    MBSTRING_ASC, (const unsigned char *)key->dom->domain, -1, -1, 0))
   1130 		fatalx("X509_NAME_add_entry_by_txt(): CN %s", ssl_errno_s);
   1131 
   1132 	if (!X509_set_issuer_name(x509, name))
   1133 		fatalx("X509_set_issuer_name(): %s", ssl_errno_s);
   1134 
   1135 	sk = sk_X509_EXTENSION_new_null();
   1136 	keymgr_x509_ext(sk, acme_oid, "critical,%s", hex);
   1137 	keymgr_x509_ext(sk, NID_subject_alt_name, "DNS:%s", key->dom->domain);
   1138 
   1139 	for (i = 0; i < sk_X509_EXTENSION_num(sk); i++) {
   1140 		ext = sk_X509_EXTENSION_value(sk, i);
   1141 		if (!X509_add_ext(x509, ext, 0))
   1142 			fatalx("X509_add_ext(): %s", ssl_errno_s);
   1143 	}
   1144 
   1145 	if (!X509_sign(x509, key->pkey, EVP_sha256()))
   1146 		fatalx("X509_sign(): %s", ssl_errno_s);
   1147 
   1148 	if ((slen = i2d_X509(x509, NULL)) <= 0)
   1149 		fatalx("i2d_X509: %s", ssl_errno_s);
   1150 
   1151 	cert = kore_calloc(1, slen);
   1152 	uptr = cert;
   1153 
   1154 	if (i2d_X509(x509, &uptr) <= 0)
   1155 		fatalx("i2d_X509: %s", ssl_errno_s);
   1156 
   1157 	keymgr_x509_msg(key->dom->domain, cert, slen,
   1158 	    KORE_MSG_WORKER_ALL, KORE_ACME_CHALLENGE_SET_CERT);
   1159 
   1160 	kore_free(cert);
   1161 	X509_free(x509);
   1162 	sk_X509_EXTENSION_pop_free(sk, X509_EXTENSION_free);
   1163 }
   1164 
   1165 static void
   1166 keymgr_acme_csr(const struct kore_keyreq *req, struct key *key)
   1167 {
   1168 	int				len;
   1169 	STACK_OF(X509_EXTENSION)	*sk;
   1170 	X509_REQ			*csr;
   1171 	X509_NAME			*name;
   1172 	u_int8_t			*data, *uptr;
   1173 
   1174 	kore_log(LOG_INFO, "[%s] creating CSR", req->domain);
   1175 
   1176 	if ((csr = X509_REQ_new()) == NULL)
   1177 		fatalx("X509_REQ_new: %s", ssl_errno_s);
   1178 
   1179 	if (!X509_REQ_set_version(csr, 3))
   1180 		fatalx("X509_REQ_set_version(): %s", ssl_errno_s);
   1181 
   1182 	if (!X509_REQ_set_pubkey(csr, key->pkey))
   1183 		fatalx("X509_REQ_set_pubkey(): %s", ssl_errno_s);
   1184 
   1185 	if ((name = X509_REQ_get_subject_name(csr)) == NULL)
   1186 		fatalx("X509_REQ_get_subject_name(): %s", ssl_errno_s);
   1187 
   1188 	if (!X509_NAME_add_entry_by_txt(name, "CN",
   1189 	    MBSTRING_ASC, (const unsigned char *)key->dom->domain, -1, -1, 0))
   1190 		fatalx("X509_NAME_add_entry_by_txt(): %s", ssl_errno_s);
   1191 
   1192 	sk = sk_X509_EXTENSION_new_null();
   1193 	keymgr_x509_ext(sk, NID_subject_alt_name, "DNS:%s", key->dom->domain);
   1194 
   1195 	if (!X509_REQ_add_extensions(csr, sk))
   1196 		fatalx("X509_REQ_add_extensions(): %s", ssl_errno_s);
   1197 
   1198 	if (!X509_REQ_sign(csr, key->pkey, EVP_sha256()))
   1199 		fatalx("X509_REQ_sign(): %s", ssl_errno_s);
   1200 
   1201 	if ((len = i2d_X509_REQ(csr, NULL)) <= 0)
   1202 		fatalx("i2d_X509_REQ: %s", ssl_errno_s);
   1203 
   1204 	data = kore_calloc(1, len);
   1205 	uptr = data;
   1206 
   1207 	if (i2d_X509_REQ(csr, &uptr) <= 0)
   1208 		fatalx("i2d_X509_REQ: %s", ssl_errno_s);
   1209 
   1210 	keymgr_x509_msg(key->dom->domain, data, len,
   1211 	    KORE_WORKER_ACME, KORE_ACME_CSR_RESPONSE);
   1212 
   1213 	kore_free(data);
   1214 	X509_REQ_free(csr);
   1215 
   1216 	sk_X509_EXTENSION_pop_free(sk, X509_EXTENSION_free);
   1217 }
   1218 
   1219 static void
   1220 keymgr_x509_ext(STACK_OF(X509_EXTENSION) *sk, int extnid, const char *fmt, ...)
   1221 {
   1222 	int			len;
   1223 	va_list			args;
   1224 	X509_EXTENSION		*ext;
   1225 	char			buf[1024];
   1226 
   1227 	va_start(args, fmt);
   1228 	len = vsnprintf(buf, sizeof(buf), fmt, args);
   1229 	va_end(args);
   1230 
   1231 	if (len == -1 || (size_t)len >= sizeof(buf))
   1232 		fatalx("failed to create buffer for extension %d", extnid);
   1233 
   1234 	if ((ext = X509V3_EXT_conf_nid(NULL, NULL, extnid, buf)) == NULL) {
   1235 		fatalx("X509V3_EXT_conf_nid(%d, %s): %s",
   1236 		    extnid, buf, ssl_errno_s);
   1237 	}
   1238 
   1239 	sk_X509_EXTENSION_push(sk, ext);
   1240 }
   1241 
   1242 static char *
   1243 keymgr_bignum_base64(const BIGNUM *bn)
   1244 {
   1245 	int		len;
   1246 	void		*buf;
   1247 	char		*encoded;
   1248 
   1249 	len = BN_num_bytes(bn);
   1250 	buf = kore_calloc(1, len);
   1251 
   1252 	if (BN_bn2bin(bn, buf) != len)
   1253 		fatalx("BN_bn2bin: %s", ssl_errno_s);
   1254 
   1255 	if (!kore_base64url_encode(buf, len, &encoded, KORE_BASE64_RAW))
   1256 		fatalx("failed to base64 encode BIGNUM");
   1257 
   1258 	return (encoded);
   1259 }
   1260 
   1261 static int
   1262 keymgr_x509_not_after(X509 *x509, time_t *out)
   1263 {
   1264 	const ASN1_TIME		*na;
   1265 	int			ret;
   1266 
   1267 	ret = KORE_RESULT_ERROR;
   1268 
   1269 	if ((na = X509_get_notAfter(x509)) == NULL) {
   1270 		kore_log(LOG_ERR, "no notAfter date in x509");
   1271 		return (KORE_RESULT_ERROR);
   1272 	}
   1273 
   1274 	switch (na->type) {
   1275 	case V_ASN1_UTCTIME:
   1276 		ret = keymgr_asn1_convert_utctime(na, out);
   1277 		break;
   1278 	case V_ASN1_GENERALIZEDTIME:
   1279 		ret = keymgr_asn1_convert_generalizedtime(na->data,
   1280 		    na->length, out);
   1281 		break;
   1282 	default:
   1283 		kore_log(LOG_ERR, "invalid notAfter type (%d)", na->type);
   1284 		break;
   1285 	}
   1286 
   1287 	return (ret);
   1288 }
   1289 
   1290 static int
   1291 keymgr_asn1_convert_utctime(const ASN1_TIME *na, time_t *out)
   1292 {
   1293 	int	len, year;
   1294 	char	buf[ASN1_GENERALIZEDTIME_LEN + 1];
   1295 
   1296 	if (na->length != ASN1_UTCTIME_LEN) {
   1297 		kore_log(LOG_ERR, "invalid UTCTIME: too short (%d)",
   1298 		    na->length);
   1299 		return (KORE_RESULT_ERROR);
   1300 	}
   1301 
   1302 	if (!isdigit(na->data[0]) || !isdigit(na->data[1])) {
   1303 		kore_log(LOG_ERR, "invalid UTCTIME: YY are not digits");
   1304 		return (KORE_RESULT_ERROR);
   1305 	}
   1306 
   1307 	year = (na->data[0] - '0') * 10 + (na->data[1] - '0');
   1308 
   1309 	/* RFC 5280 says years >= 50 are interpreted as 19YY */
   1310 	if (year >= 50)
   1311 		year = 1900 + year;
   1312 	else
   1313 		year = 2000 + year;
   1314 
   1315 	/* Convert it to GENERALIZEDTIME format and call that parser. */
   1316 	len = snprintf(buf, sizeof(buf), "%04d%.*s", year,
   1317 	    na->length - 2, (const char *)na->data+ 2);
   1318 	if (len == -1 || (size_t)len >= sizeof(buf)) {
   1319 		kore_log(LOG_ERR, "invalid UTCTIME: failed to convert");
   1320 		return (KORE_RESULT_ERROR);
   1321 	}
   1322 
   1323 	return (keymgr_asn1_convert_generalizedtime(buf, len, out));
   1324 }
   1325 
   1326 static int
   1327 keymgr_asn1_convert_generalizedtime(const void *ptr, size_t len, time_t *out)
   1328 {
   1329 	size_t			i;
   1330 	struct tm		tm;
   1331 	const u_int8_t		*buf;
   1332 
   1333 	if (len != ASN1_GENERALIZEDTIME_LEN) {
   1334 		kore_log(LOG_ERR, "invalid GENERALIZEDTIME: too short (%zu)",
   1335 		    len);
   1336 		return (KORE_RESULT_ERROR);
   1337 	}
   1338 
   1339 	buf = ptr;
   1340 
   1341 	for (i = 0; i < len - 1; i++) {
   1342 		if (!isdigit(buf[i])) {
   1343 			kore_log(LOG_ERR,
   1344 			    "invalid GENERALIZEDTIME: invalid bytes");
   1345 			return (KORE_RESULT_ERROR);
   1346 		}
   1347 	}
   1348 
   1349 	/* RFC 5280 states that Zulu time must be used (Z). */
   1350 	if (buf[i] != 'Z') {
   1351 		kore_log(LOG_ERR, "invalid GENERALIZEDTIME: not Zulu time");
   1352 		return (KORE_RESULT_ERROR);
   1353 	}
   1354 
   1355 	memset(&tm, 0, sizeof(tm));
   1356 
   1357 	tm.tm_year = (buf[0] - '0') * 1000 + (buf[1] - '0') * 100 +
   1358 	    (buf[2] - '0') * 10 + (buf[3] - '0');
   1359 
   1360 	tm.tm_mon = (buf[4] - '0') * 10 + (buf[5] - '0');
   1361 	tm.tm_mday = (buf[6] - '0') * 10 + (buf[7] - '0');
   1362 	tm.tm_hour = (buf[8] - '0') * 10 + (buf[9] - '0');
   1363 	tm.tm_min = (buf[10] - '0') * 10 + (buf[11] - '0');
   1364 	tm.tm_sec = (buf[12] - '0') * 10 + (buf[13] - '0');
   1365 
   1366 	tm.tm_mon = tm.tm_mon - 1;
   1367 	tm.tm_year = tm.tm_year - 1900;
   1368 
   1369 	*out = mktime(&tm);
   1370 
   1371 	return (KORE_RESULT_OK);
   1372 }
   1373 #endif