xref: /openbsd-src/lib/libtls/tls_server.c (revision ae6dba76668bd8245e9073ca37f7742b08f93f0c)
1 /* $OpenBSD: tls_server.c,v 1.38 2017/06/22 17:34:25 jsing 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 <arpa/inet.h>
21 
22 #include <openssl/ec.h>
23 #include <openssl/err.h>
24 #include <openssl/ssl.h>
25 
26 #include <tls.h>
27 #include "tls_internal.h"
28 
29 struct tls *
30 tls_server(void)
31 {
32 	struct tls *ctx;
33 
34 	if ((ctx = tls_new()) == NULL)
35 		return (NULL);
36 
37 	ctx->flags |= TLS_SERVER;
38 
39 	return (ctx);
40 }
41 
42 struct tls *
43 tls_server_conn(struct tls *ctx)
44 {
45 	struct tls *conn_ctx;
46 
47 	if ((conn_ctx = tls_new()) == NULL)
48 		return (NULL);
49 
50 	conn_ctx->flags |= TLS_SERVER_CONN;
51 
52 	ctx->config->refcount++;
53 	conn_ctx->config = ctx->config;
54 
55 	return (conn_ctx);
56 }
57 
58 static int
59 tls_server_alpn_cb(SSL *ssl, const unsigned char **out, unsigned char *outlen,
60     const unsigned char *in, unsigned int inlen, void *arg)
61 {
62 	struct tls *ctx = arg;
63 
64 	if (SSL_select_next_proto((unsigned char**)out, outlen,
65 	    ctx->config->alpn, ctx->config->alpn_len, in, inlen) ==
66 	    OPENSSL_NPN_NEGOTIATED)
67 		return (SSL_TLSEXT_ERR_OK);
68 
69 	return (SSL_TLSEXT_ERR_NOACK);
70 }
71 
72 static int
73 tls_servername_cb(SSL *ssl, int *al, void *arg)
74 {
75 	struct tls *ctx = (struct tls *)arg;
76 	struct tls_sni_ctx *sni_ctx;
77 	union tls_addr addrbuf;
78 	struct tls *conn_ctx;
79 	const char *name;
80 	int match;
81 
82 	if ((conn_ctx = SSL_get_app_data(ssl)) == NULL)
83 		goto err;
84 
85 	if ((name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name)) ==
86 	    NULL) {
87 		/*
88 		 * The servername callback gets called even when there is no
89 		 * TLS servername extension provided by the client. Sigh!
90 		 */
91 		return (SSL_TLSEXT_ERR_NOACK);
92 	}
93 
94 	/* Per RFC 6066 section 3: ensure that name is not an IP literal. */
95 	if (inet_pton(AF_INET, name, &addrbuf) == 1 ||
96             inet_pton(AF_INET6, name, &addrbuf) == 1)
97 		goto err;
98 
99 	free((char *)conn_ctx->servername);
100 	if ((conn_ctx->servername = strdup(name)) == NULL)
101 		goto err;
102 
103 	/* Find appropriate SSL context for requested servername. */
104 	for (sni_ctx = ctx->sni_ctx; sni_ctx != NULL; sni_ctx = sni_ctx->next) {
105 		if (tls_check_name(ctx, sni_ctx->ssl_cert, name,
106 		    &match) == -1)
107 			goto err;
108 		if (match) {
109 			SSL_set_SSL_CTX(conn_ctx->ssl_conn, sni_ctx->ssl_ctx);
110 			return (SSL_TLSEXT_ERR_OK);
111 		}
112 	}
113 
114 	/* No match, use the existing context/certificate. */
115 	return (SSL_TLSEXT_ERR_OK);
116 
117  err:
118 	/*
119 	 * There is no way to tell libssl that an internal failure occurred.
120 	 * The only option we have is to return a fatal alert.
121 	 */
122 	*al = TLS1_AD_INTERNAL_ERROR;
123 	return (SSL_TLSEXT_ERR_ALERT_FATAL);
124 }
125 
126 static struct tls_ticket_key *
127 tls_server_ticket_key(struct tls_config *config, unsigned char *keyname)
128 {
129 	struct tls_ticket_key *key = NULL;
130 	time_t now;
131 	int i;
132 
133 	now = time(NULL);
134 	if (config->ticket_autorekey == 1) {
135 		if (now - 3 * (config->session_lifetime / 4) >
136 		    config->ticket_keys[0].time) {
137 			if (tls_config_ticket_autorekey(config) == -1)
138 				return (NULL);
139 		}
140 	}
141 	for (i = 0; i < TLS_NUM_TICKETS; i++) {
142 		struct tls_ticket_key *tk = &config->ticket_keys[i];
143 		if (now - config->session_lifetime > tk->time)
144 			continue;
145 		if (keyname == NULL || timingsafe_memcmp(keyname,
146 		    tk->key_name, sizeof(tk->key_name)) == 0) {
147 			key = tk;
148 			break;
149 		}
150 	}
151 	return (key);
152 }
153 
154 static int
155 tls_server_ticket_cb(SSL *ssl, unsigned char *keyname, unsigned char *iv,
156     EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int mode)
157 {
158 	struct tls_ticket_key *key;
159 	struct tls *tls_ctx;
160 
161 	if ((tls_ctx = SSL_get_app_data(ssl)) == NULL)
162 		return (-1);
163 
164 	if (mode == 1) {
165 		/* create new session */
166 		key = tls_server_ticket_key(tls_ctx->config, NULL);
167 		if (key == NULL) {
168 			tls_set_errorx(tls_ctx, "no valid ticket key found");
169 			return (-1);
170 		}
171 
172 		memcpy(keyname, key->key_name, sizeof(key->key_name));
173 		arc4random_buf(iv, EVP_MAX_IV_LENGTH);
174 		EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL,
175 		    key->aes_key, iv);
176 		HMAC_Init_ex(hctx, key->hmac_key, sizeof(key->hmac_key),
177 		    EVP_sha256(), NULL);
178 		return (0);
179 	} else {
180 		/* get key by name */
181 		key = tls_server_ticket_key(tls_ctx->config, keyname);
182 		if (key == NULL)
183 			return (0);
184 
185 		EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL,
186 		    key->aes_key, iv);
187 		HMAC_Init_ex(hctx, key->hmac_key, sizeof(key->hmac_key),
188 		    EVP_sha256(), NULL);
189 
190 		/* time to renew the ticket? is it the primary key? */
191 		if (key != &tls_ctx->config->ticket_keys[0])
192 			return (2);
193 		return (1);
194 	}
195 }
196 
197 static int
198 tls_keypair_load_cert(struct tls_keypair *keypair, struct tls_error *error,
199     X509 **cert)
200 {
201 	char *errstr = "unknown";
202 	BIO *cert_bio = NULL;
203 	int ssl_err;
204 	int rv = -1;
205 
206 	X509_free(*cert);
207 	*cert = NULL;
208 
209 	if (keypair->cert_mem == NULL) {
210 		tls_error_set(error, "keypair has no certificate");
211 		goto err;
212 	}
213 	if ((cert_bio = BIO_new_mem_buf(keypair->cert_mem,
214 	    keypair->cert_len)) == NULL) {
215 		tls_error_set(error, "failed to create certificate bio");
216 		goto err;
217 	}
218 	if ((*cert = PEM_read_bio_X509(cert_bio, NULL, NULL, NULL)) == NULL) {
219 		if ((ssl_err = ERR_peek_error()) != 0)
220 		    errstr = ERR_error_string(ssl_err, NULL);
221 		tls_error_set(error, "failed to load certificate: %s", errstr);
222 		goto err;
223 	}
224 
225 	rv = 0;
226 
227  err:
228 	BIO_free(cert_bio);
229 
230 	return (rv);
231 }
232 
233 static int
234 tls_configure_server_ssl(struct tls *ctx, SSL_CTX **ssl_ctx,
235     struct tls_keypair *keypair)
236 {
237 	EC_KEY *ecdh_key;
238 
239 	SSL_CTX_free(*ssl_ctx);
240 
241 	if ((*ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
242 		tls_set_errorx(ctx, "ssl context failure");
243 		goto err;
244 	}
245 
246 	SSL_CTX_set_options(*ssl_ctx, SSL_OP_NO_CLIENT_RENEGOTIATION);
247 
248 	if (SSL_CTX_set_tlsext_servername_callback(*ssl_ctx,
249 	    tls_servername_cb) != 1) {
250 		tls_set_error(ctx, "failed to set servername callback");
251 		goto err;
252 	}
253 	if (SSL_CTX_set_tlsext_servername_arg(*ssl_ctx, ctx) != 1) {
254 		tls_set_error(ctx, "failed to set servername callback arg");
255 		goto err;
256 	}
257 
258 	if (tls_configure_ssl(ctx, *ssl_ctx) != 0)
259 		goto err;
260 	if (tls_configure_ssl_keypair(ctx, *ssl_ctx, keypair, 1) != 0)
261 		goto err;
262 	if (ctx->config->verify_client != 0) {
263 		int verify = SSL_VERIFY_PEER;
264 		if (ctx->config->verify_client == 1)
265 			verify |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
266 		if (tls_configure_ssl_verify(ctx, *ssl_ctx, verify) == -1)
267 			goto err;
268 	}
269 
270 	if (ctx->config->alpn != NULL)
271 		SSL_CTX_set_alpn_select_cb(*ssl_ctx, tls_server_alpn_cb,
272 		    ctx);
273 
274 	if (ctx->config->dheparams == -1)
275 		SSL_CTX_set_dh_auto(*ssl_ctx, 1);
276 	else if (ctx->config->dheparams == 1024)
277 		SSL_CTX_set_dh_auto(*ssl_ctx, 2);
278 
279 	if (ctx->config->ecdhecurve == -1) {
280 		SSL_CTX_set_ecdh_auto(*ssl_ctx, 1);
281 	} else if (ctx->config->ecdhecurve != NID_undef) {
282 		if ((ecdh_key = EC_KEY_new_by_curve_name(
283 		    ctx->config->ecdhecurve)) == NULL) {
284 			tls_set_errorx(ctx, "failed to set ECDHE curve");
285 			goto err;
286 		}
287 		SSL_CTX_set_options(*ssl_ctx, SSL_OP_SINGLE_ECDH_USE);
288 		SSL_CTX_set_tmp_ecdh(*ssl_ctx, ecdh_key);
289 		EC_KEY_free(ecdh_key);
290 	}
291 
292 	if (ctx->config->ciphers_server == 1)
293 		SSL_CTX_set_options(*ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
294 
295 	if (SSL_CTX_set_tlsext_status_cb(*ssl_ctx, tls_ocsp_stapling_cb) != 1) {
296 		tls_set_errorx(ctx, "failed to add OCSP stapling callback");
297 		goto err;
298 	}
299 
300 	if (ctx->config->session_lifetime > 0) {
301 		/* set the session lifetime and enable tickets */
302 		SSL_CTX_set_timeout(*ssl_ctx, ctx->config->session_lifetime);
303 		SSL_CTX_clear_options(*ssl_ctx, SSL_OP_NO_TICKET);
304 		if (!SSL_CTX_set_tlsext_ticket_key_cb(*ssl_ctx,
305 		    tls_server_ticket_cb)) {
306 			tls_set_error(ctx,
307 			    "failed to set the TLS ticket callback");
308 			goto err;
309 		}
310 	}
311 
312 	if (SSL_CTX_set_session_id_context(*ssl_ctx, ctx->config->session_id,
313 	    sizeof(ctx->config->session_id)) != 1) {
314 		tls_set_error(ctx, "failed to set session id context");
315 		goto err;
316 	}
317 
318 	return (0);
319 
320   err:
321 	SSL_CTX_free(*ssl_ctx);
322 	*ssl_ctx = NULL;
323 
324 	return (-1);
325 }
326 
327 static int
328 tls_configure_server_sni(struct tls *ctx)
329 {
330 	struct tls_sni_ctx **sni_ctx;
331 	struct tls_keypair *kp;
332 
333 	if (ctx->config->keypair->next == NULL)
334 		return (0);
335 
336 	/* Set up additional SSL contexts for SNI. */
337 	sni_ctx = &ctx->sni_ctx;
338 	for (kp = ctx->config->keypair->next; kp != NULL; kp = kp->next) {
339 		if ((*sni_ctx = tls_sni_ctx_new()) == NULL) {
340 			tls_set_errorx(ctx, "out of memory");
341 			goto err;
342 		}
343 		if (tls_configure_server_ssl(ctx, &(*sni_ctx)->ssl_ctx, kp) == -1)
344 			goto err;
345 		if (tls_keypair_load_cert(kp, &ctx->error,
346 		    &(*sni_ctx)->ssl_cert) == -1)
347 			goto err;
348 		sni_ctx = &(*sni_ctx)->next;
349 	}
350 
351 	return (0);
352 
353  err:
354 	return (-1);
355 }
356 
357 int
358 tls_configure_server(struct tls *ctx)
359 {
360 	if (tls_configure_server_ssl(ctx, &ctx->ssl_ctx,
361 	    ctx->config->keypair) == -1)
362 		goto err;
363 	if (tls_configure_server_sni(ctx) == -1)
364 		goto err;
365 
366 	return (0);
367 
368  err:
369 	return (-1);
370 }
371 
372 static struct tls *
373 tls_accept_common(struct tls *ctx)
374 {
375 	struct tls *conn_ctx = NULL;
376 
377 	if ((ctx->flags & TLS_SERVER) == 0) {
378 		tls_set_errorx(ctx, "not a server context");
379 		goto err;
380 	}
381 
382 	if ((conn_ctx = tls_server_conn(ctx)) == NULL) {
383 		tls_set_errorx(ctx, "connection context failure");
384 		goto err;
385 	}
386 
387 	if ((conn_ctx->ssl_conn = SSL_new(ctx->ssl_ctx)) == NULL) {
388 		tls_set_errorx(ctx, "ssl failure");
389 		goto err;
390 	}
391 
392 	if (SSL_set_app_data(conn_ctx->ssl_conn, conn_ctx) != 1) {
393 		tls_set_errorx(ctx, "ssl application data failure");
394 		goto err;
395 	}
396 
397 	return conn_ctx;
398 
399  err:
400 	tls_free(conn_ctx);
401 
402 	return (NULL);
403 }
404 
405 int
406 tls_accept_socket(struct tls *ctx, struct tls **cctx, int s)
407 {
408 	return (tls_accept_fds(ctx, cctx, s, s));
409 }
410 
411 int
412 tls_accept_fds(struct tls *ctx, struct tls **cctx, int fd_read, int fd_write)
413 {
414 	struct tls *conn_ctx;
415 
416 	if ((conn_ctx = tls_accept_common(ctx)) == NULL)
417 		goto err;
418 
419 	if (SSL_set_rfd(conn_ctx->ssl_conn, fd_read) != 1 ||
420 	    SSL_set_wfd(conn_ctx->ssl_conn, fd_write) != 1) {
421 		tls_set_errorx(ctx, "ssl file descriptor failure");
422 		goto err;
423 	}
424 
425 	*cctx = conn_ctx;
426 
427 	return (0);
428  err:
429 	tls_free(conn_ctx);
430 	*cctx = NULL;
431 
432 	return (-1);
433 }
434 
435 int
436 tls_accept_cbs(struct tls *ctx, struct tls **cctx,
437     tls_read_cb read_cb, tls_write_cb write_cb, void *cb_arg)
438 {
439 	struct tls *conn_ctx;
440 
441 	if ((conn_ctx = tls_accept_common(ctx)) == NULL)
442 		goto err;
443 
444 	if (tls_set_cbs(conn_ctx, read_cb, write_cb, cb_arg) != 0)
445 		goto err;
446 
447 	*cctx = conn_ctx;
448 
449 	return (0);
450  err:
451 	tls_free(conn_ctx);
452 	*cctx = NULL;
453 
454 	return (-1);
455 }
456 
457 int
458 tls_handshake_server(struct tls *ctx)
459 {
460 	int ssl_ret;
461 	int rv = -1;
462 
463 	if ((ctx->flags & TLS_SERVER_CONN) == 0) {
464 		tls_set_errorx(ctx, "not a server connection context");
465 		goto err;
466 	}
467 
468 	ctx->state |= TLS_SSL_NEEDS_SHUTDOWN;
469 
470 	ERR_clear_error();
471 	if ((ssl_ret = SSL_accept(ctx->ssl_conn)) != 1) {
472 		rv = tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "handshake");
473 		goto err;
474 	}
475 
476 	ctx->state |= TLS_HANDSHAKE_COMPLETE;
477 	rv = 0;
478 
479  err:
480 	return (rv);
481 }
482