xref: /openbsd/usr.sbin/relayd/ca.c (revision 7084d095)
1 /*	$OpenBSD: ca.c,v 1.33 2018/01/24 13:51:36 claudio 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 	X509		*cert = NULL;
117 	off_t		 len;
118 
119 	TAILQ_FOREACH(rlay, env->sc_relays, rl_entry) {
120 		if ((rlay->rl_conf.flags & (F_TLS|F_TLSCLIENT)) == 0)
121 			continue;
122 
123 		if (rlay->rl_tls_cert_fd != -1) {
124 			if ((buf = relay_load_fd(rlay->rl_tls_cert_fd,
125 			    &len)) == NULL)
126 				fatal("ca_launch: cert relay_load_fd");
127 
128 			if ((in = BIO_new_mem_buf(buf, len)) == NULL)
129 				fatalx("ca_launch: cert BIO_new_mem_buf");
130 
131 			if ((cert = PEM_read_bio_X509(in, NULL,
132 			    NULL, NULL)) == NULL)
133 				fatalx("ca_launch: cert PEM_read_bio_X509");
134 
135 			hash_x509(cert, hash, sizeof(hash));
136 
137 			BIO_free(in);
138 			X509_free(cert);
139 			purge_key(&buf, len);
140 		}
141 		if (rlay->rl_conf.tls_key_len) {
142 			if ((in = BIO_new_mem_buf(rlay->rl_tls_key,
143 			    rlay->rl_conf.tls_key_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 			BIO_free(in);
150 
151 			rlay->rl_tls_pkey = pkey;
152 
153 			if (pkey_add(env, pkey, hash) == NULL)
154 				fatalx("tls pkey");
155 
156 			purge_key(&rlay->rl_tls_key,
157 			    rlay->rl_conf.tls_key_len);
158 		}
159 
160 		if (rlay->rl_tls_cacert_fd != -1) {
161 			if ((buf = relay_load_fd(rlay->rl_tls_cacert_fd,
162 			    &len)) == NULL)
163 				fatal("ca_launch: cacert relay_load_fd");
164 
165 			if ((in = BIO_new_mem_buf(buf, len)) == NULL)
166 				fatalx("ca_launch: cacert BIO_new_mem_buf");
167 
168 			if ((cert = PEM_read_bio_X509(in, NULL,
169 			    NULL, NULL)) == NULL)
170 				fatalx("ca_launch: cacert PEM_read_bio_X509");
171 
172 			hash_x509(cert, hash, sizeof(hash));
173 
174 			BIO_free(in);
175 			X509_free(cert);
176 			purge_key(&buf, len);
177 		}
178 		if (rlay->rl_conf.tls_cakey_len) {
179 			if ((in = BIO_new_mem_buf(rlay->rl_tls_cakey,
180 			    rlay->rl_conf.tls_cakey_len)) == NULL)
181 				fatalx("%s: key", __func__);
182 
183 			if ((pkey = PEM_read_bio_PrivateKey(in,
184 			    NULL, NULL, NULL)) == NULL)
185 				fatalx("%s: PEM", __func__);
186 			BIO_free(in);
187 
188 			rlay->rl_tls_capkey = pkey;
189 
190 			if (pkey_add(env, pkey, hash) == NULL)
191 				fatalx("ca pkey");
192 
193 			purge_key(&rlay->rl_tls_cakey,
194 			    rlay->rl_conf.tls_cakey_len);
195 		}
196 		close(rlay->rl_tls_ca_fd);
197 	}
198 }
199 
200 int
201 ca_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
202 {
203 	switch (imsg->hdr.type) {
204 	case IMSG_CFG_RELAY:
205 		config_getrelay(env, imsg);
206 		break;
207 	case IMSG_CFG_RELAY_FD:
208 		config_getrelayfd(env, imsg);
209 		break;
210 	case IMSG_CFG_DONE:
211 		config_getcfg(env, imsg);
212 		break;
213 	case IMSG_CTL_START:
214 		ca_launch();
215 		break;
216 	case IMSG_CTL_RESET:
217 		config_getreset(env, imsg);
218 		break;
219 	default:
220 		return (-1);
221 	}
222 
223 	return (0);
224 }
225 
226 int
227 ca_dispatch_relay(int fd, struct privsep_proc *p, struct imsg *imsg)
228 {
229 	struct ctl_keyop	 cko;
230 	EVP_PKEY		*pkey;
231 	RSA			*rsa;
232 	u_char			*from = NULL, *to = NULL;
233 	struct iovec		 iov[2];
234 	int			 c = 0;
235 
236 	switch (imsg->hdr.type) {
237 	case IMSG_CA_PRIVENC:
238 	case IMSG_CA_PRIVDEC:
239 		IMSG_SIZE_CHECK(imsg, (&cko));
240 		bcopy(imsg->data, &cko, sizeof(cko));
241 		if (cko.cko_proc > env->sc_conf.prefork_relay)
242 			fatalx("%s: invalid relay proc", __func__);
243 		if (IMSG_DATA_SIZE(imsg) != (sizeof(cko) + cko.cko_flen))
244 			fatalx("%s: invalid key operation", __func__);
245 		if ((pkey = pkey_find(env, cko.cko_hash)) == NULL)
246 			fatalx("%s: invalid relay hash '%s'",
247 			    __func__, cko.cko_hash);
248 		if ((rsa = EVP_PKEY_get1_RSA(pkey)) == NULL)
249 			fatalx("%s: invalid relay key", __func__);
250 
251 		DPRINTF("%s:%d: key hash %s proc %d",
252 		    __func__, __LINE__, cko.cko_hash, cko.cko_proc);
253 
254 		from = (u_char *)imsg->data + sizeof(cko);
255 		if ((to = calloc(1, cko.cko_tlen)) == NULL)
256 			fatalx("%s: calloc", __func__);
257 
258 		switch (imsg->hdr.type) {
259 		case IMSG_CA_PRIVENC:
260 			cko.cko_tlen = RSA_private_encrypt(cko.cko_flen,
261 			    from, to, rsa, cko.cko_padding);
262 			break;
263 		case IMSG_CA_PRIVDEC:
264 			cko.cko_tlen = RSA_private_decrypt(cko.cko_flen,
265 			    from, to, rsa, cko.cko_padding);
266 			break;
267 		}
268 
269 		if (cko.cko_tlen == -1) {
270 			char buf[256];
271 			log_warnx("%s: %s", __func__,
272 			    ERR_error_string(ERR_get_error(), buf));
273 		}
274 
275 		iov[c].iov_base = &cko;
276 		iov[c++].iov_len = sizeof(cko);
277 		if (cko.cko_tlen > 0) {
278 			iov[c].iov_base = to;
279 			iov[c++].iov_len = cko.cko_tlen;
280 		}
281 
282 		if (proc_composev_imsg(env->sc_ps, PROC_RELAY, cko.cko_proc,
283 		    imsg->hdr.type, -1, -1, iov, c) == -1)
284 			log_warn("%s: proc_composev_imsg", __func__);
285 
286 		free(to);
287 		RSA_free(rsa);
288 		break;
289 	default:
290 		return (-1);
291 	}
292 
293 	return (0);
294 }
295 
296 /*
297  * RSA privsep engine (called from unprivileged processes)
298  */
299 
300 const RSA_METHOD *rsa_default = NULL;
301 
302 static RSA_METHOD rsae_method = {
303 	"RSA privsep engine",
304 	rsae_pub_enc,
305 	rsae_pub_dec,
306 	rsae_priv_enc,
307 	rsae_priv_dec,
308 	rsae_mod_exp,
309 	rsae_bn_mod_exp,
310 	rsae_init,
311 	rsae_finish,
312 	0,
313 	NULL,
314 	rsae_sign,
315 	rsae_verify,
316 	rsae_keygen
317 };
318 
319 static int
320 rsae_send_imsg(int flen, const u_char *from, u_char *to, RSA *rsa,
321     int padding, u_int cmd)
322 {
323 	struct privsep	*ps = env->sc_ps;
324 	struct pollfd	 pfd[1];
325 	struct ctl_keyop cko;
326 	int		 ret = 0;
327 	char		*hash;
328 	struct iovec	 iov[2];
329 	struct imsgbuf	*ibuf;
330 	struct imsgev	*iev;
331 	struct imsg	 imsg;
332 	int		 n, done = 0, cnt = 0;
333 	u_char		*toptr;
334 
335 	if ((hash = RSA_get_ex_data(rsa, 0)) == NULL)
336 		return (0);
337 
338 	iev = proc_iev(ps, PROC_CA, ps->ps_instance);
339 	ibuf = &iev->ibuf;
340 
341 	/*
342 	 * XXX this could be nicer...
343 	 */
344 
345 	(void)strlcpy(cko.cko_hash, hash, sizeof(cko.cko_hash));
346 	cko.cko_proc = ps->ps_instance;
347 	cko.cko_flen = flen;
348 	cko.cko_tlen = RSA_size(rsa);
349 	cko.cko_padding = padding;
350 
351 	iov[cnt].iov_base = &cko;
352 	iov[cnt++].iov_len = sizeof(cko);
353 	iov[cnt].iov_base = (void *)(uintptr_t)from;
354 	iov[cnt++].iov_len = flen;
355 
356 	/*
357 	 * Send a synchronous imsg because we cannot defer the RSA
358 	 * operation in OpenSSL's engine layer.
359 	 */
360 	if (imsg_composev(ibuf, cmd, 0, 0, -1, iov, cnt) == -1)
361 		log_warn("%s: imsg_composev", __func__);
362 	if (imsg_flush(ibuf) == -1)
363 		log_warn("%s: imsg_flush", __func__);
364 
365 	pfd[0].fd = ibuf->fd;
366 	pfd[0].events = POLLIN;
367 	while (!done) {
368 		switch (poll(pfd, 1, RELAY_TLS_PRIV_TIMEOUT)) {
369 		case -1:
370 			fatal("%s: poll", __func__);
371 		case 0:
372 			log_warnx("%s: poll timeout", __func__);
373 			return -1;
374 		default:
375 			break;
376 		}
377 		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
378 			fatalx("imsg_read");
379 		if (n == 0)
380 			fatalx("pipe closed");
381 
382 		while (!done) {
383 			if ((n = imsg_get(ibuf, &imsg)) == -1)
384 				fatalx("imsg_get error");
385 			if (n == 0)
386 				break;
387 			if (imsg.hdr.type != cmd)
388 				fatalx("invalid response");
389 
390 			IMSG_SIZE_CHECK(&imsg, (&cko));
391 			memcpy(&cko, imsg.data, sizeof(cko));
392 
393 			ret = cko.cko_tlen;
394 			if (ret > 0) {
395 				if (IMSG_DATA_SIZE(&imsg) !=
396 				    (sizeof(cko) + ret))
397 					fatalx("data size");
398 				toptr = (u_char *)imsg.data + sizeof(cko);
399 				memcpy(to, toptr, ret);
400 			}
401 			done = 1;
402 
403 			imsg_free(&imsg);
404 		}
405 	}
406 	imsg_event_add(iev);
407 
408 	return (ret);
409 }
410 
411 int
412 rsae_pub_enc(int flen,const u_char *from, u_char *to, RSA *rsa,int padding)
413 {
414 	DPRINTF("%s:%d", __func__, __LINE__);
415 	return (rsa_default->rsa_pub_enc(flen, from, to, rsa, padding));
416 }
417 
418 int
419 rsae_pub_dec(int flen,const u_char *from, u_char *to, RSA *rsa,int padding)
420 {
421 	DPRINTF("%s:%d", __func__, __LINE__);
422 	return (rsa_default->rsa_pub_dec(flen, from, to, rsa, padding));
423 }
424 
425 int
426 rsae_priv_enc(int flen, const u_char *from, u_char *to, RSA *rsa, int padding)
427 {
428 	DPRINTF("%s:%d", __func__, __LINE__);
429 	return (rsae_send_imsg(flen, from, to, rsa, padding,
430 	    IMSG_CA_PRIVENC));
431 }
432 
433 int
434 rsae_priv_dec(int flen, const u_char *from, u_char *to, RSA *rsa, int padding)
435 {
436 	DPRINTF("%s:%d", __func__, __LINE__);
437 	return (rsae_send_imsg(flen, from, to, rsa, padding,
438 	    IMSG_CA_PRIVDEC));
439 }
440 
441 int
442 rsae_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
443 {
444 	DPRINTF("%s:%d", __func__, __LINE__);
445 	return (rsa_default->rsa_mod_exp(r0, I, rsa, ctx));
446 }
447 
448 int
449 rsae_bn_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
450     const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
451 {
452 	DPRINTF("%s:%d", __func__, __LINE__);
453 	return (rsa_default->bn_mod_exp(r, a, p, m, ctx, m_ctx));
454 }
455 
456 int
457 rsae_init(RSA *rsa)
458 {
459 	DPRINTF("%s:%d", __func__, __LINE__);
460 	if (rsa_default->init == NULL)
461 		return (1);
462 	return (rsa_default->init(rsa));
463 }
464 
465 int
466 rsae_finish(RSA *rsa)
467 {
468 	DPRINTF("%s:%d", __func__, __LINE__);
469 	if (rsa_default->finish == NULL)
470 		return (1);
471 	return (rsa_default->finish(rsa));
472 }
473 
474 int
475 rsae_sign(int type, const u_char *m, u_int m_length, u_char *sigret,
476     u_int *siglen, const RSA *rsa)
477 {
478 	DPRINTF("%s:%d", __func__, __LINE__);
479 	return (rsa_default->rsa_sign(type, m, m_length,
480 	    sigret, siglen, rsa));
481 }
482 
483 int
484 rsae_verify(int dtype, const u_char *m, u_int m_length, const u_char *sigbuf,
485     u_int siglen, const RSA *rsa)
486 {
487 	DPRINTF("%s:%d", __func__, __LINE__);
488 	return (rsa_default->rsa_verify(dtype, m, m_length,
489 	    sigbuf, siglen, rsa));
490 }
491 
492 int
493 rsae_keygen(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb)
494 {
495 	DPRINTF("%s:%d", __func__, __LINE__);
496 	return (rsa_default->rsa_keygen(rsa, bits, e, cb));
497 }
498 
499 void
500 ca_engine_init(struct relayd *x_env)
501 {
502 	ENGINE		*e = NULL;
503 	const char	*errstr, *name;
504 
505 	if (env == NULL)
506 		env = x_env;
507 
508 	if (rsa_default != NULL)
509 		return;
510 
511 	if ((e = ENGINE_get_default_RSA()) == NULL) {
512 		if ((e = ENGINE_new()) == NULL) {
513 			errstr = "ENGINE_new";
514 			goto fail;
515 		}
516 		if (!ENGINE_set_name(e, rsae_method.name)) {
517 			errstr = "ENGINE_set_name";
518 			goto fail;
519 		}
520 		if ((rsa_default = RSA_get_default_method()) == NULL) {
521 			errstr = "RSA_get_default_method";
522 			goto fail;
523 		}
524 	} else if ((rsa_default = ENGINE_get_RSA(e)) == NULL) {
525 		errstr = "ENGINE_get_RSA";
526 		goto fail;
527 	}
528 
529 	if ((name = ENGINE_get_name(e)) == NULL)
530 		name = "unknown RSA engine";
531 
532 	log_debug("%s: using %s", __func__, name);
533 
534 	if (rsa_default->flags & RSA_FLAG_SIGN_VER)
535 		fatalx("unsupported RSA engine");
536 
537 	if (rsa_default->rsa_mod_exp == NULL)
538 		rsae_method.rsa_mod_exp = NULL;
539 	if (rsa_default->bn_mod_exp == NULL)
540 		rsae_method.bn_mod_exp = NULL;
541 	if (rsa_default->rsa_keygen == NULL)
542 		rsae_method.rsa_keygen = NULL;
543 	rsae_method.flags = rsa_default->flags |
544 	    RSA_METHOD_FLAG_NO_CHECK;
545 	rsae_method.app_data = rsa_default->app_data;
546 
547 	if (!ENGINE_set_RSA(e, &rsae_method)) {
548 		errstr = "ENGINE_set_RSA";
549 		goto fail;
550 	}
551 	if (!ENGINE_set_default_RSA(e)) {
552 		errstr = "ENGINE_set_default_RSA";
553 		goto fail;
554 	}
555 
556 	return;
557 
558  fail:
559 	fatalx("%s: %s", __func__, errstr);
560 }
561