aboutsummaryrefslogtreecommitdiffstats
path: root/smtpd/cert.c
blob: 05aff4181b18d0f2a706acc0689e9ff90b61d0d4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/*	$OpenBSD: cert.c,v 1.2 2018/12/11 07:25:57 eric Exp $	*/

/*
 * Copyright (c) 2018 Eric Faurot <eric@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/tree.h>
#include <sys/queue.h>
#include <netinet/in.h>

#include <imsg.h>
#include <limits.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <stdio.h>
#include <string.h>

#include "log.h"
#include "smtpd.h"
#include "ssl.h"

#define p_cert p_lka

struct request {
	SPLAY_ENTRY(request)	 entry;
	uint32_t		 id;
	void			(*cb_get_certificate)(void *, int, const char *,
				    const void *, size_t);
	void			(*cb_verify)(void *, int);
	void			*arg;
};

#define MAX_CERTS	16
#define MAX_CERT_LEN	(MAX_IMSGSIZE - (IMSG_HEADER_SIZE + sizeof(size_t)))

struct session {
	SPLAY_ENTRY(session)	 entry;
	uint32_t		 id;
	struct mproc		*proc;
	char			*cert[MAX_CERTS];
	size_t			 cert_len[MAX_CERTS];
	int			 cert_count;
};

SPLAY_HEAD(cert_reqtree, request);
SPLAY_HEAD(cert_sestree, session);

static int request_cmp(struct request *, struct request *);
static int session_cmp(struct session *, struct session *);
SPLAY_PROTOTYPE(cert_reqtree, request, entry, request_cmp);
SPLAY_PROTOTYPE(cert_sestree, session, entry, session_cmp);

static void cert_do_verify(struct session *, const char *, int);
static int cert_X509_verify(struct session *, const char *, const char *);

static struct cert_reqtree reqs = SPLAY_INITIALIZER(&reqs);
static struct cert_sestree sess = SPLAY_INITIALIZER(&sess);

int
cert_init(const char *name, int fallback, void (*cb)(void *, int,
    const char *, const void *, size_t), void *arg)
{
	struct request *req;

	req = calloc(1, sizeof(*req));
	if (req ==  NULL) {
		cb(arg, CA_FAIL, NULL, NULL, 0);
		return 0;
	}
	while (req->id == 0 || SPLAY_FIND(cert_reqtree, &reqs, req))
		req->id = arc4random();
	req->cb_get_certificate = cb;
	req->arg = arg;
	SPLAY_INSERT(cert_reqtree, &reqs, req);

	m_create(p_cert, IMSG_CERT_INIT, req->id, 0, -1);
	m_add_string(p_cert, name);
	m_add_int(p_cert, fallback);
	m_close(p_cert);

	return 1;
}

int
cert_verify(const void *ssl, const char *name, int fallback,
    void (*cb)(void *, int), void *arg)
{
	struct request	       *req;
	X509		       *x;
	STACK_OF(X509)	       *xchain;
	unsigned char	       *cert_der[MAX_CERTS];
	int			cert_len[MAX_CERTS];
	int			i, cert_count, ret;

	x = SSL_get_peer_certificate(ssl);
	if (x == NULL) {
		cb(arg, CERT_NOCERT);
		return 0;
	}

	ret = 0;
	memset(cert_der, 0, sizeof(cert_der));

	req = calloc(1, sizeof(*req));
	if (req ==  NULL)
		goto end;
	while (req->id == 0 || SPLAY_FIND(cert_reqtree, &reqs, req))
		req->id = arc4random();
	req->cb_verify = cb;
	req->arg = arg;
	SPLAY_INSERT(cert_reqtree, &reqs, req);

	cert_count = 1;
	if ((xchain = SSL_get_peer_cert_chain(ssl))) {
		cert_count += sk_X509_num(xchain);
		if (cert_count > MAX_CERTS) {
			log_warnx("warn: certificate chain too long");
			goto end;
		}
	}

	for (i = 0; i < cert_count; ++i) {
		if (i != 0) {
			if ((x = sk_X509_value(xchain, i - 1)) == NULL) {
				log_warnx("warn: failed to retrieve certificate");
				goto end;
			}
		}

		cert_len[i] = i2d_X509(x, &cert_der[i]);
		if (i == 0)
			X509_free(x);

		if (cert_len[i] < 0) {
			log_warnx("warn: failed to encode certificate");
			goto end;
		}

		log_debug("debug: certificate %i: len=%d", i, cert_len[i]);
		if (cert_len[i] > (int)MAX_CERT_LEN) {
			log_warnx("warn: certificate too long");
			goto end;
		}
	}

	/* Send the cert chain, one cert at a time */
	for (i = 0; i < cert_count; ++i) {
		m_create(p_cert, IMSG_CERT_CERTIFICATE, req->id, 0, -1);
		m_add_data(p_cert, cert_der[i], cert_len[i]);
		m_close(p_cert);
	}

	/* Tell lookup process that it can start verifying, we're done */
	m_create(p_cert, IMSG_CERT_VERIFY, req->id, 0, -1);
	m_add_string(p_cert, name);
	m_add_int(p_cert, fallback);
	m_close(p_cert);

	ret = 1;

    end:
	for (i = 0; i < MAX_CERTS; ++i)
		free(cert_der[i]);

	if (ret == 0) {
		if (req)
			SPLAY_REMOVE(cert_reqtree, &reqs, req);
		free(req);
		cb(arg, CERT_ERROR);
	}

	return ret;
}


void
cert_dispatch_request(struct mproc *proc, struct imsg *imsg)
{
	struct pki *pki;
	struct session key, *s;
	const char *name;
	const void *data;
	size_t datalen;
	struct msg m;
	uint32_t reqid;
	char buf[LINE_MAX];
	int fallback;

	reqid = imsg->hdr.peerid;
	m_msg(&m, imsg);

	switch (imsg->hdr.type) {

	case IMSG_CERT_INIT:
		m_get_string(&m, &name);
		m_get_int(&m, &fallback);
		m_end(&m);

		xlowercase(buf, name, sizeof(buf));
		log_debug("debug: looking up pki \"%s\"", buf);
		pki = dict_get(env->sc_pki_dict, buf);
		if (pki == NULL && fallback)
			pki = dict_get(env->sc_pki_dict, "*");

		m_create(proc, IMSG_CERT_INIT, reqid, 0, -1);
		if (pki) {
			m_add_int(proc, CA_OK);
			m_add_string(proc, pki->pki_name);
			m_add_data(proc, pki->pki_cert, pki->pki_cert_len);
		} else {
			m_add_int(proc, CA_FAIL);
			m_add_string(proc, NULL);
			m_add_data(proc, NULL, 0);
		}
		m_close(proc);
		return;

	case IMSG_CERT_CERTIFICATE:
		m_get_data(&m, &data, &datalen);
		m_end(&m);

		key.id = reqid;
		key.proc = proc;
		s = SPLAY_FIND(cert_sestree, &sess, &key);
		if (s == NULL) {
			s = calloc(1, sizeof(*s));
			s->proc = proc;
			s->id = reqid;
			SPLAY_INSERT(cert_sestree, &sess, s);
		}

		if (s->cert_count == MAX_CERTS)
			fatalx("%s: certificate chain too long", __func__);

		s->cert[s->cert_count] = xmemdup(data, datalen);
		s->cert_len[s->cert_count] = datalen;
		s->cert_count++;
		return;

	case IMSG_CERT_VERIFY:
		m_get_string(&m, &name);
		m_get_int(&m, &fallback);
		m_end(&m);

		key.id = reqid;
		key.proc = proc;
		s = SPLAY_FIND(cert_sestree, &sess, &key);
		if (s == NULL)
			fatalx("%s: no certificate", __func__);

		SPLAY_REMOVE(cert_sestree, &sess, s);
		cert_do_verify(s, name, fallback);
		return;

	default:
		fatalx("%s: %s", __func__, imsg_to_str(imsg->hdr.type));
	}
}

void
cert_dispatch_result(struct mproc *proc, struct imsg *imsg)
{
	struct request key, *req;
	struct msg m;
	const void *cert;
	const char *name;
	size_t cert_len;
	int res;

	key.id = imsg->hdr.peerid;
	req = SPLAY_FIND(cert_reqtree, &reqs, &key);
	if (req == NULL)
		fatalx("%s: unknown request %08x", __func__, imsg->hdr.peerid);

	m_msg(&m, imsg);

	switch (imsg->hdr.type) {

	case IMSG_CERT_INIT:
		m_get_int(&m, &res);
		m_get_string(&m, &name);
		m_get_data(&m, &cert, &cert_len);
		m_end(&m);
		SPLAY_REMOVE(cert_reqtree, &reqs, req);
		req->cb_get_certificate(req->arg, res, name, cert, cert_len);
		free(req);
		break;

	case IMSG_CERT_VERIFY:
		m_get_int(&m, &res);
		m_end(&m);
		SPLAY_REMOVE(cert_reqtree, &reqs, req);
		req->cb_verify(req->arg, res);
		free(req);
		break;
	}
}

static void
cert_do_verify(struct session *s, const char *name, int fallback)
{
	struct ca *ca;
	const char *cafile;
	int i, res;

	ca = dict_get(env->sc_ca_dict, name);
	if (ca == NULL)
		if (fallback)
			ca = dict_get(env->sc_ca_dict, "*");
	cafile = ca ? ca->ca_cert_file : CA_FILE;

	if (ca == NULL && !fallback)
		res = CERT_NOCA;
	else if (!cert_X509_verify(s, cafile, NULL))
		res = CERT_INVALID;
	else
		res = CERT_OK;

	for (i = 0; i < s->cert_count; ++i)
		free(s->cert[i]);

	m_create(s->proc, IMSG_CERT_VERIFY, s->id, 0, -1);
	m_add_int(s->proc, res);
	m_close(s->proc);

	free(s);
}

static int
cert_X509_verify(struct session *s, const char *CAfile,
    const char *CRLfile)
{
	X509			*x509;
	X509			*x509_tmp;
	STACK_OF(X509)		*x509_chain;
	const unsigned char    	*d2i;
	int			i, ret = 0;
	const char		*errstr;

	x509 = NULL;
	x509_tmp = NULL;
	x509_chain = NULL;

	d2i = s->cert[0];
	if (d2i_X509(&x509, &d2i, s->cert_len[0]) == NULL) {
		x509 = NULL;
		goto end;
	}

	if (s->cert_count > 1) {
		x509_chain = sk_X509_new_null();
		for (i = 1; i < s->cert_count; ++i) {
			d2i = s->cert[i];
			if (d2i_X509(&x509_tmp, &d2i, s->cert_len[i]) == NULL)
				goto end;
			sk_X509_insert(x509_chain, x509_tmp, i);
			x509_tmp = NULL;
		}
	}
	if (!ca_X509_verify(x509, x509_chain, CAfile, NULL, &errstr))
		log_debug("debug: X509 verify: %s", errstr);
	else
		ret = 1;

end:
	X509_free(x509);
	X509_free(x509_tmp);
	if (x509_chain)
		sk_X509_pop_free(x509_chain, X509_free);

	return ret;
}

static int
request_cmp(struct request *a, struct request *b)
{
	if (a->id < b->id)
		return -1;
	if (a->id > b->id)
		return 1;
	return 0;
}

SPLAY_GENERATE(cert_reqtree, request, entry, request_cmp);

static int
session_cmp(struct session *a, struct session *b)
{
	if (a->id < b->id)
		return -1;
	if (a->id > b->id)
		return 1;
	if (a->proc < b->proc)
		return -1;
	if (a->proc > b->proc)
		return 1;
	return 0;
}

SPLAY_GENERATE(cert_sestree, session, entry, session_cmp);