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