xref: /openbsd-src/usr.sbin/smtpd/ssl.c (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1 /*	$OpenBSD: ssl.c,v 1.69 2014/07/10 20:16:48 jsg Exp $	*/
2 
3 /*
4  * Copyright (c) 2008 Pierre-Yves Ritschard <pyr@openbsd.org>
5  * Copyright (c) 2008 Reyk Floeter <reyk@openbsd.org>
6  * Copyright (c) 2012 Gilles Chehade <gilles@poolp.org>
7  *
8  * Permission to use, copy, modify, and distribute this software for any
9  * purpose with or without fee is hereby granted, provided that the above
10  * copyright notice and this permission notice appear in all copies.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19  */
20 
21 #include <sys/types.h>
22 #include <sys/queue.h>
23 #include <sys/tree.h>
24 #include <sys/socket.h>
25 #include <sys/stat.h>
26 
27 #include <ctype.h>
28 #include <event.h>
29 #include <fcntl.h>
30 #include <imsg.h>
31 #include <limits.h>
32 #include <pwd.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 
38 #include <openssl/ssl.h>
39 #include <openssl/engine.h>
40 #include <openssl/err.h>
41 #include <openssl/rsa.h>
42 #include <openssl/dh.h>
43 #include <openssl/bn.h>
44 
45 #include "log.h"
46 #include "ssl.h"
47 
48 void
49 ssl_init(void)
50 {
51 	static int	inited = 0;
52 
53 	if (inited)
54 		return;
55 
56 	SSL_library_init();
57 	SSL_load_error_strings();
58 
59 	OpenSSL_add_all_algorithms();
60 
61 	/* Init hardware crypto engines. */
62 	ENGINE_load_builtin_engines();
63 	ENGINE_register_all_complete();
64 	inited = 1;
65 }
66 
67 int
68 ssl_setup(SSL_CTX **ctxp, struct pki *pki)
69 {
70 	DH	*dh;
71 	SSL_CTX	*ctx;
72 
73 	ctx = ssl_ctx_create(pki->pki_name, pki->pki_cert, pki->pki_cert_len);
74 
75 	if (!SSL_CTX_set_session_id_context(ctx,
76 		(const unsigned char *)pki->pki_name,
77 		strlen(pki->pki_name) + 1))
78 		goto err;
79 
80 	if (pki->pki_dhparams_len == 0)
81 		dh = get_dh1024();
82 	else
83 		dh = get_dh_from_memory(pki->pki_dhparams,
84 		    pki->pki_dhparams_len);
85 	ssl_set_ephemeral_key_exchange(ctx, dh);
86 	DH_free(dh);
87 
88 	ssl_set_ecdh_curve(ctx, SSL_ECDH_CURVE);
89 
90 	*ctxp = ctx;
91 	return 1;
92 
93 err:
94 	SSL_CTX_free(ctx);
95 	ssl_error("ssl_setup");
96 	return 0;
97 }
98 
99 char *
100 ssl_load_file(const char *name, off_t *len, mode_t perm)
101 {
102 	struct stat	 st;
103 	off_t		 size;
104 	char		*buf = NULL;
105 	int		 fd, saved_errno;
106 	char		 mode[12];
107 
108 	if ((fd = open(name, O_RDONLY)) == -1)
109 		return (NULL);
110 	if (fstat(fd, &st) != 0)
111 		goto fail;
112 	if (st.st_uid != 0) {
113 		log_warnx("warn:  %s: not owned by uid 0", name);
114 		errno = EACCES;
115 		goto fail;
116 	}
117 	if (st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO) & ~perm) {
118 		strmode(perm, mode);
119 		log_warnx("warn:  %s: insecure permissions: must be at most %s",
120 		    name, &mode[1]);
121 		errno = EACCES;
122 		goto fail;
123 	}
124 	size = st.st_size;
125 	if ((buf = calloc(1, size + 1)) == NULL)
126 		goto fail;
127 	if (read(fd, buf, size) != size)
128 		goto fail;
129 	close(fd);
130 
131 	*len = size + 1;
132 	return (buf);
133 
134 fail:
135 	if (buf != NULL)
136 		free(buf);
137 	saved_errno = errno;
138 	close(fd);
139 	errno = saved_errno;
140 	return (NULL);
141 }
142 
143 #if 0
144 static int
145 ssl_password_cb(char *buf, int size, int rwflag, void *u)
146 {
147 	size_t	len;
148 	if (u == NULL) {
149 		memset(buf, 0, size);
150 		return (0);
151 	}
152 	if ((len = strlcpy(buf, u, size)) >= (size_t)size)
153 		return (0);
154 	return (len);
155 }
156 #endif
157 
158 static int
159 ssl_password_cb(char *buf, int size, int rwflag, void *u)
160 {
161 	int	ret = 0;
162 	size_t	len;
163 	char	*pass;
164 
165 	pass = getpass((const char *)u);
166 	if (pass == NULL)
167 		return 0;
168 	len = strlen(pass);
169 	if (strlcpy(buf, pass, size) >= (size_t)size)
170 		goto end;
171 	ret = len;
172 end:
173 	if (len)
174 		memset(pass, 0, len);
175 	return ret;
176 }
177 
178 char *
179 ssl_load_key(const char *name, off_t *len, char *pass, mode_t perm, const char *pkiname)
180 {
181 	FILE		*fp = NULL;
182 	EVP_PKEY	*key = NULL;
183 	BIO		*bio = NULL;
184 	long		 size;
185 	char		*data, *buf = NULL;
186 	struct stat	 st;
187 	char		 mode[12];
188 	char		 prompt[2048];
189 
190 	/* Initialize SSL library once */
191 	ssl_init();
192 
193 	/*
194 	 * Read (possibly) encrypted key from file
195 	 */
196 	if ((fp = fopen(name, "r")) == NULL)
197 		return (NULL);
198 
199 	if (fstat(fileno(fp), &st) != 0)
200 		goto fail;
201 	if (st.st_uid != 0) {
202 		log_warnx("warn:  %s: not owned by uid 0", name);
203 		errno = EACCES;
204 		goto fail;
205 	}
206 	if (st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO) & ~perm) {
207 		strmode(perm, mode);
208 		log_warnx("warn:  %s: insecure permissions: must be at most %s",
209 		    name, &mode[1]);
210 		errno = EACCES;
211 		goto fail;
212 	}
213 
214 	(void)snprintf(prompt, sizeof prompt, "passphrase for %s: ", pkiname);
215 	key = PEM_read_PrivateKey(fp, NULL, ssl_password_cb, prompt);
216 	fclose(fp);
217 	fp = NULL;
218 	if (key == NULL)
219 		goto fail;
220 	/*
221 	 * Write unencrypted key to memory buffer
222 	 */
223 	if ((bio = BIO_new(BIO_s_mem())) == NULL)
224 		goto fail;
225 	if (!PEM_write_bio_PrivateKey(bio, key, NULL, NULL, 0, NULL, NULL))
226 		goto fail;
227 	if ((size = BIO_get_mem_data(bio, &data)) <= 0)
228 		goto fail;
229 	if ((buf = calloc(1, size + 1)) == NULL)
230 		goto fail;
231 	memcpy(buf, data, size);
232 
233 	BIO_free_all(bio);
234 	EVP_PKEY_free(key);
235 
236 	*len = (off_t)size + 1;
237 	return (buf);
238 
239 fail:
240 	ssl_error("ssl_load_key");
241 	free(buf);
242 	if (bio != NULL)
243 		BIO_free_all(bio);
244 	if (key != NULL)
245 		EVP_PKEY_free(key);
246 	if (fp)
247 		fclose(fp);
248 	return (NULL);
249 }
250 
251 SSL_CTX *
252 ssl_ctx_create(const char *pkiname, char *cert, off_t cert_len)
253 {
254 	SSL_CTX	*ctx;
255 	size_t	 pkinamelen = 0;
256 
257 	ctx = SSL_CTX_new(SSLv23_method());
258 	if (ctx == NULL) {
259 		ssl_error("ssl_ctx_create");
260 		fatal("ssl_ctx_create: could not create SSL context");
261 	}
262 
263 	SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
264 	SSL_CTX_set_timeout(ctx, SSL_SESSION_TIMEOUT);
265 	SSL_CTX_set_options(ctx,
266 	    SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_TICKET);
267 	SSL_CTX_set_options(ctx,
268 	    SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
269 
270 	if (!SSL_CTX_set_cipher_list(ctx, SSL_CIPHERS)) {
271 		ssl_error("ssl_ctx_create");
272 		fatal("ssl_ctx_create: could not set cipher list");
273 	}
274 
275 	if (cert != NULL) {
276 		if (pkiname != NULL)
277 			pkinamelen = strlen(pkiname) + 1;
278 		if (!ssl_ctx_use_certificate_chain(ctx, cert, cert_len)) {
279 			ssl_error("ssl_ctx_create");
280 			fatal("ssl_ctx_create: invalid certificate chain");
281 		} else if (!ssl_ctx_fake_private_key(ctx,
282 		    pkiname, pkinamelen, cert, cert_len, NULL, NULL)) {
283 			ssl_error("ssl_ctx_create");
284 			fatal("ssl_ctx_create: could not fake private key");
285 		} else if (!SSL_CTX_check_private_key(ctx)) {
286 			ssl_error("ssl_ctx_create");
287 			fatal("ssl_ctx_create: invalid private key");
288 		}
289 	}
290 
291 	return (ctx);
292 }
293 
294 int
295 ssl_load_certificate(struct pki *p, const char *pathname)
296 {
297 	p->pki_cert = ssl_load_file(pathname, &p->pki_cert_len, 0755);
298 	if (p->pki_cert == NULL)
299 		return 0;
300 	return 1;
301 }
302 
303 int
304 ssl_load_keyfile(struct pki *p, const char *pathname, const char *pkiname)
305 {
306 	char	pass[1024];
307 
308 	p->pki_key = ssl_load_key(pathname, &p->pki_key_len, pass, 0700, pkiname);
309 	if (p->pki_key == NULL)
310 		return 0;
311 	return 1;
312 }
313 
314 int
315 ssl_load_cafile(struct pki *p, const char *pathname)
316 {
317 	p->pki_ca = ssl_load_file(pathname, &p->pki_ca_len, 0755);
318 	if (p->pki_ca == NULL)
319 		return 0;
320 	return 1;
321 }
322 
323 int
324 ssl_load_dhparams(struct pki *p, const char *pathname)
325 {
326 	p->pki_dhparams = ssl_load_file(pathname, &p->pki_dhparams_len, 0755);
327 	if (p->pki_dhparams == NULL) {
328 		if (errno == EACCES)
329 			return 0;
330 		log_info("info: No DH parameters found in %s: "
331 		    "using built-in parameters", pathname);
332 	}
333 	return 1;
334 }
335 
336 const char *
337 ssl_to_text(const SSL *ssl)
338 {
339 	static char buf[256];
340 
341 	(void)snprintf(buf, sizeof buf, "version=%s, cipher=%s, bits=%d",
342 	    SSL_get_cipher_version(ssl),
343 	    SSL_get_cipher_name(ssl),
344 	    SSL_get_cipher_bits(ssl, NULL));
345 
346 	return (buf);
347 }
348 
349 void
350 ssl_error(const char *where)
351 {
352 	unsigned long	code;
353 	char		errbuf[128];
354 
355 	for (; (code = ERR_get_error()) != 0 ;) {
356 		ERR_error_string_n(code, errbuf, sizeof(errbuf));
357 		log_debug("debug: SSL library error: %s: %s", where, errbuf);
358 	}
359 }
360 
361 /* From OpenSSL's documentation:
362  *
363  * If "strong" primes were used to generate the DH parameters, it is
364  * not strictly necessary to generate a new key for each handshake
365  * but it does improve forward secrecy.
366  *
367  * -- gilles@
368  */
369 DH *
370 get_dh1024(void)
371 {
372 	DH *dh;
373 	unsigned char dh1024_p[] = {
374 		0xAD,0x37,0xBB,0x26,0x75,0x01,0x27,0x75,
375 		0x06,0xB5,0xE7,0x1E,0x1F,0x2B,0xBC,0x51,
376 		0xC0,0xF4,0xEB,0x42,0x7A,0x2A,0x83,0x1E,
377 		0xE8,0xD1,0xD8,0xCC,0x9E,0xE6,0x15,0x1D,
378 		0x06,0x46,0x50,0x94,0xB9,0xEE,0xB6,0x89,
379 		0xB7,0x3C,0xAC,0x07,0x5E,0x29,0x37,0xCC,
380 		0x8F,0xDF,0x48,0x56,0x85,0x83,0x26,0x02,
381 		0xB8,0xB6,0x63,0xAF,0x2D,0x4A,0x57,0x93,
382 		0x6B,0x54,0xE1,0x8F,0x28,0x76,0x9C,0x5D,
383 		0x90,0x65,0xD1,0x07,0xFE,0x5B,0x05,0x65,
384 		0xDA,0xD2,0xE2,0xAF,0x23,0xCA,0x2F,0xD6,
385 		0x4B,0xD2,0x04,0xFE,0xDF,0x21,0x2A,0xE1,
386 		0xCD,0x1B,0x70,0x76,0xB3,0x51,0xA4,0xC9,
387 		0x2B,0x68,0xE3,0xDD,0xCB,0x97,0xDA,0x59,
388 		0x50,0x93,0xEE,0xDB,0xBF,0xC7,0xFA,0xA7,
389 		0x47,0xC4,0x4D,0xF0,0xC6,0x09,0x4A,0x4B
390 	};
391 	unsigned char dh1024_g[] = {
392 		0x02
393 	};
394 
395 	if ((dh = DH_new()) == NULL)
396 		return NULL;
397 
398 	dh->p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), NULL);
399 	dh->g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), NULL);
400 	if (dh->p == NULL || dh->g == NULL) {
401 		DH_free(dh);
402 		return NULL;
403 	}
404 
405 	return dh;
406 }
407 
408 DH *
409 get_dh_from_memory(char *params, size_t len)
410 {
411 	BIO *mem;
412 	DH *dh;
413 
414 	mem = BIO_new_mem_buf(params, len);
415 	if (mem == NULL)
416 		return NULL;
417 	dh = PEM_read_bio_DHparams(mem, NULL, NULL, NULL);
418 	if (dh == NULL)
419 		goto err;
420 	if (dh->p == NULL || dh->g == NULL)
421 		goto err;
422 	return dh;
423 
424 err:
425 	if (mem != NULL)
426 		BIO_free(mem);
427 	if (dh != NULL)
428 		DH_free(dh);
429 	return NULL;
430 }
431 
432 
433 void
434 ssl_set_ephemeral_key_exchange(SSL_CTX *ctx, DH *dh)
435 {
436 	if (dh == NULL || !SSL_CTX_set_tmp_dh(ctx, dh)) {
437 		ssl_error("ssl_set_ephemeral_key_exchange");
438 		fatal("ssl_set_ephemeral_key_exchange: cannot set tmp dh");
439 	}
440 }
441 
442 void
443 ssl_set_ecdh_curve(SSL_CTX *ctx, const char *curve)
444 {
445 	int	nid;
446 	EC_KEY *ecdh;
447 
448 	if (curve == NULL)
449 		curve = SSL_ECDH_CURVE;
450 	if ((nid = OBJ_sn2nid(curve)) == 0) {
451 		ssl_error("ssl_set_ecdh_curve");
452 		fatal("ssl_set_ecdh_curve: unknown curve name "
453 		    SSL_ECDH_CURVE);
454 	}
455 
456 	if ((ecdh = EC_KEY_new_by_curve_name(nid)) == NULL) {
457 		ssl_error("ssl_set_ecdh_curve");
458 		fatal("ssl_set_ecdh_curve: unable to create curve "
459 		    SSL_ECDH_CURVE);
460 	}
461 
462 	SSL_CTX_set_tmp_ecdh(ctx, ecdh);
463 	SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
464 	EC_KEY_free(ecdh);
465 }
466 
467 int
468 ssl_load_pkey(const void *data, size_t datalen, char *buf, off_t len,
469     X509 **x509ptr, EVP_PKEY **pkeyptr)
470 {
471 	BIO		*in;
472 	X509		*x509 = NULL;
473 	EVP_PKEY	*pkey = NULL;
474 	RSA		*rsa = NULL;
475 	void		*exdata = NULL;
476 
477 	if ((in = BIO_new_mem_buf(buf, len)) == NULL) {
478 		SSLerr(SSL_F_SSL_CTX_USE_PRIVATEKEY, ERR_R_BUF_LIB);
479 		return (0);
480 	}
481 
482 	if ((x509 = PEM_read_bio_X509(in, NULL,
483 	    ssl_password_cb, NULL)) == NULL) {
484 		SSLerr(SSL_F_SSL_CTX_USE_PRIVATEKEY, ERR_R_PEM_LIB);
485 		goto fail;
486 	}
487 
488 	if ((pkey = X509_get_pubkey(x509)) == NULL) {
489 		SSLerr(SSL_F_SSL_CTX_USE_PRIVATEKEY, ERR_R_X509_LIB);
490 		goto fail;
491 	}
492 
493 	BIO_free(in);
494 
495 	if (data != NULL && datalen) {
496 		if ((rsa = EVP_PKEY_get1_RSA(pkey)) == NULL ||
497 		    (exdata = malloc(datalen)) == NULL) {
498 			SSLerr(SSL_F_SSL_CTX_USE_PRIVATEKEY, ERR_R_EVP_LIB);
499 			goto fail;
500 		}
501 
502 		memcpy(exdata, data, datalen);
503 		RSA_set_ex_data(rsa, 0, exdata);
504 		RSA_free(rsa); /* dereference, will be cleaned up with pkey */
505 	}
506 
507 	*x509ptr = x509;
508 	*pkeyptr = pkey;
509 
510 	return (1);
511 
512  fail:
513 	if (rsa != NULL)
514 		RSA_free(rsa);
515 	if (in != NULL)
516 		BIO_free(in);
517 	if (pkey != NULL)
518 		EVP_PKEY_free(pkey);
519 	if (x509 != NULL)
520 		X509_free(x509);
521 
522 	return (0);
523 }
524 
525 int
526 ssl_ctx_fake_private_key(SSL_CTX *ctx, const void *data, size_t datalen,
527     char *buf, off_t len, X509 **x509ptr, EVP_PKEY **pkeyptr)
528 {
529 	int		 ret = 0;
530 	EVP_PKEY	*pkey = NULL;
531 	X509		*x509 = NULL;
532 
533 	if (!ssl_load_pkey(data, datalen, buf, len, &x509, &pkey))
534 		return (0);
535 
536 	/*
537 	 * Use the public key as the "private" key - the secret key
538 	 * parameters are hidden in an extra process that will be
539 	 * contacted by the RSA engine.  The SSL/TLS library needs at
540 	 * least the public key parameters in the current process.
541 	 */
542 	ret = SSL_CTX_use_PrivateKey(ctx, pkey);
543 	if (!ret)
544 		SSLerr(SSL_F_SSL_CTX_USE_PRIVATEKEY, ERR_R_SSL_LIB);
545 
546 	if (pkeyptr != NULL)
547 		*pkeyptr = pkey;
548 	else if (pkey != NULL)
549 		EVP_PKEY_free(pkey);
550 
551 	if (x509ptr != NULL)
552 		*x509ptr = x509;
553 	else if (x509 != NULL)
554 		X509_free(x509);
555 
556 	return (ret);
557 }
558