xref: /openbsd-src/lib/libtls/tls.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1 /* $OpenBSD: tls.c,v 1.49 2016/09/04 12:26:43 bcook Exp $ */
2 /*
3  * Copyright (c) 2014 Joel Sing <jsing@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include <sys/socket.h>
19 
20 #include <errno.h>
21 #include <limits.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 
25 #include <openssl/bio.h>
26 #include <openssl/err.h>
27 #include <openssl/evp.h>
28 #include <openssl/pem.h>
29 #include <openssl/x509.h>
30 
31 #include <tls.h>
32 #include "tls_internal.h"
33 
34 static struct tls_config *tls_config_default;
35 
36 int
37 tls_init(void)
38 {
39 	static int tls_initialised = 0;
40 
41 	if (tls_initialised)
42 		return (0);
43 
44 	SSL_load_error_strings();
45 	SSL_library_init();
46 
47 	if (BIO_sock_init() != 1)
48 		return (-1);
49 
50 	if ((tls_config_default = tls_config_new()) == NULL)
51 		return (-1);
52 
53 	tls_initialised = 1;
54 
55 	return (0);
56 }
57 
58 const char *
59 tls_error(struct tls *ctx)
60 {
61 	return ctx->error.msg;
62 }
63 
64 static int
65 tls_error_vset(struct tls_error *error, int errnum, const char *fmt, va_list ap)
66 {
67 	char *errmsg = NULL;
68 	int rv = -1;
69 
70 	free(error->msg);
71 	error->msg = NULL;
72 	error->num = errnum;
73 
74 	if (vasprintf(&errmsg, fmt, ap) == -1) {
75 		errmsg = NULL;
76 		goto err;
77 	}
78 
79 	if (errnum == -1) {
80 		error->msg = errmsg;
81 		return (0);
82 	}
83 
84 	if (asprintf(&error->msg, "%s: %s", errmsg, strerror(errnum)) == -1) {
85 		error->msg = NULL;
86 		goto err;
87 	}
88 	rv = 0;
89 
90  err:
91 	free(errmsg);
92 
93 	return (rv);
94 }
95 
96 int
97 tls_error_set(struct tls_error *error, const char *fmt, ...)
98 {
99 	va_list ap;
100 	int errnum, rv;
101 
102 	errnum = errno;
103 
104 	va_start(ap, fmt);
105 	rv = tls_error_vset(error, errnum, fmt, ap);
106 	va_end(ap);
107 
108 	return (rv);
109 }
110 
111 int
112 tls_error_setx(struct tls_error *error, const char *fmt, ...)
113 {
114 	va_list ap;
115 	int rv;
116 
117 	va_start(ap, fmt);
118 	rv = tls_error_vset(error, -1, fmt, ap);
119 	va_end(ap);
120 
121 	return (rv);
122 }
123 
124 int
125 tls_config_set_error(struct tls_config *config, const char *fmt, ...)
126 {
127 	va_list ap;
128 	int errnum, rv;
129 
130 	errnum = errno;
131 
132 	va_start(ap, fmt);
133 	rv = tls_error_vset(&config->error, errnum, fmt, ap);
134 	va_end(ap);
135 
136 	return (rv);
137 }
138 
139 int
140 tls_config_set_errorx(struct tls_config *config, const char *fmt, ...)
141 {
142 	va_list ap;
143 	int rv;
144 
145 	va_start(ap, fmt);
146 	rv = tls_error_vset(&config->error, -1, fmt, ap);
147 	va_end(ap);
148 
149 	return (rv);
150 }
151 
152 int
153 tls_set_error(struct tls *ctx, const char *fmt, ...)
154 {
155 	va_list ap;
156 	int errnum, rv;
157 
158 	errnum = errno;
159 
160 	va_start(ap, fmt);
161 	rv = tls_error_vset(&ctx->error, errnum, fmt, ap);
162 	va_end(ap);
163 
164 	return (rv);
165 }
166 
167 int
168 tls_set_errorx(struct tls *ctx, const char *fmt, ...)
169 {
170 	va_list ap;
171 	int rv;
172 
173 	va_start(ap, fmt);
174 	rv = tls_error_vset(&ctx->error, -1, fmt, ap);
175 	va_end(ap);
176 
177 	return (rv);
178 }
179 
180 struct tls_sni_ctx *
181 tls_sni_ctx_new(void)
182 {
183 	return (calloc(1, sizeof(struct tls_sni_ctx)));
184 }
185 
186 void
187 tls_sni_ctx_free(struct tls_sni_ctx *sni_ctx)
188 {
189 	if (sni_ctx == NULL)
190 		return;
191 
192 	SSL_CTX_free(sni_ctx->ssl_ctx);
193 	X509_free(sni_ctx->ssl_cert);
194 
195 	free(sni_ctx);
196 }
197 
198 struct tls *
199 tls_new(void)
200 {
201 	struct tls *ctx;
202 
203 	if ((ctx = calloc(1, sizeof(*ctx))) == NULL)
204 		return (NULL);
205 
206 	ctx->config = tls_config_default;
207 
208 	tls_reset(ctx);
209 
210 	return (ctx);
211 }
212 
213 int
214 tls_configure(struct tls *ctx, struct tls_config *config)
215 {
216 	if (config == NULL)
217 		config = tls_config_default;
218 
219 	ctx->config = config;
220 
221 	if ((ctx->flags & TLS_SERVER) != 0)
222 		return (tls_configure_server(ctx));
223 
224 	return (0);
225 }
226 
227 int
228 tls_configure_ssl_keypair(struct tls *ctx, SSL_CTX *ssl_ctx,
229     struct tls_keypair *keypair, int required)
230 {
231 	EVP_PKEY *pkey = NULL;
232 	X509 *cert = NULL;
233 	BIO *bio = NULL;
234 
235 	if (!required &&
236 	    keypair->cert_mem == NULL &&
237 	    keypair->key_mem == NULL)
238 		return(0);
239 
240 	if (keypair->cert_mem != NULL) {
241 		if (keypair->cert_len > INT_MAX) {
242 			tls_set_errorx(ctx, "certificate too long");
243 			goto err;
244 		}
245 
246 		if (SSL_CTX_use_certificate_chain_mem(ssl_ctx,
247 		    keypair->cert_mem, keypair->cert_len) != 1) {
248 			tls_set_errorx(ctx, "failed to load certificate");
249 			goto err;
250 		}
251 		cert = NULL;
252 	}
253 	if (keypair->key_mem != NULL) {
254 		if (keypair->key_len > INT_MAX) {
255 			tls_set_errorx(ctx, "key too long");
256 			goto err;
257 		}
258 
259 		if ((bio = BIO_new_mem_buf(keypair->key_mem,
260 		    keypair->key_len)) == NULL) {
261 			tls_set_errorx(ctx, "failed to create buffer");
262 			goto err;
263 		}
264 		if ((pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL,
265 		    NULL)) == NULL) {
266 			tls_set_errorx(ctx, "failed to read private key");
267 			goto err;
268 		}
269 		if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1) {
270 			tls_set_errorx(ctx, "failed to load private key");
271 			goto err;
272 		}
273 		BIO_free(bio);
274 		bio = NULL;
275 		EVP_PKEY_free(pkey);
276 		pkey = NULL;
277 	}
278 
279 	if (SSL_CTX_check_private_key(ssl_ctx) != 1) {
280 		tls_set_errorx(ctx, "private/public key mismatch");
281 		goto err;
282 	}
283 
284 	return (0);
285 
286  err:
287 	EVP_PKEY_free(pkey);
288 	X509_free(cert);
289 	BIO_free(bio);
290 
291 	return (1);
292 }
293 
294 int
295 tls_configure_ssl(struct tls *ctx, SSL_CTX *ssl_ctx)
296 {
297 	SSL_CTX_set_mode(ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
298 	SSL_CTX_set_mode(ssl_ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
299 
300 	SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2);
301 	SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv3);
302 
303 	SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TLSv1);
304 	SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TLSv1_1);
305 	SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TLSv1_2);
306 
307 	if ((ctx->config->protocols & TLS_PROTOCOL_TLSv1_0) == 0)
308 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1);
309 	if ((ctx->config->protocols & TLS_PROTOCOL_TLSv1_1) == 0)
310 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_1);
311 	if ((ctx->config->protocols & TLS_PROTOCOL_TLSv1_2) == 0)
312 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_2);
313 
314 	if (ctx->config->alpn != NULL) {
315 		if (SSL_CTX_set_alpn_protos(ssl_ctx, ctx->config->alpn,
316 		    ctx->config->alpn_len) != 0) {
317 			tls_set_errorx(ctx, "failed to set alpn");
318 			goto err;
319 		}
320 	}
321 
322 	if (ctx->config->ciphers != NULL) {
323 		if (SSL_CTX_set_cipher_list(ssl_ctx,
324 		    ctx->config->ciphers) != 1) {
325 			tls_set_errorx(ctx, "failed to set ciphers");
326 			goto err;
327 		}
328 	}
329 
330 	if (ctx->config->verify_time == 0) {
331 		X509_VERIFY_PARAM_set_flags(ssl_ctx->param,
332 		    X509_V_FLAG_NO_CHECK_TIME);
333 	}
334 
335 	return (0);
336 
337  err:
338 	return (-1);
339 }
340 
341 int
342 tls_configure_ssl_verify(struct tls *ctx, SSL_CTX *ssl_ctx, int verify)
343 {
344 	size_t ca_len = ctx->config->ca_len;
345 	char *ca_mem = ctx->config->ca_mem;
346 	char *ca_free = NULL;
347 
348 	SSL_CTX_set_verify(ssl_ctx, verify, NULL);
349 
350 	/* If no CA has been specified, attempt to load the default. */
351 	if (ctx->config->ca_mem == NULL && ctx->config->ca_path == NULL) {
352 		if (tls_config_load_file(&ctx->error, "CA", _PATH_SSL_CA_FILE,
353 		    &ca_mem, &ca_len) != 0)
354 			goto err;
355 		ca_free = ca_mem;
356 	}
357 
358 	if (ca_mem != NULL) {
359 		if (ca_len > INT_MAX) {
360 			tls_set_errorx(ctx, "ca too long");
361 			goto err;
362 		}
363 		if (SSL_CTX_load_verify_mem(ssl_ctx, ca_mem, ca_len) != 1) {
364 			tls_set_errorx(ctx, "ssl verify memory setup failure");
365 			goto err;
366 		}
367 	} else if (SSL_CTX_load_verify_locations(ssl_ctx, NULL,
368 	    ctx->config->ca_path) != 1) {
369 		tls_set_errorx(ctx, "ssl verify locations failure");
370 		goto err;
371 	}
372 	if (ctx->config->verify_depth >= 0)
373 		SSL_CTX_set_verify_depth(ssl_ctx, ctx->config->verify_depth);
374 
375 	free(ca_free);
376 
377 	return (0);
378 
379  err:
380 	free(ca_free);
381 
382 	return (-1);
383 }
384 
385 void
386 tls_free(struct tls *ctx)
387 {
388 	if (ctx == NULL)
389 		return;
390 
391 	tls_reset(ctx);
392 
393 	free(ctx);
394 }
395 
396 void
397 tls_reset(struct tls *ctx)
398 {
399 	struct tls_sni_ctx *sni, *nsni;
400 
401 	SSL_CTX_free(ctx->ssl_ctx);
402 	SSL_free(ctx->ssl_conn);
403 	X509_free(ctx->ssl_peer_cert);
404 
405 	ctx->ssl_conn = NULL;
406 	ctx->ssl_ctx = NULL;
407 	ctx->ssl_peer_cert = NULL;
408 
409 	ctx->socket = -1;
410 	ctx->state = 0;
411 
412 	free(ctx->servername);
413 	ctx->servername = NULL;
414 
415 	free(ctx->error.msg);
416 	ctx->error.msg = NULL;
417 	ctx->error.num = -1;
418 
419 	tls_conninfo_free(ctx->conninfo);
420 	ctx->conninfo = NULL;
421 
422 	for (sni = ctx->sni_ctx; sni != NULL; sni = nsni) {
423 		nsni = sni->next;
424 		tls_sni_ctx_free(sni);
425 	}
426 	ctx->sni_ctx = NULL;
427 
428 	ctx->read_cb = NULL;
429 	ctx->write_cb = NULL;
430 	ctx->cb_arg = NULL;
431 }
432 
433 int
434 tls_ssl_error(struct tls *ctx, SSL *ssl_conn, int ssl_ret, const char *prefix)
435 {
436 	const char *errstr = "unknown error";
437 	unsigned long err;
438 	int ssl_err;
439 
440 	ssl_err = SSL_get_error(ssl_conn, ssl_ret);
441 	switch (ssl_err) {
442 	case SSL_ERROR_NONE:
443 	case SSL_ERROR_ZERO_RETURN:
444 		return (0);
445 
446 	case SSL_ERROR_WANT_READ:
447 		return (TLS_WANT_POLLIN);
448 
449 	case SSL_ERROR_WANT_WRITE:
450 		return (TLS_WANT_POLLOUT);
451 
452 	case SSL_ERROR_SYSCALL:
453 		if ((err = ERR_peek_error()) != 0) {
454 			errstr = ERR_error_string(err, NULL);
455 		} else if (ssl_ret == 0) {
456 			if ((ctx->state & TLS_HANDSHAKE_COMPLETE) != 0) {
457 				ctx->state |= TLS_EOF_NO_CLOSE_NOTIFY;
458 				return (0);
459 			}
460 			errstr = "unexpected EOF";
461 		} else if (ssl_ret == -1) {
462 			errstr = strerror(errno);
463 		}
464 		tls_set_errorx(ctx, "%s failed: %s", prefix, errstr);
465 		return (-1);
466 
467 	case SSL_ERROR_SSL:
468 		if ((err = ERR_peek_error()) != 0) {
469 			errstr = ERR_error_string(err, NULL);
470 		}
471 		tls_set_errorx(ctx, "%s failed: %s", prefix, errstr);
472 		return (-1);
473 
474 	case SSL_ERROR_WANT_CONNECT:
475 	case SSL_ERROR_WANT_ACCEPT:
476 	case SSL_ERROR_WANT_X509_LOOKUP:
477 	default:
478 		tls_set_errorx(ctx, "%s failed (%i)", prefix, ssl_err);
479 		return (-1);
480 	}
481 }
482 
483 int
484 tls_handshake(struct tls *ctx)
485 {
486 	int rv = -1;
487 
488 	if ((ctx->flags & (TLS_CLIENT | TLS_SERVER_CONN)) == 0) {
489 		tls_set_errorx(ctx, "invalid operation for context");
490 		goto out;
491 	}
492 
493 	if ((ctx->flags & TLS_CLIENT) != 0)
494 		rv = tls_handshake_client(ctx);
495 	else if ((ctx->flags & TLS_SERVER_CONN) != 0)
496 		rv = tls_handshake_server(ctx);
497 
498 	if (rv == 0) {
499 		ctx->ssl_peer_cert =  SSL_get_peer_certificate(ctx->ssl_conn);
500 		if (tls_conninfo_populate(ctx) == -1)
501 		    rv = -1;
502 	}
503  out:
504 	/* Prevent callers from performing incorrect error handling */
505 	errno = 0;
506 	return (rv);
507 }
508 
509 ssize_t
510 tls_read(struct tls *ctx, void *buf, size_t buflen)
511 {
512 	ssize_t rv = -1;
513 	int ssl_ret;
514 
515 	if ((ctx->state & TLS_HANDSHAKE_COMPLETE) == 0) {
516 		if ((rv = tls_handshake(ctx)) != 0)
517 			goto out;
518 	}
519 
520 	if (buflen > INT_MAX) {
521 		tls_set_errorx(ctx, "buflen too long");
522 		goto out;
523 	}
524 
525 	ERR_clear_error();
526 	if ((ssl_ret = SSL_read(ctx->ssl_conn, buf, buflen)) > 0) {
527 		rv = (ssize_t)ssl_ret;
528 		goto out;
529 	}
530 	rv = (ssize_t)tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "read");
531 
532  out:
533 	/* Prevent callers from performing incorrect error handling */
534 	errno = 0;
535 	return (rv);
536 }
537 
538 ssize_t
539 tls_write(struct tls *ctx, const void *buf, size_t buflen)
540 {
541 	ssize_t rv = -1;
542 	int ssl_ret;
543 
544 	if ((ctx->state & TLS_HANDSHAKE_COMPLETE) == 0) {
545 		if ((rv = tls_handshake(ctx)) != 0)
546 			goto out;
547 	}
548 
549 	if (buflen > INT_MAX) {
550 		tls_set_errorx(ctx, "buflen too long");
551 		goto out;
552 	}
553 
554 	ERR_clear_error();
555 	if ((ssl_ret = SSL_write(ctx->ssl_conn, buf, buflen)) > 0) {
556 		rv = (ssize_t)ssl_ret;
557 		goto out;
558 	}
559 	rv =  (ssize_t)tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "write");
560 
561  out:
562 	/* Prevent callers from performing incorrect error handling */
563 	errno = 0;
564 	return (rv);
565 }
566 
567 int
568 tls_close(struct tls *ctx)
569 {
570 	int ssl_ret;
571 	int rv = 0;
572 
573 	if ((ctx->flags & (TLS_CLIENT | TLS_SERVER_CONN)) == 0) {
574 		tls_set_errorx(ctx, "invalid operation for context");
575 		rv = -1;
576 		goto out;
577 	}
578 
579 	if (ctx->ssl_conn != NULL) {
580 		ERR_clear_error();
581 		ssl_ret = SSL_shutdown(ctx->ssl_conn);
582 		if (ssl_ret < 0) {
583 			rv = tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret,
584 			    "shutdown");
585 			if (rv == TLS_WANT_POLLIN || rv == TLS_WANT_POLLOUT)
586 				goto out;
587 		}
588 	}
589 
590 	if (ctx->socket != -1) {
591 		if (shutdown(ctx->socket, SHUT_RDWR) != 0) {
592 			if (rv == 0 &&
593 			    errno != ENOTCONN && errno != ECONNRESET) {
594 				tls_set_error(ctx, "shutdown");
595 				rv = -1;
596 			}
597 		}
598 		if (close(ctx->socket) != 0) {
599 			if (rv == 0) {
600 				tls_set_error(ctx, "close");
601 				rv = -1;
602 			}
603 		}
604 		ctx->socket = -1;
605 	}
606 
607 	if ((ctx->state & TLS_EOF_NO_CLOSE_NOTIFY) != 0) {
608 		tls_set_errorx(ctx, "EOF without close notify");
609 		rv = -1;
610 	}
611 
612  out:
613 	/* Prevent callers from performing incorrect error handling */
614 	errno = 0;
615 	return (rv);
616 }
617