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