ca.c revision 1.29
1/*	$OpenBSD: ca.c,v 1.29 2018/05/24 11:38:24 gilles 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
45static int	 ca_verify_cb(int, X509_STORE_CTX *);
46
47static int	 rsae_send_imsg(int, const unsigned char *, unsigned char *,
48		    RSA *, int, unsigned int);
49static int	 rsae_pub_enc(int, const unsigned char *, unsigned char *,
50		    RSA *, int);
51static int	 rsae_pub_dec(int,const unsigned char *, unsigned char *,
52		    RSA *, int);
53static int	 rsae_priv_enc(int, const unsigned char *, unsigned char *,
54		    RSA *, int);
55static int	 rsae_priv_dec(int, const unsigned char *, unsigned char *,
56		    RSA *, int);
57static int	 rsae_mod_exp(BIGNUM *, const BIGNUM *, RSA *, BN_CTX *);
58static int	 rsae_bn_mod_exp(BIGNUM *, const BIGNUM *, const BIGNUM *,
59		    const BIGNUM *, BN_CTX *, BN_MONT_CTX *);
60static int	 rsae_init(RSA *);
61static int	 rsae_finish(RSA *);
62static int	 rsae_keygen(RSA *, int, BIGNUM *, BN_GENCB *);
63
64static uint64_t	 rsae_reqid = 0;
65
66static void
67ca_shutdown(void)
68{
69	log_debug("debug: ca agent exiting");
70	_exit(0);
71}
72
73int
74ca(void)
75{
76	struct passwd	*pw;
77
78	purge_config(PURGE_LISTENERS|PURGE_TABLES|PURGE_RULES|PURGE_DISPATCHERS);
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
119void
120ca_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		freezero(pki->pki_key, pki->pki_key_len);
146		pki->pki_key = NULL;
147	}
148}
149
150static int
151ca_verify_cb(int ok, X509_STORE_CTX *ctx)
152{
153	switch (X509_STORE_CTX_get_error(ctx)) {
154	case X509_V_OK:
155		break;
156        case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
157		break;
158        case X509_V_ERR_CERT_NOT_YET_VALID:
159        case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
160		break;
161        case X509_V_ERR_CERT_HAS_EXPIRED:
162        case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
163		break;
164        case X509_V_ERR_NO_EXPLICIT_POLICY:
165		break;
166	}
167	return ok;
168}
169
170int
171ca_X509_verify(void *certificate, void *chain, const char *CAfile,
172    const char *CRLfile, const char **errstr)
173{
174	X509_STORE     *store = NULL;
175	X509_STORE_CTX *xsc = NULL;
176	int		ret = 0;
177
178	if ((store = X509_STORE_new()) == NULL)
179		goto end;
180
181	if (!X509_STORE_load_locations(store, CAfile, NULL)) {
182		log_warn("warn: unable to load CA file %s", CAfile);
183		goto end;
184	}
185	X509_STORE_set_default_paths(store);
186
187	if ((xsc = X509_STORE_CTX_new()) == NULL)
188		goto end;
189
190	if (X509_STORE_CTX_init(xsc, store, certificate, chain) != 1)
191		goto end;
192
193	X509_STORE_CTX_set_verify_cb(xsc, ca_verify_cb);
194
195	ret = X509_verify_cert(xsc);
196
197end:
198	*errstr = NULL;
199	if (ret != 1) {
200		if (xsc)
201			*errstr = X509_verify_cert_error_string(xsc->error);
202		else if (ERR_peek_last_error())
203			*errstr = ERR_error_string(ERR_peek_last_error(), NULL);
204	}
205
206	X509_STORE_CTX_free(xsc);
207	X509_STORE_free(store);
208
209	return ret > 0 ? 1 : 0;
210}
211
212void
213ca_imsg(struct mproc *p, struct imsg *imsg)
214{
215	RSA			*rsa;
216	const void		*from = NULL;
217	unsigned char		*to = NULL;
218	struct msg		 m;
219	const char		*pkiname;
220	size_t			 flen, tlen, padding;
221	struct pki		*pki;
222	int			 ret = 0;
223	uint64_t		 id;
224	int			 v;
225
226	if (imsg == NULL)
227		ca_shutdown();
228
229	switch (imsg->hdr.type) {
230	case IMSG_CONF_START:
231		return;
232	case IMSG_CONF_END:
233		ca_init();
234
235		/* Start fulfilling requests */
236		mproc_enable(p_pony);
237		return;
238
239	case IMSG_CTL_VERBOSE:
240		m_msg(&m, imsg);
241		m_get_int(&m, &v);
242		m_end(&m);
243		log_trace_verbose(v);
244		return;
245
246	case IMSG_CTL_PROFILE:
247		m_msg(&m, imsg);
248		m_get_int(&m, &v);
249		m_end(&m);
250		profiling = v;
251		return;
252
253	case IMSG_CA_PRIVENC:
254	case IMSG_CA_PRIVDEC:
255		m_msg(&m, imsg);
256		m_get_id(&m, &id);
257		m_get_string(&m, &pkiname);
258		m_get_data(&m, &from, &flen);
259		m_get_size(&m, &tlen);
260		m_get_size(&m, &padding);
261		m_end(&m);
262
263		pki = dict_get(env->sc_pki_dict, pkiname);
264		if (pki == NULL || pki->pki_pkey == NULL ||
265		    (rsa = EVP_PKEY_get1_RSA(pki->pki_pkey)) == NULL)
266			fatalx("ca_imsg: invalid pki");
267
268		if ((to = calloc(1, tlen)) == NULL)
269			fatalx("ca_imsg: calloc");
270
271		switch (imsg->hdr.type) {
272		case IMSG_CA_PRIVENC:
273			ret = RSA_private_encrypt(flen, from, to, rsa,
274			    padding);
275			break;
276		case IMSG_CA_PRIVDEC:
277			ret = RSA_private_decrypt(flen, from, to, rsa,
278			    padding);
279			break;
280		}
281
282		m_create(p, imsg->hdr.type, 0, 0, -1);
283		m_add_id(p, id);
284		m_add_int(p, ret);
285		if (ret > 0)
286			m_add_data(p, to, (size_t)ret);
287		m_close(p);
288
289		free(to);
290		RSA_free(rsa);
291
292		return;
293	}
294
295	errx(1, "ca_imsg: unexpected %s imsg", imsg_to_str(imsg->hdr.type));
296}
297
298/*
299 * RSA privsep engine (called from unprivileged processes)
300 */
301
302const RSA_METHOD *rsa_default = NULL;
303
304static RSA_METHOD rsae_method = {
305	"RSA privsep engine",
306	rsae_pub_enc,
307	rsae_pub_dec,
308	rsae_priv_enc,
309	rsae_priv_dec,
310	rsae_mod_exp,
311	rsae_bn_mod_exp,
312	rsae_init,
313	rsae_finish,
314	0,
315	NULL,
316	NULL,
317	NULL,
318	rsae_keygen
319};
320
321static int
322rsae_send_imsg(int flen, const unsigned char *from, unsigned char *to,
323    RSA *rsa, int padding, unsigned int cmd)
324{
325	int		 ret = 0;
326	struct imsgbuf	*ibuf;
327	struct imsg	 imsg;
328	int		 n, done = 0;
329	const void	*toptr;
330	char		*pkiname;
331	size_t		 tlen;
332	struct msg	 m;
333	uint64_t	 id;
334
335	if ((pkiname = RSA_get_ex_data(rsa, 0)) == NULL)
336		return (0);
337
338	/*
339	 * Send a synchronous imsg because we cannot defer the RSA
340	 * operation in OpenSSL's engine layer.
341	 */
342	m_create(p_ca, cmd, 0, 0, -1);
343	rsae_reqid++;
344	m_add_id(p_ca, rsae_reqid);
345	m_add_string(p_ca, pkiname);
346	m_add_data(p_ca, (const void *)from, (size_t)flen);
347	m_add_size(p_ca, (size_t)RSA_size(rsa));
348	m_add_size(p_ca, (size_t)padding);
349	m_flush(p_ca);
350
351	ibuf = &p_ca->imsgbuf;
352
353	while (!done) {
354		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
355			fatalx("imsg_read");
356		if (n == 0)
357			fatalx("pipe closed");
358
359		while (!done) {
360			if ((n = imsg_get(ibuf, &imsg)) == -1)
361				fatalx("imsg_get error");
362			if (n == 0)
363				break;
364
365			log_imsg(PROC_PONY, PROC_CA, &imsg);
366
367			switch (imsg.hdr.type) {
368			case IMSG_CA_PRIVENC:
369			case IMSG_CA_PRIVDEC:
370				break;
371			default:
372				/* Another imsg is queued up in the buffer */
373				pony_imsg(p_ca, &imsg);
374				imsg_free(&imsg);
375				continue;
376			}
377
378			m_msg(&m, &imsg);
379			m_get_id(&m, &id);
380			if (id != rsae_reqid)
381				fatalx("invalid response id");
382			m_get_int(&m, &ret);
383			if (ret > 0)
384				m_get_data(&m, &toptr, &tlen);
385			m_end(&m);
386
387			if (ret > 0)
388				memcpy(to, toptr, tlen);
389			done = 1;
390
391			imsg_free(&imsg);
392		}
393	}
394	mproc_event_add(p_ca);
395
396	return (ret);
397}
398
399static int
400rsae_pub_enc(int flen,const unsigned char *from, unsigned char *to, RSA *rsa,
401    int padding)
402{
403	log_debug("debug: %s: %s", proc_name(smtpd_process), __func__);
404	return (rsa_default->rsa_pub_enc(flen, from, to, rsa, padding));
405}
406
407static int
408rsae_pub_dec(int flen,const unsigned char *from, unsigned char *to, RSA *rsa,
409    int padding)
410{
411	log_debug("debug: %s: %s", proc_name(smtpd_process), __func__);
412	return (rsa_default->rsa_pub_dec(flen, from, to, rsa, padding));
413}
414
415static int
416rsae_priv_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa,
417    int padding)
418{
419	log_debug("debug: %s: %s", proc_name(smtpd_process), __func__);
420	if (RSA_get_ex_data(rsa, 0) != NULL) {
421		return (rsae_send_imsg(flen, from, to, rsa, padding,
422		    IMSG_CA_PRIVENC));
423	}
424	return (rsa_default->rsa_priv_enc(flen, from, to, rsa, padding));
425}
426
427static int
428rsae_priv_dec(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_PRIVDEC));
435	}
436	return (rsa_default->rsa_priv_dec(flen, from, to, rsa, padding));
437}
438
439static int
440rsae_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
441{
442	log_debug("debug: %s: %s", proc_name(smtpd_process), __func__);
443	return (rsa_default->rsa_mod_exp(r0, I, rsa, ctx));
444}
445
446static int
447rsae_bn_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
448    const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
449{
450	log_debug("debug: %s: %s", proc_name(smtpd_process), __func__);
451	return (rsa_default->bn_mod_exp(r, a, p, m, ctx, m_ctx));
452}
453
454static int
455rsae_init(RSA *rsa)
456{
457	log_debug("debug: %s: %s", proc_name(smtpd_process), __func__);
458	if (rsa_default->init == NULL)
459		return (1);
460	return (rsa_default->init(rsa));
461}
462
463static int
464rsae_finish(RSA *rsa)
465{
466	log_debug("debug: %s: %s", proc_name(smtpd_process), __func__);
467	if (rsa_default->finish == NULL)
468		return (1);
469	return (rsa_default->finish(rsa));
470}
471
472static int
473rsae_keygen(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb)
474{
475	log_debug("debug: %s: %s", proc_name(smtpd_process), __func__);
476	return (rsa_default->rsa_keygen(rsa, bits, e, cb));
477}
478
479void
480ca_engine_init(void)
481{
482	ENGINE		*e;
483	const char	*errstr, *name;
484
485	if ((e = ENGINE_get_default_RSA()) == NULL) {
486		if ((e = ENGINE_new()) == NULL) {
487			errstr = "ENGINE_new";
488			goto fail;
489		}
490		if (!ENGINE_set_name(e, rsae_method.name)) {
491			errstr = "ENGINE_set_name";
492			goto fail;
493		}
494		if ((rsa_default = RSA_get_default_method()) == NULL) {
495			errstr = "RSA_get_default_method";
496			goto fail;
497		}
498	} else if ((rsa_default = ENGINE_get_RSA(e)) == NULL) {
499		errstr = "ENGINE_get_RSA";
500		goto fail;
501	}
502
503	if ((name = ENGINE_get_name(e)) == NULL)
504		name = "unknown RSA engine";
505
506	log_debug("debug: %s: using %s", __func__, name);
507
508	if (rsa_default->flags & RSA_FLAG_SIGN_VER)
509		fatalx("unsupported RSA engine");
510
511	if (rsa_default->rsa_mod_exp == NULL)
512		rsae_method.rsa_mod_exp = NULL;
513	if (rsa_default->bn_mod_exp == NULL)
514		rsae_method.bn_mod_exp = NULL;
515	if (rsa_default->rsa_keygen == NULL)
516		rsae_method.rsa_keygen = NULL;
517	rsae_method.flags = rsa_default->flags |
518	    RSA_METHOD_FLAG_NO_CHECK;
519	rsae_method.app_data = rsa_default->app_data;
520
521	if (!ENGINE_set_RSA(e, &rsae_method)) {
522		errstr = "ENGINE_set_RSA";
523		goto fail;
524	}
525	if (!ENGINE_set_default_RSA(e)) {
526		errstr = "ENGINE_set_default_RSA";
527		goto fail;
528	}
529
530	return;
531
532 fail:
533	ssl_error(errstr);
534	fatalx("%s", errstr);
535}
536