xref: /openbsd-src/usr.sbin/smtpd/ca.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1 /*	$OpenBSD: ca.c,v 1.25 2016/09/08 12:06:43 eric Exp $	*/
2 
3 /*
4  * Copyright (c) 2014 Reyk Floeter <reyk@openbsd.org>
5  * Copyright (c) 2012 Gilles Chehade <gilles@poolp.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/types.h>
21 #include <sys/queue.h>
22 #include <sys/socket.h>
23 #include <sys/tree.h>
24 
25 #include <err.h>
26 #include <imsg.h>
27 #include <limits.h>
28 #include <pwd.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33 
34 #include <openssl/ssl.h>
35 #include <openssl/pem.h>
36 #include <openssl/evp.h>
37 #include <openssl/rsa.h>
38 #include <openssl/engine.h>
39 #include <openssl/err.h>
40 
41 #include "smtpd.h"
42 #include "log.h"
43 #include "ssl.h"
44 
45 static int	 ca_verify_cb(int, X509_STORE_CTX *);
46 
47 static int	 rsae_send_imsg(int, const unsigned char *, unsigned char *,
48 		    RSA *, int, unsigned int);
49 static int	 rsae_pub_enc(int, const unsigned char *, unsigned char *,
50 		    RSA *, int);
51 static int	 rsae_pub_dec(int,const unsigned char *, unsigned char *,
52 		    RSA *, int);
53 static int	 rsae_priv_enc(int, const unsigned char *, unsigned char *,
54 		    RSA *, int);
55 static int	 rsae_priv_dec(int, const unsigned char *, unsigned char *,
56 		    RSA *, int);
57 static int	 rsae_mod_exp(BIGNUM *, const BIGNUM *, RSA *, BN_CTX *);
58 static int	 rsae_bn_mod_exp(BIGNUM *, const BIGNUM *, const BIGNUM *,
59 		    const BIGNUM *, BN_CTX *, BN_MONT_CTX *);
60 static int	 rsae_init(RSA *);
61 static int	 rsae_finish(RSA *);
62 static int	 rsae_keygen(RSA *, int, BIGNUM *, BN_GENCB *);
63 
64 static uint64_t	 rsae_reqid = 0;
65 
66 static void
67 ca_shutdown(void)
68 {
69 	log_debug("debug: ca agent exiting");
70 	_exit(0);
71 }
72 
73 int
74 ca(void)
75 {
76 	struct passwd	*pw;
77 
78 	purge_config(PURGE_LISTENERS|PURGE_TABLES|PURGE_RULES);
79 
80 	if ((pw = getpwnam(SMTPD_USER)) == NULL)
81 		fatalx("unknown user " SMTPD_USER);
82 
83 	if (chroot(PATH_CHROOT) == -1)
84 		fatal("ca: chroot");
85 	if (chdir("/") == -1)
86 		fatal("ca: chdir(\"/\")");
87 
88 	config_process(PROC_CA);
89 
90 	if (setgroups(1, &pw->pw_gid) ||
91 	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
92 	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
93 		fatal("ca: cannot drop privileges");
94 
95 	imsg_callback = ca_imsg;
96 	event_init();
97 
98 	signal(SIGINT, SIG_IGN);
99 	signal(SIGTERM, SIG_IGN);
100 	signal(SIGPIPE, SIG_IGN);
101 	signal(SIGHUP, SIG_IGN);
102 
103 	config_peer(PROC_CONTROL);
104 	config_peer(PROC_PARENT);
105 	config_peer(PROC_PONY);
106 
107 	/* Ignore them until we get our config */
108 	mproc_disable(p_pony);
109 
110 	if (pledge("stdio", NULL) == -1)
111 		err(1, "pledge");
112 
113 	event_dispatch();
114 	fatalx("exited event loop");
115 
116 	return (0);
117 }
118 
119 void
120 ca_init(void)
121 {
122 	BIO		*in = NULL;
123 	EVP_PKEY	*pkey = NULL;
124 	struct pki	*pki;
125 	const char	*k;
126 	void		*iter_dict;
127 
128 	log_debug("debug: init private ssl-tree");
129 	iter_dict = NULL;
130 	while (dict_iter(env->sc_pki_dict, &iter_dict, &k, (void **)&pki)) {
131 		if (pki->pki_key == NULL)
132 			continue;
133 
134 		if ((in = BIO_new_mem_buf(pki->pki_key,
135 		    pki->pki_key_len)) == NULL)
136 			fatalx("ca_launch: key");
137 
138 		if ((pkey = PEM_read_bio_PrivateKey(in,
139 		    NULL, NULL, NULL)) == NULL)
140 			fatalx("ca_launch: PEM");
141 		BIO_free(in);
142 
143 		pki->pki_pkey = pkey;
144 
145 		explicit_bzero(pki->pki_key, pki->pki_key_len);
146 		free(pki->pki_key);
147 		pki->pki_key = NULL;
148 	}
149 }
150 
151 static int
152 ca_verify_cb(int ok, X509_STORE_CTX *ctx)
153 {
154 	switch (X509_STORE_CTX_get_error(ctx)) {
155 	case X509_V_OK:
156 		break;
157         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
158 		break;
159         case X509_V_ERR_CERT_NOT_YET_VALID:
160         case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
161 		break;
162         case X509_V_ERR_CERT_HAS_EXPIRED:
163         case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
164 		break;
165         case X509_V_ERR_NO_EXPLICIT_POLICY:
166 		break;
167 	}
168 	return ok;
169 }
170 
171 int
172 ca_X509_verify(void *certificate, void *chain, const char *CAfile,
173     const char *CRLfile, const char **errstr)
174 {
175 	X509_STORE     *store = NULL;
176 	X509_STORE_CTX *xsc = NULL;
177 	int		ret = 0;
178 
179 	if ((store = X509_STORE_new()) == NULL)
180 		goto end;
181 
182 	if (!X509_STORE_load_locations(store, CAfile, NULL)) {
183 		log_warn("warn: unable to load CA file %s", CAfile);
184 		goto end;
185 	}
186 	X509_STORE_set_default_paths(store);
187 
188 	if ((xsc = X509_STORE_CTX_new()) == NULL)
189 		goto end;
190 
191 	if (X509_STORE_CTX_init(xsc, store, certificate, chain) != 1)
192 		goto end;
193 
194 	X509_STORE_CTX_set_verify_cb(xsc, ca_verify_cb);
195 
196 	ret = X509_verify_cert(xsc);
197 
198 end:
199 	*errstr = NULL;
200 	if (ret != 1) {
201 		if (xsc)
202 			*errstr = X509_verify_cert_error_string(xsc->error);
203 		else if (ERR_peek_last_error())
204 			*errstr = ERR_error_string(ERR_peek_last_error(), NULL);
205 	}
206 
207 	if (xsc)
208 		X509_STORE_CTX_free(xsc);
209 	if (store)
210 		X509_STORE_free(store);
211 
212 	return ret > 0 ? 1 : 0;
213 }
214 
215 void
216 ca_imsg(struct mproc *p, struct imsg *imsg)
217 {
218 	RSA			*rsa;
219 	const void		*from = NULL;
220 	unsigned char		*to = NULL;
221 	struct msg		 m;
222 	const char		*pkiname;
223 	size_t			 flen, tlen, padding;
224 	struct pki		*pki;
225 	int			 ret = 0;
226 	uint64_t		 id;
227 	int			 v;
228 
229 	if (imsg == NULL)
230 		ca_shutdown();
231 
232 	if (p->proc == PROC_PARENT) {
233 		switch (imsg->hdr.type) {
234 		case IMSG_CONF_START:
235 			return;
236 		case IMSG_CONF_END:
237 			ca_init();
238 
239 			/* Start fulfilling requests */
240 			mproc_enable(p_pony);
241 			return;
242 		}
243 	}
244 
245 	if (p->proc == PROC_CONTROL) {
246 		switch (imsg->hdr.type) {
247 		case IMSG_CTL_VERBOSE:
248 			m_msg(&m, imsg);
249 			m_get_int(&m, &v);
250 			m_end(&m);
251 			log_verbose(v);
252 			return;
253 		case IMSG_CTL_PROFILE:
254 			m_msg(&m, imsg);
255 			m_get_int(&m, &v);
256 			m_end(&m);
257 			profiling = v;
258 			return;
259 		}
260 	}
261 
262 	if (p->proc == PROC_PONY) {
263 		switch (imsg->hdr.type) {
264 		case IMSG_CA_PRIVENC:
265 		case IMSG_CA_PRIVDEC:
266 			m_msg(&m, imsg);
267 			m_get_id(&m, &id);
268 			m_get_string(&m, &pkiname);
269 			m_get_data(&m, &from, &flen);
270 			m_get_size(&m, &tlen);
271 			m_get_size(&m, &padding);
272 			m_end(&m);
273 
274 			pki = dict_get(env->sc_pki_dict, pkiname);
275 			if (pki == NULL || pki->pki_pkey == NULL ||
276 			    (rsa = EVP_PKEY_get1_RSA(pki->pki_pkey)) == NULL)
277 				fatalx("ca_imsg: invalid pki");
278 
279 			if ((to = calloc(1, tlen)) == NULL)
280 				fatalx("ca_imsg: calloc");
281 
282 			switch (imsg->hdr.type) {
283 			case IMSG_CA_PRIVENC:
284 				ret = RSA_private_encrypt(flen, from, to, rsa,
285 				    padding);
286 				break;
287 			case IMSG_CA_PRIVDEC:
288 				ret = RSA_private_decrypt(flen, from, to, rsa,
289 				    padding);
290 				break;
291 			}
292 
293 			m_create(p, imsg->hdr.type, 0, 0, -1);
294 			m_add_id(p, id);
295 			m_add_int(p, ret);
296 			if (ret > 0)
297 				m_add_data(p, to, (size_t)ret);
298 			m_close(p);
299 
300 			free(to);
301 			RSA_free(rsa);
302 
303 			return;
304 		}
305 	}
306 
307 	errx(1, "ca_imsg: unexpected %s imsg", imsg_to_str(imsg->hdr.type));
308 }
309 
310 /*
311  * RSA privsep engine (called from unprivileged processes)
312  */
313 
314 const RSA_METHOD *rsa_default = NULL;
315 
316 static RSA_METHOD rsae_method = {
317 	"RSA privsep engine",
318 	rsae_pub_enc,
319 	rsae_pub_dec,
320 	rsae_priv_enc,
321 	rsae_priv_dec,
322 	rsae_mod_exp,
323 	rsae_bn_mod_exp,
324 	rsae_init,
325 	rsae_finish,
326 	0,
327 	NULL,
328 	NULL,
329 	NULL,
330 	rsae_keygen
331 };
332 
333 static int
334 rsae_send_imsg(int flen, const unsigned char *from, unsigned char *to,
335     RSA *rsa, int padding, unsigned int cmd)
336 {
337 	int		 ret = 0;
338 	struct imsgbuf	*ibuf;
339 	struct imsg	 imsg;
340 	int		 n, done = 0;
341 	const void	*toptr;
342 	char		*pkiname;
343 	size_t		 tlen;
344 	struct msg	 m;
345 	uint64_t	 id;
346 
347 	if ((pkiname = RSA_get_ex_data(rsa, 0)) == NULL)
348 		return (0);
349 
350 	/*
351 	 * Send a synchronous imsg because we cannot defer the RSA
352 	 * operation in OpenSSL's engine layer.
353 	 */
354 	m_create(p_ca, cmd, 0, 0, -1);
355 	rsae_reqid++;
356 	m_add_id(p_ca, rsae_reqid);
357 	m_add_string(p_ca, pkiname);
358 	m_add_data(p_ca, (const void *)from, (size_t)flen);
359 	m_add_size(p_ca, (size_t)RSA_size(rsa));
360 	m_add_size(p_ca, (size_t)padding);
361 	m_flush(p_ca);
362 
363 	ibuf = &p_ca->imsgbuf;
364 
365 	while (!done) {
366 		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
367 			fatalx("imsg_read");
368 		if (n == 0)
369 			fatalx("pipe closed");
370 
371 		while (!done) {
372 			if ((n = imsg_get(ibuf, &imsg)) == -1)
373 				fatalx("imsg_get error");
374 			if (n == 0)
375 				break;
376 
377 			log_imsg(PROC_PONY, PROC_CA, &imsg);
378 
379 			switch (imsg.hdr.type) {
380 			case IMSG_CA_PRIVENC:
381 			case IMSG_CA_PRIVDEC:
382 				break;
383 			default:
384 				/* Another imsg is queued up in the buffer */
385 				pony_imsg(p_ca, &imsg);
386 				imsg_free(&imsg);
387 				continue;
388 			}
389 
390 			m_msg(&m, &imsg);
391 			m_get_id(&m, &id);
392 			if (id != rsae_reqid)
393 				fatalx("invalid response id");
394 			m_get_int(&m, &ret);
395 			if (ret > 0)
396 				m_get_data(&m, &toptr, &tlen);
397 			m_end(&m);
398 
399 			if (ret > 0)
400 				memcpy(to, toptr, tlen);
401 			done = 1;
402 
403 			imsg_free(&imsg);
404 		}
405 	}
406 	mproc_event_add(p_ca);
407 
408 	return (ret);
409 }
410 
411 static int
412 rsae_pub_enc(int flen,const unsigned char *from, unsigned char *to, RSA *rsa,
413     int padding)
414 {
415 	log_debug("debug: %s: %s", proc_name(smtpd_process), __func__);
416 	return (rsa_default->rsa_pub_enc(flen, from, to, rsa, padding));
417 }
418 
419 static int
420 rsae_pub_dec(int flen,const unsigned char *from, unsigned char *to, RSA *rsa,
421     int padding)
422 {
423 	log_debug("debug: %s: %s", proc_name(smtpd_process), __func__);
424 	return (rsa_default->rsa_pub_dec(flen, from, to, rsa, padding));
425 }
426 
427 static int
428 rsae_priv_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa,
429     int padding)
430 {
431 	log_debug("debug: %s: %s", proc_name(smtpd_process), __func__);
432 	if (RSA_get_ex_data(rsa, 0) != NULL) {
433 		return (rsae_send_imsg(flen, from, to, rsa, padding,
434 		    IMSG_CA_PRIVENC));
435 	}
436 	return (rsa_default->rsa_priv_enc(flen, from, to, rsa, padding));
437 }
438 
439 static int
440 rsae_priv_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa,
441     int padding)
442 {
443 	log_debug("debug: %s: %s", proc_name(smtpd_process), __func__);
444 	if (RSA_get_ex_data(rsa, 0) != NULL) {
445 		return (rsae_send_imsg(flen, from, to, rsa, padding,
446 		    IMSG_CA_PRIVDEC));
447 	}
448 	return (rsa_default->rsa_priv_dec(flen, from, to, rsa, padding));
449 }
450 
451 static int
452 rsae_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
453 {
454 	log_debug("debug: %s: %s", proc_name(smtpd_process), __func__);
455 	return (rsa_default->rsa_mod_exp(r0, I, rsa, ctx));
456 }
457 
458 static int
459 rsae_bn_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
460     const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
461 {
462 	log_debug("debug: %s: %s", proc_name(smtpd_process), __func__);
463 	return (rsa_default->bn_mod_exp(r, a, p, m, ctx, m_ctx));
464 }
465 
466 static int
467 rsae_init(RSA *rsa)
468 {
469 	log_debug("debug: %s: %s", proc_name(smtpd_process), __func__);
470 	if (rsa_default->init == NULL)
471 		return (1);
472 	return (rsa_default->init(rsa));
473 }
474 
475 static int
476 rsae_finish(RSA *rsa)
477 {
478 	log_debug("debug: %s: %s", proc_name(smtpd_process), __func__);
479 	if (rsa_default->finish == NULL)
480 		return (1);
481 	return (rsa_default->finish(rsa));
482 }
483 
484 static int
485 rsae_keygen(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb)
486 {
487 	log_debug("debug: %s: %s", proc_name(smtpd_process), __func__);
488 	return (rsa_default->rsa_keygen(rsa, bits, e, cb));
489 }
490 
491 void
492 ca_engine_init(void)
493 {
494 	ENGINE		*e;
495 	const char	*errstr, *name;
496 
497 	if ((e = ENGINE_get_default_RSA()) == NULL) {
498 		if ((e = ENGINE_new()) == NULL) {
499 			errstr = "ENGINE_new";
500 			goto fail;
501 		}
502 		if (!ENGINE_set_name(e, rsae_method.name)) {
503 			errstr = "ENGINE_set_name";
504 			goto fail;
505 		}
506 		if ((rsa_default = RSA_get_default_method()) == NULL) {
507 			errstr = "RSA_get_default_method";
508 			goto fail;
509 		}
510 	} else if ((rsa_default = ENGINE_get_RSA(e)) == NULL) {
511 		errstr = "ENGINE_get_RSA";
512 		goto fail;
513 	}
514 
515 	if ((name = ENGINE_get_name(e)) == NULL)
516 		name = "unknown RSA engine";
517 
518 	log_debug("debug: %s: using %s", __func__, name);
519 
520 	if (rsa_default->flags & RSA_FLAG_SIGN_VER)
521 		fatalx("unsupported RSA engine");
522 
523 	if (rsa_default->rsa_mod_exp == NULL)
524 		rsae_method.rsa_mod_exp = NULL;
525 	if (rsa_default->bn_mod_exp == NULL)
526 		rsae_method.bn_mod_exp = NULL;
527 	if (rsa_default->rsa_keygen == NULL)
528 		rsae_method.rsa_keygen = NULL;
529 	rsae_method.flags = rsa_default->flags |
530 	    RSA_METHOD_FLAG_NO_CHECK;
531 	rsae_method.app_data = rsa_default->app_data;
532 
533 	if (!ENGINE_set_RSA(e, &rsae_method)) {
534 		errstr = "ENGINE_set_RSA";
535 		goto fail;
536 	}
537 	if (!ENGINE_set_default_RSA(e)) {
538 		errstr = "ENGINE_set_default_RSA";
539 		goto fail;
540 	}
541 
542 	return;
543 
544  fail:
545 	ssl_error(errstr);
546 	fatalx("%s", errstr);
547 }
548