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