tls.c 35.9 KB
Newer Older
1 2
/*
 * Copyright (C) 2016 American Civil Liberties Union (ACLU)
3
 *               2016-2018 CZ.NIC, z.s.p.o
4
 *
5
 * Initial Author: Daniel Kahn Gillmor <dkg@fifthhorseman.net>
6
 *                 Ondřej Surý <ondrej@sury.org>
7
 *
8 9 10 11
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
12
 *
13 14 15 16
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
17
 *
18 19 20 21
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

22 23
#include <gnutls/abstract.h>
#include <gnutls/crypto.h>
Marek Vavrusa's avatar
Marek Vavrusa committed
24
#include <gnutls/gnutls.h>
25
#include <gnutls/x509.h>
26 27
#include <uv.h>

28 29 30 31 32
#include <assert.h>
#include <errno.h>
#include <stdlib.h>

#include "contrib/ucw/lib.h"
33
#include "contrib/base64.h"
34
#include "daemon/io.h"
35 36
#include "daemon/tls.h"
#include "daemon/worker.h"
37
#include "daemon/session.h"
38

39
#define EPHEMERAL_CERT_EXPIRATION_SECONDS_RENEW_BEFORE (60*60*24*7)
40
#define GNUTLS_PIN_MIN_VERSION  0x030400
41

42 43
/** @internal Debugging facility. */
#ifdef DEBUG
44
#define DEBUG_MSG(...) kr_log_verbose("[tls] " __VA_ARGS__)
45
#else
46
#define DEBUG_MSG(...)
47 48
#endif

49 50 51
struct async_write_ctx {
	uv_write_t write_req;
	struct tls_common_ctx *t;
52
	char buf[];
53 54
};

55
static char const server_logstring[] = "tls";
56
static char const client_logstring[] = "tls_client";
57

58 59
static int client_verify_certificate(gnutls_session_t tls_session);

60 61 62 63 64 65 66
/**
 * Set mandatory security settings from
 * https://tools.ietf.org/html/draft-ietf-dprive-dtls-and-tls-profiles-11#section-9
 * Performance optimizations are not implemented at the moment.
 */
static int kres_gnutls_set_priority(gnutls_session_t session) {
	static const char * const priorities =
67
		"NORMAL:" /* GnuTLS defaults */
68
		"-VERS-TLS1.0:-VERS-TLS1.1:" /* TLS 1.2 and higher */
69 70 71
		 /* Some distros by default allow features that are considered
		  * too insecure nowadays, so let's disable them explicitly. */
		"-VERS-SSL3.0:-ARCFOUR-128:-COMP-ALL:+COMP-NULL";
72 73 74 75 76 77 78 79 80
	const char *errpos = NULL;
	int err = gnutls_priority_set_direct(session, priorities, &errpos);
	if (err != GNUTLS_E_SUCCESS) {
		kr_log_error("[tls] setting priority '%s' failed at character %zd (...'%s') with %s (%d)\n",
			     priorities, errpos - priorities, errpos, gnutls_strerror_name(err), err);
	}
	return err;
}

81
static ssize_t kres_gnutls_pull(gnutls_transport_ptr_t h, void *buf, size_t len)
82
{
83
	struct tls_common_ctx *t = (struct tls_common_ctx *)h;
Marek Vavrusa's avatar
Marek Vavrusa committed
84
	assert(t != NULL);
85

Marek Vavrusa's avatar
Marek Vavrusa committed
86
	ssize_t	avail = t->nread - t->consumed;
87 88
	DEBUG_MSG("[%s] pull wanted: %zu available: %zu\n",
		  t->client_side ? "tls_client" : "tls", len, avail);
89 90 91 92 93
	if (t->nread <= t->consumed) {
		errno = EAGAIN;
		return -1;
	}

Marek Vavrusa's avatar
Marek Vavrusa committed
94
	ssize_t	transfer = MIN(avail, len);
95 96 97 98 99
	memcpy(buf, t->buf + t->consumed, transfer);
	t->consumed += transfer;
	return transfer;
}

100 101 102
static void on_write_complete(uv_write_t *req, int status)
{
	assert(req->data != NULL);
103 104 105 106
	struct async_write_ctx *async_ctx = (struct async_write_ctx *)req->data;
	struct tls_common_ctx *t = async_ctx->t;
	assert(t->write_queue_size);
	t->write_queue_size -= 1;
107 108 109
	free(req->data);
}

110
static bool stream_queue_is_empty(struct tls_common_ctx *t)
111
{
112
	return (t->write_queue_size == 0);
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
}

static ssize_t kres_gnutls_vec_push(gnutls_transport_ptr_t h, const giovec_t * iov, int iovcnt)
{
	struct tls_common_ctx *t = (struct tls_common_ctx *)h;

	if (t == NULL) {
		errno = EFAULT;
		return -1;
	}

	if (iovcnt == 0) {
		return 0;
	}

128 129 130
	assert(t->session);
	uv_stream_t *handle = (uv_stream_t *)session_get_handle(t->session);
	assert(handle && handle->type == UV_TCP);
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150

	/*
	 * This is a little bit complicated. There are two different writes:
	 * 1. Immediate, these don't need to own the buffered data and return immediately
	 * 2. Asynchronous, these need to own the buffers until the write completes
	 * In order to avoid copying the buffer, an immediate write is tried first if possible.
	 * If it isn't possible to write the data without queueing, an asynchronous write
	 * is created (with copied buffered data).
	 */

	size_t total_len = 0;
	uv_buf_t uv_buf[iovcnt];
	for (int i = 0; i < iovcnt; ++i) {
		uv_buf[i].base = iov[i].iov_base;
		uv_buf[i].len = iov[i].iov_len;
		total_len += iov[i].iov_len;
	}

	/* Try to perform the immediate write first to avoid copy */
	int ret = 0;
151
	if (stream_queue_is_empty(t)) {
152 153 154
		ret = uv_try_write(handle, uv_buf, iovcnt);
		DEBUG_MSG("[%s] push %zu <%p> = %d\n",
		    t->client_side ? "tls_client" : "tls", total_len, h, ret);
155 156 157 158 159
		/* from libuv documentation -
		   uv_try_write will return either:
		     > 0: number of bytes written (can be less than the supplied buffer size).
		     < 0: negative error code (UV_EAGAIN is returned if no data can be sent immediately).
		*/
160 161 162 163 164 165 166 167
		if (ret == total_len) {
			/* All the data were buffered by libuv.
			 * Return. */
			return ret;
		}

		if (ret < 0 && ret != UV_EAGAIN) {
			/* uv_try_write() has returned error code other then UV_EAGAIN.
168
			 * Return. */
169 170
			ret = -1;
			errno = EIO;
171 172
			return ret;
		}
173 174 175 176 177 178 179 180 181 182 183
		/* Since we are here expression below is true
		 * (ret != total_len) && (ret >= 0 || ret == UV_EAGAIN)
		 * or the same
		 * (ret != total_len && ret >= 0) || (ret != total_len && ret == UV_EAGAIN)
		 * i.e. either occurs partial write or UV_EAGAIN.
		 * Proceed and copy data amount to owned memory and perform async write.
		 */
		if (ret == UV_EAGAIN) {
			/* No data were buffered, so we must buffer all the data. */
			ret = 0;
		}
184 185 186
	}

	/* Fallback when the queue is full, and it's not possible to do an immediate write */
187 188 189 190 191 192
	char *p = malloc(sizeof(struct async_write_ctx) + total_len - ret);
	if (p != NULL) {
		struct async_write_ctx *async_ctx = (struct async_write_ctx *)p;
		/* Save pointer to session tls context */
		async_ctx->t = t;
		char *buf = async_ctx->buf;
193
		/* Skip data written in the partial write */
194
		size_t to_skip = ret;
195 196 197
		/* Copy the buffer into owned memory */
		size_t off = 0;
		for (int i = 0; i < iovcnt; ++i) {
198 199 200 201 202 203 204 205 206 207 208
			if (to_skip > 0) {
				/* Ignore current buffer if it's all skipped */
				if (to_skip >= uv_buf[i].len) {
					to_skip -= uv_buf[i].len;
					continue;
				}
				/* Skip only part of the buffer */
				uv_buf[i].base += to_skip;
				uv_buf[i].len -= to_skip;
				to_skip = 0;
			}
209 210 211 212
			memcpy(buf + off, uv_buf[i].base, uv_buf[i].len);
			off += uv_buf[i].len;
		}
		uv_buf[0].base = buf;
213
		uv_buf[0].len = off;
214 215

		/* Create an asynchronous write request */
216 217 218
		uv_write_t *write_req = &async_ctx->write_req;
		memset(write_req, 0, sizeof(uv_write_t));
		write_req->data = p;
219 220 221 222

		/* Perform an asynchronous write with a callback */
		if (uv_write(write_req, handle, uv_buf, 1, on_write_complete) == 0) {
			ret = total_len;
223
			t->write_queue_size += 1;
224
		} else {
225
			free(p);
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
			errno = EIO;
			ret = -1;
		}
	} else {
		errno = ENOMEM;
		ret = -1;
	}

	DEBUG_MSG("[%s] queued %zu <%p> = %d\n",
	    t->client_side ? "tls_client" : "tls", total_len, h, ret);

	return ret;
}

/** Perform TLS handshake and handle error codes according to the documentation.
  * See See https://gnutls.org/manual/html_node/TLS-handshake.html#TLS-handshake
  * The function returns kr_ok() or success or non fatal error, kr_error(EAGAIN) on blocking, or kr_error(EIO) on fatal error.
  */
static int tls_handshake(struct tls_common_ctx *ctx, tls_handshake_cb handshake_cb) {
	struct session *session = ctx->session;
	const char *logstring = ctx->client_side ? client_logstring : server_logstring;

	int err = gnutls_handshake(ctx->tls_session);
	if (err == GNUTLS_E_SUCCESS) {
		/* Handshake finished, return success */
		ctx->handshake_state = TLS_HS_DONE;
252
		struct sockaddr *peer = session_get_peer(session);
253
		kr_log_verbose("[%s] TLS handshake with %s has completed\n",
254
			       logstring,  kr_straddr(peer));
255
		if (handshake_cb) {
256 257 258
			if (handshake_cb(session, 0) != kr_ok()) {
				return kr_error(EIO);
			}
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
		}
	} else if (err == GNUTLS_E_AGAIN) {
		return kr_error(EAGAIN);
	} else if (gnutls_error_is_fatal(err)) {
		/* Fatal errors, return error as it's not recoverable */
		kr_log_verbose("[%s] gnutls_handshake failed: %s (%d)\n",
			     logstring,
		             gnutls_strerror_name(err), err);
		if (handshake_cb) {
			handshake_cb(session, -1);
		}
		return kr_error(EIO);
	} else if (err == GNUTLS_E_WARNING_ALERT_RECEIVED) {
		/* Handle warning when in verbose mode */
		const char *alert_name = gnutls_alert_get_name(gnutls_alert_get(ctx->tls_session));
		if (alert_name != NULL) {
275
			struct sockaddr *peer = session_get_peer(session);
276
			kr_log_verbose("[%s] TLS alert from %s received: %s\n",
277
				       logstring, kr_straddr(peer), alert_name);
278 279 280 281 282 283
		}
	}
	return kr_ok();
}


284
struct tls_ctx_t *tls_new(struct worker_ctx *worker)
285
{
Marek Vavrusa's avatar
Marek Vavrusa committed
286
	assert(worker != NULL);
287 288
	assert(worker->engine != NULL);

289 290
	struct network *net = &worker->engine->net;
	if (!net->tls_credentials) {
291 292 293 294 295
		net->tls_credentials = tls_get_ephemeral_credentials(worker->engine);
		if (!net->tls_credentials) {
			kr_log_error("[tls] X.509 credentials are missing, and ephemeral credentials failed; no TLS\n");
			return NULL;
		}
296
		kr_log_info("[tls] Using ephemeral TLS credentials:\n");
297
		tls_credentials_log_pins(net->tls_credentials);
298 299
	}

300
	time_t now = time(NULL);
301 302 303
	if (net->tls_credentials->valid_until != GNUTLS_X509_NO_WELL_DEFINED_EXPIRATION) {
		if (net->tls_credentials->ephemeral_servicename) {
			/* ephemeral cert: refresh if due to expire within a week */
304
			if (now >= net->tls_credentials->valid_until - EPHEMERAL_CERT_EXPIRATION_SECONDS_RENEW_BEFORE) {
305 306 307 308 309 310 311
				struct tls_credentials *newcreds = tls_get_ephemeral_credentials(worker->engine);
				if (newcreds) {
					tls_credentials_release(net->tls_credentials);
					net->tls_credentials = newcreds;
					kr_log_info("[tls] Renewed expiring ephemeral X.509 cert\n");
				} else {
					kr_log_error("[tls] Failed to renew expiring ephemeral X.509 cert, using existing one\n");
312
				}
313 314 315 316 317 318 319 320
			}
		} else {
			/* non-ephemeral cert: warn once when certificate expires */
			if (now >= net->tls_credentials->valid_until) {
				kr_log_error("[tls] X.509 certificate has expired!\n");
				net->tls_credentials->valid_until = GNUTLS_X509_NO_WELL_DEFINED_EXPIRATION;
			}
		}
321 322
	}

Marek Vavrusa's avatar
Marek Vavrusa committed
323
	struct tls_ctx_t *tls = calloc(1, sizeof(struct tls_ctx_t));
324
	if (tls == NULL) {
325 326 327
		kr_log_error("[tls] failed to allocate TLS context\n");
		return NULL;
	}
328

329
	int err = gnutls_init(&tls->c.tls_session, GNUTLS_SERVER | GNUTLS_NONBLOCK);
330
	if (err != GNUTLS_E_SUCCESS) {
Marek Vavrusa's avatar
Marek Vavrusa committed
331
		kr_log_error("[tls] gnutls_init(): %s (%d)\n", gnutls_strerror_name(err), err);
332
		tls_free(tls);
333 334
		return NULL;
	}
335
	tls->credentials = tls_credentials_reserve(net->tls_credentials);
336 337
	err = gnutls_credentials_set(tls->c.tls_session, GNUTLS_CRD_CERTIFICATE,
				     tls->credentials->credentials);
338
	if (err != GNUTLS_E_SUCCESS) {
Marek Vavrusa's avatar
Marek Vavrusa committed
339
		kr_log_error("[tls] gnutls_credentials_set(): %s (%d)\n", gnutls_strerror_name(err), err);
340 341
		tls_free(tls);
		return NULL;
342
	}
343
	if (kres_gnutls_set_priority(tls->c.tls_session) != GNUTLS_E_SUCCESS) {
344
		tls_free(tls);
345
		return NULL;
346
	}
Marek Vavrusa's avatar
Marek Vavrusa committed
347

348 349
	tls->c.worker = worker;
	tls->c.client_side = false;
350

351
	gnutls_transport_set_pull_function(tls->c.tls_session, kres_gnutls_pull);
352
	gnutls_transport_set_vec_push_function(tls->c.tls_session, kres_gnutls_vec_push);
353
	gnutls_transport_set_ptr(tls->c.tls_session, tls);
354

355 356 357
	if (net->tls_session_ticket_ctx) {
		tls_session_ticket_enable(net->tls_session_ticket_ctx,
					  tls->c.tls_session);
358 359
	}

360
	return tls;
361 362
}

363
void tls_close(struct tls_common_ctx *ctx)
364 365 366 367 368 369 370
{
	if (ctx == NULL || ctx->tls_session == NULL) {
		return;
	}

	assert(ctx->session);

371
	if (ctx->handshake_state == TLS_HS_DONE) {
372
		const struct sockaddr *peer = session_get_peer(ctx->session);
373
		kr_log_verbose("[%s] closing tls connection to `%s`\n",
374
			       ctx->client_side ? "tls_client" : "tls",
375
			       kr_straddr(peer));
376
		ctx->handshake_state = TLS_HS_CLOSING;
377 378 379 380
		gnutls_bye(ctx->tls_session, GNUTLS_SHUT_RDWR);
	}
}

381
void tls_free(struct tls_ctx_t *tls)
382 383 384 385
{
	if (!tls) {
		return;
	}
386

387
	if (tls->c.tls_session) {
Marek Vavrusa's avatar
Marek Vavrusa committed
388
		/* Don't terminate TLS connection, just tear it down */
389 390
		gnutls_deinit(tls->c.tls_session);
		tls->c.tls_session = NULL;
391
	}
Marek Vavrusa's avatar
Marek Vavrusa committed
392 393

	tls_credentials_release(tls->credentials);
394 395 396
	free(tls);
}

397
int tls_write(uv_write_t *req, uv_handle_t *handle, knot_pkt_t *pkt, uv_write_cb cb)
398
{
399 400
	if (!pkt || !handle || !handle->data) {
		return kr_error(EINVAL);
401 402
	}

403 404
	struct session *s = handle->data;
	struct tls_common_ctx *tls_ctx = session_tls_get_common_ctx(s);
405 406

	assert (tls_ctx);
407
	assert (session_flags(s)->outgoing == tls_ctx->client_side);
408

Marek Vavrusa's avatar
Marek Vavrusa committed
409
	const uint16_t pkt_size = htons(pkt->size);
410 411 412
	const char *logstring = tls_ctx->client_side ? client_logstring : server_logstring;
	gnutls_session_t tls_session = tls_ctx->tls_session;

413
	gnutls_record_cork(tls_session);
Marek Vavrusa's avatar
Marek Vavrusa committed
414
	ssize_t count = 0;
415 416 417 418
	if ((count = gnutls_record_send(tls_session, &pkt_size, sizeof(pkt_size)) < 0) ||
	    (count = gnutls_record_send(tls_session, pkt->wire, pkt->size) < 0)) {
		kr_log_error("[%s] gnutls_record_send failed: %s (%zd)\n",
			     logstring, gnutls_strerror_name(count), count);
419
		return kr_error(EIO);
420
	}
421

422 423 424
	const ssize_t submitted = sizeof(pkt_size) + pkt->size;

	int ret = gnutls_record_uncork(tls_session, GNUTLS_RECORD_WAIT);
425 426 427 428 429 430 431 432
	if (ret < 0) {
		if (!gnutls_error_is_fatal(ret)) {
			return kr_error(EAGAIN);
		} else {
			kr_log_error("[%s] gnutls_record_uncork failed: %s (%d)\n",
				     logstring, gnutls_strerror_name(ret), ret);
			return kr_error(EIO);
		}
433 434 435 436 437 438 439 440 441 442 443
	}

	if (ret != submitted) {
		kr_log_error("[%s] gnutls_record_uncork didn't send all data (%d of %zd)\n",
		             logstring, ret, submitted);
		return kr_error(EIO);
	}

	/* The data is now accepted in gnutls internal buffers, the message can be treated as sent */
	req->handle = (uv_stream_t *)handle;
	cb(req, 0);
444

445 446
	return kr_ok();
}
447

448
ssize_t tls_process_input_data(struct session *s, const uint8_t *buf, ssize_t nread)
449
{
450
	struct tls_common_ctx *tls_p = session_tls_get_common_ctx(s);
451 452 453 454
	if (!tls_p) {
		return kr_error(ENOSYS);
	}

455
	assert(tls_p->session == s);
456 457 458 459 460 461
	const bool ok = tls_p->recv_buf == buf && nread <= sizeof(tls_p->recv_buf);
	if (!ok) {
		assert(false);
		/* don't risk overflowing the buffer if we have a mistake somewhere */
		return kr_error(EINVAL);
	}
462

463 464
	const char *logstring = tls_p->client_side ? client_logstring : server_logstring;

465
	tls_p->buf = buf;
466
	tls_p->nread = nread >= 0 ? nread : 0;
467
	tls_p->consumed = 0;
468

469 470 471 472 473 474 475 476
	/* Ensure TLS handshake is performed before receiving data.
	 * See https://www.gnutls.org/manual/html_node/TLS-handshake.html */
	while (tls_p->handshake_state <= TLS_HS_IN_PROGRESS) {
		int err = tls_handshake(tls_p, tls_p->handshake_cb);
		if (err == kr_error(EAGAIN)) {
			return 0; /* Wait for more data */
		} else if (err != kr_ok()) {
			return err;
477 478
		}
	}
479

480
	/* See https://gnutls.org/manual/html_node/Data-transfer-and-termination.html#Data-transfer-and-termination */
481 482 483
	ssize_t submitted = 0;
	uint8_t *wire_buf = session_wirebuf_get_free_start(s);
	size_t wire_buf_size = session_wirebuf_get_free_size(s);
484
	while (true) {
485
		ssize_t count = gnutls_record_recv(tls_p->tls_session, wire_buf, wire_buf_size);
486
		if (count == GNUTLS_E_AGAIN) {
487 488 489 490 491
			break; /* No data available */
		} else if (count == GNUTLS_E_INTERRUPTED) {
			continue;
		} else if (count == GNUTLS_E_REHANDSHAKE) {
			/* See https://www.gnutls.org/manual/html_node/Re_002dauthentication.html */
492 493 494
			struct sockaddr *peer = session_get_peer(s);
			kr_log_verbose("[%s] TLS rehandshake with %s has started\n",
				       logstring,  kr_straddr(peer));
495
			tls_set_hs_state(tls_p, TLS_HS_IN_PROGRESS);
496
			int err = kr_ok();
497
			while (tls_p->handshake_state <= TLS_HS_IN_PROGRESS) {
498
				err = tls_handshake(tls_p, tls_p->handshake_cb);
499 500 501 502 503
				if (err == kr_error(EAGAIN)) {
					break;
				} else if (err != kr_ok()) {
					return err;
				}
504
			}
505 506 507 508 509 510
			if (err == kr_error(EAGAIN)) {
				/* pull function is out of data */
				break;
			}
			/* There are can be data available, check it. */
			continue;
511
		} else if (count < 0) {
512
			kr_log_verbose("[%s] gnutls_record_recv failed: %s (%zd)\n",
513
				     logstring, gnutls_strerror_name(count), count);
514
			return kr_error(EIO);
515
		} else if (count == 0) {
516 517
			break;
		}
518 519 520 521
		DEBUG_MSG("[%s] received %zd data\n", logstring, count);
		wire_buf += count;
		wire_buf_size -= count;
		submitted += count;
522 523 524 525 526 527 528 529 530 531 532 533 534 535
		if (wire_buf_size == 0 && tls_p->consumed != tls_p->nread) {
			/* session buffer is full
			 * whereas not all the data were consumed */
			return kr_error(ENOSPC);
		}
	}
	/* Here all data must be consumed. */
	if (tls_p->consumed != tls_p->nread) {
		/* Something went wrong, better return error.
		 * This is most probably due to gnutls_record_recv() did not
		 * consume all available network data by calling kres_gnutls_pull().
		 * TODO assess the need for buffering of data amount.
		 */
		return kr_error(ENOSPC);
536
	}
537
	return submitted;
538 539
}

540
#if TLS_CAN_USE_PINS
541 542 543
/*
  DNS-over-TLS Out of band key-pinned authentication profile uses the
  same form of pins as HPKP:
544

545
  e.g.  pin-sha256="FHkyLhvI0n70E47cJlRTamTrnYVcsYdjUGbr79CfAVI="
546

547 548 549
  DNS-over-TLS OOB key-pins: https://tools.ietf.org/html/rfc7858#appendix-A
  HPKP pin reference:        https://tools.ietf.org/html/rfc7469#appendix-A
*/
550
#define PINLEN  ((((32) * 8 + 4)/6) + 3 + 1)
551

552 553 554 555 556 557
/* Compute pin_sha256 for the certificate.
 * It may be in raw format - just TLS_SHA256_RAW_LEN bytes without termination,
 * or it may be a base64 0-terminated string requiring up to
 * TLS_SHA256_BASE64_BUFLEN bytes.
 * \return error code */
static int get_oob_key_pin(gnutls_x509_crt_t crt, char *outchar, ssize_t outchar_len, bool raw)
558
{
559 560 561 562 563
	if (raw && outchar_len < TLS_SHA256_RAW_LEN) {
		assert(false);
		return kr_error(ENOSPC);
		/* With !raw we have check inside base64_encode. */
	}
564
	gnutls_pubkey_t key;
565 566
	int err = gnutls_pubkey_init(&key);
	if (err != GNUTLS_E_SUCCESS) return err;
567

568 569 570
	gnutls_datum_t datum = { .data = NULL, .size = 0 };
	err = gnutls_pubkey_import_x509(key, crt, 0);
	if (err != GNUTLS_E_SUCCESS) goto leave;
571

572 573 574
	err = gnutls_pubkey_export2(key, GNUTLS_X509_FMT_DER, &datum);
	if (err != GNUTLS_E_SUCCESS) goto leave;

Petr Špaček's avatar
Petr Špaček committed
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
	char raw_pin[TLS_SHA256_RAW_LEN]; /* TMP buffer if raw == false */
	err = gnutls_hash_fast(GNUTLS_DIG_SHA256, datum.data, datum.size,
				(raw ? outchar : raw_pin));
	if (err != GNUTLS_E_SUCCESS || raw/*success*/)
		goto leave;
	/* Convert to non-raw. */
	err = base64_encode((uint8_t *)raw_pin, sizeof(raw_pin),
			    (uint8_t *)outchar, outchar_len);
	if (err >= 0 && err < outchar_len) {
		err = GNUTLS_E_SUCCESS;
		outchar[err] = '\0'; /* base64_encode() doesn't do it */
	} else if (err >= 0) {
		assert(false);
		err = kr_error(ENOSPC); /* base64 fits but '\0' doesn't */
		outchar[outchar_len - 1] = '\0';
590 591 592 593 594 595 596 597 598 599 600 601
	}
leave:
	gnutls_free(datum.data);
	gnutls_pubkey_deinit(key);
	return err;
}

void tls_credentials_log_pins(struct tls_credentials *tls_credentials)
{
	for (int index = 0;; index++) {
		gnutls_x509_crt_t *certs = NULL;
		unsigned int cert_count = 0;
602 603 604
		int err = gnutls_certificate_get_x509_crt(tls_credentials->credentials,
							index, &certs, &cert_count);
		if (err != GNUTLS_E_SUCCESS) {
605
			if (err != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
606 607
				kr_log_error("[tls] could not get X.509 certificates (%d) %s\n",
						err, gnutls_strerror_name(err));
608 609 610 611 612
			}
			return;
		}

		for (int i = 0; i < cert_count; i++) {
613 614 615 616 617
			char pin[TLS_SHA256_BASE64_BUFLEN] = { 0 };
			err = get_oob_key_pin(certs[i], pin, sizeof(pin), false);
			if (err != GNUTLS_E_SUCCESS) {
				kr_log_error("[tls] could not calculate RFC 7858 OOB key-pin from cert %d (%d) %s\n",
						i, err, gnutls_strerror_name(err));
618
			} else {
619 620
				kr_log_info("[tls] RFC 7858 OOB key-pin (%d): pin-sha256=\"%s\"\n",
						i, pin);
621 622 623 624 625 626
			}
			gnutls_x509_crt_deinit(certs[i]);
		}
		gnutls_free(certs);
	}
}
627 628 629 630 631 632
#else
void tls_credentials_log_pins(struct tls_credentials *tls_credentials)
{
	kr_log_error("[tls] could not calculate RFC 7858 OOB key-pin; GnuTLS 3.4.0+ required\n");
}
#endif
633

634 635 636 637 638 639 640 641 642 643 644 645
static int str_replace(char **where_ptr, const char *with)
{
	char *copy = with ? strdup(with) : NULL;
	if (with && !copy) {
		return kr_error(ENOMEM);
	}

	free(*where_ptr);
	*where_ptr = copy;
	return kr_ok();
}

646 647 648 649 650 651 652
static time_t _get_end_entity_expiration(gnutls_certificate_credentials_t creds)
{
	gnutls_datum_t data;
	gnutls_x509_crt_t cert = NULL;
	int err;
	time_t ret = GNUTLS_X509_NO_WELL_DEFINED_EXPIRATION;

653
	if ((err = gnutls_certificate_get_crt_raw(creds, 0, 0, &data)) != GNUTLS_E_SUCCESS) {
654 655 656 657
		kr_log_error("[tls] failed to get cert to check expiration: (%d) %s\n",
			     err, gnutls_strerror_name(err));
		goto done;
	}
658
	if ((err = gnutls_x509_crt_init(&cert)) != GNUTLS_E_SUCCESS) {
659 660 661 662
		kr_log_error("[tls] failed to initialize cert: (%d) %s\n",
			     err, gnutls_strerror_name(err));
		goto done;
	}
663
	if ((err = gnutls_x509_crt_import(cert, &data, GNUTLS_X509_FMT_DER)) != GNUTLS_E_SUCCESS) {
664 665 666 667 668 669 670 671 672 673 674 675 676
		kr_log_error("[tls] failed to construct cert while checking expiration: (%d) %s\n",
			     err, gnutls_strerror_name(err));
		goto done;
	}

	ret = gnutls_x509_crt_get_expiration_time (cert);
 done:
	/* do not free data; g_c_get_crt_raw() says to treat it as
	 * constant. */
	gnutls_x509_crt_deinit(cert);
	return ret;
}

677
int tls_certificate_set(struct network *net, const char *tls_cert, const char *tls_key)
678
{
679
	if (!net) {
680 681 682
		return kr_error(EINVAL);
	}

683
	struct tls_credentials *tls_credentials = calloc(1, sizeof(*tls_credentials));
684
	if (tls_credentials == NULL) {
685 686
		return kr_error(ENOMEM);
	}
687

Marek Vavrusa's avatar
Marek Vavrusa committed
688
	int err = 0;
689
	if ((err = gnutls_certificate_allocate_credentials(&tls_credentials->credentials)) != GNUTLS_E_SUCCESS) {
690 691
		kr_log_error("[tls] gnutls_certificate_allocate_credentials() failed: (%d) %s\n",
			     err, gnutls_strerror_name(err));
692
		tls_credentials_free(tls_credentials);
693 694
		return kr_error(ENOMEM);
	}
695
	if ((err = gnutls_certificate_set_x509_system_trust(tls_credentials->credentials)) < 0) {
696 697 698
		if (err != GNUTLS_E_UNIMPLEMENTED_FEATURE) {
			kr_log_error("[tls] warning: gnutls_certificate_set_x509_system_trust() failed: (%d) %s\n",
				     err, gnutls_strerror_name(err));
699
			tls_credentials_free(tls_credentials);
700
			return err;
701
		}
702
	}
703

704 705 706
	if ((str_replace(&tls_credentials->tls_cert, tls_cert) != 0) ||
	    (str_replace(&tls_credentials->tls_key, tls_key) != 0)) {
		tls_credentials_free(tls_credentials);
707 708
		return kr_error(ENOMEM);
	}
709

710
	if ((err = gnutls_certificate_set_x509_key_file(tls_credentials->credentials,
711
							tls_cert, tls_key, GNUTLS_X509_FMT_PEM)) != GNUTLS_E_SUCCESS) {
712
		tls_credentials_free(tls_credentials);
713 714 715 716
		kr_log_error("[tls] gnutls_certificate_set_x509_key_file(%s,%s) failed: %d (%s)\n",
			     tls_cert, tls_key, err, gnutls_strerror_name(err));
		return kr_error(EINVAL);
	}
717 718 719 720
	/* record the expiration date: */
	tls_credentials->valid_until = _get_end_entity_expiration(tls_credentials->credentials);

	/* Exchange the x509 credentials */
721
	struct tls_credentials *old_credentials = net->tls_credentials;
722

723
	/* Start using the new x509_credentials */
724
	net->tls_credentials = tls_credentials;
725
	tls_credentials_log_pins(net->tls_credentials);
726 727

	if (old_credentials) {
728 729 730 731
		err = tls_credentials_release(old_credentials);
		if (err != kr_error(EBUSY)) {
			return err;
		}
732 733 734
	}

	return kr_ok();
735 736
}

737 738 739 740 741 742
struct tls_credentials *tls_credentials_reserve(struct tls_credentials *tls_credentials) {
	if (!tls_credentials) {
		return NULL;
	}
	tls_credentials->count++;
	return tls_credentials;
743 744
}

745
int tls_credentials_release(struct tls_credentials *tls_credentials) {
746 747 748 749
	if (!tls_credentials) {
		return kr_error(EINVAL);
	}
	if (--tls_credentials->count < 0) {
750
		tls_credentials_free(tls_credentials);
751 752 753 754 755 756
	} else {
		return kr_error(EBUSY);
	}
	return kr_ok();
}

757
void tls_credentials_free(struct tls_credentials *tls_credentials) {
758 759 760 761 762 763 764 765 766 767 768 769 770
	if (!tls_credentials) {
		return;
	}

	if (tls_credentials->credentials) {
		gnutls_certificate_free_credentials(tls_credentials->credentials);
	}
	if (tls_credentials->tls_cert) {
		free(tls_credentials->tls_cert);
	}
	if (tls_credentials->tls_key) {
		free(tls_credentials->tls_key);
	}
771 772 773
	if (tls_credentials->ephemeral_servicename) {
		free(tls_credentials->ephemeral_servicename);
	}
774 775 776
	free(tls_credentials);
}

777
void tls_client_param_unref(tls_client_param_t *entry)
778
{
779 780 781 782 783
	if (!entry) return;
	assert(entry->refs); /* Well, we'd only leak memory. */
	--(entry->refs);
	if (entry->refs) return;

784
	DEBUG_MSG("freeing TLS parameters %p\n", (void *)entry);
785

786 787
	for (int i = 0; i < entry->ca_files.len; ++i) {
		free_const(entry->ca_files.at[i]);
788
	}
789
	array_clear(entry->ca_files);
790

791
	free_const(entry->hostname);
792

793 794
	for (int i = 0; i < entry->pins.len; ++i) {
		free_const(entry->pins.at[i]);
795 796 797 798 799 800 801
	}
	array_clear(entry->pins);

	if (entry->credentials) {
		gnutls_certificate_free_credentials(entry->credentials);
	}

802 803 804 805
	if (entry->session_data.data) {
		gnutls_free(entry->session_data.data);
	}

806 807
	free(entry);
}
808
static int param_free(void **param, void *null)
809
{
810 811 812
	assert(param && *param);
	tls_client_param_unref(*param);
	return 0;
813
}
814
void tls_client_params_free(tls_client_params_t *params)
815
{
816 817 818
	if (!params) return;
	trie_apply(params, param_free, NULL);
	trie_free(params);
819 820
}

821
tls_client_param_t * tls_client_param_new()
822
{
823 824 825
	tls_client_param_t *e = calloc(1, sizeof(*e));
	if (!e) {
		assert(!ENOMEM);
826 827
		return NULL;
	}
828 829 830 831 832 833 834
	/* Note: those array_t don't need further initialization. */
	e->refs = 1;
	int ret = gnutls_certificate_allocate_credentials(&e->credentials);
	if (ret != GNUTLS_E_SUCCESS) {
		kr_log_error("[tls_client] error: gnutls_certificate_allocate_credentials() fails (%s)\n",
			     gnutls_strerror_name(ret));
		free(e);
835 836
		return NULL;
	}
837 838
	gnutls_certificate_set_verify_function(e->credentials, client_verify_certificate);
	return e;
839 840
}

841 842 843 844 845 846 847 848
/**
 * Convert an IP address and port number to binary key.
 *
 * \precond buffer \param key must have sufficient size
 * \param addr[in]
 * \param len[out] output length
 * \param key[out] output buffer
 */
849
static bool construct_key(const union inaddr *addr, uint32_t *len, char *key)
850
{
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
	switch (addr->ip.sa_family) {
	case AF_INET:
		memcpy(key, &addr->ip4.sin_port, sizeof(addr->ip4.sin_port));
		memcpy(key + sizeof(addr->ip4.sin_port), &addr->ip4.sin_addr,
			sizeof(addr->ip4.sin_addr));
		*len = sizeof(addr->ip4.sin_port) + sizeof(addr->ip4.sin_addr);
		return true;
	case AF_INET6:
		memcpy(key, &addr->ip6.sin6_port, sizeof(addr->ip6.sin6_port));
		memcpy(key + sizeof(addr->ip6.sin6_port), &addr->ip6.sin6_addr,
			sizeof(addr->ip6.sin6_addr));
		*len = sizeof(addr->ip6.sin6_port) + sizeof(addr->ip6.sin6_addr);
		return true;
	default:
		assert(!EINVAL);
		return false;
867 868
	}
}
869 870
tls_client_param_t ** tls_client_param_getptr(tls_client_params_t **params,
				const struct sockaddr *addr, bool do_insert)
871
{
872 873 874 875 876 877 878 879
	assert(params && addr);
	/* We accept NULL for empty map; ensure the map exists if needed. */
	if (!*params) {
		if (!do_insert) return NULL;
		*params = trie_create(NULL);
		if (!*params) {
			assert(!ENOMEM);
			return NULL;
880 881
		}
	}
882 883 884 885 886 887 888 889 890
	/* Construct the key. */
	const union inaddr *ia = (const union inaddr *)addr;
	char key[sizeof(ia->ip6.sin6_port) + sizeof(ia->ip6.sin6_addr)];
	uint32_t len;
	if (!construct_key(ia, &len, key))
		return NULL;
	/* Get the entry. */
	return (tls_client_param_t **)
		(do_insert ? trie_get_ins : trie_get_try)(*params, key, len);
891 892
}

893
int tls_client_param_remove(tls_client_params_t *params, const struct sockaddr *addr)
894
{
895 896 897 898
	const union inaddr *ia = (const union inaddr *)addr;
	char key[sizeof(ia->ip6.sin6_port) + sizeof(ia->ip6.sin6_addr)];
	uint32_t len;
	if (!construct_key(ia, &len, key))
899
		return kr_error(EINVAL);
900 901 902 903 904
	trie_val_t param_ptr;
	int ret = trie_del(params, key, len, &param_ptr);
	if (ret)
		return kr_error(ret);
	tls_client_param_unref(param_ptr);
905 906 907
	return kr_ok();
}

908 909 910 911 912 913 914 915
/**
 * Verify that at least one certificate in the certificate chain matches
 * at least one certificate pin in the non-empty params->pins array.
 * \returns GNUTLS_E_SUCCESS if pin matches, any other value is an error
 */
static int client_verify_pin(const unsigned int cert_list_size,
				const gnutls_datum_t *cert_list,
				tls_client_param_t *params)
916
{
917
	assert(params->pins.len > 0);
918
#if TLS_CAN_USE_PINS
919 920 921 922 923 924 925 926 927 928 929 930 931
	for (int i = 0; i < cert_list_size; i++) {
		gnutls_x509_crt_t cert;
		int ret = gnutls_x509_crt_init(&cert);
		if (ret != GNUTLS_E_SUCCESS) {
			return ret;
		}

		ret = gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER);
		if (ret != GNUTLS_E_SUCCESS) {
			gnutls_x509_crt_deinit(cert);
			return ret;
		}

932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
	#ifdef DEBUG
		if (VERBOSE_STATUS) {
			char pin_base64[TLS_SHA256_BASE64_BUFLEN];
			/* DEBUG: additionally compute and print the base64 pin.
			 * Not very efficient, but that's OK for DEBUG. */
			ret = get_oob_key_pin(cert, pin_base64, sizeof(pin_base64), false);
			if (ret == GNUTLS_E_SUCCESS) {
				DEBUG_MSG("[tls_client] received pin: %s\n", pin_base64);
			} else {
				DEBUG_MSG("[tls_client] failed to convert received pin\n");
				/* Now we hope that `ret` below can't differ. */
			}
		}
	#endif
		char cert_pin[TLS_SHA256_RAW_LEN];
		/* Get raw pin and compare. */
		ret = get_oob_key_pin(cert, cert_pin, sizeof(cert_pin), true);
949 950 951 952
		gnutls_x509_crt_deinit(cert);
		if (ret != GNUTLS_E_SUCCESS) {
			return ret;
		}
953 954
		for (size_t j = 0; j < params->pins.len; ++j) {
			const uint8_t *pin = params->pins.at[j];
955 956 957 958
			if (memcmp(cert_pin, pin, TLS_SHA256_RAW_LEN) != 0)
				continue; /* mismatch */
			DEBUG_MSG("[tls_client] matched a configured pin no. %zd\n", j);
			return GNUTLS_E_SUCCESS;
959
		}
960
		DEBUG_MSG("[tls_client] none of %zd configured pin(s) matched\n",
961
				params->pins.len);
962 963
	}

964 965
	kr_log_error("[tls_client] no pin matched: %zu pins * %d certificates\n",
			params->pins.len, cert_list_size);
966 967 968
	return GNUTLS_E_CERTIFICATE_ERROR;

#else /* TLS_CAN_USE_PINS */
969 970 971
	kr_log_error("[tls_client] internal inconsistency: TLS_CAN_USE_PINS\n");
	assert(false);
	return GNUTLS_E_CERTIFICATE_ERROR;
972
#endif
973
}
974

975 976 977 978 979 980 981 982 983
/**
 * Verify that \param tls_session contains a valid X.509 certificate chain
 * with given hostname.
 *
 * \returns GNUTLS_E_SUCCESS if certificate chain is valid, any other value is an error
 */
static int client_verify_certchain(gnutls_session_t tls_session, const char *hostname)
{
	if (!hostname) {
984 985
		kr_log_error("[tls_client] internal config inconsistency: no hostname set\n");
		assert(false);
986 987 988
		return GNUTLS_E_CERTIFICATE_ERROR;
	}

989
	unsigned int status;
990
	int ret = gnutls_certificate_verify_peers3(tls_session, hostname, &status);
991 992
	if ((ret == GNUTLS_E_SUCCESS) && (status == 0)) {
		return GNUTLS_E_SUCCESS;
993 994
	}

995 996 997
	if (ret == GNUTLS_E_SUCCESS) {
		gnutls_datum_t msg;
		ret = gnutls_certificate_verification_status_print(
998
			status, gnutls_certificate_type_get(tls_session), &msg, 0);
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
		if (ret == GNUTLS_E_SUCCESS) {
			kr_log_error("[tls_client] failed to verify peer certificate: "
					"%s\n", msg.data);
			gnutls_free(msg.data);
		} else {
			kr_log_error("[tls_client] failed to verify peer certificate: "
					"unable to print reason: %s (%s)\n",
					gnutls_strerror(ret), gnutls_strerror_name(ret));
		} /* gnutls_certificate_verification_status_print end */
	} else {
		kr_log_error("[tls_client] failed to verify peer certificate: "
			     "gnutls_certificate_verify_peers3 error: %s (%s)\n",
			     gnutls_strerror(ret), gnutls_strerror_name(ret));
	} /* gnutls_certificate_verify_peers3 end */
1013
	return GNUTLS_E_CERTIFICATE_ERROR;
1014 1015
}

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
/**
 * Verify that actual TLS security parameters of \param tls_session
 * match requirements provided by user in tls_session->params.
 * \returns GNUTLS_E_SUCCESS if requirements were met, any other value is an error
 */
static int client_verify_certificate(gnutls_session_t tls_session)
{
	struct tls_client_ctx_t *ctx = gnutls_session_get_ptr(tls_session);
	assert(ctx->params != NULL);

	if (ctx->params->insecure) {
		return GNUTLS_E_SUCCESS;
	}

	gnutls_certificate_type_t cert_type = gnutls_certificate_type_get(tls_session);
	if (cert_type != GNUTLS_CRT_X509) {
		kr_log_error("[tls_client] invalid certificate type %i has been received\n",
			     cert_type);
		return GNUTLS_E_CERTIFICATE_ERROR;
	}
	unsigned int cert_list_size = 0;
	const gnutls_datum_t *cert_list =
		gnutls_certificate_get_peers(tls_session, &cert_list_size);
	if (cert_list == NULL || cert_list_size == 0) {
		kr_log_error("[tls_client] empty certificate list\n");
		return GNUTLS_E_CERTIFICATE_ERROR;
	}

	if (ctx->params->pins.len > 0)
		/* check hash of the certificate but ignore everything else */
		return client_verify_pin(cert_list_size, cert_list, ctx->params);
	else
		return client_verify_certchain(ctx->c.tls_session, ctx->params->hostname);
}

1051
struct tls_client_ctx_t *tls_client_ctx_new(tls_client_param_t *entry,
1052
					    struct worker_ctx *worker)
1053 1054 1055 1056 1057
{
	struct tls_client_ctx_t *ctx = calloc(1, sizeof (struct tls_client_ctx_t));
	if (!ctx) {
		return NULL;
	}
1058 1059 1060 1061 1062 1063
	unsigned int flags = GNUTLS_CLIENT | GNUTLS_NONBLOCK
#ifdef GNUTLS_ENABLE_FALSE_START
			     | GNUTLS_ENABLE_FALSE_START
#endif
	;
	int ret = gnutls_init(&ctx->c.tls_session,  flags);
1064 1065 1066 1067 1068
	if (ret != GNUTLS_E_SUCCESS) {
		tls_client_ctx_free(ctx);
		return NULL;
	}

1069
	ret = kres_gnutls_set_priority(ctx->c.tls_session);
1070 1071 1072 1073 1074
	if (ret != GNUTLS_E_SUCCESS) {
		tls_client_ctx_free(ctx);
		return NULL;
	}

1075 1076
	/* Must take a reference on parameters as the credentials are owned by it
	 * and must not be freed while the session is active. */
1077
	++(entry->refs);
1078 1079
	ctx->params = entry;

1080
	ret = gnutls_credentials_set(ctx->c.tls_session, GNUTLS_CRD_CERTIFICATE,
1081
	                             entry->credentials);
1082 1083 1084
	if (ret == GNUTLS_E_SUCCESS && entry->hostname) {
		ret = gnutls_server_name_set(ctx->c.tls_session, GNUTLS_NAME_DNS,
					entry->hostname, strlen(entry->hostname));
1085 1086 1087
		kr_log_verbose("[tls_client] set hostname, ret = %d\n", ret);
	} else if (!entry->hostname) {
		kr_log_verbose("[tls_client] no hostname\n");
1088
	}
1089 1090 1091 1092 1093
	if (ret != GNUTLS_E_SUCCESS) {
		tls_client_ctx_free(ctx);
		return NULL;
	}

1094 1095
	ctx->c.worker = worker;
	ctx->c.client_side = true;
1096

1097
	gnutls_transport_set_pull_function(ctx->c.tls_session, kres_gnutls_pull);
1098
	gnutls_transport_set_vec_push_function(ctx->c.tls_session, kres_gnutls_vec_push);
1099
	gnutls_transport_set_ptr(ctx->c.tls_session, ctx);
1100 1101 1102 1103 1104 1105 1106 1107 1108
	return ctx;
}

void tls_client_ctx_free(struct tls_client_ctx_t *ctx)
{
	if (ctx == NULL) {
		return;
	}

1109 1110 1111
	if (ctx->c.tls_session != NULL) {
		gnutls_deinit(ctx->c.tls_session);
		ctx->c.tls_session = NULL;
1112 1113
	}

1114
	/* Must decrease the refcount for referenced parameters */
1115
	tls_client_param_unref(ctx->params);
1116

1117 1118 1119
	free (ctx);
}

1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
int  tls_pull_timeout_func(gnutls_transport_ptr_t h, unsigned int ms)
{
	struct tls_common_ctx *t = (struct tls_common_ctx *)h;
	assert(t != NULL);
	ssize_t	avail = t->nread - t->consumed;
	DEBUG_MSG("[%s] timeout check: available: %zu\n",
		  t->client_side ? "tls_client" : "tls", avail);
	if (avail <= 0) {
		errno = EAGAIN;
		return -1;
	}
	return avail;
}

1134
int tls_client_connect_start(struct tls_client_ctx_t *client_ctx,
1135 1136 1137
			     struct session *session,
			     tls_handshake_cb handshake_cb)
{
1138
	if (session == NULL || client_ctx == NULL) {
1139 1140 1141
		return kr_error(EINVAL);
	}

1142
	assert(session_flags(session)->outgoing && session_get_handle(session)->type == UV_TCP);
1143

1144 1145 1146
	struct tls_common_ctx *ctx = &client_ctx->c;

	gnutls_session_set_ptr(ctx->tls_session, client_ctx);
1147
	gnutls_handshake_set_timeout(ctx->tls_session, ctx->worker->engine->net.tcp.tls_handshake_timeout);
1148
	gnutls_transport_set_pull_timeout_function(ctx->tls_session, tls_pull_timeout_func);
1149
	session_tls_set_client_ctx(session, client_ctx);
1150 1151 1152 1153
	ctx->handshake_cb = handshake_cb;
	ctx->handshake_state = TLS_HS_IN_PROGRESS;
	ctx->session = session;

1154
	tls_client_param_t *tls_params = client_ctx->params;
1155 1156 1157 1158 1159
	if (tls_params->session_data.data != NULL) {
		gnutls_session_set_data(ctx->tls_session, tls_params->session_data.data,
					tls_params->session_data.size);
	}

1160 1161
	/* See https://www.gnutls.org/manual/html_node/Asynchronous-operation.html */
	while (ctx->handshake_state <= TLS_HS_IN_PROGRESS) {
1162
		int ret = tls_handshake(ctx, handshake_cb);
1163 1164 1165
		if (ret != kr_ok()) {
			return ret;
		}
1166
	}
1167
	return kr_ok();
1168 1169
}

1170
tls_hs_state_t tls_get_hs_state(const struct tls_common_ctx *ctx)
1171 1172 1173 1174
{
	return ctx->handshake_state;
}

1175
int tls_set_hs_state(struct tls_common_ctx *ctx, tls_hs_state_t state)
1176 1177 1178 1179 1180 1181 1182 1183
{
	if (state >= TLS_HS_LAST) {
		return kr_error(EINVAL);
	}
	ctx->handshake_state = state;
	return kr_ok();
}

1184
int tls_client_ctx_set_session(struct tls_client_ctx_t *ctx, struct session *session)
1185 1186 1187 1188
{
	if (!ctx) {
		return kr_error(EINVAL);
	}
1189
	ctx->c.session = session;
1190 1191 1192
	return kr_ok();
}

1193
#undef DEBUG_MSG