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