xref: /openbsd/usr.sbin/relayd/ca.c (revision d89ec533)
1 /*	$OpenBSD: ca.c,v 1.37 2021/12/08 03:40:44 tb Exp $	*/
2 
3 /*
4  * Copyright (c) 2014 Reyk Floeter <reyk@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 #include <sys/queue.h>
21 #include <sys/uio.h>
22 
23 #include <unistd.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <poll.h>
27 #include <imsg.h>
28 
29 #include <openssl/bio.h>
30 #include <openssl/pem.h>
31 #include <openssl/evp.h>
32 #include <openssl/rsa.h>
33 #include <openssl/engine.h>
34 
35 #include "relayd.h"
36 
37 void	 ca_init(struct privsep *, struct privsep_proc *p, void *);
38 void	 ca_launch(void);
39 
40 int	 ca_dispatch_parent(int, struct privsep_proc *, struct imsg *);
41 int	 ca_dispatch_relay(int, struct privsep_proc *, struct imsg *);
42 
43 int	 rsae_pub_enc(int, const u_char *, u_char *, RSA *, int);
44 int	 rsae_pub_dec(int,const u_char *, u_char *, RSA *, int);
45 int	 rsae_priv_enc(int, const u_char *, u_char *, RSA *, int);
46 int	 rsae_priv_dec(int, const u_char *, u_char *, RSA *, int);
47 int	 rsae_mod_exp(BIGNUM *, const BIGNUM *, RSA *, BN_CTX *);
48 int	 rsae_bn_mod_exp(BIGNUM *, const BIGNUM *, const BIGNUM *,
49 	    const BIGNUM *, BN_CTX *, BN_MONT_CTX *);
50 int	 rsae_init(RSA *);
51 int	 rsae_finish(RSA *);
52 int	 rsae_sign(int, const u_char *, u_int, u_char *, u_int *,
53 	    const RSA *);
54 int	 rsae_verify(int dtype, const u_char *m, u_int, const u_char *,
55 	    u_int, const RSA *);
56 int	 rsae_keygen(RSA *, int, BIGNUM *, BN_GENCB *);
57 
58 static struct relayd *env = NULL;
59 
60 static struct privsep_proc procs[] = {
61 	{ "parent",	PROC_PARENT,	ca_dispatch_parent },
62 	{ "relay",	PROC_RELAY,	ca_dispatch_relay },
63 };
64 
65 void
66 ca(struct privsep *ps, struct privsep_proc *p)
67 {
68 	env = ps->ps_env;
69 
70 	proc_run(ps, p, procs, nitems(procs), ca_init, NULL);
71 }
72 
73 void
74 ca_init(struct privsep *ps, struct privsep_proc *p, void *arg)
75 {
76 	if (pledge("stdio recvfd", NULL) == -1)
77 		fatal("pledge");
78 
79 	if (config_init(ps->ps_env) == -1)
80 		fatal("failed to initialize configuration");
81 
82 	env->sc_id = getpid() & 0xffff;
83 }
84 
85 void
86 hash_x509(X509 *cert, char *hash, size_t hashlen)
87 {
88 	static const char	hex[] = "0123456789abcdef";
89 	size_t			off;
90 	char			digest[EVP_MAX_MD_SIZE];
91 	int			dlen, i;
92 
93 	if (X509_pubkey_digest(cert, EVP_sha256(), digest, &dlen) != 1)
94 		fatalx("%s: X509_pubkey_digest failed", __func__);
95 
96 	if (hashlen < 2 * dlen + sizeof("SHA256:"))
97 		fatalx("%s: hash buffer to small", __func__);
98 
99 	off = strlcpy(hash, "SHA256:", hashlen);
100 
101 	for (i = 0; i < dlen; i++) {
102 		hash[off++] = hex[(digest[i] >> 4) & 0x0f];
103 		hash[off++] = hex[digest[i] & 0x0f];
104 	}
105 	hash[off] = 0;
106 }
107 
108 void
109 ca_launch(void)
110 {
111 	char			 hash[TLS_CERT_HASH_SIZE];
112 	char			*buf;
113 	BIO			*in = NULL;
114 	EVP_PKEY		*pkey = NULL;
115 	struct relay		*rlay;
116 	struct relay_cert	*cert;
117 	X509			*x509 = NULL;
118 	off_t			 len;
119 
120 	TAILQ_FOREACH(cert, env->sc_certs, cert_entry) {
121 		if (cert->cert_fd == -1 || cert->cert_key_fd == -1)
122 			continue;
123 
124 		if ((buf = relay_load_fd(cert->cert_fd, &len)) == NULL)
125 			fatal("ca_launch: cert relay_load_fd");
126 
127 		if ((in = BIO_new_mem_buf(buf, len)) == NULL)
128 			fatalx("ca_launch: cert BIO_new_mem_buf");
129 
130 		if ((x509 = PEM_read_bio_X509(in, NULL,
131 		    NULL, NULL)) == NULL)
132 			fatalx("ca_launch: cert PEM_read_bio_X509");
133 
134 		hash_x509(x509, hash, sizeof(hash));
135 
136 		BIO_free(in);
137 		X509_free(x509);
138 		purge_key(&buf, len);
139 
140 		if ((buf = relay_load_fd(cert->cert_key_fd, &len)) == NULL)
141 			fatal("ca_launch: key relay_load_fd");
142 
143 		if ((in = BIO_new_mem_buf(buf, len)) == NULL)
144 			fatalx("%s: key", __func__);
145 
146 		if ((pkey = PEM_read_bio_PrivateKey(in,
147 		    NULL, NULL, NULL)) == NULL)
148 			fatalx("%s: PEM", __func__);
149 
150 		cert->cert_pkey = pkey;
151 
152 		if (pkey_add(env, pkey, hash) == NULL)
153 			fatalx("tls pkey");
154 
155 		BIO_free(in);
156 		purge_key(&buf, len);
157 	}
158 
159 	TAILQ_FOREACH(rlay, env->sc_relays, rl_entry) {
160 		if ((rlay->rl_conf.flags & (F_TLS|F_TLSCLIENT)) == 0)
161 			continue;
162 
163 		if (rlay->rl_tls_cacert_fd != -1 &&
164 		    rlay->rl_conf.tls_cakey_len) {
165 			if ((buf = relay_load_fd(rlay->rl_tls_cacert_fd,
166 			    &len)) == NULL)
167 				fatal("ca_launch: cacert relay_load_fd");
168 
169 			if ((in = BIO_new_mem_buf(buf, len)) == NULL)
170 				fatalx("ca_launch: cacert BIO_new_mem_buf");
171 
172 			if ((x509 = PEM_read_bio_X509(in, NULL,
173 			    NULL, NULL)) == NULL)
174 				fatalx("ca_launch: cacert PEM_read_bio_X509");
175 
176 			hash_x509(x509, hash, sizeof(hash));
177 
178 			BIO_free(in);
179 			X509_free(x509);
180 			purge_key(&buf, len);
181 
182 			if ((in = BIO_new_mem_buf(rlay->rl_tls_cakey,
183 			    rlay->rl_conf.tls_cakey_len)) == NULL)
184 				fatalx("%s: key", __func__);
185 
186 			if ((pkey = PEM_read_bio_PrivateKey(in,
187 			    NULL, NULL, NULL)) == NULL)
188 				fatalx("%s: PEM", __func__);
189 			BIO_free(in);
190 
191 			rlay->rl_tls_capkey = pkey;
192 
193 			if (pkey_add(env, pkey, hash) == NULL)
194 				fatalx("ca pkey");
195 
196 			purge_key(&rlay->rl_tls_cakey,
197 			    rlay->rl_conf.tls_cakey_len);
198 		}
199 		close(rlay->rl_tls_ca_fd);
200 	}
201 }
202 
203 int
204 ca_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
205 {
206 	switch (imsg->hdr.type) {
207 	case IMSG_CFG_RELAY:
208 		config_getrelay(env, imsg);
209 		break;
210 	case IMSG_CFG_RELAY_FD:
211 		config_getrelayfd(env, imsg);
212 		break;
213 	case IMSG_CFG_DONE:
214 		config_getcfg(env, imsg);
215 		break;
216 	case IMSG_CTL_START:
217 		ca_launch();
218 		break;
219 	case IMSG_CTL_RESET:
220 		config_getreset(env, imsg);
221 		break;
222 	default:
223 		return (-1);
224 	}
225 
226 	return (0);
227 }
228 
229 int
230 ca_dispatch_relay(int fd, struct privsep_proc *p, struct imsg *imsg)
231 {
232 	struct ctl_keyop	 cko;
233 	EVP_PKEY		*pkey;
234 	RSA			*rsa;
235 	u_char			*from = NULL, *to = NULL;
236 	struct iovec		 iov[2];
237 	int			 c = 0;
238 
239 	switch (imsg->hdr.type) {
240 	case IMSG_CA_PRIVENC:
241 	case IMSG_CA_PRIVDEC:
242 		IMSG_SIZE_CHECK(imsg, (&cko));
243 		bcopy(imsg->data, &cko, sizeof(cko));
244 		if (cko.cko_proc > env->sc_conf.prefork_relay)
245 			fatalx("%s: invalid relay proc", __func__);
246 		if (IMSG_DATA_SIZE(imsg) != (sizeof(cko) + cko.cko_flen))
247 			fatalx("%s: invalid key operation", __func__);
248 		if ((pkey = pkey_find(env, cko.cko_hash)) == NULL)
249 			fatalx("%s: invalid relay hash '%s'",
250 			    __func__, cko.cko_hash);
251 		if ((rsa = EVP_PKEY_get1_RSA(pkey)) == NULL)
252 			fatalx("%s: invalid relay key", __func__);
253 
254 		DPRINTF("%s:%d: key hash %s proc %d",
255 		    __func__, __LINE__, cko.cko_hash, cko.cko_proc);
256 
257 		from = (u_char *)imsg->data + sizeof(cko);
258 		if ((to = calloc(1, cko.cko_tlen)) == NULL)
259 			fatalx("%s: calloc", __func__);
260 
261 		switch (imsg->hdr.type) {
262 		case IMSG_CA_PRIVENC:
263 			cko.cko_tlen = RSA_private_encrypt(cko.cko_flen,
264 			    from, to, rsa, cko.cko_padding);
265 			break;
266 		case IMSG_CA_PRIVDEC:
267 			cko.cko_tlen = RSA_private_decrypt(cko.cko_flen,
268 			    from, to, rsa, cko.cko_padding);
269 			break;
270 		}
271 
272 		if (cko.cko_tlen == -1) {
273 			char buf[256];
274 			log_warnx("%s: %s", __func__,
275 			    ERR_error_string(ERR_get_error(), buf));
276 		}
277 
278 		iov[c].iov_base = &cko;
279 		iov[c++].iov_len = sizeof(cko);
280 		if (cko.cko_tlen > 0) {
281 			iov[c].iov_base = to;
282 			iov[c++].iov_len = cko.cko_tlen;
283 		}
284 
285 		if (proc_composev_imsg(env->sc_ps, PROC_RELAY, cko.cko_proc,
286 		    imsg->hdr.type, -1, -1, iov, c) == -1)
287 			log_warn("%s: proc_composev_imsg", __func__);
288 
289 		free(to);
290 		RSA_free(rsa);
291 		break;
292 	default:
293 		return (-1);
294 	}
295 
296 	return (0);
297 }
298 
299 /*
300  * RSA privsep engine (called from unprivileged processes)
301  */
302 
303 const RSA_METHOD *rsa_default = NULL;
304 
305 static RSA_METHOD rsae_method = {
306 	"RSA privsep engine",
307 	rsae_pub_enc,
308 	rsae_pub_dec,
309 	rsae_priv_enc,
310 	rsae_priv_dec,
311 	rsae_mod_exp,
312 	rsae_bn_mod_exp,
313 	rsae_init,
314 	rsae_finish,
315 	0,
316 	NULL,
317 	rsae_sign,
318 	rsae_verify,
319 	rsae_keygen
320 };
321 
322 static int
323 rsae_send_imsg(int flen, const u_char *from, u_char *to, RSA *rsa,
324     int padding, u_int cmd)
325 {
326 	struct privsep	*ps = env->sc_ps;
327 	struct pollfd	 pfd[1];
328 	struct ctl_keyop cko;
329 	int		 ret = 0;
330 	char		*hash;
331 	struct iovec	 iov[2];
332 	struct imsgbuf	*ibuf;
333 	struct imsgev	*iev;
334 	struct imsg	 imsg;
335 	int		 n, done = 0, cnt = 0;
336 	u_char		*toptr;
337 	static u_int	 seq = 0;
338 
339 	if ((hash = RSA_get_ex_data(rsa, 0)) == NULL)
340 		return (0);
341 
342 	iev = proc_iev(ps, PROC_CA, ps->ps_instance);
343 	ibuf = &iev->ibuf;
344 
345 	/*
346 	 * XXX this could be nicer...
347 	 */
348 
349 	(void)strlcpy(cko.cko_hash, hash, sizeof(cko.cko_hash));
350 	cko.cko_proc = ps->ps_instance;
351 	cko.cko_flen = flen;
352 	cko.cko_tlen = RSA_size(rsa);
353 	cko.cko_padding = padding;
354 	cko.cko_cookie = seq++;
355 
356 	iov[cnt].iov_base = &cko;
357 	iov[cnt++].iov_len = sizeof(cko);
358 	iov[cnt].iov_base = (void *)(uintptr_t)from;
359 	iov[cnt++].iov_len = flen;
360 
361 	/*
362 	 * Send a synchronous imsg because we cannot defer the RSA
363 	 * operation in OpenSSL's engine layer.
364 	 */
365 	if (imsg_composev(ibuf, cmd, 0, 0, -1, iov, cnt) == -1)
366 		log_warn("%s: imsg_composev", __func__);
367 	if (imsg_flush(ibuf) == -1)
368 		log_warn("%s: imsg_flush", __func__);
369 
370 	pfd[0].fd = ibuf->fd;
371 	pfd[0].events = POLLIN;
372 	while (!done) {
373 		switch (poll(pfd, 1, RELAY_TLS_PRIV_TIMEOUT)) {
374 		case -1:
375 			fatal("%s: poll", __func__);
376 		case 0:
377 			log_warnx("%s: priv%s poll timeout, keyop #%x",
378 			    __func__,
379 			    cmd == IMSG_CA_PRIVENC ? "enc" : "dec",
380 			    cko.cko_cookie);
381 			return (-1);
382 		default:
383 			break;
384 		}
385 		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
386 			fatalx("imsg_read");
387 		if (n == 0)
388 			fatalx("pipe closed");
389 
390 		while (!done) {
391 			if ((n = imsg_get(ibuf, &imsg)) == -1)
392 				fatalx("imsg_get error");
393 			if (n == 0)
394 				break;
395 
396 			IMSG_SIZE_CHECK(&imsg, (&cko));
397 			memcpy(&cko, imsg.data, sizeof(cko));
398 
399 			/*
400 			 * Due to earlier timed out requests, there may be
401 			 * responses that need to be skipped.
402 			 */
403 			if (cko.cko_cookie != seq - 1) {
404 				log_warnx(
405 				    "%s: priv%s obsolete keyop #%x", __func__,
406 				    cmd == IMSG_CA_PRIVENC ? "enc" : "dec",
407 				    cko.cko_cookie);
408 				continue;
409 			}
410 
411 			if (imsg.hdr.type != cmd)
412 				fatalx("invalid response");
413 
414 			ret = cko.cko_tlen;
415 			if (ret > 0) {
416 				if (IMSG_DATA_SIZE(&imsg) !=
417 				    (sizeof(cko) + ret))
418 					fatalx("data size");
419 				toptr = (u_char *)imsg.data + sizeof(cko);
420 				memcpy(to, toptr, ret);
421 			}
422 			done = 1;
423 
424 			imsg_free(&imsg);
425 		}
426 	}
427 	imsg_event_add(iev);
428 
429 	return (ret);
430 }
431 
432 int
433 rsae_pub_enc(int flen,const u_char *from, u_char *to, RSA *rsa,int padding)
434 {
435 	DPRINTF("%s:%d", __func__, __LINE__);
436 	return (rsa_default->rsa_pub_enc(flen, from, to, rsa, padding));
437 }
438 
439 int
440 rsae_pub_dec(int flen,const u_char *from, u_char *to, RSA *rsa,int padding)
441 {
442 	DPRINTF("%s:%d", __func__, __LINE__);
443 	return (rsa_default->rsa_pub_dec(flen, from, to, rsa, padding));
444 }
445 
446 int
447 rsae_priv_enc(int flen, const u_char *from, u_char *to, RSA *rsa, int padding)
448 {
449 	DPRINTF("%s:%d", __func__, __LINE__);
450 	return (rsae_send_imsg(flen, from, to, rsa, padding,
451 	    IMSG_CA_PRIVENC));
452 }
453 
454 int
455 rsae_priv_dec(int flen, const u_char *from, u_char *to, RSA *rsa, int padding)
456 {
457 	DPRINTF("%s:%d", __func__, __LINE__);
458 	return (rsae_send_imsg(flen, from, to, rsa, padding,
459 	    IMSG_CA_PRIVDEC));
460 }
461 
462 int
463 rsae_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
464 {
465 	DPRINTF("%s:%d", __func__, __LINE__);
466 	return (rsa_default->rsa_mod_exp(r0, I, rsa, ctx));
467 }
468 
469 int
470 rsae_bn_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
471     const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
472 {
473 	DPRINTF("%s:%d", __func__, __LINE__);
474 	return (rsa_default->bn_mod_exp(r, a, p, m, ctx, m_ctx));
475 }
476 
477 int
478 rsae_init(RSA *rsa)
479 {
480 	DPRINTF("%s:%d", __func__, __LINE__);
481 	if (rsa_default->init == NULL)
482 		return (1);
483 	return (rsa_default->init(rsa));
484 }
485 
486 int
487 rsae_finish(RSA *rsa)
488 {
489 	DPRINTF("%s:%d", __func__, __LINE__);
490 	if (rsa_default->finish == NULL)
491 		return (1);
492 	return (rsa_default->finish(rsa));
493 }
494 
495 int
496 rsae_sign(int type, const u_char *m, u_int m_length, u_char *sigret,
497     u_int *siglen, const RSA *rsa)
498 {
499 	DPRINTF("%s:%d", __func__, __LINE__);
500 	return (rsa_default->rsa_sign(type, m, m_length,
501 	    sigret, siglen, rsa));
502 }
503 
504 int
505 rsae_verify(int dtype, const u_char *m, u_int m_length, const u_char *sigbuf,
506     u_int siglen, const RSA *rsa)
507 {
508 	DPRINTF("%s:%d", __func__, __LINE__);
509 	return (rsa_default->rsa_verify(dtype, m, m_length,
510 	    sigbuf, siglen, rsa));
511 }
512 
513 int
514 rsae_keygen(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb)
515 {
516 	DPRINTF("%s:%d", __func__, __LINE__);
517 	return (rsa_default->rsa_keygen(rsa, bits, e, cb));
518 }
519 
520 void
521 ca_engine_init(struct relayd *x_env)
522 {
523 	ENGINE		*e = NULL;
524 	const char	*errstr, *name;
525 
526 	if (env == NULL)
527 		env = x_env;
528 
529 	if (rsa_default != NULL)
530 		return;
531 
532 	if ((e = ENGINE_get_default_RSA()) == NULL) {
533 		if ((e = ENGINE_new()) == NULL) {
534 			errstr = "ENGINE_new";
535 			goto fail;
536 		}
537 		if (!ENGINE_set_name(e, rsae_method.name)) {
538 			errstr = "ENGINE_set_name";
539 			goto fail;
540 		}
541 		if ((rsa_default = RSA_get_default_method()) == NULL) {
542 			errstr = "RSA_get_default_method";
543 			goto fail;
544 		}
545 	} else if ((rsa_default = ENGINE_get_RSA(e)) == NULL) {
546 		errstr = "ENGINE_get_RSA";
547 		goto fail;
548 	}
549 
550 	if ((name = ENGINE_get_name(e)) == NULL)
551 		name = "unknown RSA engine";
552 
553 	log_debug("%s: using %s", __func__, name);
554 
555 	if (rsa_default->flags & RSA_FLAG_SIGN_VER)
556 		fatalx("unsupported RSA engine");
557 
558 	if (rsa_default->rsa_mod_exp == NULL)
559 		rsae_method.rsa_mod_exp = NULL;
560 	if (rsa_default->bn_mod_exp == NULL)
561 		rsae_method.bn_mod_exp = NULL;
562 	if (rsa_default->rsa_keygen == NULL)
563 		rsae_method.rsa_keygen = NULL;
564 	rsae_method.flags = rsa_default->flags |
565 	    RSA_METHOD_FLAG_NO_CHECK;
566 	rsae_method.app_data = rsa_default->app_data;
567 
568 	if (!ENGINE_set_RSA(e, &rsae_method)) {
569 		errstr = "ENGINE_set_RSA";
570 		goto fail;
571 	}
572 	if (!ENGINE_set_default_RSA(e)) {
573 		errstr = "ENGINE_set_default_RSA";
574 		goto fail;
575 	}
576 
577 	return;
578 
579  fail:
580 	fatalx("%s: %s", __func__, errstr);
581 }
582