xref: /openbsd-src/usr.sbin/smtpd/ssl.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1 /*	$OpenBSD: ssl.c,v 1.87 2016/09/02 09:43:54 gilles 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     int (*sni_cb)(SSL *,int *,void *), const char *ciphers)
70 {
71 	SSL_CTX	*ctx;
72 	uint8_t sid[SSL_MAX_SID_CTX_LENGTH];
73 
74 	ctx = ssl_ctx_create(pki->pki_name, pki->pki_cert, pki->pki_cert_len, ciphers);
75 
76 	/*
77 	 * Set session ID context to a random value.  We don't support
78 	 * persistent caching of sessions so it is OK to set a temporary
79 	 * session ID context that is valid during run time.
80 	 */
81 	arc4random_buf(sid, sizeof(sid));
82 	if (!SSL_CTX_set_session_id_context(ctx, sid, sizeof(sid)))
83 		goto err;
84 
85 	if (sni_cb)
86 		SSL_CTX_set_tlsext_servername_callback(ctx, sni_cb);
87 
88 	SSL_CTX_set_dh_auto(ctx, pki->pki_dhe);
89 
90 	SSL_CTX_set_ecdh_auto(ctx, 1);
91 
92 	*ctxp = ctx;
93 	return 1;
94 
95 err:
96 	SSL_CTX_free(ctx);
97 	ssl_error("ssl_setup");
98 	return 0;
99 }
100 
101 char *
102 ssl_load_file(const char *name, off_t *len, mode_t perm)
103 {
104 	struct stat	 st;
105 	off_t		 size;
106 	char		*buf = NULL;
107 	int		 fd, saved_errno;
108 	char		 mode[12];
109 
110 	if ((fd = open(name, O_RDONLY)) == -1)
111 		return (NULL);
112 	if (fstat(fd, &st) != 0)
113 		goto fail;
114 	if (st.st_uid != 0) {
115 		log_warnx("warn:  %s: not owned by uid 0", name);
116 		errno = EACCES;
117 		goto fail;
118 	}
119 	if (st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO) & ~perm) {
120 		strmode(perm, mode);
121 		log_warnx("warn:  %s: insecure permissions: must be at most %s",
122 		    name, &mode[1]);
123 		errno = EACCES;
124 		goto fail;
125 	}
126 	size = st.st_size;
127 	if ((buf = calloc(1, size + 1)) == NULL)
128 		goto fail;
129 	if (read(fd, buf, size) != size)
130 		goto fail;
131 	close(fd);
132 
133 	*len = size + 1;
134 	return (buf);
135 
136 fail:
137 	free(buf);
138 	saved_errno = errno;
139 	close(fd);
140 	errno = saved_errno;
141 	return (NULL);
142 }
143 
144 #if 0
145 static int
146 ssl_password_cb(char *buf, int size, int rwflag, void *u)
147 {
148 	size_t	len;
149 	if (u == NULL) {
150 		explicit_bzero(buf, size);
151 		return (0);
152 	}
153 	if ((len = strlcpy(buf, u, size)) >= (size_t)size)
154 		return (0);
155 	return (len);
156 }
157 #endif
158 
159 static int
160 ssl_password_cb(char *buf, int size, int rwflag, void *u)
161 {
162 	int	ret = 0;
163 	size_t	len;
164 	char	*pass;
165 
166 	pass = getpass((const char *)u);
167 	if (pass == NULL)
168 		return 0;
169 	len = strlen(pass);
170 	if (strlcpy(buf, pass, size) >= (size_t)size)
171 		goto end;
172 	ret = len;
173 end:
174 	if (len)
175 		explicit_bzero(pass, len);
176 	return ret;
177 }
178 
179 char *
180 ssl_load_key(const char *name, off_t *len, char *pass, mode_t perm, const char *pkiname)
181 {
182 	FILE		*fp = NULL;
183 	EVP_PKEY	*key = NULL;
184 	BIO		*bio = NULL;
185 	long		 size;
186 	char		*data, *buf = NULL;
187 	struct stat	 st;
188 	char		 mode[12];
189 	char		 prompt[2048];
190 
191 	/* Initialize SSL library once */
192 	ssl_init();
193 
194 	/*
195 	 * Read (possibly) encrypted key from file
196 	 */
197 	if ((fp = fopen(name, "r")) == NULL)
198 		return (NULL);
199 
200 	if (fstat(fileno(fp), &st) != 0)
201 		goto fail;
202 	if (st.st_uid != 0) {
203 		log_warnx("warn:  %s: not owned by uid 0", name);
204 		errno = EACCES;
205 		goto fail;
206 	}
207 	if (st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO) & ~perm) {
208 		strmode(perm, mode);
209 		log_warnx("warn:  %s: insecure permissions: must be at most %s",
210 		    name, &mode[1]);
211 		errno = EACCES;
212 		goto fail;
213 	}
214 
215 	(void)snprintf(prompt, sizeof prompt, "passphrase for %s: ", pkiname);
216 	key = PEM_read_PrivateKey(fp, NULL, ssl_password_cb, prompt);
217 	fclose(fp);
218 	fp = NULL;
219 	if (key == NULL)
220 		goto fail;
221 	/*
222 	 * Write unencrypted key to memory buffer
223 	 */
224 	if ((bio = BIO_new(BIO_s_mem())) == NULL)
225 		goto fail;
226 	if (!PEM_write_bio_PrivateKey(bio, key, NULL, NULL, 0, NULL, NULL))
227 		goto fail;
228 	if ((size = BIO_get_mem_data(bio, &data)) <= 0)
229 		goto fail;
230 	if ((buf = calloc(1, size + 1)) == NULL)
231 		goto fail;
232 	memcpy(buf, data, size);
233 
234 	BIO_free_all(bio);
235 	EVP_PKEY_free(key);
236 
237 	*len = (off_t)size + 1;
238 	return (buf);
239 
240 fail:
241 	ssl_error("ssl_load_key");
242 	free(buf);
243 	if (bio != NULL)
244 		BIO_free_all(bio);
245 	if (key != NULL)
246 		EVP_PKEY_free(key);
247 	if (fp)
248 		fclose(fp);
249 	return (NULL);
250 }
251 
252 SSL_CTX *
253 ssl_ctx_create(const char *pkiname, char *cert, off_t cert_len, const char *ciphers)
254 {
255 	SSL_CTX	*ctx;
256 	size_t	 pkinamelen = 0;
257 
258 	ctx = SSL_CTX_new(SSLv23_method());
259 	if (ctx == NULL) {
260 		ssl_error("ssl_ctx_create");
261 		fatal("ssl_ctx_create: could not create SSL context");
262 	}
263 
264 	SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
265 	SSL_CTX_set_timeout(ctx, SSL_SESSION_TIMEOUT);
266 	SSL_CTX_set_options(ctx,
267 	    SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TICKET);
268 	SSL_CTX_set_options(ctx,
269 	    SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
270 	SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
271 
272 	if (ciphers == NULL)
273 		ciphers = SSL_CIPHERS;
274 	if (!SSL_CTX_set_cipher_list(ctx, ciphers)) {
275 		ssl_error("ssl_ctx_create");
276 		fatal("ssl_ctx_create: could not set cipher list");
277 	}
278 
279 	if (cert != NULL) {
280 		if (pkiname != NULL)
281 			pkinamelen = strlen(pkiname) + 1;
282 		if (!SSL_CTX_use_certificate_chain_mem(ctx, cert, cert_len)) {
283 			ssl_error("ssl_ctx_create");
284 			fatal("ssl_ctx_create: invalid certificate chain");
285 		} else if (!ssl_ctx_fake_private_key(ctx,
286 		    pkiname, pkinamelen, cert, cert_len, NULL, NULL)) {
287 			ssl_error("ssl_ctx_create");
288 			fatal("ssl_ctx_create: could not fake private key");
289 		} else if (!SSL_CTX_check_private_key(ctx)) {
290 			ssl_error("ssl_ctx_create");
291 			fatal("ssl_ctx_create: invalid private key");
292 		}
293 	}
294 
295 	return (ctx);
296 }
297 
298 int
299 ssl_load_certificate(struct pki *p, const char *pathname)
300 {
301 	p->pki_cert = ssl_load_file(pathname, &p->pki_cert_len, 0755);
302 	if (p->pki_cert == NULL)
303 		return 0;
304 	return 1;
305 }
306 
307 int
308 ssl_load_keyfile(struct pki *p, const char *pathname, const char *pkiname)
309 {
310 	char	pass[1024];
311 
312 	p->pki_key = ssl_load_key(pathname, &p->pki_key_len, pass, 0740, pkiname);
313 	if (p->pki_key == NULL)
314 		return 0;
315 	return 1;
316 }
317 
318 int
319 ssl_load_cafile(struct ca *c, const char *pathname)
320 {
321 	c->ca_cert = ssl_load_file(pathname, &c->ca_cert_len, 0755);
322 	if (c->ca_cert == NULL)
323 		return 0;
324 	return 1;
325 }
326 
327 const char *
328 ssl_to_text(const SSL *ssl)
329 {
330 	static char buf[256];
331 
332 	(void)snprintf(buf, sizeof buf, "version=%s, cipher=%s, bits=%d",
333 	    SSL_get_version(ssl),
334 	    SSL_get_cipher_name(ssl),
335 	    SSL_get_cipher_bits(ssl, NULL));
336 
337 	return (buf);
338 }
339 
340 void
341 ssl_error(const char *where)
342 {
343 	unsigned long	code;
344 	char		errbuf[128];
345 
346 	for (; (code = ERR_get_error()) != 0 ;) {
347 		ERR_error_string_n(code, errbuf, sizeof(errbuf));
348 		log_debug("debug: SSL library error: %s: %s", where, errbuf);
349 	}
350 }
351 
352 int
353 ssl_load_pkey(const void *data, size_t datalen, char *buf, off_t len,
354     X509 **x509ptr, EVP_PKEY **pkeyptr)
355 {
356 	BIO		*in;
357 	X509		*x509 = NULL;
358 	EVP_PKEY	*pkey = NULL;
359 	RSA		*rsa = NULL;
360 	void		*exdata = NULL;
361 
362 	if ((in = BIO_new_mem_buf(buf, len)) == NULL) {
363 		SSLerr(SSL_F_SSL_CTX_USE_PRIVATEKEY, ERR_R_BUF_LIB);
364 		return (0);
365 	}
366 
367 	if ((x509 = PEM_read_bio_X509(in, NULL,
368 	    ssl_password_cb, NULL)) == NULL) {
369 		SSLerr(SSL_F_SSL_CTX_USE_PRIVATEKEY, ERR_R_PEM_LIB);
370 		goto fail;
371 	}
372 
373 	if ((pkey = X509_get_pubkey(x509)) == NULL) {
374 		SSLerr(SSL_F_SSL_CTX_USE_PRIVATEKEY, ERR_R_X509_LIB);
375 		goto fail;
376 	}
377 
378 	BIO_free(in);
379 	in = NULL;
380 
381 	if (data != NULL && datalen) {
382 		if ((rsa = EVP_PKEY_get1_RSA(pkey)) == NULL ||
383 		    (exdata = malloc(datalen)) == NULL) {
384 			SSLerr(SSL_F_SSL_CTX_USE_PRIVATEKEY, ERR_R_EVP_LIB);
385 			goto fail;
386 		}
387 
388 		memcpy(exdata, data, datalen);
389 		RSA_set_ex_data(rsa, 0, exdata);
390 		RSA_free(rsa); /* dereference, will be cleaned up with pkey */
391 	}
392 
393 	*x509ptr = x509;
394 	*pkeyptr = pkey;
395 
396 	return (1);
397 
398  fail:
399 	if (rsa != NULL)
400 		RSA_free(rsa);
401 	if (in != NULL)
402 		BIO_free(in);
403 	if (pkey != NULL)
404 		EVP_PKEY_free(pkey);
405 	if (x509 != NULL)
406 		X509_free(x509);
407 	free(exdata);
408 
409 	return (0);
410 }
411 
412 int
413 ssl_ctx_fake_private_key(SSL_CTX *ctx, const void *data, size_t datalen,
414     char *buf, off_t len, X509 **x509ptr, EVP_PKEY **pkeyptr)
415 {
416 	int		 ret = 0;
417 	EVP_PKEY	*pkey = NULL;
418 	X509		*x509 = NULL;
419 
420 	if (!ssl_load_pkey(data, datalen, buf, len, &x509, &pkey))
421 		return (0);
422 
423 	/*
424 	 * Use the public key as the "private" key - the secret key
425 	 * parameters are hidden in an extra process that will be
426 	 * contacted by the RSA engine.  The SSL/TLS library needs at
427 	 * least the public key parameters in the current process.
428 	 */
429 	ret = SSL_CTX_use_PrivateKey(ctx, pkey);
430 	if (!ret)
431 		SSLerr(SSL_F_SSL_CTX_USE_PRIVATEKEY, ERR_R_SSL_LIB);
432 
433 	if (pkeyptr != NULL)
434 		*pkeyptr = pkey;
435 	else if (pkey != NULL)
436 		EVP_PKEY_free(pkey);
437 
438 	if (x509ptr != NULL)
439 		*x509ptr = x509;
440 	else if (x509 != NULL)
441 		X509_free(x509);
442 
443 	return (ret);
444 }
445