1 
2 /*
3  * SSL/TLS transport layer over SOCK_STREAM sockets
4  *
5  * Copyright (C) 2012 EXCELIANCE, Emeric Brun <ebrun@exceliance.fr>
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version
10  * 2 of the License, or (at your option) any later version.
11  *
12  * Acknowledgement:
13  *   We'd like to specially thank the Stud project authors for a very clean
14  *   and well documented code which helped us understand how the OpenSSL API
15  *   ought to be used in non-blocking mode. This is one difficult part which
16  *   is not easy to get from the OpenSSL doc, and reading the Stud code made
17  *   it much more obvious than the examples in the OpenSSL package. Keep up
18  *   the good works, guys !
19  *
20  *   Stud is an extremely efficient and scalable SSL/TLS proxy which combines
21  *   particularly well with haproxy. For more info about this project, visit :
22  *       https://github.com/bumptech/stud
23  *
24  */
25 
26 /* Note: do NOT include openssl/xxx.h here, do it in openssl-compat.h */
27 #define _GNU_SOURCE
28 #include <ctype.h>
29 #include <dirent.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 
37 #include <sys/socket.h>
38 #include <sys/stat.h>
39 #include <sys/types.h>
40 #include <netdb.h>
41 #include <netinet/tcp.h>
42 
43 #include <import/lru.h>
44 #include <import/xxhash.h>
45 
46 #include <common/buffer.h>
47 #include <common/chunk.h>
48 #include <common/compat.h>
49 #include <common/config.h>
50 #include <common/debug.h>
51 #include <common/errors.h>
52 #include <common/initcall.h>
53 #include <common/openssl-compat.h>
54 #include <common/standard.h>
55 #include <common/ticks.h>
56 #include <common/time.h>
57 #include <common/cfgparse.h>
58 #include <common/base64.h>
59 
60 #include <ebsttree.h>
61 
62 #include <types/applet.h>
63 #include <types/cli.h>
64 #include <types/global.h>
65 #include <types/ssl_sock.h>
66 #include <types/stats.h>
67 
68 #include <proto/acl.h>
69 #include <proto/arg.h>
70 #include <proto/channel.h>
71 #include <proto/connection.h>
72 #include <proto/cli.h>
73 #include <proto/fd.h>
74 #include <proto/freq_ctr.h>
75 #include <proto/frontend.h>
76 #include <proto/http_rules.h>
77 #include <proto/listener.h>
78 #include <proto/pattern.h>
79 #include <proto/proto_tcp.h>
80 #include <proto/proto_http.h>
81 #include <proto/server.h>
82 #include <proto/stream_interface.h>
83 #include <proto/log.h>
84 #include <proto/proxy.h>
85 #include <proto/shctx.h>
86 #include <proto/ssl_sock.h>
87 #include <proto/stream.h>
88 #include <proto/task.h>
89 #include <proto/vars.h>
90 
91 /* ***** READ THIS before adding code here! *****
92  *
93  * Due to API incompatibilities between multiple OpenSSL versions and their
94  * derivatives, it's often tempting to add macros to (re-)define certain
95  * symbols. Please do not do this here, and do it in common/openssl-compat.h
96  * exclusively so that the whole code consistently uses the same macros.
97  *
98  * Whenever possible if a macro is missing in certain versions, it's better
99  * to conditionally define it in openssl-compat.h than using lots of ifdefs.
100  */
101 
102 /* Warning, these are bits, not integers! */
103 #define SSL_SOCK_ST_FL_VERIFY_DONE  0x00000001
104 #define SSL_SOCK_ST_FL_16K_WBFSIZE  0x00000002
105 #define SSL_SOCK_SEND_UNLIMITED     0x00000004
106 #define SSL_SOCK_RECV_HEARTBEAT     0x00000008
107 
108 /* bits 0xFFFF0000 are reserved to store verify errors */
109 
110 /* Verify errors macros */
111 #define SSL_SOCK_CA_ERROR_TO_ST(e) (((e > 63) ? 63 : e) << (16))
112 #define SSL_SOCK_CAEDEPTH_TO_ST(d) (((d > 15) ? 15 : d) << (6+16))
113 #define SSL_SOCK_CRTERROR_TO_ST(e) (((e > 63) ? 63 : e) << (4+6+16))
114 
115 #define SSL_SOCK_ST_TO_CA_ERROR(s) ((s >> (16)) & 63)
116 #define SSL_SOCK_ST_TO_CAEDEPTH(s) ((s >> (6+16)) & 15)
117 #define SSL_SOCK_ST_TO_CRTERROR(s) ((s >> (4+6+16)) & 63)
118 
119 /* ssl_methods flags for ssl options */
120 #define MC_SSL_O_ALL            0x0000
121 #define MC_SSL_O_NO_SSLV3       0x0001	/* disable SSLv3 */
122 #define MC_SSL_O_NO_TLSV10      0x0002	/* disable TLSv10 */
123 #define MC_SSL_O_NO_TLSV11      0x0004	/* disable TLSv11 */
124 #define MC_SSL_O_NO_TLSV12      0x0008	/* disable TLSv12 */
125 #define MC_SSL_O_NO_TLSV13      0x0010	/* disable TLSv13 */
126 
127 /* ssl_methods versions */
128 enum {
129 	CONF_TLSV_NONE = 0,
130 	CONF_TLSV_MIN  = 1,
131 	CONF_SSLV3     = 1,
132 	CONF_TLSV10    = 2,
133 	CONF_TLSV11    = 3,
134 	CONF_TLSV12    = 4,
135 	CONF_TLSV13    = 5,
136 	CONF_TLSV_MAX  = 5,
137 };
138 
139 /* server and bind verify method, it uses a global value as default */
140 enum {
141 	SSL_SOCK_VERIFY_DEFAULT  = 0,
142 	SSL_SOCK_VERIFY_REQUIRED = 1,
143 	SSL_SOCK_VERIFY_OPTIONAL = 2,
144 	SSL_SOCK_VERIFY_NONE     = 3,
145 };
146 
147 
148 int sslconns = 0;
149 int totalsslconns = 0;
150 static struct xprt_ops ssl_sock;
151 int nb_engines = 0;
152 
153 static struct {
154 	char *crt_base;             /* base directory path for certificates */
155 	char *ca_base;              /* base directory path for CAs and CRLs */
156 	int  async;                 /* whether we use ssl async mode */
157 
158 	char *listen_default_ciphers;
159 	char *connect_default_ciphers;
160 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
161 	char *listen_default_ciphersuites;
162 	char *connect_default_ciphersuites;
163 #endif
164 	int listen_default_ssloptions;
165 	int connect_default_ssloptions;
166 	struct tls_version_filter listen_default_sslmethods;
167 	struct tls_version_filter connect_default_sslmethods;
168 
169 	int private_cache; /* Force to use a private session cache even if nbproc > 1 */
170 	unsigned int life_time;   /* SSL session lifetime in seconds */
171 	unsigned int max_record; /* SSL max record size */
172 	unsigned int default_dh_param; /* SSL maximum DH parameter size */
173 	int ctx_cache; /* max number of entries in the ssl_ctx cache. */
174 	int capture_cipherlist; /* Size of the cipherlist buffer. */
175 } global_ssl = {
176 #ifdef LISTEN_DEFAULT_CIPHERS
177 	.listen_default_ciphers = LISTEN_DEFAULT_CIPHERS,
178 #endif
179 #ifdef CONNECT_DEFAULT_CIPHERS
180 	.connect_default_ciphers = CONNECT_DEFAULT_CIPHERS,
181 #endif
182 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
183 #ifdef LISTEN_DEFAULT_CIPHERSUITES
184 	.listen_default_ciphersuites = LISTEN_DEFAULT_CIPHERSUITES,
185 #endif
186 #ifdef CONNECT_DEFAULT_CIPHERSUITES
187 	.connect_default_ciphersuites = CONNECT_DEFAULT_CIPHERSUITES,
188 #endif
189 #endif
190 	.listen_default_ssloptions = BC_SSL_O_NONE,
191 	.connect_default_ssloptions = SRV_SSL_O_NONE,
192 
193 	.listen_default_sslmethods.flags = MC_SSL_O_ALL,
194 	.listen_default_sslmethods.min = CONF_TLSV_NONE,
195 	.listen_default_sslmethods.max = CONF_TLSV_NONE,
196 	.connect_default_sslmethods.flags = MC_SSL_O_ALL,
197 	.connect_default_sslmethods.min = CONF_TLSV_NONE,
198 	.connect_default_sslmethods.max = CONF_TLSV_NONE,
199 
200 #ifdef DEFAULT_SSL_MAX_RECORD
201 	.max_record = DEFAULT_SSL_MAX_RECORD,
202 #endif
203 	.default_dh_param = SSL_DEFAULT_DH_PARAM,
204 	.ctx_cache = DEFAULT_SSL_CTX_CACHE,
205 	.capture_cipherlist = 0,
206 };
207 
208 static BIO_METHOD *ha_meth;
209 
210 struct ssl_sock_ctx {
211 	struct connection *conn;
212 	SSL *ssl;
213 	BIO *bio;
214 	const struct xprt_ops *xprt;
215 	void *xprt_ctx;
216 	struct wait_event wait_event;
217 	struct wait_event *recv_wait;
218 	struct wait_event *send_wait;
219 	int xprt_st;                  /* transport layer state, initialized to zero */
220 	struct buffer early_buf;      /* buffer to store the early data received */
221 	int sent_early_data;          /* Amount of early data we sent so far */
222 
223 };
224 
225 DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx_pool", sizeof(struct ssl_sock_ctx));
226 
227 static struct task *ssl_sock_io_cb(struct task *, void *, unsigned short);
228 static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
229 
230 /* Methods to implement OpenSSL BIO */
ha_ssl_write(BIO * h,const char * buf,int num)231 static int ha_ssl_write(BIO *h, const char *buf, int num)
232 {
233 	struct buffer tmpbuf;
234 	struct ssl_sock_ctx *ctx;
235 	int ret;
236 
237 	ctx = BIO_get_data(h);
238 	tmpbuf.size = num;
239 	tmpbuf.area = (void *)(uintptr_t)buf;
240 	tmpbuf.data = num;
241 	tmpbuf.head = 0;
242 	ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, 0);
243 	if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
244 		BIO_set_retry_write(h);
245 		ret = -1;
246 	} else if (ret == 0)
247 		 BIO_clear_retry_flags(h);
248 	return ret;
249 }
250 
ha_ssl_gets(BIO * h,char * buf,int size)251 static int ha_ssl_gets(BIO *h, char *buf, int size)
252 {
253 
254 	return 0;
255 }
256 
ha_ssl_puts(BIO * h,const char * str)257 static int ha_ssl_puts(BIO *h, const char *str)
258 {
259 
260 	return ha_ssl_write(h, str, strlen(str));
261 }
262 
ha_ssl_read(BIO * h,char * buf,int size)263 static int ha_ssl_read(BIO *h, char *buf, int size)
264 {
265 	struct buffer tmpbuf;
266 	struct ssl_sock_ctx *ctx;
267 	int ret;
268 
269 	ctx = BIO_get_data(h);
270 	tmpbuf.size = size;
271 	tmpbuf.area = buf;
272 	tmpbuf.data = 0;
273 	tmpbuf.head = 0;
274 	ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
275 	if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
276 		BIO_set_retry_read(h);
277 		ret = -1;
278 	} else if (ret == 0)
279 		BIO_clear_retry_flags(h);
280 
281 	return ret;
282 }
283 
ha_ssl_ctrl(BIO * h,int cmd,long arg1,void * arg2)284 static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
285 {
286 	int ret = 0;
287 	switch (cmd) {
288 	case BIO_CTRL_DUP:
289 	case BIO_CTRL_FLUSH:
290 		ret = 1;
291 		break;
292 	}
293 	return ret;
294 }
295 
ha_ssl_new(BIO * h)296 static int ha_ssl_new(BIO *h)
297 {
298 	BIO_set_init(h, 1);
299 	BIO_set_data(h, NULL);
300 	BIO_clear_flags(h, ~0);
301 	return 1;
302 }
303 
ha_ssl_free(BIO * data)304 static int ha_ssl_free(BIO *data)
305 {
306 
307 	return 1;
308 }
309 
310 
311 #if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
312 
313 static HA_RWLOCK_T *ssl_rwlocks;
314 
315 
ssl_id_function(void)316 unsigned long ssl_id_function(void)
317 {
318 	return (unsigned long)tid;
319 }
320 
ssl_locking_function(int mode,int n,const char * file,int line)321 void ssl_locking_function(int mode, int n, const char * file, int line)
322 {
323 	if (mode & CRYPTO_LOCK) {
324 		if (mode & CRYPTO_READ)
325 			HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
326 		else
327 			HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
328 	}
329 	else {
330 		if (mode & CRYPTO_READ)
331 			HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
332 		else
333 			HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
334 	}
335 }
336 
ssl_locking_init(void)337 static int ssl_locking_init(void)
338 {
339 	int i;
340 
341 	ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
342 	if (!ssl_rwlocks)
343 		return -1;
344 
345 	for (i = 0 ; i < CRYPTO_num_locks() ; i++)
346 		HA_RWLOCK_INIT(&ssl_rwlocks[i]);
347 
348 	CRYPTO_set_id_callback(ssl_id_function);
349 	CRYPTO_set_locking_callback(ssl_locking_function);
350 
351 	return 0;
352 }
353 
354 #endif
355 
356 
357 
358 /* This memory pool is used for capturing clienthello parameters. */
359 struct ssl_capture {
360 	unsigned long long int xxh64;
361 	unsigned char ciphersuite_len;
362 	char ciphersuite[0];
363 };
364 struct pool_head *pool_head_ssl_capture = NULL;
365 static int ssl_capture_ptr_index = -1;
366 static int ssl_app_data_index = -1;
367 
368 static int ssl_pkey_info_index = -1;
369 
370 #if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
371 struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
372 #endif
373 
374 #ifndef OPENSSL_NO_ENGINE
375 static unsigned int openssl_engines_initialized;
376 struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
377 struct ssl_engine_list {
378 	struct list list;
379 	ENGINE *e;
380 };
381 #endif
382 
383 #ifndef OPENSSL_NO_DH
384 static int ssl_dh_ptr_index = -1;
385 static DH *global_dh = NULL;
386 static DH *local_dh_1024 = NULL;
387 static DH *local_dh_2048 = NULL;
388 static DH *local_dh_4096 = NULL;
389 static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen);
390 #endif /* OPENSSL_NO_DH */
391 
392 #if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
393 /* X509V3 Extensions that will be added on generated certificates */
394 #define X509V3_EXT_SIZE 5
395 static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
396 	"basicConstraints",
397 	"nsComment",
398 	"subjectKeyIdentifier",
399 	"authorityKeyIdentifier",
400 	"keyUsage",
401 };
402 static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
403 	"CA:FALSE",
404 	"\"OpenSSL Generated Certificate\"",
405 	"hash",
406 	"keyid,issuer:always",
407 	"nonRepudiation,digitalSignature,keyEncipherment"
408 };
409 /* LRU cache to store generated certificate */
410 static struct lru64_head *ssl_ctx_lru_tree = NULL;
411 static unsigned int       ssl_ctx_lru_seed = 0;
412 static unsigned int	  ssl_ctx_serial;
413 __decl_rwlock(ssl_ctx_lru_rwlock);
414 
415 #endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
416 
417 static struct ssl_bind_kw ssl_bind_kws[];
418 
419 #if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL
420 /* The order here matters for picking a default context,
421  * keep the most common keytype at the bottom of the list
422  */
423 const char *SSL_SOCK_KEYTYPE_NAMES[] = {
424 	"dsa",
425 	"ecdsa",
426 	"rsa"
427 };
428 #define SSL_SOCK_NUM_KEYTYPES 3
429 #else
430 #define SSL_SOCK_NUM_KEYTYPES 1
431 #endif
432 
433 static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
434 static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
435 
436 #define sh_ssl_sess_tree_delete(s)	ebmb_delete(&(s)->key);
437 
438 #define sh_ssl_sess_tree_insert(s)	(struct sh_ssl_sess_hdr *)ebmb_insert(sh_ssl_sess_tree, \
439 								     &(s)->key, SSL_MAX_SSL_SESSION_ID_LENGTH);
440 
441 #define sh_ssl_sess_tree_lookup(k)	(struct sh_ssl_sess_hdr *)ebmb_lookup(sh_ssl_sess_tree, \
442 								     (k), SSL_MAX_SSL_SESSION_ID_LENGTH);
443 
444 /*
445  * This function gives the detail of the SSL error. It is used only
446  * if the debug mode and the verbose mode are activated. It dump all
447  * the SSL error until the stack was empty.
448  */
ssl_sock_dump_errors(struct connection * conn)449 static forceinline void ssl_sock_dump_errors(struct connection *conn)
450 {
451 	unsigned long ret;
452 
453 	if (unlikely(global.mode & MODE_DEBUG)) {
454 		while(1) {
455 			ret = ERR_get_error();
456 			if (ret == 0)
457 				return;
458 			fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
459 			        conn->handle.fd, ret,
460 			        ERR_func_error_string(ret), ERR_reason_error_string(ret));
461 		}
462 	}
463 }
464 
465 
466 #ifndef OPENSSL_NO_ENGINE
ssl_init_single_engine(const char * engine_id,const char * def_algorithms)467 static int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
468 {
469 	int err_code = ERR_ABORT;
470 	ENGINE *engine;
471 	struct ssl_engine_list *el;
472 
473 	/* grab the structural reference to the engine */
474 	engine = ENGINE_by_id(engine_id);
475 	if (engine  == NULL) {
476 		ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
477 		goto fail_get;
478 	}
479 
480 	if (!ENGINE_init(engine)) {
481 		/* the engine couldn't initialise, release it */
482 		ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
483 		goto fail_init;
484 	}
485 
486 	if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
487 		ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
488 		goto fail_set_method;
489 	}
490 
491 	el = calloc(1, sizeof(*el));
492 	if (!el)
493 		goto fail_alloc;
494 	el->e = engine;
495 	LIST_ADD(&openssl_engines, &el->list);
496 	nb_engines++;
497 	if (global_ssl.async)
498 		global.ssl_used_async_engines = nb_engines;
499 	return 0;
500 
501 fail_alloc:
502 fail_set_method:
503 	/* release the functional reference from ENGINE_init() */
504 	ENGINE_finish(engine);
505 
506 fail_init:
507 	/* release the structural reference from ENGINE_by_id() */
508 	ENGINE_free(engine);
509 
510 fail_get:
511 	return err_code;
512 }
513 #endif
514 
515 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
516 /*
517  * openssl async fd handler
518  */
ssl_async_fd_handler(int fd)519 void ssl_async_fd_handler(int fd)
520 {
521 	struct ssl_sock_ctx *ctx = fdtab[fd].owner;
522 
523 	/* fd is an async enfine fd, we must stop
524 	 * to poll this fd until it is requested
525 	 */
526         fd_stop_recv(fd);
527         fd_cant_recv(fd);
528 
529 	/* crypto engine is available, let's notify the associated
530 	 * connection that it can pursue its processing.
531 	 */
532 	ssl_sock_io_cb(NULL, ctx, 0);
533 }
534 
535 /*
536  * openssl async delayed SSL_free handler
537  */
ssl_async_fd_free(int fd)538 void ssl_async_fd_free(int fd)
539 {
540 	SSL *ssl = fdtab[fd].owner;
541 	OSSL_ASYNC_FD all_fd[32];
542 	size_t num_all_fds = 0;
543 	int i;
544 
545 	/* We suppose that the async job for a same SSL *
546 	 * are serialized. So if we are awake it is
547 	 * because the running job has just finished
548 	 * and we can remove all async fds safely
549 	 */
550 	SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
551 	if (num_all_fds > 32) {
552 		send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
553 		return;
554 	}
555 
556 	SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
557 	for (i=0 ; i < num_all_fds ; i++)
558 		fd_remove(all_fd[i]);
559 
560 	/* Now we can safely call SSL_free, no more pending job in engines */
561 	SSL_free(ssl);
562 	_HA_ATOMIC_SUB(&sslconns, 1);
563 	_HA_ATOMIC_SUB(&jobs, 1);
564 }
565 /*
566  * function used to manage a returned SSL_ERROR_WANT_ASYNC
567  * and enable/disable polling for async fds
568  */
ssl_async_process_fds(struct ssl_sock_ctx * ctx)569 static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
570 {
571 	OSSL_ASYNC_FD add_fd[32];
572 	OSSL_ASYNC_FD del_fd[32];
573 	SSL *ssl = ctx->ssl;
574 	size_t num_add_fds = 0;
575 	size_t num_del_fds = 0;
576 	int i;
577 
578 	SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
579 			&num_del_fds);
580 	if (num_add_fds > 32 || num_del_fds > 32) {
581 		send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
582 		return;
583 	}
584 
585 	SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
586 
587 	/* We remove unused fds from the fdtab */
588 	for (i=0 ; i < num_del_fds ; i++)
589 		fd_remove(del_fd[i]);
590 
591 	/* We add new fds to the fdtab */
592 	for (i=0 ; i < num_add_fds ; i++) {
593 		fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tid_bit);
594 	}
595 
596 	num_add_fds = 0;
597 	SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
598 	if (num_add_fds > 32) {
599 		send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
600 		return;
601 	}
602 
603 	/* We activate the polling for all known async fds */
604 	SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
605 	for (i=0 ; i < num_add_fds ; i++) {
606 		fd_want_recv(add_fd[i]);
607 		/* To ensure that the fd cache won't be used
608 		 * We'll prefer to catch a real RD event
609 		 * because handling an EAGAIN on this fd will
610 		 * result in a context switch and also
611 		 * some engines uses a fd in blocking mode.
612 		 */
613 		fd_cant_recv(add_fd[i]);
614 	}
615 
616 }
617 #endif
618 
619 #if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
620 /*
621  *  This function returns the number of seconds  elapsed
622  *  since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
623  *  date presented un ASN1_GENERALIZEDTIME.
624  *
625  *  In parsing error case, it returns -1.
626  */
asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME * d)627 static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
628 {
629 	long epoch;
630 	char *p, *end;
631 	const unsigned short month_offset[12] = {
632 		0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
633 	};
634 	unsigned long year, month;
635 
636 	if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
637 
638 	p = (char *)d->data;
639 	end = p + d->length;
640 
641 	if (end - p < 4) return -1;
642 	year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
643 	p += 4;
644 	if (end - p < 2) return -1;
645 	month = 10 * (p[0] - '0') + p[1] - '0';
646 	if (month < 1 || month > 12) return -1;
647 	/* Compute the number of seconds since 1 jan 1970 and the beginning of current month
648 	   We consider leap years and the current month (<marsh or not) */
649 	epoch = (  ((year - 1970) * 365)
650 		 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
651 		 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
652 		 + month_offset[month-1]
653 		) * 24 * 60 * 60;
654 	p += 2;
655 	if (end - p < 2) return -1;
656 	/* Add the number of seconds of completed days of current month */
657 	epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
658 	p += 2;
659 	if (end - p < 2) return -1;
660 	/* Add the completed hours of the current day */
661 	epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
662 	p += 2;
663 	if (end - p < 2) return -1;
664 	/* Add the completed minutes of the current hour */
665 	epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
666 	p += 2;
667 	if (p == end) return -1;
668 	/* Test if there is available seconds */
669 	if (p[0] < '0' || p[0] > '9')
670 		goto nosec;
671 	if (end - p < 2) return -1;
672 	/* Add the seconds of the current minute */
673 	epoch += 10 * (p[0] - '0') + p[1] - '0';
674 	p += 2;
675 	if (p == end) return -1;
676 	/* Ignore seconds float part if present */
677 	if (p[0] == '.') {
678 		do {
679 			if (++p == end) return -1;
680 		} while (p[0] >= '0' && p[0] <= '9');
681 	}
682 
683 nosec:
684 	if (p[0] == 'Z') {
685 		if (end - p != 1) return -1;
686 		return epoch;
687 	}
688 	else if (p[0] == '+') {
689 		if (end - p != 5) return -1;
690 		/* Apply timezone offset */
691 		return epoch - ((10 * (p[1] - '0') + p[2] - '0') * 60 * 60 + (10 * (p[3] - '0') + p[4] - '0')) * 60;
692 	}
693 	else if (p[0] == '-') {
694 		if (end - p != 5) return -1;
695 		/* Apply timezone offset */
696 		return epoch + ((10 * (p[1] - '0') + p[2] - '0') * 60 * 60 + (10 * (p[3] - '0') + p[4] - '0')) * 60;
697 	}
698 
699 	return -1;
700 }
701 
702 /*
703  * struct alignment works here such that the key.key is the same as key_data
704  * Do not change the placement of key_data
705  */
706 struct certificate_ocsp {
707 	struct ebmb_node key;
708 	unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
709 	struct buffer response;
710 	long expire;
711 };
712 
713 struct ocsp_cbk_arg {
714 	int is_single;
715 	int single_kt;
716 	union {
717 		struct certificate_ocsp *s_ocsp;
718 		/*
719 		 * m_ocsp will have multiple entries dependent on key type
720 		 * Entry 0 - DSA
721 		 * Entry 1 - ECDSA
722 		 * Entry 2 - RSA
723 		 */
724 		struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
725 	};
726 };
727 
728 static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
729 
730 /* This function starts to check if the OCSP response (in DER format) contained
731  * in chunk 'ocsp_response' is valid (else exits on error).
732  * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
733  * contained in the OCSP Response and exits on error if no match.
734  * If it's a valid OCSP Response:
735  *  If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
736  * pointed by 'ocsp'.
737  *  If 'ocsp' is NULL, the function looks up into the OCSP response's
738  * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
739  * from the response) and exits on error if not found. Finally, If an OCSP response is
740  * already present in the container, it will be overwritten.
741  *
742  * Note: OCSP response containing more than one OCSP Single response is not
743  * considered valid.
744  *
745  * Returns 0 on success, 1 in error case.
746  */
ssl_sock_load_ocsp_response(struct buffer * ocsp_response,struct certificate_ocsp * ocsp,OCSP_CERTID * cid,char ** err)747 static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
748 				       struct certificate_ocsp *ocsp,
749 				       OCSP_CERTID *cid, char **err)
750 {
751 	OCSP_RESPONSE *resp;
752 	OCSP_BASICRESP *bs = NULL;
753 	OCSP_SINGLERESP *sr;
754 	OCSP_CERTID *id;
755 	unsigned char *p = (unsigned char *) ocsp_response->area;
756 	int rc , count_sr;
757 	ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
758 	int reason;
759 	int ret = 1;
760 
761 	resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
762 				 ocsp_response->data);
763 	if (!resp) {
764 		memprintf(err, "Unable to parse OCSP response");
765 		goto out;
766 	}
767 
768 	rc = OCSP_response_status(resp);
769 	if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
770 		memprintf(err, "OCSP response status not successful");
771 		goto out;
772 	}
773 
774 	bs = OCSP_response_get1_basic(resp);
775 	if (!bs) {
776 		memprintf(err, "Failed to get basic response from OCSP Response");
777 		goto out;
778 	}
779 
780 	count_sr = OCSP_resp_count(bs);
781 	if (count_sr > 1) {
782 		memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
783 		goto out;
784 	}
785 
786 	sr = OCSP_resp_get0(bs, 0);
787 	if (!sr) {
788 		memprintf(err, "Failed to get OCSP single response");
789 		goto out;
790 	}
791 
792 	id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
793 
794 	rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
795 	if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
796 		memprintf(err, "OCSP single response: certificate status is unknown");
797 		goto out;
798 	}
799 
800 	if (!nextupd) {
801 		memprintf(err, "OCSP single response: missing nextupdate");
802 		goto out;
803 	}
804 
805 	rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
806 	if (!rc) {
807 		memprintf(err, "OCSP single response: no longer valid.");
808 		goto out;
809 	}
810 
811 	if (cid) {
812 		if (OCSP_id_cmp(id, cid)) {
813 			memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
814 			goto out;
815 		}
816 	}
817 
818 	if (!ocsp) {
819 		unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
820 		unsigned char *p;
821 
822 		rc = i2d_OCSP_CERTID(id, NULL);
823 		if (!rc) {
824 			memprintf(err, "OCSP single response: Unable to encode Certificate ID");
825 			goto out;
826 		}
827 
828 		if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
829 			memprintf(err, "OCSP single response: Certificate ID too long");
830 			goto out;
831 		}
832 
833 		p = key;
834 		memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
835 		i2d_OCSP_CERTID(id, &p);
836 		ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
837 		if (!ocsp) {
838 			memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
839 			goto out;
840 		}
841 	}
842 
843 	/* According to comments on "chunk_dup", the
844 	   previous chunk buffer will be freed */
845 	if (!chunk_dup(&ocsp->response, ocsp_response)) {
846 		memprintf(err, "OCSP response: Memory allocation error");
847 		goto out;
848 	}
849 
850 	ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
851 	if (ocsp->expire < 0) {
852 		memprintf(err, "OCSP single response: Invalid \"Next Update\" time");
853 		goto out;
854 	}
855 
856 	ret = 0;
857 out:
858 	ERR_clear_error();
859 
860 	if (bs)
861 		 OCSP_BASICRESP_free(bs);
862 
863 	if (resp)
864 		OCSP_RESPONSE_free(resp);
865 
866 	return ret;
867 }
868 /*
869  * External function use to update the OCSP response in the OCSP response's
870  * containers tree. The chunk 'ocsp_response' must contain the OCSP response
871  * to update in DER format.
872  *
873  * Returns 0 on success, 1 in error case.
874  */
ssl_sock_update_ocsp_response(struct buffer * ocsp_response,char ** err)875 int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
876 {
877 	return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
878 }
879 
880 /*
881  * This function load the OCSP Resonse in DER format contained in file at
882  * path 'ocsp_path' and call 'ssl_sock_load_ocsp_response'
883  *
884  * Returns 0 on success, 1 in error case.
885  */
ssl_sock_load_ocsp_response_from_file(const char * ocsp_path,struct certificate_ocsp * ocsp,OCSP_CERTID * cid,char ** err)886 static int ssl_sock_load_ocsp_response_from_file(const char *ocsp_path, struct certificate_ocsp *ocsp, OCSP_CERTID *cid, char **err)
887 {
888 	int fd = -1;
889 	int r = 0;
890 	int ret = 1;
891 
892 	fd = open(ocsp_path, O_RDONLY);
893 	if (fd == -1) {
894 		memprintf(err, "Error opening OCSP response file");
895 		goto end;
896 	}
897 
898 	trash.data = 0;
899 	while (trash.data < trash.size) {
900 		r = read(fd, trash.area + trash.data, trash.size - trash.data);
901 		if (r < 0) {
902 			if (errno == EINTR)
903 				continue;
904 
905 			memprintf(err, "Error reading OCSP response from file");
906 			goto end;
907 		}
908 		else if (r == 0) {
909 			break;
910 		}
911 		trash.data += r;
912 	}
913 
914 	close(fd);
915 	fd = -1;
916 
917 	ret = ssl_sock_load_ocsp_response(&trash, ocsp, cid, err);
918 end:
919 	if (fd != -1)
920 		close(fd);
921 
922 	return ret;
923 }
924 #endif
925 
926 #if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
ssl_tlsext_ticket_key_cb(SSL * s,unsigned char key_name[16],unsigned char * iv,EVP_CIPHER_CTX * ectx,HMAC_CTX * hctx,int enc)927 static int ssl_tlsext_ticket_key_cb(SSL *s, unsigned char key_name[16], unsigned char *iv, EVP_CIPHER_CTX *ectx, HMAC_CTX *hctx, int enc)
928 {
929 	struct tls_keys_ref *ref;
930 	union tls_sess_key *keys;
931 	struct connection *conn;
932 	int head;
933 	int i;
934 	int ret = -1; /* error by default */
935 
936 	conn = SSL_get_ex_data(s, ssl_app_data_index);
937 	ref  = __objt_listener(conn->target)->bind_conf->keys_ref;
938 	HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
939 
940 	keys = ref->tlskeys;
941 	head = ref->tls_ticket_enc_index;
942 
943 	if (enc) {
944 		memcpy(key_name, keys[head].name, 16);
945 
946 		if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
947 			goto end;
948 
949 		if (ref->key_size_bits == 128) {
950 
951 			if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
952 				goto end;
953 
954 			HMAC_Init_ex(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT(), NULL);
955 			ret = 1;
956 		}
957 		else if (ref->key_size_bits == 256 ) {
958 
959 			if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
960 				goto end;
961 
962 			HMAC_Init_ex(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT(), NULL);
963 			ret = 1;
964 		}
965 	} else {
966 		for (i = 0; i < TLS_TICKETS_NO; i++) {
967 			if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
968 				goto found;
969 		}
970 		ret = 0;
971 		goto end;
972 
973 	  found:
974 		if (ref->key_size_bits == 128) {
975 			HMAC_Init_ex(hctx, keys[(head + i) % TLS_TICKETS_NO].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT(), NULL);
976 			if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
977 				goto end;
978 			/* 2 for key renewal, 1 if current key is still valid */
979 			ret = i ? 2 : 1;
980 		}
981 		else if (ref->key_size_bits == 256) {
982 			HMAC_Init_ex(hctx, keys[(head + i) % TLS_TICKETS_NO].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT(), NULL);
983 			if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
984 				goto end;
985 			/* 2 for key renewal, 1 if current key is still valid */
986 			ret = i ? 2 : 1;
987 		}
988 	}
989 
990   end:
991 	HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
992 	return ret;
993 }
994 
tlskeys_ref_lookup(const char * filename)995 struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
996 {
997         struct tls_keys_ref *ref;
998 
999         list_for_each_entry(ref, &tlskeys_reference, list)
1000                 if (ref->filename && strcmp(filename, ref->filename) == 0)
1001                         return ref;
1002         return NULL;
1003 }
1004 
tlskeys_ref_lookupid(int unique_id)1005 struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1006 {
1007         struct tls_keys_ref *ref;
1008 
1009         list_for_each_entry(ref, &tlskeys_reference, list)
1010                 if (ref->unique_id == unique_id)
1011                         return ref;
1012         return NULL;
1013 }
1014 
1015 /* Update the key into ref: if keysize doesnt
1016  * match existing ones, this function returns -1
1017  * else it returns 0 on success.
1018  */
ssl_sock_update_tlskey_ref(struct tls_keys_ref * ref,struct buffer * tlskey)1019 int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
1020 				struct buffer *tlskey)
1021 {
1022 	if (ref->key_size_bits == 128) {
1023 		if (tlskey->data != sizeof(struct tls_sess_key_128))
1024 			       return -1;
1025 	}
1026 	else if (ref->key_size_bits == 256) {
1027 		if (tlskey->data != sizeof(struct tls_sess_key_256))
1028 			       return -1;
1029 	}
1030 	else
1031 		return -1;
1032 
1033 	HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1034 	memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1035 	       tlskey->area, tlskey->data);
1036 	ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1037 	HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1038 
1039 	return 0;
1040 }
1041 
ssl_sock_update_tlskey(char * filename,struct buffer * tlskey,char ** err)1042 int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
1043 {
1044 	struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1045 
1046 	if(!ref) {
1047 		memprintf(err, "Unable to locate the referenced filename: %s", filename);
1048 		return 1;
1049 	}
1050 	if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1051 		memprintf(err, "Invalid key size");
1052 		return 1;
1053 	}
1054 
1055 	return 0;
1056 }
1057 
1058 /* This function finalize the configuration parsing. Its set all the
1059  * automatic ids. It's called just after the basic checks. It returns
1060  * 0 on success otherwise ERR_*.
1061  */
tlskeys_finalize_config(void)1062 static int tlskeys_finalize_config(void)
1063 {
1064 	int i = 0;
1065 	struct tls_keys_ref *ref, *ref2, *ref3;
1066 	struct list tkr = LIST_HEAD_INIT(tkr);
1067 
1068 	list_for_each_entry(ref, &tlskeys_reference, list) {
1069 		if (ref->unique_id == -1) {
1070 			/* Look for the first free id. */
1071 			while (1) {
1072 				list_for_each_entry(ref2, &tlskeys_reference, list) {
1073 					if (ref2->unique_id == i) {
1074 						i++;
1075 						break;
1076 					}
1077 				}
1078 				if (&ref2->list == &tlskeys_reference)
1079 					break;
1080 			}
1081 
1082 			/* Uses the unique id and increment it for the next entry. */
1083 			ref->unique_id = i;
1084 			i++;
1085 		}
1086 	}
1087 
1088 	/* This sort the reference list by id. */
1089 	list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
1090 		LIST_DEL(&ref->list);
1091 		list_for_each_entry(ref3, &tkr, list) {
1092 			if (ref->unique_id < ref3->unique_id) {
1093 				LIST_ADDQ(&ref3->list, &ref->list);
1094 				break;
1095 			}
1096 		}
1097 		if (&ref3->list == &tkr)
1098 			LIST_ADDQ(&tkr, &ref->list);
1099 	}
1100 
1101 	/* swap root */
1102 	LIST_ADD(&tkr, &tlskeys_reference);
1103 	LIST_DEL(&tkr);
1104 	return 0;
1105 }
1106 #endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1107 
1108 #ifndef OPENSSL_NO_OCSP
ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)1109 int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1110 {
1111 	switch (evp_keytype) {
1112 	case EVP_PKEY_RSA:
1113 		return 2;
1114 	case EVP_PKEY_DSA:
1115 		return 0;
1116 	case EVP_PKEY_EC:
1117 		return 1;
1118 	}
1119 
1120 	return -1;
1121 }
1122 
1123 /*
1124  * Callback used to set OCSP status extension content in server hello.
1125  */
ssl_sock_ocsp_stapling_cbk(SSL * ssl,void * arg)1126 int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1127 {
1128 	struct certificate_ocsp *ocsp;
1129 	struct ocsp_cbk_arg *ocsp_arg;
1130 	char *ssl_buf;
1131 	EVP_PKEY *ssl_pkey;
1132 	int key_type;
1133 	int index;
1134 
1135 	ocsp_arg = arg;
1136 
1137 	ssl_pkey = SSL_get_privatekey(ssl);
1138 	if (!ssl_pkey)
1139 		return SSL_TLSEXT_ERR_NOACK;
1140 
1141 	key_type = EVP_PKEY_base_id(ssl_pkey);
1142 
1143 	if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1144 		ocsp = ocsp_arg->s_ocsp;
1145 	else {
1146 		/* For multiple certs per context, we have to find the correct OCSP response based on
1147 		 * the certificate type
1148 		 */
1149 		index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1150 
1151 		if (index < 0)
1152 			return SSL_TLSEXT_ERR_NOACK;
1153 
1154 		ocsp = ocsp_arg->m_ocsp[index];
1155 
1156 	}
1157 
1158 	if (!ocsp ||
1159 	    !ocsp->response.area ||
1160 	    !ocsp->response.data ||
1161 	    (ocsp->expire < now.tv_sec))
1162 		return SSL_TLSEXT_ERR_NOACK;
1163 
1164 	ssl_buf = OPENSSL_malloc(ocsp->response.data);
1165 	if (!ssl_buf)
1166 		return SSL_TLSEXT_ERR_NOACK;
1167 
1168 	memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
1169 	SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.data);
1170 
1171 	return SSL_TLSEXT_ERR_OK;
1172 }
1173 
1174 /*
1175  * This function enables the handling of OCSP status extension on 'ctx' if a
1176  * file name 'cert_path' suffixed using ".ocsp" is present.
1177  * To enable OCSP status extension, the issuer's certificate is mandatory.
1178  * It should be present in the certificate's extra chain builded from file
1179  * 'cert_path'. If not found, the issuer certificate is loaded from a file
1180  * named 'cert_path' suffixed using '.issuer'.
1181  *
1182  * In addition, ".ocsp" file content is loaded as a DER format of an OCSP
1183  * response. If file is empty or content is not a valid OCSP response,
1184  * OCSP status extension is enabled but OCSP response is ignored (a warning
1185  * is displayed).
1186  *
1187  * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
1188  * successfully enabled, or -1 in other error case.
1189  */
ssl_sock_load_ocsp(SSL_CTX * ctx,const char * cert_path)1190 static int ssl_sock_load_ocsp(SSL_CTX *ctx, const char *cert_path)
1191 {
1192 
1193 	BIO *in = NULL;
1194 	X509 *x, *xi = NULL, *issuer = NULL;
1195 	STACK_OF(X509) *chain = NULL;
1196 	OCSP_CERTID *cid = NULL;
1197 	SSL *ssl;
1198 	char ocsp_path[MAXPATHLEN+1];
1199 	int i, ret = -1;
1200 	struct stat st;
1201 	struct certificate_ocsp *ocsp = NULL, *iocsp;
1202 	char *warn = NULL;
1203 	unsigned char *p;
1204 	pem_password_cb *passwd_cb;
1205 	void *passwd_cb_userdata;
1206 	void (*callback) (void);
1207 
1208 	snprintf(ocsp_path, MAXPATHLEN+1, "%s.ocsp", cert_path);
1209 
1210 	if (stat(ocsp_path, &st))
1211 		return 1;
1212 
1213 	ssl = SSL_new(ctx);
1214 	if (!ssl)
1215 		goto out;
1216 
1217 	x = SSL_get_certificate(ssl);
1218 	if (!x)
1219 		goto out;
1220 
1221 	/* Try to lookup for issuer in certificate extra chain */
1222 	SSL_CTX_get_extra_chain_certs(ctx, &chain);
1223 	for (i = 0; i < sk_X509_num(chain); i++) {
1224 		issuer = sk_X509_value(chain, i);
1225 		if (X509_check_issued(issuer, x) == X509_V_OK)
1226 			break;
1227 		else
1228 			issuer = NULL;
1229 	}
1230 
1231 	/* If not found try to load issuer from a suffixed file */
1232 	if (!issuer) {
1233 		char issuer_path[MAXPATHLEN+1];
1234 
1235 		in = BIO_new(BIO_s_file());
1236 		if (!in)
1237 			goto out;
1238 
1239 		snprintf(issuer_path, MAXPATHLEN+1, "%s.issuer", cert_path);
1240 		if (BIO_read_filename(in, issuer_path) <= 0)
1241 			goto out;
1242 
1243 		passwd_cb = SSL_CTX_get_default_passwd_cb(ctx);
1244 		passwd_cb_userdata = SSL_CTX_get_default_passwd_cb_userdata(ctx);
1245 
1246 		xi = PEM_read_bio_X509_AUX(in, NULL, passwd_cb, passwd_cb_userdata);
1247 		if (!xi)
1248 			goto out;
1249 
1250 		if (X509_check_issued(xi, x) != X509_V_OK)
1251 			goto out;
1252 
1253 		issuer = xi;
1254 	}
1255 
1256 	cid = OCSP_cert_to_id(0, x, issuer);
1257 	if (!cid)
1258 		goto out;
1259 
1260 	i = i2d_OCSP_CERTID(cid, NULL);
1261 	if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1262 		goto out;
1263 
1264 	ocsp = calloc(1, sizeof(*ocsp));
1265 	if (!ocsp)
1266 		goto out;
1267 
1268 	p = ocsp->key_data;
1269 	i2d_OCSP_CERTID(cid, &p);
1270 
1271 	iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1272 	if (iocsp == ocsp)
1273 		ocsp = NULL;
1274 
1275 #ifndef SSL_CTX_get_tlsext_status_cb
1276 # define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1277 	*cb = (void (*) (void))ctx->tlsext_status_cb;
1278 #endif
1279 	SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1280 
1281 	if (!callback) {
1282 		struct ocsp_cbk_arg *cb_arg;
1283 		EVP_PKEY *pkey;
1284 
1285 		cb_arg = calloc(1, sizeof(*cb_arg));
1286 		if (!cb_arg)
1287 			goto out;
1288 
1289 		cb_arg->is_single = 1;
1290 		cb_arg->s_ocsp = iocsp;
1291 
1292 		pkey = X509_get_pubkey(x);
1293 		cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1294 		EVP_PKEY_free(pkey);
1295 
1296 		SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
1297 		SSL_CTX_set_tlsext_status_arg(ctx, cb_arg);
1298 	} else {
1299 		/*
1300 		 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1301 		 * Update that cb_arg with the new cert's staple
1302 		 */
1303 		struct ocsp_cbk_arg *cb_arg;
1304 		struct certificate_ocsp *tmp_ocsp;
1305 		int index;
1306 		int key_type;
1307 		EVP_PKEY *pkey;
1308 
1309 #ifdef SSL_CTX_get_tlsext_status_arg
1310 		SSL_CTX_ctrl(ctx, SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB_ARG, 0, &cb_arg);
1311 #else
1312 		cb_arg = ctx->tlsext_status_arg;
1313 #endif
1314 
1315 		/*
1316 		 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1317 		 * the order of operations below matter, take care when changing it
1318 		 */
1319 		tmp_ocsp = cb_arg->s_ocsp;
1320 		index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1321 		cb_arg->s_ocsp = NULL;
1322 		cb_arg->m_ocsp[index] = tmp_ocsp;
1323 		cb_arg->is_single = 0;
1324 		cb_arg->single_kt = 0;
1325 
1326 		pkey = X509_get_pubkey(x);
1327 		key_type = EVP_PKEY_base_id(pkey);
1328 		EVP_PKEY_free(pkey);
1329 
1330 		index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1331 		if (index >= 0 && !cb_arg->m_ocsp[index])
1332 			cb_arg->m_ocsp[index] = iocsp;
1333 
1334 	}
1335 
1336 	ret = 0;
1337 
1338 	warn = NULL;
1339 	if (ssl_sock_load_ocsp_response_from_file(ocsp_path, iocsp, cid, &warn)) {
1340 		memprintf(&warn, "Loading '%s': %s. Content will be ignored", ocsp_path, warn ? warn : "failure");
1341 		ha_warning("%s.\n", warn);
1342 	}
1343 
1344 out:
1345 	if (ssl)
1346 		SSL_free(ssl);
1347 
1348 	if (in)
1349 		BIO_free(in);
1350 
1351 	if (xi)
1352 		X509_free(xi);
1353 
1354 	if (cid)
1355 		OCSP_CERTID_free(cid);
1356 
1357 	if (ocsp)
1358 		free(ocsp);
1359 
1360 	if (warn)
1361 		free(warn);
1362 
1363 
1364 	return ret;
1365 }
1366 
1367 #endif
1368 
1369 #ifdef OPENSSL_IS_BORINGSSL
ssl_sock_set_ocsp_response_from_file(SSL_CTX * ctx,const char * cert_path)1370 static int ssl_sock_set_ocsp_response_from_file(SSL_CTX *ctx, const char *cert_path)
1371 {
1372 	char ocsp_path[MAXPATHLEN+1];
1373 	struct stat st;
1374 	int fd = -1, r = 0;
1375 
1376 	snprintf(ocsp_path, MAXPATHLEN+1, "%s.ocsp", cert_path);
1377 	if (stat(ocsp_path, &st))
1378 		return 0;
1379 
1380 	fd = open(ocsp_path, O_RDONLY);
1381 	if (fd == -1) {
1382 		ha_warning("Error opening OCSP response file %s.\n", ocsp_path);
1383 		return -1;
1384 	}
1385 
1386 	trash.data = 0;
1387 	while (trash.data < trash.size) {
1388 		r = read(fd, trash.area + trash.data, trash.size - trash.data);
1389 		if (r < 0) {
1390 			if (errno == EINTR)
1391 				continue;
1392 			ha_warning("Error reading OCSP response from file %s.\n", ocsp_path);
1393 			close(fd);
1394 			return -1;
1395 		}
1396 		else if (r == 0) {
1397 			break;
1398 		}
1399 		trash.data += r;
1400 	}
1401 	close(fd);
1402 	return SSL_CTX_set_ocsp_response(ctx, (const uint8_t *) trash.area,
1403 					 trash.data);
1404 }
1405 #endif
1406 
1407 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
1408 
1409 #define CT_EXTENSION_TYPE 18
1410 
1411 static int sctl_ex_index = -1;
1412 
1413 /*
1414  * Try to parse Signed Certificate Timestamp List structure. This function
1415  * makes only basic test if the data seems like SCTL. No signature validation
1416  * is performed.
1417  */
ssl_sock_parse_sctl(struct buffer * sctl)1418 static int ssl_sock_parse_sctl(struct buffer *sctl)
1419 {
1420 	int ret = 1;
1421 	int len, pos, sct_len;
1422 	unsigned char *data;
1423 
1424 	if (sctl->data < 2)
1425 		goto out;
1426 
1427 	data = (unsigned char *) sctl->area;
1428 	len = (data[0] << 8) | data[1];
1429 
1430 	if (len + 2 != sctl->data)
1431 		goto out;
1432 
1433 	data = data + 2;
1434 	pos = 0;
1435 	while (pos < len) {
1436 		if (len - pos < 2)
1437 			goto out;
1438 
1439 		sct_len = (data[pos] << 8) | data[pos + 1];
1440 		if (pos + sct_len + 2 > len)
1441 			goto out;
1442 
1443 		pos += sct_len + 2;
1444 	}
1445 
1446 	ret = 0;
1447 
1448 out:
1449 	return ret;
1450 }
1451 
ssl_sock_load_sctl_from_file(const char * sctl_path,struct buffer ** sctl)1452 static int ssl_sock_load_sctl_from_file(const char *sctl_path,
1453 					struct buffer **sctl)
1454 {
1455 	int fd = -1;
1456 	int r = 0;
1457 	int ret = 1;
1458 
1459 	*sctl = NULL;
1460 
1461 	fd = open(sctl_path, O_RDONLY);
1462 	if (fd == -1)
1463 		goto end;
1464 
1465 	trash.data = 0;
1466 	while (trash.data < trash.size) {
1467 		r = read(fd, trash.area + trash.data, trash.size - trash.data);
1468 		if (r < 0) {
1469 			if (errno == EINTR)
1470 				continue;
1471 
1472 			goto end;
1473 		}
1474 		else if (r == 0) {
1475 			break;
1476 		}
1477 		trash.data += r;
1478 	}
1479 
1480 	ret = ssl_sock_parse_sctl(&trash);
1481 	if (ret)
1482 		goto end;
1483 
1484 	*sctl = calloc(1, sizeof(**sctl));
1485 	if (!chunk_dup(*sctl, &trash)) {
1486 		free(*sctl);
1487 		*sctl = NULL;
1488 		goto end;
1489 	}
1490 
1491 end:
1492 	if (fd != -1)
1493 		close(fd);
1494 
1495 	return ret;
1496 }
1497 
ssl_sock_sctl_add_cbk(SSL * ssl,unsigned ext_type,const unsigned char ** out,size_t * outlen,int * al,void * add_arg)1498 int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1499 {
1500 	struct buffer *sctl = add_arg;
1501 
1502 	*out = (unsigned char *) sctl->area;
1503 	*outlen = sctl->data;
1504 
1505 	return 1;
1506 }
1507 
ssl_sock_sctl_parse_cbk(SSL * s,unsigned int ext_type,const unsigned char * in,size_t inlen,int * al,void * parse_arg)1508 int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1509 {
1510 	return 1;
1511 }
1512 
ssl_sock_load_sctl(SSL_CTX * ctx,const char * cert_path)1513 static int ssl_sock_load_sctl(SSL_CTX *ctx, const char *cert_path)
1514 {
1515 	char sctl_path[MAXPATHLEN+1];
1516 	int ret = -1;
1517 	struct stat st;
1518 	struct buffer *sctl = NULL;
1519 
1520 	snprintf(sctl_path, MAXPATHLEN+1, "%s.sctl", cert_path);
1521 
1522 	if (stat(sctl_path, &st))
1523 		return 1;
1524 
1525 	if (ssl_sock_load_sctl_from_file(sctl_path, &sctl))
1526 		goto out;
1527 
1528 	if (!SSL_CTX_add_server_custom_ext(ctx, CT_EXTENSION_TYPE, ssl_sock_sctl_add_cbk, NULL, sctl, ssl_sock_sctl_parse_cbk, NULL)) {
1529 		free(sctl);
1530 		goto out;
1531 	}
1532 
1533 	SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1534 
1535 	ret = 0;
1536 
1537 out:
1538 	return ret;
1539 }
1540 
1541 #endif
1542 
ssl_sock_infocbk(const SSL * ssl,int where,int ret)1543 void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1544 {
1545 	struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1546 	struct ssl_sock_ctx *ctx = conn->xprt_ctx;
1547 	BIO *write_bio;
1548 	(void)ret; /* shut gcc stupid warning */
1549 
1550 #ifndef SSL_OP_NO_RENEGOTIATION
1551 	/* Please note that BoringSSL defines this macro to zero so don't
1552 	 * change this to #if and do not assign a default value to this macro!
1553 	 */
1554 	if (where & SSL_CB_HANDSHAKE_START) {
1555 		/* Disable renegotiation (CVE-2009-3555) */
1556 		if ((conn->flags & (CO_FL_CONNECTED | CO_FL_EARLY_SSL_HS | CO_FL_EARLY_DATA)) == CO_FL_CONNECTED) {
1557 			conn->flags |= CO_FL_ERROR;
1558 			conn->err_code = CO_ER_SSL_RENEG;
1559 		}
1560 	}
1561 #endif
1562 
1563 	if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
1564 		if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
1565 			/* Long certificate chains optimz
1566 			   If write and read bios are differents, we
1567 			   consider that the buffering was activated,
1568                            so we rise the output buffer size from 4k
1569 			   to 16k */
1570 			write_bio = SSL_get_wbio(ssl);
1571 			if (write_bio != SSL_get_rbio(ssl)) {
1572 				BIO_set_write_buffer_size(write_bio, 16384);
1573 				ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
1574 			}
1575 		}
1576 	}
1577 }
1578 
1579 /* Callback is called for each certificate of the chain during a verify
1580    ok is set to 1 if preverify detect no error on current certificate.
1581    Returns 0 to break the handshake, 1 otherwise. */
ssl_sock_bind_verifycbk(int ok,X509_STORE_CTX * x_store)1582 int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
1583 {
1584 	SSL *ssl;
1585 	struct connection *conn;
1586 	struct ssl_sock_ctx *ctx;
1587 	int err, depth;
1588 
1589 	ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
1590 	conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1591 
1592 	ctx = conn->xprt_ctx;
1593 
1594 	ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
1595 
1596 	if (ok) /* no errors */
1597 		return ok;
1598 
1599 	depth = X509_STORE_CTX_get_error_depth(x_store);
1600 	err = X509_STORE_CTX_get_error(x_store);
1601 
1602 	/* check if CA error needs to be ignored */
1603 	if (depth > 0) {
1604 		if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1605 			ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1606 			ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
1607 		}
1608 
1609 		if (err < 64 && __objt_listener(conn->target)->bind_conf->ca_ignerr & (1ULL << err)) {
1610 			ssl_sock_dump_errors(conn);
1611 			ERR_clear_error();
1612 			return 1;
1613 		}
1614 
1615 		conn->err_code = CO_ER_SSL_CA_FAIL;
1616 		return 0;
1617 	}
1618 
1619 	if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1620 		ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
1621 
1622 	/* check if certificate error needs to be ignored */
1623 	if (err < 64 && __objt_listener(conn->target)->bind_conf->crt_ignerr & (1ULL << err)) {
1624 		ssl_sock_dump_errors(conn);
1625 		ERR_clear_error();
1626 		return 1;
1627 	}
1628 
1629 	conn->err_code = CO_ER_SSL_CRT_FAIL;
1630 	return 0;
1631 }
1632 
1633 static inline
ssl_sock_parse_clienthello(int write_p,int version,int content_type,const void * buf,size_t len,SSL * ssl)1634 void ssl_sock_parse_clienthello(int write_p, int version, int content_type,
1635                                 const void *buf, size_t len, SSL *ssl)
1636 {
1637 	struct ssl_capture *capture;
1638 	unsigned char *msg;
1639 	unsigned char *end;
1640 	size_t rec_len;
1641 
1642 	/* This function is called for "from client" and "to server"
1643 	 * connections. The combination of write_p == 0 and content_type == 22
1644 	 * is only available during "from client" connection.
1645 	 */
1646 
1647 	/* "write_p" is set to 0 is the bytes are received messages,
1648 	 * otherwise it is set to 1.
1649 	 */
1650 	if (write_p != 0)
1651 		return;
1652 
1653 	/* content_type contains the type of message received or sent
1654 	 * according with the SSL/TLS protocol spec. This message is
1655 	 * encoded with one byte. The value 256 (two bytes) is used
1656 	 * for designing the SSL/TLS record layer. According with the
1657 	 * rfc6101, the expected message (other than 256) are:
1658 	 *  - change_cipher_spec(20)
1659 	 *  - alert(21)
1660 	 *  - handshake(22)
1661 	 *  - application_data(23)
1662 	 *  - (255)
1663 	 * We are interessed by the handshake and specially the client
1664 	 * hello.
1665 	 */
1666 	if (content_type != 22)
1667 		return;
1668 
1669 	/* The message length is at least 4 bytes, containing the
1670 	 * message type and the message length.
1671 	 */
1672 	if (len < 4)
1673 		return;
1674 
1675 	/* First byte of the handshake message id the type of
1676 	 * message. The konwn types are:
1677 	 *  - hello_request(0)
1678 	 *  - client_hello(1)
1679 	 *  - server_hello(2)
1680 	 *  - certificate(11)
1681 	 *  - server_key_exchange (12)
1682 	 *  - certificate_request(13)
1683 	 *  - server_hello_done(14)
1684 	 * We are interested by the client hello.
1685 	 */
1686 	msg = (unsigned char *)buf;
1687 	if (msg[0] != 1)
1688 		return;
1689 
1690 	/* Next three bytes are the length of the message. The total length
1691 	 * must be this decoded length + 4. If the length given as argument
1692 	 * is not the same, we abort the protocol dissector.
1693 	 */
1694 	rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1695 	if (len < rec_len + 4)
1696 		return;
1697 	msg += 4;
1698 	end = msg + rec_len;
1699 	if (end < msg)
1700 		return;
1701 
1702 	/* Expect 2 bytes for protocol version (1 byte for major and 1 byte
1703 	 * for minor, the random, composed by 4 bytes for the unix time and
1704 	 * 28 bytes for unix payload. So we jump 1 + 1 + 4 + 28.
1705 	 */
1706 	msg += 1 + 1 + 4 + 28;
1707 	if (msg > end)
1708 		return;
1709 
1710 	/* Next, is session id:
1711 	 * if present, we have to jump by length + 1 for the size information
1712 	 * if not present, we have to jump by 1 only
1713 	 */
1714 	if (msg[0] > 0)
1715 		msg += msg[0];
1716 	msg += 1;
1717 	if (msg > end)
1718 		return;
1719 
1720 	/* Next two bytes are the ciphersuite length. */
1721 	if (msg + 2 > end)
1722 		return;
1723 	rec_len = (msg[0] << 8) + msg[1];
1724 	msg += 2;
1725 	if (msg + rec_len > end || msg + rec_len < msg)
1726 		return;
1727 
1728 	capture = pool_alloc_dirty(pool_head_ssl_capture);
1729 	if (!capture)
1730 		return;
1731 	/* Compute the xxh64 of the ciphersuite. */
1732 	capture->xxh64 = XXH64(msg, rec_len, 0);
1733 
1734 	/* Capture the ciphersuite. */
1735 	capture->ciphersuite_len = (global_ssl.capture_cipherlist < rec_len) ?
1736 		global_ssl.capture_cipherlist : rec_len;
1737 	memcpy(capture->ciphersuite, msg, capture->ciphersuite_len);
1738 
1739 	SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
1740 }
1741 
1742 /* Callback is called for ssl protocol analyse */
ssl_sock_msgcbk(int write_p,int version,int content_type,const void * buf,size_t len,SSL * ssl,void * arg)1743 void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1744 {
1745 #ifdef TLS1_RT_HEARTBEAT
1746 	/* test heartbeat received (write_p is set to 0
1747 	   for a received record) */
1748 	if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
1749 		struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1750 		struct ssl_sock_ctx *ctx = conn->xprt_ctx;
1751 		const unsigned char *p = buf;
1752 		unsigned int payload;
1753 
1754 		ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1755 
1756 		/* Check if this is a CVE-2014-0160 exploitation attempt. */
1757 		if (*p != TLS1_HB_REQUEST)
1758 			return;
1759 
1760 		if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1761 			goto kill_it;
1762 
1763 		payload = (p[1] * 256) + p[2];
1764 		if (3 + payload + 16 <= len)
1765 			return; /* OK no problem */
1766 	kill_it:
1767 		/* We have a clear heartbleed attack (CVE-2014-0160), the
1768 		 * advertised payload is larger than the advertised packet
1769 		 * length, so we have garbage in the buffer between the
1770 		 * payload and the end of the buffer (p+len). We can't know
1771 		 * if the SSL stack is patched, and we don't know if we can
1772 		 * safely wipe out the area between p+3+len and payload.
1773 		 * So instead, we prevent the response from being sent by
1774 		 * setting the max_send_fragment to 0 and we report an SSL
1775 		 * error, which will kill this connection. It will be reported
1776 		 * above as SSL_ERROR_SSL while an other handshake failure with
1777 		 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1778 		 */
1779 		ssl->max_send_fragment = 0;
1780 		SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1781 		return;
1782 	}
1783 #endif
1784 	if (global_ssl.capture_cipherlist > 0)
1785 		ssl_sock_parse_clienthello(write_p, version, content_type, buf, len, ssl);
1786 }
1787 
1788 #if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
ssl_sock_srv_select_protos(SSL * s,unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)1789 static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1790                                       const unsigned char *in, unsigned int inlen,
1791 				      void *arg)
1792 {
1793 	struct server *srv = arg;
1794 
1795 	if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1796 	    srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1797 		return SSL_TLSEXT_ERR_OK;
1798 	return SSL_TLSEXT_ERR_NOACK;
1799 }
1800 #endif
1801 
1802 #if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
1803 /* This callback is used so that the server advertises the list of
1804  * negociable protocols for NPN.
1805  */
ssl_sock_advertise_npn_protos(SSL * s,const unsigned char ** data,unsigned int * len,void * arg)1806 static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1807                                          unsigned int *len, void *arg)
1808 {
1809 	struct ssl_bind_conf *conf = arg;
1810 
1811 	*data = (const unsigned char *)conf->npn_str;
1812 	*len = conf->npn_len;
1813 	return SSL_TLSEXT_ERR_OK;
1814 }
1815 #endif
1816 
1817 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
1818 /* This callback is used so that the server advertises the list of
1819  * negociable protocols for ALPN.
1820  */
ssl_sock_advertise_alpn_protos(SSL * s,const unsigned char ** out,unsigned char * outlen,const unsigned char * server,unsigned int server_len,void * arg)1821 static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1822                                           unsigned char *outlen,
1823                                           const unsigned char *server,
1824                                           unsigned int server_len, void *arg)
1825 {
1826 	struct ssl_bind_conf *conf = arg;
1827 
1828 	if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1829 	                          conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
1830 		return SSL_TLSEXT_ERR_NOACK;
1831 	}
1832 	return SSL_TLSEXT_ERR_OK;
1833 }
1834 #endif
1835 
1836 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1837 #ifndef SSL_NO_GENERATE_CERTIFICATES
1838 
1839 /* Create a X509 certificate with the specified servername and serial. This
1840  * function returns a SSL_CTX object or NULL if an error occurs. */
1841 static SSL_CTX *
ssl_sock_do_create_cert(const char * servername,struct bind_conf * bind_conf,SSL * ssl)1842 ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
1843 {
1844 	X509         *cacert  = bind_conf->ca_sign_cert;
1845 	EVP_PKEY     *capkey  = bind_conf->ca_sign_pkey;
1846 	SSL_CTX      *ssl_ctx = NULL;
1847 	X509         *newcrt  = NULL;
1848 	EVP_PKEY     *pkey    = NULL;
1849 	SSL          *tmp_ssl = NULL;
1850 	CONF         *ctmp    = NULL;
1851 	X509_NAME    *name;
1852 	const EVP_MD *digest;
1853 	X509V3_CTX    ctx;
1854 	unsigned int  i;
1855 	int 	      key_type;
1856 
1857 	/* Get the private key of the default certificate and use it */
1858 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10002000L)
1859 	pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1860 #else
1861 	tmp_ssl = SSL_new(bind_conf->default_ctx);
1862 	if (tmp_ssl)
1863 		pkey = SSL_get_privatekey(tmp_ssl);
1864 #endif
1865 	if (!pkey)
1866 		goto mkcert_error;
1867 
1868 	/* Create the certificate */
1869 	if (!(newcrt = X509_new()))
1870 		goto mkcert_error;
1871 
1872 	/* Set version number for the certificate (X509v3) and the serial
1873 	 * number */
1874 	if (X509_set_version(newcrt, 2L) != 1)
1875 		goto mkcert_error;
1876 	ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD(&ssl_ctx_serial, 1));
1877 
1878 	/* Set duration for the certificate */
1879 	if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1880 	    !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
1881 		goto mkcert_error;
1882 
1883 	/* set public key in the certificate */
1884 	if (X509_set_pubkey(newcrt, pkey) != 1)
1885 		goto mkcert_error;
1886 
1887 	/* Set issuer name from the CA */
1888 	if (!(name = X509_get_subject_name(cacert)))
1889 		goto mkcert_error;
1890 	if (X509_set_issuer_name(newcrt, name) != 1)
1891 		goto mkcert_error;
1892 
1893 	/* Set the subject name using the same, but the CN */
1894 	name = X509_NAME_dup(name);
1895 	if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1896 				       (const unsigned char *)servername,
1897 				       -1, -1, 0) != 1) {
1898 		X509_NAME_free(name);
1899 		goto mkcert_error;
1900 	}
1901 	if (X509_set_subject_name(newcrt, name) != 1) {
1902 		X509_NAME_free(name);
1903 		goto mkcert_error;
1904 	}
1905 	X509_NAME_free(name);
1906 
1907 	/* Add x509v3 extensions as specified */
1908 	ctmp = NCONF_new(NULL);
1909 	X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1910 	for (i = 0; i < X509V3_EXT_SIZE; i++) {
1911 		X509_EXTENSION *ext;
1912 
1913 		if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
1914 			goto mkcert_error;
1915 		if (!X509_add_ext(newcrt, ext, -1)) {
1916 			X509_EXTENSION_free(ext);
1917 			goto mkcert_error;
1918 		}
1919 		X509_EXTENSION_free(ext);
1920 	}
1921 
1922 	/* Sign the certificate with the CA private key */
1923 
1924 	key_type = EVP_PKEY_base_id(capkey);
1925 
1926 	if (key_type == EVP_PKEY_DSA)
1927 		digest = EVP_sha1();
1928 	else if (key_type == EVP_PKEY_RSA)
1929 		digest = EVP_sha256();
1930 	else if (key_type == EVP_PKEY_EC)
1931 		digest = EVP_sha256();
1932 	else {
1933 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1000000fL) && !defined(OPENSSL_IS_BORINGSSL)
1934 		int nid;
1935 
1936 		if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
1937 			goto mkcert_error;
1938 		if (!(digest = EVP_get_digestbynid(nid)))
1939 			goto mkcert_error;
1940 #else
1941 		goto mkcert_error;
1942 #endif
1943 	}
1944 
1945 	if (!(X509_sign(newcrt, capkey, digest)))
1946 		goto mkcert_error;
1947 
1948 	/* Create and set the new SSL_CTX */
1949 	if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
1950 		goto mkcert_error;
1951 	if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
1952 		goto mkcert_error;
1953 	if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
1954 		goto mkcert_error;
1955 	if (!SSL_CTX_check_private_key(ssl_ctx))
1956 		goto mkcert_error;
1957 
1958 	if (newcrt) X509_free(newcrt);
1959 
1960 #ifndef OPENSSL_NO_DH
1961 	SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh);
1962 #endif
1963 #if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
1964 	{
1965 		const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
1966 		EC_KEY     *ecc;
1967 		int         nid;
1968 
1969 		if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
1970 			goto end;
1971 		if (!(ecc = EC_KEY_new_by_curve_name(nid)))
1972 			goto end;
1973 		SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
1974 		EC_KEY_free(ecc);
1975 	}
1976 #endif
1977  end:
1978 	return ssl_ctx;
1979 
1980  mkcert_error:
1981 	if (ctmp) NCONF_free(ctmp);
1982 	if (tmp_ssl) SSL_free(tmp_ssl);
1983 	if (ssl_ctx) SSL_CTX_free(ssl_ctx);
1984 	if (newcrt)  X509_free(newcrt);
1985 	return NULL;
1986 }
1987 
1988 SSL_CTX *
ssl_sock_create_cert(struct connection * conn,const char * servername,unsigned int key)1989 ssl_sock_create_cert(struct connection *conn, const char *servername, unsigned int key)
1990 {
1991 	struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
1992 	struct ssl_sock_ctx *ctx = conn->xprt_ctx;
1993 
1994 	return ssl_sock_do_create_cert(servername, bind_conf, ctx->ssl);
1995 }
1996 
1997 /* Do a lookup for a certificate in the LRU cache used to store generated
1998  * certificates and immediately assign it to the SSL session if not null. */
1999 SSL_CTX *
ssl_sock_assign_generated_cert(unsigned int key,struct bind_conf * bind_conf,SSL * ssl)2000 ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
2001 {
2002 	struct lru64 *lru = NULL;
2003 
2004 	if (ssl_ctx_lru_tree) {
2005 		HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
2006 		lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_cert, 0);
2007 		if (lru && lru->domain) {
2008 			if (ssl)
2009 				SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
2010 			HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
2011 			return (SSL_CTX *)lru->data;
2012 		}
2013 		HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
2014 	}
2015 	return NULL;
2016 }
2017 
2018 /* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2019  * function is not thread-safe, it should only be used to check if a certificate
2020  * exists in the lru cache (with no warranty it will not be removed by another
2021  * thread). It is kept for backward compatibility. */
2022 SSL_CTX *
ssl_sock_get_generated_cert(unsigned int key,struct bind_conf * bind_conf)2023 ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2024 {
2025 	return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2026 }
2027 
2028 /* Set a certificate int the LRU cache used to store generated
2029  * certificate. Return 0 on success, otherwise -1 */
2030 int
ssl_sock_set_generated_cert(SSL_CTX * ssl_ctx,unsigned int key,struct bind_conf * bind_conf)2031 ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
2032 {
2033 	struct lru64 *lru = NULL;
2034 
2035 	if (ssl_ctx_lru_tree) {
2036 		HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
2037 		lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_cert, 0);
2038 		if (!lru) {
2039 			HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
2040 			return -1;
2041 		}
2042 		if (lru->domain && lru->data)
2043 			lru->free((SSL_CTX *)lru->data);
2044 		lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_cert, 0, (void (*)(void *))SSL_CTX_free);
2045 		HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
2046 		return 0;
2047 	}
2048 	return -1;
2049 }
2050 
2051 /* Compute the key of the certificate. */
2052 unsigned int
ssl_sock_generated_cert_key(const void * data,size_t len)2053 ssl_sock_generated_cert_key(const void *data, size_t len)
2054 {
2055 	return XXH32(data, len, ssl_ctx_lru_seed);
2056 }
2057 
2058 /* Generate a cert and immediately assign it to the SSL session so that the cert's
2059  * refcount is maintained regardless of the cert's presence in the LRU cache.
2060  */
2061 static int
ssl_sock_generate_certificate(const char * servername,struct bind_conf * bind_conf,SSL * ssl)2062 ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
2063 {
2064 	X509         *cacert  = bind_conf->ca_sign_cert;
2065 	SSL_CTX      *ssl_ctx = NULL;
2066 	struct lru64 *lru     = NULL;
2067 	unsigned int  key;
2068 
2069 	key = ssl_sock_generated_cert_key(servername, strlen(servername));
2070 	if (ssl_ctx_lru_tree) {
2071 		HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
2072 		lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
2073 		if (lru && lru->domain)
2074 			ssl_ctx = (SSL_CTX *)lru->data;
2075 		if (!ssl_ctx && lru) {
2076 			ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
2077 			lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
2078 		}
2079 		SSL_set_SSL_CTX(ssl, ssl_ctx);
2080 		HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
2081 		return 1;
2082 	}
2083 	else {
2084 		ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
2085 		SSL_set_SSL_CTX(ssl, ssl_ctx);
2086 		/* No LRU cache, this CTX will be released as soon as the session dies */
2087 		SSL_CTX_free(ssl_ctx);
2088 		return 1;
2089 	}
2090 	return 0;
2091 }
2092 static int
ssl_sock_generate_certificate_from_conn(struct bind_conf * bind_conf,SSL * ssl)2093 ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2094 {
2095 	unsigned int key;
2096 	struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2097 
2098 	conn_get_to_addr(conn);
2099 	if (conn->flags & CO_FL_ADDR_TO_SET) {
2100 		key = ssl_sock_generated_cert_key(&conn->addr.to, get_addr_len(&conn->addr.to));
2101 		if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
2102 			return 1;
2103 	}
2104 	return 0;
2105 }
2106 #endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
2107 
2108 #if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
2109 typedef enum { SET_CLIENT, SET_SERVER } set_context_func;
2110 
ctx_set_SSLv3_func(SSL_CTX * ctx,set_context_func c)2111 static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
2112 {
2113 #if SSL_OP_NO_SSLv3
2114 	c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
2115 		: SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2116 #endif
2117 }
ctx_set_TLSv10_func(SSL_CTX * ctx,set_context_func c)2118 static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2119 	c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
2120 		: SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2121 }
ctx_set_TLSv11_func(SSL_CTX * ctx,set_context_func c)2122 static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2123 #if SSL_OP_NO_TLSv1_1
2124 	c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
2125 		: SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2126 #endif
2127 }
ctx_set_TLSv12_func(SSL_CTX * ctx,set_context_func c)2128 static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2129 #if SSL_OP_NO_TLSv1_2
2130 	c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
2131 		: SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2132 #endif
2133 }
2134 /* TLSv1.2 is the last supported version in this context. */
ctx_set_TLSv13_func(SSL_CTX * ctx,set_context_func c)2135 static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2136 /* Unusable in this context. */
ssl_set_SSLv3_func(SSL * ssl,set_context_func c)2137 static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
ssl_set_TLSv10_func(SSL * ssl,set_context_func c)2138 static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
ssl_set_TLSv11_func(SSL * ssl,set_context_func c)2139 static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
ssl_set_TLSv12_func(SSL * ssl,set_context_func c)2140 static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
ssl_set_TLSv13_func(SSL * ssl,set_context_func c)2141 static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
2142 #else /* openssl >= 1.1.0 */
2143 typedef enum { SET_MIN, SET_MAX } set_context_func;
2144 
ctx_set_SSLv3_func(SSL_CTX * ctx,set_context_func c)2145 static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2146 	c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
2147 		: SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2148 }
ssl_set_SSLv3_func(SSL * ssl,set_context_func c)2149 static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2150 	c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2151 		: SSL_set_min_proto_version(ssl, SSL3_VERSION);
2152 }
ctx_set_TLSv10_func(SSL_CTX * ctx,set_context_func c)2153 static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2154 	c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
2155 		: SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2156 }
ssl_set_TLSv10_func(SSL * ssl,set_context_func c)2157 static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2158 	c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2159 		: SSL_set_min_proto_version(ssl, TLS1_VERSION);
2160 }
ctx_set_TLSv11_func(SSL_CTX * ctx,set_context_func c)2161 static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2162 	c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
2163 		: SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2164 }
ssl_set_TLSv11_func(SSL * ssl,set_context_func c)2165 static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2166 	c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2167 		: SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2168 }
ctx_set_TLSv12_func(SSL_CTX * ctx,set_context_func c)2169 static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2170 	c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
2171 		: SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2172 }
ssl_set_TLSv12_func(SSL * ssl,set_context_func c)2173 static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2174 	c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2175 		: SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2176 }
ctx_set_TLSv13_func(SSL_CTX * ctx,set_context_func c)2177 static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
2178 #if SSL_OP_NO_TLSv1_3
2179 	c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
2180 		: SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2181 #endif
2182 }
ssl_set_TLSv13_func(SSL * ssl,set_context_func c)2183 static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
2184 #if SSL_OP_NO_TLSv1_3
2185 	c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2186 		: SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
2187 #endif
2188 }
2189 #endif
ctx_set_None_func(SSL_CTX * ctx,set_context_func c)2190 static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
ssl_set_None_func(SSL * ssl,set_context_func c)2191 static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
2192 
2193 static struct {
2194 	int      option;
2195 	uint16_t flag;
2196 	void   (*ctx_set_version)(SSL_CTX *, set_context_func);
2197 	void   (*ssl_set_version)(SSL *, set_context_func);
2198 	const char *name;
2199 } methodVersions[] = {
2200 	{0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"},   /* CONF_TLSV_NONE */
2201 	{SSL_OP_NO_SSLv3,   MC_SSL_O_NO_SSLV3,  ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"},    /* CONF_SSLV3 */
2202 	{SSL_OP_NO_TLSv1,   MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2203 	{SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2204 	{SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2205 	{SSL_OP_NO_TLSv1_3, MC_SSL_O_NO_TLSV13, ctx_set_TLSv13_func, ssl_set_TLSv13_func, "TLSv1.3"}, /* CONF_TLSV13 */
2206 };
2207 
ssl_sock_switchctx_set(SSL * ssl,SSL_CTX * ctx)2208 static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2209 {
2210 	SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2211 	SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2212 	SSL_set_SSL_CTX(ssl, ctx);
2213 }
2214 
2215 #if ((HA_OPENSSL_VERSION_NUMBER >= 0x10101000L) || defined(OPENSSL_IS_BORINGSSL))
2216 
ssl_sock_switchctx_err_cbk(SSL * ssl,int * al,void * priv)2217 static int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
2218 {
2219 	struct bind_conf *s = priv;
2220 	(void)al; /* shut gcc stupid warning */
2221 
2222 	if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || s->generate_certs)
2223 		return SSL_TLSEXT_ERR_OK;
2224 	return SSL_TLSEXT_ERR_NOACK;
2225 }
2226 
2227 #ifdef OPENSSL_IS_BORINGSSL
ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx * ctx)2228 static int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
2229 {
2230 	SSL *ssl = ctx->ssl;
2231 #else
2232 static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
2233 {
2234 #endif
2235 	struct connection *conn;
2236 	struct bind_conf *s;
2237 	const uint8_t *extension_data;
2238 	size_t extension_len;
2239 	int has_rsa_sig = 0, has_ecdsa_sig = 0;
2240 
2241 	char *wildp = NULL;
2242 	const uint8_t *servername;
2243 	size_t servername_len;
2244 	struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
2245 	int allow_early = 0;
2246 	int i;
2247 
2248 	conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2249 	s = __objt_listener(conn->target)->bind_conf;
2250 
2251 	if (s->ssl_conf.early_data)
2252 		allow_early = 1;
2253 #ifdef OPENSSL_IS_BORINGSSL
2254 	if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2255 						 &extension_data, &extension_len)) {
2256 #else
2257 	if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2258 #endif
2259 		/*
2260 		 * The server_name extension was given too much extensibility when it
2261 		 * was written, so parsing the normal case is a bit complex.
2262 		 */
2263 		size_t len;
2264 		if (extension_len <= 2)
2265 			goto abort;
2266 		/* Extract the length of the supplied list of names. */
2267 		len = (*extension_data++) << 8;
2268 		len |= *extension_data++;
2269 		if (len + 2 != extension_len)
2270 			goto abort;
2271 		/*
2272 		 * The list in practice only has a single element, so we only consider
2273 		 * the first one.
2274 		 */
2275 		if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2276 			goto abort;
2277 		extension_len = len - 1;
2278 		/* Now we can finally pull out the byte array with the actual hostname. */
2279 		if (extension_len <= 2)
2280 			goto abort;
2281 		len = (*extension_data++) << 8;
2282 		len |= *extension_data++;
2283 		if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2284 		    || memchr(extension_data, 0, len) != NULL)
2285 			goto abort;
2286 		servername = extension_data;
2287 		servername_len = len;
2288 	} else {
2289 #if (!defined SSL_NO_GENERATE_CERTIFICATES)
2290 		if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl)) {
2291 			goto allow_early;
2292 		}
2293 #endif
2294 		/* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
2295 		if (!s->strict_sni) {
2296 			ssl_sock_switchctx_set(ssl, s->default_ctx);
2297 			goto allow_early;
2298 		}
2299 		goto abort;
2300 	}
2301 
2302 	/* extract/check clientHello informations */
2303 #ifdef OPENSSL_IS_BORINGSSL
2304 	if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2305 #else
2306 	if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2307 #endif
2308 		uint8_t sign;
2309 		size_t len;
2310 		if (extension_len < 2)
2311 			goto abort;
2312 		len = (*extension_data++) << 8;
2313 		len |= *extension_data++;
2314 		if (len + 2 != extension_len)
2315 			goto abort;
2316 		if (len % 2 != 0)
2317 			goto abort;
2318 		for (; len > 0; len -= 2) {
2319 			extension_data++; /* hash */
2320 			sign = *extension_data++;
2321 			switch (sign) {
2322 			case TLSEXT_signature_rsa:
2323 				has_rsa_sig = 1;
2324 				break;
2325 			case TLSEXT_signature_ecdsa:
2326 				has_ecdsa_sig = 1;
2327 				break;
2328 			default:
2329 				continue;
2330 			}
2331 			if (has_ecdsa_sig && has_rsa_sig)
2332 				break;
2333 		}
2334 	} else {
2335 		/* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
2336 		has_rsa_sig = 1;
2337 	}
2338 	if (has_ecdsa_sig) {  /* in very rare case: has ecdsa sign but not a ECDSA cipher */
2339 		const SSL_CIPHER *cipher;
2340 		size_t len;
2341 		const uint8_t *cipher_suites;
2342 		has_ecdsa_sig = 0;
2343 #ifdef OPENSSL_IS_BORINGSSL
2344 		len = ctx->cipher_suites_len;
2345 		cipher_suites = ctx->cipher_suites;
2346 #else
2347 		len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2348 #endif
2349 		if (len % 2 != 0)
2350 			goto abort;
2351 		for (; len != 0; len -= 2, cipher_suites += 2) {
2352 #ifdef OPENSSL_IS_BORINGSSL
2353 			uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
2354 			cipher = SSL_get_cipher_by_value(cipher_suite);
2355 #else
2356 			cipher = SSL_CIPHER_find(ssl, cipher_suites);
2357 #endif
2358 			if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
2359 				has_ecdsa_sig = 1;
2360 				break;
2361 			}
2362 		}
2363 	}
2364 
2365 	for (i = 0; i < trash.size && i < servername_len; i++) {
2366 		trash.area[i] = tolower(servername[i]);
2367 		if (!wildp && (trash.area[i] == '.'))
2368 			wildp = &trash.area[i];
2369 	}
2370 	trash.area[i] = 0;
2371 
2372 
2373 	/* Look for an ECDSA, RSA and DSA certificate, first in the single
2374 	 * name and if not found in the wildcard  */
2375 	for (i = 0; i < 2; i++) {
2376 		if (i == 0) 	/* lookup in full qualified names */
2377 			node = ebst_lookup(&s->sni_ctx, trash.area);
2378 		else if (i == 1 && wildp) /* lookup in wildcards names */
2379 			node = ebst_lookup(&s->sni_w_ctx, wildp);
2380 		else
2381 			break;
2382 		for (n = node; n; n = ebmb_next_dup(n)) {
2383 			/* lookup a not neg filter */
2384 			if (!container_of(n, struct sni_ctx, name)->neg) {
2385 				switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
2386 				case TLSEXT_signature_ecdsa:
2387 					if (!node_ecdsa)
2388 						node_ecdsa = n;
2389 					break;
2390 				case TLSEXT_signature_rsa:
2391 					if (!node_rsa)
2392 						node_rsa = n;
2393 					break;
2394 				default: /* TLSEXT_signature_anonymous|dsa */
2395 					if (!node_anonymous)
2396 						node_anonymous = n;
2397 					break;
2398 				}
2399 			}
2400 		}
2401 	}
2402 	/* Once the certificates are found, select them depending on what is
2403 	 * supported in the client and by key_signature priority order: EDSA >
2404 	 * RSA > DSA */
2405 	node = (has_ecdsa_sig && node_ecdsa) ? node_ecdsa
2406 		: ((has_rsa_sig && node_rsa) ? node_rsa
2407 		   : (node_anonymous ? node_anonymous
2408 		      : (node_ecdsa ? node_ecdsa      /* no ecdsa signature case (< TLSv1.2) */
2409 			 : node_rsa                   /* no rsa signature case (far far away) */
2410 			 )));
2411 	if (node) {
2412 		/* switch ctx */
2413 		struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2414 		ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2415 		if (conf) {
2416 			methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2417 			methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2418 			if (conf->early_data)
2419 				allow_early = 1;
2420 		}
2421 		goto allow_early;
2422 	}
2423 #if (!defined SSL_NO_GENERATE_CERTIFICATES)
2424 	if (s->generate_certs && ssl_sock_generate_certificate(trash.area, s, ssl)) {
2425 		/* switch ctx done in ssl_sock_generate_certificate */
2426 		goto allow_early;
2427 	}
2428 #endif
2429 	if (!s->strict_sni) {
2430 		/* no certificate match, is the default_ctx */
2431 		ssl_sock_switchctx_set(ssl, s->default_ctx);
2432 		goto allow_early;
2433 	}
2434 
2435 	/* other cases fallback on abort, if strict-sni is set but no node was found */
2436 
2437  abort:
2438 	/* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
2439 	conn->err_code = CO_ER_SSL_HANDSHAKE;
2440 #ifdef OPENSSL_IS_BORINGSSL
2441 	return ssl_select_cert_error;
2442 #else
2443 	*al = SSL_AD_UNRECOGNIZED_NAME;
2444 	return 0;
2445 #endif
2446 
2447 allow_early:
2448 #ifdef OPENSSL_IS_BORINGSSL
2449 	if (allow_early)
2450 		SSL_set_early_data_enabled(ssl, 1);
2451 #else
2452 	if (!allow_early)
2453 		SSL_set_max_early_data(ssl, 0);
2454 #endif
2455 	return 1;
2456 }
2457 
2458 #else /* OPENSSL_IS_BORINGSSL */
2459 
2460 /* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2461  * warning when no match is found, which implies the default (first) cert
2462  * will keep being used.
2463  */
2464 static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
2465 {
2466 	const char *servername;
2467 	const char *wildp = NULL;
2468 	struct ebmb_node *node, *n;
2469 	struct bind_conf *s = priv;
2470 	int i;
2471 	(void)al; /* shut gcc stupid warning */
2472 
2473 	servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
2474 	if (!servername) {
2475 #if (!defined SSL_NO_GENERATE_CERTIFICATES)
2476 		if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl))
2477 			return SSL_TLSEXT_ERR_OK;
2478 #endif
2479 		if (s->strict_sni)
2480 			return SSL_TLSEXT_ERR_ALERT_FATAL;
2481 		ssl_sock_switchctx_set(ssl, s->default_ctx);
2482 		return SSL_TLSEXT_ERR_NOACK;
2483 	}
2484 
2485 	for (i = 0; i < trash.size; i++) {
2486 		if (!servername[i])
2487 			break;
2488 		trash.area[i] = tolower(servername[i]);
2489 		if (!wildp && (trash.area[i] == '.'))
2490 			wildp = &trash.area[i];
2491 	}
2492 	trash.area[i] = 0;
2493 
2494 	node = NULL;
2495 	/* lookup in full qualified names */
2496 	for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2497 		/* lookup a not neg filter */
2498 		if (!container_of(n, struct sni_ctx, name)->neg) {
2499 			node = n;
2500 			break;
2501 		}
2502 	}
2503 	if (!node && wildp) {
2504 		/* lookup in wildcards names */
2505 		for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2506 			/* lookup a not neg filter */
2507 			if (!container_of(n, struct sni_ctx, name)->neg) {
2508 				node = n;
2509 				break;
2510 			}
2511 		}
2512 	}
2513 	if (!node) {
2514 #if (!defined SSL_NO_GENERATE_CERTIFICATES)
2515 		if (s->generate_certs && ssl_sock_generate_certificate(servername, s, ssl)) {
2516 			/* switch ctx done in ssl_sock_generate_certificate */
2517 			return SSL_TLSEXT_ERR_OK;
2518 		}
2519 #endif
2520 		if (s->strict_sni)
2521 			return SSL_TLSEXT_ERR_ALERT_FATAL;
2522 		ssl_sock_switchctx_set(ssl, s->default_ctx);
2523 		return SSL_TLSEXT_ERR_OK;
2524 	}
2525 
2526 	/* switch ctx */
2527 	ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2528 	return SSL_TLSEXT_ERR_OK;
2529 }
2530 #endif /* (!) OPENSSL_IS_BORINGSSL */
2531 #endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2532 
2533 #ifndef OPENSSL_NO_DH
2534 
2535 static DH * ssl_get_dh_1024(void)
2536 {
2537 	static unsigned char dh1024_p[]={
2538 		0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2539 		0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2540 		0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2541 		0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2542 		0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2543 		0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2544 		0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2545 		0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2546 		0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2547 		0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2548 		0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2549 		};
2550 	static unsigned char dh1024_g[]={
2551 		0x02,
2552 		};
2553 
2554 	BIGNUM *p;
2555 	BIGNUM *g;
2556 	DH *dh = DH_new();
2557 	if (dh) {
2558 		p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2559 		g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
2560 
2561 		if (!p || !g) {
2562 			DH_free(dh);
2563 			dh = NULL;
2564 		} else {
2565 			DH_set0_pqg(dh, p, NULL, g);
2566 		}
2567 	}
2568 	return dh;
2569 }
2570 
2571 static DH *ssl_get_dh_2048(void)
2572 {
2573 	static unsigned char dh2048_p[]={
2574 		0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2575 		0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2576 		0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2577 		0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2578 		0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2579 		0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2580 		0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2581 		0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2582 		0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2583 		0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2584 		0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2585 		0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2586 		0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2587 		0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2588 		0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2589 		0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2590 		0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2591 		0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2592 		0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2593 		0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2594 		0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2595 		0xB7,0x1F,0x77,0xF3,
2596 		};
2597 	static unsigned char dh2048_g[]={
2598 		0x02,
2599 		};
2600 
2601 	BIGNUM *p;
2602 	BIGNUM *g;
2603 	DH *dh = DH_new();
2604 	if (dh) {
2605 		p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2606 		g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
2607 
2608 		if (!p || !g) {
2609 			DH_free(dh);
2610 			dh = NULL;
2611 		} else {
2612 			DH_set0_pqg(dh, p, NULL, g);
2613 		}
2614 	}
2615 	return dh;
2616 }
2617 
2618 static DH *ssl_get_dh_4096(void)
2619 {
2620 	static unsigned char dh4096_p[]={
2621 		0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2622 		0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2623 		0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2624 		0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2625 		0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2626 		0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2627 		0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2628 		0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2629 		0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2630 		0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2631 		0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2632 		0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2633 		0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2634 		0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2635 		0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2636 		0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2637 		0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2638 		0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2639 		0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2640 		0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2641 		0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2642 		0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2643 		0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2644 		0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2645 		0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2646 		0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2647 		0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2648 		0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2649 		0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2650 		0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2651 		0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2652 		0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2653 		0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2654 		0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2655 		0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2656 		0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2657 		0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2658 		0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2659 		0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2660 		0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2661 		0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2662 		0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2663 		0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
2664 	};
2665 	static unsigned char dh4096_g[]={
2666 		0x02,
2667 		};
2668 
2669 	BIGNUM *p;
2670 	BIGNUM *g;
2671 	DH *dh = DH_new();
2672 	if (dh) {
2673 		p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2674 		g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
2675 
2676 		if (!p || !g) {
2677 			DH_free(dh);
2678 			dh = NULL;
2679 		} else {
2680 			DH_set0_pqg(dh, p, NULL, g);
2681 		}
2682 	}
2683 	return dh;
2684 }
2685 
2686 /* Returns Diffie-Hellman parameters matching the private key length
2687    but not exceeding global_ssl.default_dh_param */
2688 static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen)
2689 {
2690 	DH *dh = NULL;
2691 	EVP_PKEY *pkey = SSL_get_privatekey(ssl);
2692 	int type;
2693 
2694 	type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
2695 
2696 	/* The keylen supplied by OpenSSL can only be 512 or 1024.
2697 	   See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2698 	 */
2699 	if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2700 		keylen = EVP_PKEY_bits(pkey);
2701 	}
2702 
2703 	if (keylen > global_ssl.default_dh_param) {
2704 		keylen = global_ssl.default_dh_param;
2705 	}
2706 
2707 	if (keylen >= 4096) {
2708 		dh = local_dh_4096;
2709 	}
2710 	else if (keylen >= 2048) {
2711 		dh = local_dh_2048;
2712 	}
2713 	else {
2714 		dh = local_dh_1024;
2715 	}
2716 
2717 	return dh;
2718 }
2719 
2720 static DH * ssl_sock_get_dh_from_file(const char *filename)
2721 {
2722 	DH *dh = NULL;
2723 	BIO *in = BIO_new(BIO_s_file());
2724 
2725 	if (in == NULL)
2726 		goto end;
2727 
2728 	if (BIO_read_filename(in, filename) <= 0)
2729 		goto end;
2730 
2731 	dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
2732 
2733 end:
2734         if (in)
2735                 BIO_free(in);
2736 
2737 	ERR_clear_error();
2738 
2739 	return dh;
2740 }
2741 
2742 int ssl_sock_load_global_dh_param_from_file(const char *filename)
2743 {
2744 	global_dh = ssl_sock_get_dh_from_file(filename);
2745 
2746 	if (global_dh) {
2747 		return 0;
2748 	}
2749 
2750 	return -1;
2751 }
2752 
2753 /* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
2754  *  If there is no DH paramater availaible in the ckchs, the global
2755  *  DH parameter is loaded into the SSL_CTX and if there is no
2756  *  DH parameter available in ckchs nor in global, the default
2757  *  DH parameters are applied on the SSL_CTX.
2758  * Returns a bitfield containing the flags:
2759  *     ERR_FATAL in any fatal error case
2760  *     ERR_ALERT if a reason of the error is availabine in err
2761  *     ERR_WARN if a warning is available into err
2762  * The value 0 means there is no error nor warning and
2763  * the operation succeed.
2764  */
2765 static int ssl_sock_load_dh_params(SSL_CTX *ctx, const char *file, char **err)
2766  {
2767 	int ret = 0;
2768 	DH *dh = ssl_sock_get_dh_from_file(file);
2769 
2770 	if (dh) {
2771 		if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
2772 			memprintf(err, "%sunable to load the DH parameter specified in '%s'",
2773 				  err && *err ? *err : "", file);
2774 #if defined(SSL_CTX_set_dh_auto)
2775 			SSL_CTX_set_dh_auto(ctx, 1);
2776 			memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2777 				  err && *err ? *err : "");
2778 #else
2779 			memprintf(err, "%s, DH ciphers won't be available.\n",
2780 				  err && *err ? *err : "");
2781 #endif
2782 			ret |= ERR_WARN;
2783 			goto end;
2784 		}
2785 
2786 		if (ssl_dh_ptr_index >= 0) {
2787 			/* store a pointer to the DH params to avoid complaining about
2788 			   ssl-default-dh-param not being set for this SSL_CTX */
2789 			SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
2790 		}
2791 	}
2792 	else if (global_dh) {
2793 		if (!SSL_CTX_set_tmp_dh(ctx, global_dh)) {
2794 			memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
2795 				  err && *err ? *err : "", file);
2796 #if defined(SSL_CTX_set_dh_auto)
2797 			SSL_CTX_set_dh_auto(ctx, 1);
2798 			memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2799 				  err && *err ? *err : "");
2800 #else
2801 			memprintf(err, "%s, DH ciphers won't be available.\n",
2802 				  err && *err ? *err : "");
2803 #endif
2804 			ret |= ERR_WARN;
2805 			goto end;
2806 		}
2807 	}
2808 	else {
2809 		/* Clear openssl global errors stack */
2810 		ERR_clear_error();
2811 
2812 		if (global_ssl.default_dh_param <= 1024) {
2813 			/* we are limited to DH parameter of 1024 bits anyway */
2814 			if (local_dh_1024 == NULL)
2815 				local_dh_1024 = ssl_get_dh_1024();
2816 
2817 			if (local_dh_1024 == NULL) {
2818 				memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
2819 					  err && *err ? *err : "", file);
2820 				ret |= ERR_ALERT | ERR_FATAL;
2821 				goto end;
2822 			}
2823 
2824 			if (!SSL_CTX_set_tmp_dh(ctx, local_dh_1024)) {
2825 				memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
2826 					  err && *err ? *err : "", file);
2827 #if defined(SSL_CTX_set_dh_auto)
2828 				SSL_CTX_set_dh_auto(ctx, 1);
2829 				memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2830 					  err && *err ? *err : "");
2831 #else
2832 				memprintf(err, "%s, DH ciphers won't be available.\n",
2833 					  err && *err ? *err : "");
2834 #endif
2835 				ret |= ERR_WARN;
2836 				goto end;
2837 			}
2838 		}
2839 		else {
2840 			SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh);
2841 		}
2842 	}
2843 
2844 end:
2845 	if (dh)
2846 		DH_free(dh);
2847 
2848 	return ret;
2849 }
2850 #endif
2851 
2852 static int ssl_sock_add_cert_sni(SSL_CTX *ctx, struct bind_conf *s, struct ssl_bind_conf *conf,
2853 				 struct pkey_info kinfo, char *name, int order)
2854 {
2855 	struct sni_ctx *sc;
2856 	int wild = 0, neg = 0;
2857 	struct ebmb_node *node;
2858 
2859 	if (*name == '!') {
2860 		neg = 1;
2861 		name++;
2862 	}
2863 	if (*name == '*') {
2864 		wild = 1;
2865 		name++;
2866 	}
2867 	/* !* filter is a nop */
2868 	if (neg && wild)
2869 		return order;
2870 	if (*name) {
2871 		int j, len;
2872 		len = strlen(name);
2873 		for (j = 0; j < len && j < trash.size; j++)
2874 			trash.area[j] = tolower(name[j]);
2875 		if (j >= trash.size)
2876 			return -1;
2877 		trash.area[j] = 0;
2878 
2879 		/* Check for duplicates. */
2880 		if (wild)
2881 			node = ebst_lookup(&s->sni_w_ctx, trash.area);
2882 		else
2883 			node = ebst_lookup(&s->sni_ctx, trash.area);
2884 		for (; node; node = ebmb_next_dup(node)) {
2885 			sc = ebmb_entry(node, struct sni_ctx, name);
2886 			if (sc->ctx == ctx && sc->conf == conf && sc->neg == neg)
2887 				return order;
2888 		}
2889 
2890 		sc = malloc(sizeof(struct sni_ctx) + len + 1);
2891 		if (!sc)
2892 			return -1;
2893 		memcpy(sc->name.key, trash.area, len + 1);
2894 		sc->ctx = ctx;
2895 		sc->conf = conf;
2896 		sc->kinfo = kinfo;
2897 		sc->order = order++;
2898 		sc->neg = neg;
2899 		if (kinfo.sig != TLSEXT_signature_anonymous)
2900 			SSL_CTX_set_ex_data(ctx, ssl_pkey_info_index, &sc->kinfo);
2901 		if (wild)
2902 			ebst_insert(&s->sni_w_ctx, &sc->name);
2903 		else
2904 			ebst_insert(&s->sni_ctx, &sc->name);
2905 	}
2906 	return order;
2907 }
2908 
2909 
2910 /* The following code is used for loading multiple crt files into
2911  * SSL_CTX's based on CN/SAN
2912  */
2913 #if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL
2914 /* This is used to preload the certifcate, private key
2915  * and Cert Chain of a file passed in via the crt
2916  * argument
2917  *
2918  * This way, we do not have to read the file multiple times
2919  */
2920 struct cert_key_and_chain {
2921 	X509 *cert;
2922 	EVP_PKEY *key;
2923 	unsigned int num_chain_certs;
2924 	/* This is an array of X509 pointers */
2925 	X509 **chain_certs;
2926 };
2927 
2928 #define SSL_SOCK_POSSIBLE_KT_COMBOS (1<<(SSL_SOCK_NUM_KEYTYPES))
2929 
2930 struct key_combo_ctx {
2931 	SSL_CTX *ctx;
2932 	int order;
2933 };
2934 
2935 /* Map used for processing multiple keypairs for a single purpose
2936  *
2937  * This maps CN/SNI name to certificate type
2938  */
2939 struct sni_keytype {
2940 	int keytypes;			  /* BITMASK for keytypes */
2941 	struct ebmb_node name;    /* node holding the servername value */
2942 };
2943 
2944 
2945 /* Frees the contents of a cert_key_and_chain
2946  */
2947 static void ssl_sock_free_cert_key_and_chain_contents(struct cert_key_and_chain *ckch)
2948 {
2949 	int i;
2950 
2951 	if (!ckch)
2952 		return;
2953 
2954 	/* Free the certificate and set pointer to NULL */
2955 	if (ckch->cert)
2956 		X509_free(ckch->cert);
2957 	ckch->cert = NULL;
2958 
2959 	/* Free the key and set pointer to NULL */
2960 	if (ckch->key)
2961 		EVP_PKEY_free(ckch->key);
2962 	ckch->key = NULL;
2963 
2964 	/* Free each certificate in the chain */
2965 	for (i = 0; i < ckch->num_chain_certs; i++) {
2966 		if (ckch->chain_certs[i])
2967 			X509_free(ckch->chain_certs[i]);
2968 	}
2969 
2970 	/* Free the chain obj itself and set to NULL */
2971 	if (ckch->num_chain_certs > 0) {
2972 		free(ckch->chain_certs);
2973 		ckch->num_chain_certs = 0;
2974 		ckch->chain_certs = NULL;
2975 	}
2976 
2977 }
2978 
2979 /* checks if a key and cert exists in the ckch
2980  */
2981 static int ssl_sock_is_ckch_valid(struct cert_key_and_chain *ckch)
2982 {
2983 	return (ckch->cert != NULL && ckch->key != NULL);
2984 }
2985 
2986 
2987 /* Loads the contents of a crt file (path) into a cert_key_and_chain
2988  * This allows us to carry the contents of the file without having to
2989  * read the file multiple times.
2990  *
2991  * returns:
2992  *      0 on Success
2993  *      1 on SSL Failure
2994  *      2 on file not found
2995  */
2996 static int ssl_sock_load_crt_file_into_ckch(const char *path, struct cert_key_and_chain *ckch, char **err)
2997 {
2998 
2999 	BIO *in;
3000 	X509 *ca = NULL;
3001 	int ret = 1;
3002 
3003 	ssl_sock_free_cert_key_and_chain_contents(ckch);
3004 
3005 	in = BIO_new(BIO_s_file());
3006 	if (in == NULL)
3007 		goto end;
3008 
3009 	if (BIO_read_filename(in, path) <= 0)
3010 		goto end;
3011 
3012 	/* Read Private Key */
3013 	ckch->key = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL);
3014 	if (ckch->key == NULL) {
3015 		memprintf(err, "%sunable to load private key from file '%s'.\n",
3016 				err && *err ? *err : "", path);
3017 		goto end;
3018 	}
3019 
3020 	/* Seek back to beginning of file */
3021 	if (BIO_reset(in) == -1) {
3022 		memprintf(err, "%san error occurred while reading the file '%s'.\n",
3023 		          err && *err ? *err : "", path);
3024 		goto end;
3025 	}
3026 
3027 	/* Read Certificate */
3028 	ckch->cert = PEM_read_bio_X509_AUX(in, NULL, NULL, NULL);
3029 	if (ckch->cert == NULL) {
3030 		memprintf(err, "%sunable to load certificate from file '%s'.\n",
3031 				err && *err ? *err : "", path);
3032 		goto end;
3033 	}
3034 
3035 	/* Read Certificate Chain */
3036 	while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
3037 		/* Grow the chain certs */
3038 		ckch->num_chain_certs++;
3039 		ckch->chain_certs = realloc(ckch->chain_certs, (ckch->num_chain_certs * sizeof(X509 *)));
3040 
3041 		/* use - 1 here since we just incremented it above */
3042 		ckch->chain_certs[ckch->num_chain_certs - 1] = ca;
3043 	}
3044 	ret = ERR_get_error();
3045 	if (ret && (ERR_GET_LIB(ret) != ERR_LIB_PEM && ERR_GET_REASON(ret) != PEM_R_NO_START_LINE)) {
3046 		memprintf(err, "%sunable to load certificate chain from file '%s'.\n",
3047 				err && *err ? *err : "", path);
3048 		ret = 1;
3049 		goto end;
3050 	}
3051 
3052 	ret = 0;
3053 
3054 end:
3055 
3056 	ERR_clear_error();
3057 	if (in)
3058 		BIO_free(in);
3059 
3060 	/* Something went wrong in one of the reads */
3061 	if (ret != 0)
3062 		ssl_sock_free_cert_key_and_chain_contents(ckch);
3063 
3064 	return ret;
3065 }
3066 
3067 /* Loads the info in ckch into ctx
3068  * Returns a bitfield containing the flags:
3069  *     ERR_FATAL in any fatal error case
3070  *     ERR_ALERT if the reason of the error is available in err
3071  *     ERR_WARN if a warning is available into err
3072  * The value 0 means there is no error nor warning and
3073  * the operation succeed.
3074  */
3075 static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
3076 {
3077 	int i = 0;
3078 	int errcode = 0;
3079 
3080 	if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3081 		memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3082 				err && *err ? *err : "", path);
3083 		errcode |= ERR_ALERT | ERR_FATAL;
3084 		return errcode;
3085 	}
3086 
3087 	if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
3088 		memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
3089 				err && *err ? *err : "", path);
3090 		errcode |= ERR_ALERT | ERR_FATAL;
3091 		goto end;
3092 	}
3093 
3094 	/* Load all certs in the ckch into the ctx_chain for the ssl_ctx */
3095 	for (i = 0; i < ckch->num_chain_certs; i++) {
3096 		if (!SSL_CTX_add1_chain_cert(ctx, ckch->chain_certs[i])) {
3097 			memprintf(err, "%sunable to load chain certificate #%d into SSL Context '%s'. Make sure you are linking against Openssl >= 1.0.2.\n",
3098 					err && *err ? *err : "", (i+1), path);
3099 			errcode |= ERR_ALERT | ERR_FATAL;
3100 			goto end;
3101 		}
3102 	}
3103 
3104 	if (SSL_CTX_check_private_key(ctx) <= 0) {
3105 		memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3106 				err && *err ? *err : "", path);
3107 		errcode |= ERR_ALERT | ERR_FATAL;
3108 	}
3109 
3110  end:
3111 	return errcode;
3112 }
3113 
3114 
3115 static int ssl_sock_populate_sni_keytypes_hplr(const char *str, struct eb_root *sni_keytypes, int key_index)
3116 {
3117 	struct sni_keytype *s_kt = NULL;
3118 	struct ebmb_node *node;
3119 	int i;
3120 
3121 	for (i = 0; i < trash.size; i++) {
3122 		if (!str[i])
3123 			break;
3124 		trash.area[i] = tolower(str[i]);
3125 	}
3126 	trash.area[i] = 0;
3127 	node = ebst_lookup(sni_keytypes, trash.area);
3128 	if (!node) {
3129 		/* CN not found in tree */
3130 		s_kt = malloc(sizeof(struct sni_keytype) + i + 1);
3131 		/* Using memcpy here instead of strncpy.
3132 		 * strncpy will cause sig_abrt errors under certain versions of gcc with -O2
3133 		 * See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=60792
3134 		 */
3135 		if (!s_kt)
3136 			return -1;
3137 
3138 		memcpy(s_kt->name.key, trash.area, i+1);
3139 		s_kt->keytypes = 0;
3140 		ebst_insert(sni_keytypes, &s_kt->name);
3141 	} else {
3142 		/* CN found in tree */
3143 		s_kt = container_of(node, struct sni_keytype, name);
3144 	}
3145 
3146 	/* Mark that this CN has the keytype of key_index via keytypes mask */
3147 	s_kt->keytypes |= 1<<key_index;
3148 
3149 	return 0;
3150 
3151 }
3152 
3153 
3154 /* Given a path that does not exist, try to check for path.rsa, path.dsa and path.ecdsa files.
3155  * If any are found, group these files into a set of SSL_CTX*
3156  * based on shared and unique CN and SAN entries. Add these SSL_CTX* to the SNI tree.
3157  *
3158  * This will allow the user to explicitly group multiple cert/keys for a single purpose
3159  *
3160  * Returns a set of ERR_* flags possibly with an error in <err>.
3161  *
3162  */
3163 static int ssl_sock_load_multi_cert(const char *path, struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
3164 				    char **sni_filter, int fcount, char **err)
3165 {
3166 	char fp[MAXPATHLEN+1] = {0};
3167 	int n = 0;
3168 	int i = 0;
3169 	struct cert_key_and_chain certs_and_keys[SSL_SOCK_NUM_KEYTYPES] = { {0} };
3170 	struct eb_root sni_keytypes_map = { {0} };
3171 	struct ebmb_node *node;
3172 	struct ebmb_node *next;
3173 	/* Array of SSL_CTX pointers corresponding to each possible combo
3174 	 * of keytypes
3175 	 */
3176 	struct key_combo_ctx key_combos[SSL_SOCK_POSSIBLE_KT_COMBOS] = { {0} };
3177 	int errcode = 0;
3178 	X509_NAME *xname = NULL;
3179 	char *str = NULL;
3180 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3181 	STACK_OF(GENERAL_NAME) *names = NULL;
3182 #endif
3183 
3184 	/* Load all possible certs and keys */
3185 	for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3186 		struct stat buf;
3187 
3188 		snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3189 		if (stat(fp, &buf) == 0) {
3190 			if (ssl_sock_load_crt_file_into_ckch(fp, &certs_and_keys[n], err) == 1) {
3191 				errcode |= ERR_ALERT | ERR_FATAL;
3192 				goto end;
3193 			}
3194 		}
3195 	}
3196 
3197 	/* Process each ckch and update keytypes for each CN/SAN
3198 	 * for example, if CN/SAN www.a.com is associated with
3199 	 * certs with keytype 0 and 2, then at the end of the loop,
3200 	 * www.a.com will have:
3201 	 *     keyindex = 0 | 1 | 4 = 5
3202 	 */
3203 	for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3204 		int ret;
3205 
3206 		if (!ssl_sock_is_ckch_valid(&certs_and_keys[n]))
3207 			continue;
3208 
3209 		if (fcount) {
3210 			for (i = 0; i < fcount; i++) {
3211 				ret = ssl_sock_populate_sni_keytypes_hplr(sni_filter[i], &sni_keytypes_map, n);
3212 				if (ret < 0) {
3213 					memprintf(err, "%sunable to allocate SSL context.\n",
3214 					          err && *err ? *err : "");
3215 					errcode |= ERR_ALERT | ERR_FATAL;
3216 					goto end;
3217 				}
3218 			}
3219 		} else {
3220 			/* A lot of the following code is OpenSSL boilerplate for processing CN's and SAN's,
3221 			 * so the line that contains logic is marked via comments
3222 			 */
3223 			xname = X509_get_subject_name(certs_and_keys[n].cert);
3224 			i = -1;
3225 			while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3226 				X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
3227 				ASN1_STRING *value;
3228 				value = X509_NAME_ENTRY_get_data(entry);
3229 				if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
3230 					/* Important line is here */
3231 					ret = ssl_sock_populate_sni_keytypes_hplr(str, &sni_keytypes_map, n);
3232 
3233 					OPENSSL_free(str);
3234 					str = NULL;
3235 					if (ret < 0) {
3236 						memprintf(err, "%sunable to allocate SSL context.\n",
3237 						          err && *err ? *err : "");
3238 						errcode |= ERR_ALERT | ERR_FATAL;
3239 						goto end;
3240 					}
3241 				}
3242 			}
3243 
3244 			/* Do the above logic for each SAN */
3245 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3246 			names = X509_get_ext_d2i(certs_and_keys[n].cert, NID_subject_alt_name, NULL, NULL);
3247 			if (names) {
3248 				for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3249 					GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3250 
3251 					if (name->type == GEN_DNS) {
3252 						if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
3253 							/* Important line is here */
3254 							ret = ssl_sock_populate_sni_keytypes_hplr(str, &sni_keytypes_map, n);
3255 
3256 							OPENSSL_free(str);
3257 							str = NULL;
3258 							if (ret < 0) {
3259 								memprintf(err, "%sunable to allocate SSL context.\n",
3260 								          err && *err ? *err : "");
3261 								errcode |= ERR_ALERT | ERR_FATAL;
3262 								goto end;
3263 							}
3264 						}
3265 					}
3266 				}
3267 			}
3268 		}
3269 #endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
3270 	}
3271 
3272 	/* If no files found, return error */
3273 	if (eb_is_empty(&sni_keytypes_map)) {
3274 		memprintf(err, "%sunable to load SSL certificate file '%s' file does not exist.\n",
3275 		          err && *err ? *err : "", path);
3276 		errcode |= ERR_ALERT | ERR_FATAL;
3277 		goto end;
3278 	}
3279 
3280 	/* We now have a map of CN/SAN to keytypes that are loaded in
3281 	 * Iterate through the map to create the SSL_CTX's (if needed)
3282 	 * and add each CTX to the SNI tree
3283 	 *
3284 	 * Some math here:
3285 	 *   There are 2^n - 1 possible combinations, each unique
3286 	 *   combination is denoted by the key in the map. Each key
3287 	 *   has a value between 1 and 2^n - 1. Conveniently, the array
3288 	 *   of SSL_CTX* is sized 2^n. So, we can simply use the i'th
3289 	 *   entry in the array to correspond to the unique combo (key)
3290 	 *   associated with i. This unique key combo (i) will be associated
3291 	 *   with combos[i-1]
3292 	 */
3293 
3294 	node = ebmb_first(&sni_keytypes_map);
3295 	while (node) {
3296 		SSL_CTX *cur_ctx;
3297 		char cur_file[MAXPATHLEN+1];
3298 		const struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
3299 
3300 		str = (char *)container_of(node, struct sni_keytype, name)->name.key;
3301 		i = container_of(node, struct sni_keytype, name)->keytypes;
3302 		cur_ctx = key_combos[i-1].ctx;
3303 
3304 		if (cur_ctx == NULL) {
3305 			/* need to create SSL_CTX */
3306 			cur_ctx = SSL_CTX_new(SSLv23_server_method());
3307 			if (cur_ctx == NULL) {
3308 				memprintf(err, "%sunable to allocate SSL context.\n",
3309 				          err && *err ? *err : "");
3310 				errcode |= ERR_ALERT | ERR_FATAL;
3311 				goto end;
3312 			}
3313 
3314 			/* Load all required certs/keys/chains/OCSPs info into SSL_CTX */
3315 			for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3316 				if (i & (1<<n)) {
3317 					/* Key combo contains ckch[n] */
3318 					snprintf(cur_file, MAXPATHLEN+1, "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3319 					errcode |= ssl_sock_put_ckch_into_ctx(cur_file, &certs_and_keys[n], cur_ctx, err);
3320 					if (errcode & ERR_CODE) {
3321 						SSL_CTX_free(cur_ctx);
3322 						goto end;
3323 					}
3324 
3325 #if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
3326 					/* Load OCSP Info into context */
3327 					if (ssl_sock_load_ocsp(cur_ctx, cur_file) < 0) {
3328 						if (err)
3329 							memprintf(err, "%s '%s.ocsp' is present and activates OCSP but it is impossible to compute the OCSP certificate ID (maybe the issuer could not be found)'.\n",
3330 							          *err ? *err : "", cur_file);
3331 						SSL_CTX_free(cur_ctx);
3332 						errcode |= ERR_ALERT | ERR_FATAL;
3333 						goto end;
3334 					}
3335 #elif (defined OPENSSL_IS_BORINGSSL)
3336 					ssl_sock_set_ocsp_response_from_file(cur_ctx, cur_file);
3337 #endif
3338 				}
3339 			}
3340 
3341 			/* Load DH params into the ctx to support DHE keys */
3342 #ifndef OPENSSL_NO_DH
3343 			if (ssl_dh_ptr_index >= 0)
3344 				SSL_CTX_set_ex_data(cur_ctx, ssl_dh_ptr_index, NULL);
3345 
3346 			errcode |= ssl_sock_load_dh_params(cur_ctx, NULL, err);
3347 			if (errcode & ERR_CODE) {
3348 				if (err)
3349 					memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3350 							*err ? *err : "", path);
3351 				goto end;
3352 			}
3353 #endif
3354 
3355 			/* Update key_combos */
3356 			key_combos[i-1].ctx = cur_ctx;
3357 		}
3358 
3359 		/* Update SNI Tree */
3360 		key_combos[i-1].order = ssl_sock_add_cert_sni(cur_ctx, bind_conf, ssl_conf,
3361 		                                              kinfo, str, key_combos[i-1].order);
3362 		if (key_combos[i-1].order < 0) {
3363 			memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
3364 			errcode |= ERR_ALERT | ERR_FATAL;
3365 			goto end;
3366 		}
3367 		node = ebmb_next(node);
3368 	}
3369 
3370 
3371 	/* Mark a default context if none exists, using the ctx that has the most shared keys */
3372 	if (!bind_conf->default_ctx) {
3373 		for (i = SSL_SOCK_POSSIBLE_KT_COMBOS - 1; i >= 0; i--) {
3374 			if (key_combos[i].ctx) {
3375 				bind_conf->default_ctx = key_combos[i].ctx;
3376 				bind_conf->default_ssl_conf = ssl_conf;
3377 				break;
3378 			}
3379 		}
3380 	}
3381 
3382 end:
3383 
3384 	if (names)
3385 		sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
3386 
3387 	for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++)
3388 		ssl_sock_free_cert_key_and_chain_contents(&certs_and_keys[n]);
3389 
3390 	node = ebmb_first(&sni_keytypes_map);
3391 	while (node) {
3392 		next = ebmb_next(node);
3393 		ebmb_delete(node);
3394 		free(ebmb_entry(node, struct sni_keytype, name));
3395 		node = next;
3396 	}
3397 
3398 	return errcode;
3399 }
3400 #else
3401 /* This is a dummy, that just logs an error and returns error */
3402 static int ssl_sock_load_multi_cert(const char *path, struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
3403 				    char **sni_filter, int fcount, char **err)
3404 {
3405 	memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3406 	          err && *err ? *err : "", path, strerror(errno));
3407 	return 1;
3408 }
3409 
3410 #endif /* #if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL: Support for loading multiple certs into a single SSL_CTX */
3411 
3412 /* Loads a certificate key and CA chain from a file. Returns 0 on error, -1 if
3413  * an early error happens and the caller must call SSL_CTX_free() by itelf.
3414  */
3415 static int ssl_sock_load_cert_chain_file(SSL_CTX *ctx, const char *file, struct bind_conf *s,
3416 					 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount)
3417 {
3418 	BIO *in;
3419 	X509 *x = NULL, *ca;
3420 	int i, err;
3421 	int ret = -1;
3422 	int order = 0;
3423 	X509_NAME *xname;
3424 	char *str;
3425 	pem_password_cb *passwd_cb;
3426 	void *passwd_cb_userdata;
3427 	EVP_PKEY *pkey;
3428 	struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
3429 
3430 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3431 	STACK_OF(GENERAL_NAME) *names;
3432 #endif
3433 
3434 	in = BIO_new(BIO_s_file());
3435 	if (in == NULL)
3436 		goto end;
3437 
3438 	if (BIO_read_filename(in, file) <= 0)
3439 		goto end;
3440 
3441 
3442 	passwd_cb = SSL_CTX_get_default_passwd_cb(ctx);
3443 	passwd_cb_userdata = SSL_CTX_get_default_passwd_cb_userdata(ctx);
3444 
3445 	x = PEM_read_bio_X509_AUX(in, NULL, passwd_cb, passwd_cb_userdata);
3446 	if (x == NULL)
3447 		goto end;
3448 
3449 	pkey = X509_get_pubkey(x);
3450 	if (pkey) {
3451 		kinfo.bits = EVP_PKEY_bits(pkey);
3452 		switch(EVP_PKEY_base_id(pkey)) {
3453 		case EVP_PKEY_RSA:
3454 			kinfo.sig = TLSEXT_signature_rsa;
3455 			break;
3456 		case EVP_PKEY_EC:
3457 			kinfo.sig = TLSEXT_signature_ecdsa;
3458 			break;
3459 		case EVP_PKEY_DSA:
3460 			kinfo.sig = TLSEXT_signature_dsa;
3461 			break;
3462 		}
3463 		EVP_PKEY_free(pkey);
3464 	}
3465 
3466 	if (fcount) {
3467 		while (fcount--) {
3468 			order = ssl_sock_add_cert_sni(ctx, s, ssl_conf, kinfo, sni_filter[fcount], order);
3469 			if (order < 0)
3470 				goto end;
3471 		}
3472 	}
3473 	else {
3474 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3475 		names = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
3476 		if (names) {
3477 			for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3478 				GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3479 				if (name->type == GEN_DNS) {
3480 					if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
3481 						order = ssl_sock_add_cert_sni(ctx, s, ssl_conf, kinfo, str, order);
3482 						OPENSSL_free(str);
3483 						if (order < 0)
3484 							goto end;
3485 					}
3486 				}
3487 			}
3488 			sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
3489 		}
3490 #endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
3491 		xname = X509_get_subject_name(x);
3492 		i = -1;
3493 		while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3494 			X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
3495 			ASN1_STRING *value;
3496 
3497 			value = X509_NAME_ENTRY_get_data(entry);
3498 			if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
3499 				order = ssl_sock_add_cert_sni(ctx, s, ssl_conf, kinfo, str, order);
3500 				OPENSSL_free(str);
3501 				if (order < 0)
3502 					goto end;
3503 			}
3504 		}
3505 	}
3506 
3507 	ret = 0; /* the caller must not free the SSL_CTX argument anymore */
3508 	if (!SSL_CTX_use_certificate(ctx, x))
3509 		goto end;
3510 
3511 #ifdef SSL_CTX_clear_extra_chain_certs
3512 	SSL_CTX_clear_extra_chain_certs(ctx);
3513 #else
3514 	if (ctx->extra_certs != NULL) {
3515 		sk_X509_pop_free(ctx->extra_certs, X509_free);
3516 		ctx->extra_certs = NULL;
3517 	}
3518 #endif
3519 
3520 	while ((ca = PEM_read_bio_X509(in, NULL, passwd_cb, passwd_cb_userdata))) {
3521 		if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
3522 			X509_free(ca);
3523 			goto end;
3524 		}
3525 	}
3526 
3527 	err = ERR_get_error();
3528 	if (!err || (ERR_GET_LIB(err) == ERR_LIB_PEM && ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3529 		/* we successfully reached the last cert in the file */
3530 		ret = 1;
3531 	}
3532 	ERR_clear_error();
3533 
3534 end:
3535 	if (x)
3536 		X509_free(x);
3537 
3538 	if (in)
3539 		BIO_free(in);
3540 
3541 	return ret;
3542 }
3543 
3544 /* Returns a set of ERR_* flags possibly with an error in <err>. */
3545 static int ssl_sock_load_cert_file(const char *path, struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
3546 				   char **sni_filter, int fcount, char **err)
3547 {
3548 	int errcode = 0;
3549 	int ret;
3550 	SSL_CTX *ctx;
3551 
3552 	ctx = SSL_CTX_new(SSLv23_server_method());
3553 	if (!ctx) {
3554 		memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3555 		          err && *err ? *err : "", path);
3556 		return ERR_ALERT | ERR_FATAL;
3557 	}
3558 
3559 	if (SSL_CTX_use_PrivateKey_file(ctx, path, SSL_FILETYPE_PEM) <= 0) {
3560 		memprintf(err, "%sunable to load SSL private key from PEM file '%s'.\n",
3561 		          err && *err ? *err : "", path);
3562 		SSL_CTX_free(ctx);
3563 		return ERR_ALERT | ERR_FATAL;
3564 	}
3565 
3566 	ret = ssl_sock_load_cert_chain_file(ctx, path, bind_conf, ssl_conf, sni_filter, fcount);
3567 	if (ret <= 0) {
3568 		memprintf(err, "%sunable to load SSL certificate from PEM file '%s'.\n",
3569 		          err && *err ? *err : "", path);
3570 		if (ret < 0) /* serious error, must do that ourselves */
3571 			SSL_CTX_free(ctx);
3572 		return ERR_ALERT | ERR_FATAL;
3573 	}
3574 
3575 	if (SSL_CTX_check_private_key(ctx) <= 0) {
3576 		memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3577 		          err && *err ? *err : "", path);
3578 		return ERR_ALERT | ERR_FATAL;
3579 	}
3580 
3581 	/* we must not free the SSL_CTX anymore below, since it's already in
3582 	 * the tree, so it will be discovered and cleaned in time.
3583 	 */
3584 #ifndef OPENSSL_NO_DH
3585 	/* store a NULL pointer to indicate we have not yet loaded
3586 	   a custom DH param file */
3587 	if (ssl_dh_ptr_index >= 0) {
3588 		SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3589 	}
3590 
3591 	errcode |= ssl_sock_load_dh_params(ctx, path, err);
3592 	if (errcode & ERR_CODE) {
3593 		if (err)
3594 			memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3595 				  *err ? *err : "", path);
3596 		return errcode;
3597 	}
3598 #endif
3599 
3600 #if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
3601 	ret = ssl_sock_load_ocsp(ctx, path);
3602 	if (ret < 0) {
3603 		if (err)
3604 			memprintf(err, "%s '%s.ocsp' is present and activates OCSP but it is impossible to compute the OCSP certificate ID (maybe the issuer could not be found)'.\n",
3605 				  *err ? *err : "", path);
3606 		return ERR_ALERT | ERR_FATAL;
3607 	}
3608 #elif (defined OPENSSL_IS_BORINGSSL)
3609 	ssl_sock_set_ocsp_response_from_file(ctx, path);
3610 #endif
3611 
3612 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
3613 	if (sctl_ex_index >= 0) {
3614 		ret = ssl_sock_load_sctl(ctx, path);
3615 		if (ret < 0) {
3616 			if (err)
3617 				memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
3618 					  *err ? *err : "", path);
3619 			return ERR_ALERT | ERR_FATAL;
3620 		}
3621 	}
3622 #endif
3623 
3624 #ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
3625 	if (bind_conf->default_ctx) {
3626 		memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3627 		          err && *err ? *err : "");
3628 		return ERR_ALERT | ERR_FATAL;
3629 	}
3630 #endif
3631 	if (!bind_conf->default_ctx) {
3632 		bind_conf->default_ctx = ctx;
3633 		bind_conf->default_ssl_conf = ssl_conf;
3634 	}
3635 
3636 	return errcode;
3637 }
3638 
3639 
3640 /* Returns a set of ERR_* flags possibly with an error in <err>. */
3641 int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3642 {
3643 	struct dirent **de_list;
3644 	int i, n;
3645 	DIR *dir;
3646 	struct stat buf;
3647 	char *end;
3648 	char fp[MAXPATHLEN+1];
3649 	int cfgerr = 0;
3650 #if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL
3651 	int is_bundle;
3652 	int j;
3653 #endif
3654 
3655 	if (stat(path, &buf) == 0) {
3656 		dir = opendir(path);
3657 		if (!dir)
3658 			return ssl_sock_load_cert_file(path, bind_conf, NULL, NULL, 0, err);
3659 
3660 		/* strip trailing slashes, including first one */
3661 		for (end = path + strlen(path) - 1; end >= path && *end == '/'; end--)
3662 			*end = 0;
3663 
3664 		n = scandir(path, &de_list, 0, alphasort);
3665 		if (n < 0) {
3666 			memprintf(err, "%sunable to scan directory '%s' : %s.\n",
3667 			          err && *err ? *err : "", path, strerror(errno));
3668 			cfgerr |= ERR_ALERT | ERR_FATAL;
3669 		}
3670 		else {
3671 			for (i = 0; i < n; i++) {
3672 				struct dirent *de = de_list[i];
3673 
3674 				end = strrchr(de->d_name, '.');
3675 				if (end && (!strcmp(end, ".issuer") || !strcmp(end, ".ocsp") || !strcmp(end, ".sctl")))
3676 					goto ignore_entry;
3677 
3678 				snprintf(fp, sizeof(fp), "%s/%s", path, de->d_name);
3679 				if (stat(fp, &buf) != 0) {
3680 					memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3681 					          err && *err ? *err : "", fp, strerror(errno));
3682 					cfgerr |= ERR_ALERT | ERR_FATAL;
3683 					goto ignore_entry;
3684 				}
3685 				if (!S_ISREG(buf.st_mode))
3686 					goto ignore_entry;
3687 
3688 #if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL
3689 				is_bundle = 0;
3690 				/* Check if current entry in directory is part of a multi-cert bundle */
3691 
3692 				if (end) {
3693 					for (j = 0; j < SSL_SOCK_NUM_KEYTYPES; j++) {
3694 						if (!strcmp(end + 1, SSL_SOCK_KEYTYPE_NAMES[j])) {
3695 							is_bundle = 1;
3696 							break;
3697 						}
3698 					}
3699 
3700 					if (is_bundle) {
3701 						int dp_len;
3702 
3703 						dp_len = end - de->d_name;
3704 
3705 						/* increment i and free de until we get to a non-bundle cert
3706 						 * Note here that we look at de_list[i + 1] before freeing de
3707 						 * this is important since ignore_entry will free de. This also
3708 						 * guarantees that de->d_name continues to hold the same prefix.
3709 						 */
3710 						while (i + 1 < n && !strncmp(de_list[i + 1]->d_name, de->d_name, dp_len)) {
3711 							free(de);
3712 							i++;
3713 							de = de_list[i];
3714 						}
3715 
3716 						snprintf(fp, sizeof(fp), "%s/%.*s", path, dp_len, de->d_name);
3717 						cfgerr |= ssl_sock_load_multi_cert(fp, bind_conf, NULL, NULL, 0, err);
3718 						/* Successfully processed the bundle */
3719 						goto ignore_entry;
3720 					}
3721 				}
3722 
3723 #endif
3724 				cfgerr |= ssl_sock_load_cert_file(fp, bind_conf, NULL, NULL, 0, err);
3725 ignore_entry:
3726 				free(de);
3727 			}
3728 			free(de_list);
3729 		}
3730 		closedir(dir);
3731 		return cfgerr;
3732 	}
3733 
3734 	cfgerr |= ssl_sock_load_multi_cert(path, bind_conf, NULL, NULL, 0, err);
3735 
3736 	return cfgerr;
3737 }
3738 
3739 /* Make sure openssl opens /dev/urandom before the chroot. The work is only
3740  * done once. Zero is returned if the operation fails. No error is returned
3741  * if the random is said as not implemented, because we expect that openssl
3742  * will use another method once needed.
3743  */
3744 static int ssl_initialize_random()
3745 {
3746 	unsigned char random;
3747 	static int random_initialized = 0;
3748 
3749 	if (!random_initialized && RAND_bytes(&random, 1) != 0)
3750 		random_initialized = 1;
3751 
3752 	return random_initialized;
3753 }
3754 
3755 /* release ssl bind conf */
3756 void ssl_sock_free_ssl_conf(struct ssl_bind_conf *conf)
3757 {
3758 	if (conf) {
3759 #if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
3760 		free(conf->npn_str);
3761 		conf->npn_str = NULL;
3762 #endif
3763 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
3764 		free(conf->alpn_str);
3765 		conf->alpn_str = NULL;
3766 #endif
3767 		free(conf->ca_file);
3768 		conf->ca_file = NULL;
3769 		free(conf->crl_file);
3770 		conf->crl_file = NULL;
3771 		free(conf->ciphers);
3772 		conf->ciphers = NULL;
3773 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
3774 		free(conf->ciphersuites);
3775 		conf->ciphersuites = NULL;
3776 #endif
3777 		free(conf->curves);
3778 		conf->curves = NULL;
3779 		free(conf->ecdhe);
3780 		conf->ecdhe = NULL;
3781 	}
3782 }
3783 
3784 /* Returns a set of ERR_* flags possibly with an error in <err>. */
3785 int ssl_sock_load_cert_list_file(char *file, struct bind_conf *bind_conf, struct proxy *curproxy, char **err)
3786 {
3787 	char thisline[CRT_LINESIZE];
3788 	char path[MAXPATHLEN+1];
3789 	FILE *f;
3790 	struct stat buf;
3791 	int linenum = 0;
3792 	int cfgerr = 0;
3793 
3794 	if ((f = fopen(file, "r")) == NULL) {
3795 		memprintf(err, "cannot open file '%s' : %s", file, strerror(errno));
3796 		return ERR_ALERT | ERR_FATAL;
3797 	}
3798 
3799 	while (fgets(thisline, sizeof(thisline), f) != NULL) {
3800 		int arg, newarg, cur_arg, i, ssl_b = 0, ssl_e = 0;
3801 		char *end;
3802 		char *args[MAX_CRT_ARGS + 1];
3803 		char *line = thisline;
3804 		char *crt_path;
3805 		struct ssl_bind_conf *ssl_conf = NULL;
3806 
3807 		linenum++;
3808 		end = line + strlen(line);
3809 		if (end-line == sizeof(thisline)-1 && *(end-1) != '\n') {
3810 			/* Check if we reached the limit and the last char is not \n.
3811 			 * Watch out for the last line without the terminating '\n'!
3812 			 */
3813 			memprintf(err, "line %d too long in file '%s', limit is %d characters",
3814 				  linenum, file, (int)sizeof(thisline)-1);
3815 			cfgerr |= ERR_ALERT | ERR_FATAL;
3816 			break;
3817 		}
3818 
3819 		arg = 0;
3820 		newarg = 1;
3821 		while (*line) {
3822 			if (*line == '#' || *line == '\n' || *line == '\r') {
3823 				/* end of string, end of loop */
3824 				*line = 0;
3825 				break;
3826 			} else if (isspace((unsigned char)*line)) {
3827 				newarg = 1;
3828 				*line = 0;
3829 			} else if (*line == '[') {
3830 				if (ssl_b) {
3831 					memprintf(err, "too many '[' on line %d in file '%s'.", linenum, file);
3832 					cfgerr |= ERR_ALERT | ERR_FATAL;
3833 					break;
3834 				}
3835 				if (!arg) {
3836 					memprintf(err, "file must start with a cert on line %d in file '%s'", linenum, file);
3837 					cfgerr |= ERR_ALERT | ERR_FATAL;
3838 					break;
3839 				}
3840 				ssl_b = arg;
3841 				newarg = 1;
3842 				*line = 0;
3843 			} else if (*line == ']') {
3844 				if (ssl_e) {
3845 					memprintf(err, "too many ']' on line %d in file '%s'.", linenum, file);
3846 					cfgerr |= ERR_ALERT | ERR_FATAL;
3847 					break;
3848 				}
3849 				if (!ssl_b) {
3850 					memprintf(err, "missing '[' in line %d in file '%s'.", linenum, file);
3851 					cfgerr |= ERR_ALERT | ERR_FATAL;
3852 					break;
3853 				}
3854 				ssl_e = arg;
3855 				newarg = 1;
3856 				*line = 0;
3857 			} else if (newarg) {
3858 				if (arg == MAX_CRT_ARGS) {
3859 					memprintf(err, "too many args on line %d in file '%s'.", linenum, file);
3860 					cfgerr |= ERR_ALERT | ERR_FATAL;
3861 					break;
3862 				}
3863 				newarg = 0;
3864 				args[arg++] = line;
3865 			}
3866 			line++;
3867 		}
3868 		if (cfgerr & ERR_CODE)
3869 			break;
3870 		args[arg++] = line;
3871 
3872 		/* empty line */
3873 		if (!*args[0])
3874 			continue;
3875 
3876 		crt_path = args[0];
3877 		if (*crt_path != '/' && global_ssl.crt_base) {
3878 			if ((strlen(global_ssl.crt_base) + 1 + strlen(crt_path)) > MAXPATHLEN) {
3879 				memprintf(err, "'%s' : path too long on line %d in file '%s'",
3880 					  crt_path, linenum, file);
3881 				cfgerr |= ERR_ALERT | ERR_FATAL;
3882 				break;
3883 			}
3884 			snprintf(path, sizeof(path), "%s/%s",  global_ssl.crt_base, crt_path);
3885 			crt_path = path;
3886 		}
3887 
3888 		ssl_conf = calloc(1, sizeof *ssl_conf);
3889 		cur_arg = ssl_b ? ssl_b : 1;
3890 		while (cur_arg < ssl_e) {
3891 			newarg = 0;
3892 			for (i = 0; ssl_bind_kws[i].kw != NULL; i++) {
3893 				if (strcmp(ssl_bind_kws[i].kw, args[cur_arg]) == 0) {
3894 					newarg = 1;
3895 					cfgerr |= ssl_bind_kws[i].parse(args, cur_arg, curproxy, ssl_conf, err);
3896 					if (cur_arg + 1 + ssl_bind_kws[i].skip > ssl_e) {
3897 						memprintf(err, "ssl args out of '[]' for %s on line %d in file '%s'",
3898 							  args[cur_arg], linenum, file);
3899 						cfgerr |= ERR_ALERT | ERR_FATAL;
3900 					}
3901 					cur_arg += 1 + ssl_bind_kws[i].skip;
3902 					break;
3903 				}
3904 			}
3905 			if (!cfgerr && !newarg) {
3906 				memprintf(err, "unknown ssl keyword %s on line %d in file '%s'.",
3907 					  args[cur_arg], linenum, file);
3908 				cfgerr |= ERR_ALERT | ERR_FATAL;
3909 				break;
3910 			}
3911 		}
3912 
3913 		if (cfgerr & ERR_CODE) {
3914 			ssl_sock_free_ssl_conf(ssl_conf);
3915 			free(ssl_conf);
3916 			ssl_conf = NULL;
3917 			break;
3918 		}
3919 
3920 		if (stat(crt_path, &buf) == 0) {
3921 			cfgerr |= ssl_sock_load_cert_file(crt_path, bind_conf, ssl_conf,
3922 							  &args[cur_arg], arg - cur_arg - 1, err);
3923 		} else {
3924 			cfgerr |= ssl_sock_load_multi_cert(crt_path, bind_conf, ssl_conf,
3925 							   &args[cur_arg], arg - cur_arg - 1, err);
3926 		}
3927 
3928 		if (cfgerr & ERR_CODE) {
3929 			memprintf(err, "error processing line %d in file '%s' : %s", linenum, file, *err);
3930 			break;
3931 		}
3932 	}
3933 	fclose(f);
3934 	return cfgerr;
3935 }
3936 
3937 /* Create an initial CTX used to start the SSL connection before switchctx */
3938 static int
3939 ssl_sock_initial_ctx(struct bind_conf *bind_conf)
3940 {
3941 	SSL_CTX *ctx = NULL;
3942 	long options =
3943 		SSL_OP_ALL | /* all known workarounds for bugs */
3944 		SSL_OP_NO_SSLv2 |
3945 		SSL_OP_NO_COMPRESSION |
3946 		SSL_OP_SINGLE_DH_USE |
3947 		SSL_OP_SINGLE_ECDH_USE |
3948 		SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
3949 		SSL_OP_PRIORITIZE_CHACHA |
3950 		SSL_OP_CIPHER_SERVER_PREFERENCE;
3951 	long mode =
3952 		SSL_MODE_ENABLE_PARTIAL_WRITE |
3953 		SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
3954 		SSL_MODE_RELEASE_BUFFERS |
3955 		SSL_MODE_SMALL_BUFFERS;
3956 	struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
3957 	int i, min, max, hole;
3958 	int flags = MC_SSL_O_ALL;
3959 	int cfgerr = 0;
3960 
3961 	ctx = SSL_CTX_new(SSLv23_server_method());
3962 	bind_conf->initial_ctx = ctx;
3963 
3964 	if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
3965 		ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
3966 			   "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3967 			   bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
3968 	else
3969 		flags = conf_ssl_methods->flags;
3970 
3971 	min = conf_ssl_methods->min;
3972 	max = conf_ssl_methods->max;
3973 	/* start with TLSv10 to remove SSLv3 per default */
3974 	if (!min && (!max || max >= CONF_TLSV10))
3975 		min = CONF_TLSV10;
3976 	/* Real min and max should be determinate with configuration and openssl's capabilities */
3977 	if (min)
3978 		flags |= (methodVersions[min].flag - 1);
3979 	if (max)
3980 		flags |= ~((methodVersions[max].flag << 1) - 1);
3981 	/* find min, max and holes */
3982 	min = max = CONF_TLSV_NONE;
3983 	hole = 0;
3984 	for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
3985 		/*  version is in openssl && version not disable in configuration */
3986 		if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
3987 			if (min) {
3988 				if (hole) {
3989 					ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
3990 						   "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3991 						   bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
3992 						   methodVersions[hole].name);
3993 					hole = 0;
3994 				}
3995 				max = i;
3996 			}
3997 			else {
3998 				min = max = i;
3999 			}
4000 		}
4001 		else {
4002 			if (min)
4003 				hole = i;
4004 		}
4005 	if (!min) {
4006 		ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4007 			 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
4008 		cfgerr += 1;
4009 	}
4010 	/* save real min/max in bind_conf */
4011 	conf_ssl_methods->min = min;
4012 	conf_ssl_methods->max = max;
4013 
4014 #if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
4015 	/* Keep force-xxx implementation as it is in older haproxy. It's a
4016 	   precautionary measure to avoid any surprise with older openssl version. */
4017 	if (min == max)
4018 		methodVersions[min].ctx_set_version(ctx, SET_SERVER);
4019 	else
4020 		for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
4021 			/* clear every version flags in case SSL_CTX_new()
4022 			 * returns an SSL_CTX with disabled versions */
4023 			SSL_CTX_clear_options(ctx, methodVersions[i].option);
4024 
4025 			if (flags & methodVersions[i].flag)
4026 				options |= methodVersions[i].option;
4027 
4028 		}
4029 #else   /* openssl >= 1.1.0 */
4030 	/* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
4031         methodVersions[min].ctx_set_version(ctx, SET_MIN);
4032         methodVersions[max].ctx_set_version(ctx, SET_MAX);
4033 #endif
4034 
4035 	if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
4036 		options |= SSL_OP_NO_TICKET;
4037 	if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
4038 		options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
4039 
4040 #ifdef SSL_OP_NO_RENEGOTIATION
4041 	options |= SSL_OP_NO_RENEGOTIATION;
4042 #endif
4043 
4044 	SSL_CTX_set_options(ctx, options);
4045 
4046 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
4047 	if (global_ssl.async)
4048 		mode |= SSL_MODE_ASYNC;
4049 #endif
4050 	SSL_CTX_set_mode(ctx, mode);
4051 	if (global_ssl.life_time)
4052 		SSL_CTX_set_timeout(ctx, global_ssl.life_time);
4053 
4054 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
4055 #ifdef OPENSSL_IS_BORINGSSL
4056 	SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
4057 	SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
4058 #elif (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
4059 	if (bind_conf->ssl_conf.early_data)
4060 		SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
4061 	SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
4062 	SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
4063 #else
4064 	SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
4065 #endif
4066 	SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
4067 #endif
4068 	return cfgerr;
4069 }
4070 
4071 
4072 static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
4073 {
4074 	if (first == block) {
4075 		struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4076 		if (first->len > 0)
4077 			sh_ssl_sess_tree_delete(sh_ssl_sess);
4078 	}
4079 }
4080 
4081 /* return first block from sh_ssl_sess  */
4082 static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
4083 {
4084 	return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
4085 
4086 }
4087 
4088 /* store a session into the cache
4089  * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
4090  * data: asn1 encoded session
4091  * data_len: asn1 encoded session length
4092  * Returns 1 id session was stored (else 0)
4093  */
4094 static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
4095 {
4096 	struct shared_block *first;
4097 	struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
4098 
4099 	first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
4100 	if (!first) {
4101 		/* Could not retrieve enough free blocks to store that session */
4102 		return 0;
4103 	}
4104 
4105 	/* STORE the key in the first elem */
4106 	sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4107 	memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
4108 	first->len = sizeof(struct sh_ssl_sess_hdr);
4109 
4110 	/* it returns the already existing node
4111            or current node if none, never returns null */
4112 	oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
4113 	if (oldsh_ssl_sess != sh_ssl_sess) {
4114 		 /* NOTE: Row couldn't be in use because we lock read & write function */
4115 		/* release the reserved row */
4116 		shctx_row_dec_hot(ssl_shctx, first);
4117 		/* replace the previous session already in the tree */
4118 		sh_ssl_sess = oldsh_ssl_sess;
4119 		/* ignore the previous session data, only use the header */
4120 		first = sh_ssl_sess_first_block(sh_ssl_sess);
4121 		shctx_row_inc_hot(ssl_shctx, first);
4122 		first->len = sizeof(struct sh_ssl_sess_hdr);
4123 	}
4124 
4125 	if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
4126 		shctx_row_dec_hot(ssl_shctx, first);
4127 		return 0;
4128 	}
4129 
4130 	shctx_row_dec_hot(ssl_shctx, first);
4131 
4132 	return 1;
4133 }
4134 
4135 /* SSL callback used when a new session is created while connecting to a server */
4136 static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4137 {
4138 	struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
4139 	struct server *s;
4140 
4141 	s = __objt_server(conn->target);
4142 
4143 	if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4144 		int len;
4145 		unsigned char *ptr;
4146 		const char *sni;
4147 
4148 		len = i2d_SSL_SESSION(sess, NULL);
4149 		sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
4150 		if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4151 			ptr = s->ssl_ctx.reused_sess[tid].ptr;
4152 		} else {
4153 			free(s->ssl_ctx.reused_sess[tid].ptr);
4154 			ptr = s->ssl_ctx.reused_sess[tid].ptr = malloc(len);
4155 			s->ssl_ctx.reused_sess[tid].allocated_size = len;
4156 		}
4157 		if (s->ssl_ctx.reused_sess[tid].ptr) {
4158 			s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4159 			    &ptr);
4160 		}
4161 
4162 		if (s->ssl_ctx.reused_sess[tid].sni) {
4163 			/* if the new sni is empty or isn' t the same as the old one */
4164 			if ((!sni) || strcmp(s->ssl_ctx.reused_sess[tid].sni, sni) != 0) {
4165 				free(s->ssl_ctx.reused_sess[tid].sni);
4166 				s->ssl_ctx.reused_sess[tid].sni = NULL;
4167 				if (sni)
4168 					s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4169 			}
4170 		} else if (sni) {
4171 			/* if there wasn't an old sni but there is a new one */
4172 			s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4173 		}
4174 	} else {
4175 		free(s->ssl_ctx.reused_sess[tid].ptr);
4176 		s->ssl_ctx.reused_sess[tid].ptr = NULL;
4177 	}
4178 
4179 	return 0;
4180 }
4181 
4182 
4183 /* SSL callback used on new session creation */
4184 int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
4185 {
4186 	unsigned char encsess[SHSESS_MAX_DATA_LEN];           /* encoded session  */
4187 	unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH];   /* encoded id */
4188 	unsigned char *p;
4189 	int data_len;
4190 	unsigned int sid_length;
4191 	const unsigned char *sid_data;
4192 
4193 	/* Session id is already stored in to key and session id is known
4194 	 * so we dont store it to keep size.
4195 	 * note: SSL_SESSION_set1_id is using
4196 	 * a memcpy so we need to use a different pointer
4197 	 * than sid_data or sid_ctx_data to avoid valgrind
4198 	 * complaining.
4199 	 */
4200 
4201 	sid_data = SSL_SESSION_get_id(sess, &sid_length);
4202 
4203 	/* copy value in an other buffer */
4204 	memcpy(encid, sid_data, sid_length);
4205 
4206 	/* pad with 0 */
4207 	if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4208 		memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4209 
4210 	/* force length to zero to avoid ASN1 encoding */
4211 	SSL_SESSION_set1_id(sess, encid, 0);
4212 
4213 	/* force length to zero to avoid ASN1 encoding */
4214 	SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
4215 
4216 	/* check if buffer is large enough for the ASN1 encoded session */
4217 	data_len = i2d_SSL_SESSION(sess, NULL);
4218 	if (data_len > SHSESS_MAX_DATA_LEN)
4219 		goto err;
4220 
4221 	p = encsess;
4222 
4223 	/* process ASN1 session encoding before the lock */
4224 	i2d_SSL_SESSION(sess, &p);
4225 
4226 
4227 	shctx_lock(ssl_shctx);
4228 	/* store to cache */
4229 	sh_ssl_sess_store(encid, encsess, data_len);
4230 	shctx_unlock(ssl_shctx);
4231 err:
4232 	/* reset original length values */
4233 	SSL_SESSION_set1_id(sess, encid, sid_length);
4234 	SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4235 
4236 	return 0; /* do not increment session reference count */
4237 }
4238 
4239 /* SSL callback used on lookup an existing session cause none found in internal cache */
4240 SSL_SESSION *sh_ssl_sess_get_cb(SSL *ssl, __OPENSSL_110_CONST__ unsigned char *key, int key_len, int *do_copy)
4241 {
4242 	struct sh_ssl_sess_hdr *sh_ssl_sess;
4243 	unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4244 	unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4245 	SSL_SESSION *sess;
4246 	struct shared_block *first;
4247 
4248 	_HA_ATOMIC_ADD(&global.shctx_lookups, 1);
4249 
4250 	/* allow the session to be freed automatically by openssl */
4251 	*do_copy = 0;
4252 
4253 	/* tree key is zeros padded sessionid */
4254 	if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4255 		memcpy(tmpkey, key, key_len);
4256 		memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4257 		key = tmpkey;
4258 	}
4259 
4260 	/* lock cache */
4261 	shctx_lock(ssl_shctx);
4262 
4263 	/* lookup for session */
4264 	sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4265 	if (!sh_ssl_sess) {
4266 		/* no session found: unlock cache and exit */
4267 		shctx_unlock(ssl_shctx);
4268 		_HA_ATOMIC_ADD(&global.shctx_misses, 1);
4269 		return NULL;
4270 	}
4271 
4272 	/* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4273 	first = sh_ssl_sess_first_block(sh_ssl_sess);
4274 
4275 	shctx_row_data_get(ssl_shctx, first, data, sizeof(struct sh_ssl_sess_hdr), first->len-sizeof(struct sh_ssl_sess_hdr));
4276 
4277 	shctx_unlock(ssl_shctx);
4278 
4279 	/* decode ASN1 session */
4280 	p = data;
4281 	sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
4282 	/* Reset session id and session id contenxt */
4283 	if (sess) {
4284 		SSL_SESSION_set1_id(sess, key, key_len);
4285 		SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4286 	}
4287 
4288 	return sess;
4289 }
4290 
4291 
4292 /* SSL callback used to signal session is no more used in internal cache */
4293 void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
4294 {
4295 	struct sh_ssl_sess_hdr *sh_ssl_sess;
4296 	unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4297 	unsigned int sid_length;
4298 	const unsigned char *sid_data;
4299 	(void)ctx;
4300 
4301 	sid_data = SSL_SESSION_get_id(sess, &sid_length);
4302 	/* tree key is zeros padded sessionid */
4303 	if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4304 		memcpy(tmpkey, sid_data, sid_length);
4305 		memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4306 		sid_data = tmpkey;
4307 	}
4308 
4309 	shctx_lock(ssl_shctx);
4310 
4311 	/* lookup for session */
4312 	sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4313 	if (sh_ssl_sess) {
4314 		/* free session */
4315 		sh_ssl_sess_tree_delete(sh_ssl_sess);
4316 	}
4317 
4318 	/* unlock cache */
4319 	shctx_unlock(ssl_shctx);
4320 }
4321 
4322 /* Set session cache mode to server and disable openssl internal cache.
4323  * Set shared cache callbacks on an ssl context.
4324  * Shared context MUST be firstly initialized */
4325 void ssl_set_shctx(SSL_CTX *ctx)
4326 {
4327 	SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4328 
4329 	if (!ssl_shctx) {
4330 		SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4331 		return;
4332 	}
4333 
4334 	SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4335 	                                    SSL_SESS_CACHE_NO_INTERNAL |
4336 	                                    SSL_SESS_CACHE_NO_AUTO_CLEAR);
4337 
4338 	/* Set callbacks */
4339 	SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4340 	SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4341 	SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
4342 }
4343 
4344 int ssl_sock_prepare_ctx(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf, SSL_CTX *ctx)
4345 {
4346 	struct proxy *curproxy = bind_conf->frontend;
4347 	int cfgerr = 0;
4348 	int verify = SSL_VERIFY_NONE;
4349 	struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
4350 	const char *conf_ciphers;
4351 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
4352 	const char *conf_ciphersuites;
4353 #endif
4354 	const char *conf_curves = NULL;
4355 
4356 	if (ssl_conf) {
4357 		struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4358 		int i, min, max;
4359 		int flags = MC_SSL_O_ALL;
4360 
4361 		/* Real min and max should be determinate with configuration and openssl's capabilities */
4362 		min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4363 		max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
4364 		if (min)
4365 			flags |= (methodVersions[min].flag - 1);
4366 		if (max)
4367 			flags |= ~((methodVersions[max].flag << 1) - 1);
4368 		min = max = CONF_TLSV_NONE;
4369 		for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4370 			if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4371 				if (min)
4372 					max = i;
4373 				else
4374 					min = max = i;
4375 			}
4376 		/* save real min/max */
4377 		conf_ssl_methods->min = min;
4378 		conf_ssl_methods->max = max;
4379 		if (!min) {
4380 			ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4381 				 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
4382 			cfgerr += 1;
4383 		}
4384 	}
4385 
4386 	switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
4387 		case SSL_SOCK_VERIFY_NONE:
4388 			verify = SSL_VERIFY_NONE;
4389 			break;
4390 		case SSL_SOCK_VERIFY_OPTIONAL:
4391 			verify = SSL_VERIFY_PEER;
4392 			break;
4393 		case SSL_SOCK_VERIFY_REQUIRED:
4394 			verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4395 			break;
4396 	}
4397 	SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4398 	if (verify & SSL_VERIFY_PEER) {
4399 		char *ca_file = (ssl_conf && ssl_conf->ca_file) ? ssl_conf->ca_file : bind_conf->ssl_conf.ca_file;
4400 		char *crl_file = (ssl_conf && ssl_conf->crl_file) ? ssl_conf->crl_file : bind_conf->ssl_conf.crl_file;
4401 		if (ca_file) {
4402 			/* load CAfile to verify */
4403 			if (!SSL_CTX_load_verify_locations(ctx, ca_file, NULL)) {
4404 				ha_alert("Proxy '%s': unable to load CA file '%s' for bind '%s' at [%s:%d].\n",
4405 					 curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4406 				cfgerr++;
4407 			}
4408 			if (!((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
4409 				/* set CA names for client cert request, function returns void */
4410 				SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(ca_file));
4411 			}
4412 		}
4413 		else {
4414 			ha_alert("Proxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4415 				 curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
4416 			cfgerr++;
4417 		}
4418 #ifdef X509_V_FLAG_CRL_CHECK
4419 		if (crl_file) {
4420 			X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4421 
4422 			if (!store || !X509_STORE_load_locations(store, crl_file, NULL)) {
4423 				ha_alert("Proxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4424 					 curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4425 				cfgerr++;
4426 			}
4427 			else {
4428 				X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4429 			}
4430 		}
4431 #endif
4432 		ERR_clear_error();
4433 	}
4434 #if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
4435 	if(bind_conf->keys_ref) {
4436 		if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, ssl_tlsext_ticket_key_cb)) {
4437 			ha_alert("Proxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4438 				 curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
4439 			cfgerr++;
4440 		}
4441 	}
4442 #endif
4443 
4444 	ssl_set_shctx(ctx);
4445 	conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4446 	if (conf_ciphers &&
4447 	    !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
4448 		ha_alert("Proxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4449 			 curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
4450 		cfgerr++;
4451 	}
4452 
4453 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
4454 	conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4455 	if (conf_ciphersuites &&
4456 	    !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
4457 		ha_alert("Proxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4458 			 curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
4459 		cfgerr++;
4460 	}
4461 #endif
4462 
4463 #ifndef OPENSSL_NO_DH
4464 	/* If tune.ssl.default-dh-param has not been set,
4465 	   neither has ssl-default-dh-file and no static DH
4466 	   params were in the certificate file. */
4467 	if (global_ssl.default_dh_param == 0 &&
4468 	    global_dh == NULL &&
4469 	    (ssl_dh_ptr_index == -1 ||
4470 	     SSL_CTX_get_ex_data(ctx, ssl_dh_ptr_index) == NULL)) {
4471 		STACK_OF(SSL_CIPHER) * ciphers = NULL;
4472 		const SSL_CIPHER * cipher = NULL;
4473 		char cipher_description[128];
4474 		/* The description of ciphers using an Ephemeral Diffie Hellman key exchange
4475 		   contains " Kx=DH " or " Kx=DH(". Beware of " Kx=DH/",
4476 		   which is not ephemeral DH. */
4477 		const char dhe_description[] = " Kx=DH ";
4478 		const char dhe_export_description[] = " Kx=DH(";
4479 		int idx = 0;
4480 		int dhe_found = 0;
4481 		SSL *ssl = NULL;
4482 
4483 		ssl = SSL_new(ctx);
4484 
4485 		if (ssl) {
4486 			ciphers = SSL_get_ciphers(ssl);
4487 
4488 			if (ciphers) {
4489 				for (idx = 0; idx < sk_SSL_CIPHER_num(ciphers); idx++) {
4490 					cipher = sk_SSL_CIPHER_value(ciphers, idx);
4491 					if (SSL_CIPHER_description(cipher, cipher_description, sizeof (cipher_description)) == cipher_description) {
4492 						if (strstr(cipher_description, dhe_description) != NULL ||
4493 						    strstr(cipher_description, dhe_export_description) != NULL) {
4494 							dhe_found = 1;
4495 							break;
4496 						}
4497 					}
4498 				}
4499 			}
4500 			SSL_free(ssl);
4501 			ssl = NULL;
4502 		}
4503 
4504 		if (dhe_found) {
4505 			ha_warning("Setting tune.ssl.default-dh-param to 1024 by default, if your workload permits it you should set it to at least 2048. Please set a value >= 1024 to make this warning disappear.\n");
4506 		}
4507 
4508 		global_ssl.default_dh_param = 1024;
4509 	}
4510 
4511 	if (global_ssl.default_dh_param >= 1024) {
4512 		if (local_dh_1024 == NULL) {
4513 			local_dh_1024 = ssl_get_dh_1024();
4514 		}
4515 		if (global_ssl.default_dh_param >= 2048) {
4516 			if (local_dh_2048 == NULL) {
4517 				local_dh_2048 = ssl_get_dh_2048();
4518 			}
4519 			if (global_ssl.default_dh_param >= 4096) {
4520 				if (local_dh_4096 == NULL) {
4521 					local_dh_4096 = ssl_get_dh_4096();
4522 				}
4523 			}
4524 		}
4525 	}
4526 #endif /* OPENSSL_NO_DH */
4527 
4528 	SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
4529 #if HA_OPENSSL_VERSION_NUMBER >= 0x00907000L
4530 	SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
4531 #endif
4532 
4533 #if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
4534 	ssl_conf_cur = NULL;
4535 	if (ssl_conf && ssl_conf->npn_str)
4536 		ssl_conf_cur = ssl_conf;
4537 	else if (bind_conf->ssl_conf.npn_str)
4538 		ssl_conf_cur = &bind_conf->ssl_conf;
4539 	if (ssl_conf_cur)
4540 		SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
4541 #endif
4542 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4543 	ssl_conf_cur = NULL;
4544 	if (ssl_conf && ssl_conf->alpn_str)
4545 		ssl_conf_cur = ssl_conf;
4546 	else if (bind_conf->ssl_conf.alpn_str)
4547 		ssl_conf_cur = &bind_conf->ssl_conf;
4548 	if (ssl_conf_cur)
4549 		SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
4550 #endif
4551 #if ((HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL) || defined(LIBRESSL_VERSION_NUMBER))
4552 	conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4553 	if (conf_curves) {
4554 		if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
4555 			ha_alert("Proxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4556 				 curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
4557 			cfgerr++;
4558 		}
4559 		(void)SSL_CTX_set_ecdh_auto(ctx, 1);
4560 	}
4561 #endif
4562 #if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
4563 	if (!conf_curves) {
4564 		int i;
4565 		EC_KEY  *ecdh;
4566 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
4567 		const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4568 			(bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4569 			 NULL);
4570 
4571 		if (ecdhe == NULL) {
4572 			(void)SSL_CTX_set_ecdh_auto(ctx, 1);
4573 			return cfgerr;
4574 		}
4575 #else
4576 		const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4577 			(bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4578 			 ECDHE_DEFAULT_CURVE);
4579 #endif
4580 
4581 		i = OBJ_sn2nid(ecdhe);
4582 		if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
4583 			ha_alert("Proxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4584 				 curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
4585 			cfgerr++;
4586 		}
4587 		else {
4588 			SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4589 			EC_KEY_free(ecdh);
4590 		}
4591 	}
4592 #endif
4593 
4594 	return cfgerr;
4595 }
4596 
4597 static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4598 {
4599 	const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4600 	size_t prefixlen, suffixlen;
4601 
4602 	/* Trivial case */
4603 	if (strcasecmp(pattern, hostname) == 0)
4604 		return 1;
4605 
4606 	/* The rest of this logic is based on RFC 6125, section 6.4.3
4607 	 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4608 
4609 	pattern_wildcard = NULL;
4610 	pattern_left_label_end = pattern;
4611 	while (*pattern_left_label_end != '.') {
4612 		switch (*pattern_left_label_end) {
4613 			case 0:
4614 				/* End of label not found */
4615 				return 0;
4616 			case '*':
4617 				/* If there is more than one wildcards */
4618                                 if (pattern_wildcard)
4619                                         return 0;
4620 				pattern_wildcard = pattern_left_label_end;
4621 				break;
4622 		}
4623 		pattern_left_label_end++;
4624 	}
4625 
4626 	/* If it's not trivial and there is no wildcard, it can't
4627 	 * match */
4628 	if (!pattern_wildcard)
4629 		return 0;
4630 
4631 	/* Make sure all labels match except the leftmost */
4632 	hostname_left_label_end = strchr(hostname, '.');
4633 	if (!hostname_left_label_end
4634 	    || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
4635 		return 0;
4636 
4637 	/* Make sure the leftmost label of the hostname is long enough
4638 	 * that the wildcard can match */
4639 	if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
4640 		return 0;
4641 
4642 	/* Finally compare the string on either side of the
4643 	 * wildcard */
4644 	prefixlen = pattern_wildcard - pattern;
4645 	suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
4646 	if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4647 	    || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
4648 		return 0;
4649 
4650 	return 1;
4651 }
4652 
4653 static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4654 {
4655 	SSL *ssl;
4656 	struct connection *conn;
4657 	struct ssl_sock_ctx *ssl_ctx;
4658 	const char *servername;
4659 	const char *sni;
4660 
4661 	int depth;
4662 	X509 *cert;
4663 	STACK_OF(GENERAL_NAME) *alt_names;
4664 	int i;
4665 	X509_NAME *cert_subject;
4666 	char *str;
4667 
4668 	if (ok == 0)
4669 		return ok;
4670 
4671 	ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
4672 	conn = SSL_get_ex_data(ssl, ssl_app_data_index);
4673 	ssl_ctx = conn->xprt_ctx;
4674 
4675 	/* We're checking if the provided hostnames match the desired one. The
4676 	 * desired hostname comes from the SNI we presented if any, or if not
4677 	 * provided then it may have been explicitly stated using a "verifyhost"
4678 	 * directive. If neither is set, we don't care about the name so the
4679 	 * verification is OK.
4680 	 */
4681 	servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
4682 	sni = servername;
4683 	if (!servername) {
4684 		servername = __objt_server(conn->target)->ssl_ctx.verify_host;
4685 		if (!servername)
4686 			return ok;
4687 	}
4688 
4689 	/* We only need to verify the CN on the actual server cert,
4690 	 * not the indirect CAs */
4691 	depth = X509_STORE_CTX_get_error_depth(ctx);
4692 	if (depth != 0)
4693 		return ok;
4694 
4695 	/* At this point, the cert is *not* OK unless we can find a
4696 	 * hostname match */
4697 	ok = 0;
4698 
4699 	cert = X509_STORE_CTX_get_current_cert(ctx);
4700 	/* It seems like this might happen if verify peer isn't set */
4701 	if (!cert)
4702 		return ok;
4703 
4704 	alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4705 	if (alt_names) {
4706 		for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4707 			GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4708 			if (name->type == GEN_DNS) {
4709 #if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
4710 				if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4711 #else
4712 				if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
4713 #endif
4714 					ok = ssl_sock_srv_hostcheck(str, servername);
4715 					OPENSSL_free(str);
4716 				}
4717 			}
4718 		}
4719 		sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
4720 	}
4721 
4722 	cert_subject = X509_get_subject_name(cert);
4723 	i = -1;
4724 	while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4725 		X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
4726 		ASN1_STRING *value;
4727 		value = X509_NAME_ENTRY_get_data(entry);
4728 		if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
4729 			ok = ssl_sock_srv_hostcheck(str, servername);
4730 			OPENSSL_free(str);
4731 		}
4732 	}
4733 
4734 	/* report the mismatch and indicate if SNI was used or not */
4735 	if (!ok && !conn->err_code)
4736 		conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
4737 	return ok;
4738 }
4739 
4740 /* prepare ssl context from servers options. Returns an error count */
4741 int ssl_sock_prepare_srv_ctx(struct server *srv)
4742 {
4743 	struct proxy *curproxy = srv->proxy;
4744 	int cfgerr = 0;
4745 	long options =
4746 		SSL_OP_ALL | /* all known workarounds for bugs */
4747 		SSL_OP_NO_SSLv2 |
4748 		SSL_OP_NO_COMPRESSION;
4749 	long mode =
4750 		SSL_MODE_ENABLE_PARTIAL_WRITE |
4751 		SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
4752 		SSL_MODE_RELEASE_BUFFERS |
4753 		SSL_MODE_SMALL_BUFFERS;
4754 	int verify = SSL_VERIFY_NONE;
4755 	SSL_CTX *ctx = NULL;
4756 	struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
4757 	int i, min, max, hole;
4758 	int flags = MC_SSL_O_ALL;
4759 
4760 	/* Make sure openssl opens /dev/urandom before the chroot */
4761 	if (!ssl_initialize_random()) {
4762 		ha_alert("OpenSSL random data generator initialization failed.\n");
4763 		cfgerr++;
4764 	}
4765 
4766 	/* Automatic memory computations need to know we use SSL there */
4767 	global.ssl_used_backend = 1;
4768 
4769 	/* Initiate SSL context for current server */
4770 	if (!srv->ssl_ctx.reused_sess) {
4771 		if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
4772 			ha_alert("Proxy '%s', server '%s' [%s:%d] out of memory.\n",
4773 				 curproxy->id, srv->id,
4774 				 srv->conf.file, srv->conf.line);
4775 			cfgerr++;
4776 			return cfgerr;
4777 		}
4778 	}
4779 	if (srv->use_ssl == 1)
4780 		srv->xprt = &ssl_sock;
4781 
4782 	ctx = SSL_CTX_new(SSLv23_client_method());
4783 	if (!ctx) {
4784 		ha_alert("config : %s '%s', server '%s': unable to allocate ssl context.\n",
4785 			 proxy_type_str(curproxy), curproxy->id,
4786 			 srv->id);
4787 		cfgerr++;
4788 		return cfgerr;
4789 	}
4790 
4791 	if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
4792 		ha_warning("config : %s '%s': no-sslv3/no-tlsv1x are ignored for server '%s'. "
4793 			   "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4794 			   proxy_type_str(curproxy), curproxy->id, srv->id);
4795 	else
4796 		flags = conf_ssl_methods->flags;
4797 
4798 	/* Real min and max should be determinate with configuration and openssl's capabilities */
4799 	if (conf_ssl_methods->min)
4800 		flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
4801 	if (conf_ssl_methods->max)
4802 		flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
4803 
4804 	/* find min, max and holes */
4805 	min = max = CONF_TLSV_NONE;
4806 	hole = 0;
4807 	for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4808 		/*  version is in openssl && version not disable in configuration */
4809 		if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4810 			if (min) {
4811 				if (hole) {
4812 					ha_warning("config : %s '%s': SSL/TLS versions range not contiguous for server '%s'. "
4813 						   "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4814 						   proxy_type_str(curproxy), curproxy->id, srv->id,
4815 						   methodVersions[hole].name);
4816 					hole = 0;
4817 				}
4818 				max = i;
4819 			}
4820 			else {
4821 				min = max = i;
4822 			}
4823 		}
4824 		else {
4825 			if (min)
4826 				hole = i;
4827 		}
4828 	if (!min) {
4829 		ha_alert("config : %s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
4830 			 proxy_type_str(curproxy), curproxy->id, srv->id);
4831 		cfgerr += 1;
4832 	}
4833 
4834 #if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
4835 	/* Keep force-xxx implementation as it is in older haproxy. It's a
4836 	   precautionary measure to avoid any surprise with older openssl version. */
4837 	if (min == max)
4838 		methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
4839 	else
4840 		for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4841 			if (flags & methodVersions[i].flag)
4842 				options |= methodVersions[i].option;
4843 #else   /* openssl >= 1.1.0 */
4844 	/* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
4845         methodVersions[min].ctx_set_version(ctx, SET_MIN);
4846         methodVersions[max].ctx_set_version(ctx, SET_MAX);
4847 #endif
4848 
4849 	if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
4850 		options |= SSL_OP_NO_TICKET;
4851 	SSL_CTX_set_options(ctx, options);
4852 
4853 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
4854 	if (global_ssl.async)
4855 		mode |= SSL_MODE_ASYNC;
4856 #endif
4857 	SSL_CTX_set_mode(ctx, mode);
4858 	srv->ssl_ctx.ctx = ctx;
4859 
4860 	if (srv->ssl_ctx.client_crt) {
4861 		if (SSL_CTX_use_PrivateKey_file(srv->ssl_ctx.ctx, srv->ssl_ctx.client_crt, SSL_FILETYPE_PEM) <= 0) {
4862 			ha_alert("config : %s '%s', server '%s': unable to load SSL private key from PEM file '%s'.\n",
4863 				 proxy_type_str(curproxy), curproxy->id,
4864 				 srv->id, srv->ssl_ctx.client_crt);
4865 			cfgerr++;
4866 		}
4867 		else if (SSL_CTX_use_certificate_chain_file(srv->ssl_ctx.ctx, srv->ssl_ctx.client_crt) <= 0) {
4868 			ha_alert("config : %s '%s', server '%s': unable to load ssl certificate from PEM file '%s'.\n",
4869 				 proxy_type_str(curproxy), curproxy->id,
4870 				 srv->id, srv->ssl_ctx.client_crt);
4871 			cfgerr++;
4872 		}
4873 		else if (SSL_CTX_check_private_key(srv->ssl_ctx.ctx) <= 0) {
4874 			ha_alert("config : %s '%s', server '%s': inconsistencies between private key and certificate loaded from PEM file '%s'.\n",
4875 				 proxy_type_str(curproxy), curproxy->id,
4876 				 srv->id, srv->ssl_ctx.client_crt);
4877 			cfgerr++;
4878 		}
4879 	}
4880 
4881 	if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
4882 		verify = SSL_VERIFY_PEER;
4883 	switch (srv->ssl_ctx.verify) {
4884 		case SSL_SOCK_VERIFY_NONE:
4885 			verify = SSL_VERIFY_NONE;
4886 			break;
4887 		case SSL_SOCK_VERIFY_REQUIRED:
4888 			verify = SSL_VERIFY_PEER;
4889 			break;
4890 	}
4891 	SSL_CTX_set_verify(srv->ssl_ctx.ctx,
4892 	                   verify,
4893 	                   (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
4894 	if (verify & SSL_VERIFY_PEER) {
4895 		if (srv->ssl_ctx.ca_file) {
4896 			/* load CAfile to verify */
4897 			if (!SSL_CTX_load_verify_locations(srv->ssl_ctx.ctx, srv->ssl_ctx.ca_file, NULL)) {
4898 				ha_alert("Proxy '%s', server '%s' [%s:%d] unable to load CA file '%s'.\n",
4899 					 curproxy->id, srv->id,
4900 					 srv->conf.file, srv->conf.line, srv->ssl_ctx.ca_file);
4901 				cfgerr++;
4902 			}
4903 		}
4904 		else {
4905 			if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
4906 				ha_alert("Proxy '%s', server '%s' [%s:%d] verify is enabled by default but no CA file specified. If you're running on a LAN where you're certain to trust the server's certificate, please set an explicit 'verify none' statement on the 'server' line, or use 'ssl-server-verify none' in the global section to disable server-side verifications by default.\n",
4907 					 curproxy->id, srv->id,
4908 					 srv->conf.file, srv->conf.line);
4909 			else
4910 				ha_alert("Proxy '%s', server '%s' [%s:%d] verify is enabled but no CA file specified.\n",
4911 					 curproxy->id, srv->id,
4912 					 srv->conf.file, srv->conf.line);
4913 			cfgerr++;
4914 		}
4915 #ifdef X509_V_FLAG_CRL_CHECK
4916 		if (srv->ssl_ctx.crl_file) {
4917 			X509_STORE *store = SSL_CTX_get_cert_store(srv->ssl_ctx.ctx);
4918 
4919 			if (!store || !X509_STORE_load_locations(store, srv->ssl_ctx.crl_file, NULL)) {
4920 				ha_alert("Proxy '%s', server '%s' [%s:%d] unable to configure CRL file '%s'.\n",
4921 					 curproxy->id, srv->id,
4922 					 srv->conf.file, srv->conf.line, srv->ssl_ctx.crl_file);
4923 				cfgerr++;
4924 			}
4925 			else {
4926 				X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4927 			}
4928 		}
4929 #endif
4930 	}
4931 
4932 	SSL_CTX_set_session_cache_mode(srv->ssl_ctx.ctx, SSL_SESS_CACHE_CLIENT |
4933 	    SSL_SESS_CACHE_NO_INTERNAL_STORE);
4934 	SSL_CTX_sess_set_new_cb(srv->ssl_ctx.ctx, ssl_sess_new_srv_cb);
4935 	if (srv->ssl_ctx.ciphers &&
4936 		!SSL_CTX_set_cipher_list(srv->ssl_ctx.ctx, srv->ssl_ctx.ciphers)) {
4937 		ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set SSL cipher list to '%s'.\n",
4938 			 curproxy->id, srv->id,
4939 			 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphers);
4940 		cfgerr++;
4941 	}
4942 
4943 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
4944 	if (srv->ssl_ctx.ciphersuites &&
4945 		!SSL_CTX_set_ciphersuites(srv->ssl_ctx.ctx, srv->ssl_ctx.ciphersuites)) {
4946 		ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set TLS 1.3 cipher suites to '%s'.\n",
4947 			 curproxy->id, srv->id,
4948 			 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphersuites);
4949 		cfgerr++;
4950 	}
4951 #endif
4952 #if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
4953 	if (srv->ssl_ctx.npn_str)
4954 		SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, srv);
4955 #endif
4956 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4957 	if (srv->ssl_ctx.alpn_str)
4958 		SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
4959 #endif
4960 
4961 
4962 	return cfgerr;
4963 }
4964 
4965 /* Walks down the two trees in bind_conf and prepares all certs. The pointer may
4966  * be NULL, in which case nothing is done. Returns the number of errors
4967  * encountered.
4968  */
4969 int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
4970 {
4971 	struct ebmb_node *node;
4972 	struct sni_ctx *sni;
4973 	int err = 0;
4974 
4975 	/* Automatic memory computations need to know we use SSL there */
4976 	global.ssl_used_frontend = 1;
4977 
4978 	/* Make sure openssl opens /dev/urandom before the chroot */
4979 	if (!ssl_initialize_random()) {
4980 		ha_alert("OpenSSL random data generator initialization failed.\n");
4981 		err++;
4982 	}
4983 	/* Create initial_ctx used to start the ssl connection before do switchctx */
4984 	if (!bind_conf->initial_ctx) {
4985 		err += ssl_sock_initial_ctx(bind_conf);
4986 		/* It should not be necessary to call this function, but it's
4987 		   necessary first to check and move all initialisation related
4988 		   to initial_ctx in ssl_sock_initial_ctx. */
4989 		err += ssl_sock_prepare_ctx(bind_conf, NULL, bind_conf->initial_ctx);
4990 	}
4991 	if (bind_conf->default_ctx)
4992 		err += ssl_sock_prepare_ctx(bind_conf, bind_conf->default_ssl_conf, bind_conf->default_ctx);
4993 
4994 	node = ebmb_first(&bind_conf->sni_ctx);
4995 	while (node) {
4996 		sni = ebmb_entry(node, struct sni_ctx, name);
4997 		if (!sni->order && sni->ctx != bind_conf->default_ctx)
4998 			/* only initialize the CTX on its first occurrence and
4999 			   if it is not the default_ctx */
5000 			err += ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx);
5001 		node = ebmb_next(node);
5002 	}
5003 
5004 	node = ebmb_first(&bind_conf->sni_w_ctx);
5005 	while (node) {
5006 		sni = ebmb_entry(node, struct sni_ctx, name);
5007 		if (!sni->order && sni->ctx != bind_conf->default_ctx)
5008 			/* only initialize the CTX on its first occurrence and
5009 			   if it is not the default_ctx */
5010 			err += ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx);
5011 		node = ebmb_next(node);
5012 	}
5013 	return err;
5014 }
5015 
5016 /* Prepares all the contexts for a bind_conf and allocates the shared SSL
5017  * context if needed. Returns < 0 on error, 0 on success. The warnings and
5018  * alerts are directly emitted since the rest of the stack does it below.
5019  */
5020 int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
5021 {
5022 	struct proxy *px = bind_conf->frontend;
5023 	int alloc_ctx;
5024 	int err;
5025 
5026 	if (!bind_conf->is_ssl) {
5027 		if (bind_conf->default_ctx) {
5028 			ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
5029 				   px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
5030 		}
5031 		return 0;
5032 	}
5033 	if (!bind_conf->default_ctx) {
5034 		if (bind_conf->strict_sni && !bind_conf->generate_certs) {
5035 			ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5036 				   px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
5037 		}
5038 		else {
5039 			ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5040 				 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
5041 			return -1;
5042 		}
5043 	}
5044 	if (!ssl_shctx && global.tune.sslcachesize) {
5045 		alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
5046 		                       sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
5047 		                       sizeof(*sh_ssl_sess_tree),
5048 		                       ((global.nbthread > 1) || (!global_ssl.private_cache && (global.nbproc > 1))) ? 1 : 0);
5049 		if (alloc_ctx <= 0) {
5050 			if (alloc_ctx == SHCTX_E_INIT_LOCK)
5051 				ha_alert("Unable to initialize the lock for the shared SSL session cache. You can retry using the global statement 'tune.ssl.force-private-cache' but it could increase CPU usage due to renegotiations if nbproc > 1.\n");
5052 			else
5053 				ha_alert("Unable to allocate SSL session cache.\n");
5054 			return -1;
5055 		}
5056 		/* free block callback */
5057 		ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5058 		/* init the root tree within the extra space */
5059 		sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5060 		*sh_ssl_sess_tree = EB_ROOT_UNIQUE;
5061 	}
5062 	err = 0;
5063 	/* initialize all certificate contexts */
5064 	err += ssl_sock_prepare_all_ctx(bind_conf);
5065 
5066 	/* initialize CA variables if the certificates generation is enabled */
5067 	err += ssl_sock_load_ca(bind_conf);
5068 
5069 	return -err;
5070 }
5071 
5072 /* release ssl context allocated for servers. */
5073 void ssl_sock_free_srv_ctx(struct server *srv)
5074 {
5075 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5076 	if (srv->ssl_ctx.alpn_str)
5077 		free(srv->ssl_ctx.alpn_str);
5078 #endif
5079 #ifdef OPENSSL_NPN_NEGOTIATED
5080 	if (srv->ssl_ctx.npn_str)
5081 		free(srv->ssl_ctx.npn_str);
5082 #endif
5083 	if (srv->ssl_ctx.reused_sess) {
5084 		int i;
5085 
5086 		for (i = 0; i < global.nbthread; i++) {
5087 			free(srv->ssl_ctx.reused_sess[i].ptr);
5088 			free(srv->ssl_ctx.reused_sess[i].sni);
5089 		}
5090 		free(srv->ssl_ctx.reused_sess);
5091 	}
5092 
5093 	if (srv->ssl_ctx.ctx)
5094 		SSL_CTX_free(srv->ssl_ctx.ctx);
5095 }
5096 
5097 /* Walks down the two trees in bind_conf and frees all the certs. The pointer may
5098  * be NULL, in which case nothing is done. The default_ctx is nullified too.
5099  */
5100 void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
5101 {
5102 	struct ebmb_node *node, *back;
5103 	struct sni_ctx *sni;
5104 
5105 	node = ebmb_first(&bind_conf->sni_ctx);
5106 	while (node) {
5107 		sni = ebmb_entry(node, struct sni_ctx, name);
5108 		back = ebmb_next(node);
5109 		ebmb_delete(node);
5110 		if (!sni->order) { /* only free the CTX on its first occurrence */
5111 			SSL_CTX_free(sni->ctx);
5112 			ssl_sock_free_ssl_conf(sni->conf);
5113 			free(sni->conf);
5114 			sni->conf = NULL;
5115 		}
5116 		free(sni);
5117 		node = back;
5118 	}
5119 
5120 	node = ebmb_first(&bind_conf->sni_w_ctx);
5121 	while (node) {
5122 		sni = ebmb_entry(node, struct sni_ctx, name);
5123 		back = ebmb_next(node);
5124 		ebmb_delete(node);
5125 		if (!sni->order) { /* only free the CTX on its first occurrence */
5126 			SSL_CTX_free(sni->ctx);
5127 			ssl_sock_free_ssl_conf(sni->conf);
5128 			free(sni->conf);
5129 			sni->conf = NULL;
5130 		}
5131 		free(sni);
5132 		node = back;
5133 	}
5134 	SSL_CTX_free(bind_conf->initial_ctx);
5135 	bind_conf->initial_ctx = NULL;
5136 	bind_conf->default_ctx = NULL;
5137 	bind_conf->default_ssl_conf = NULL;
5138 }
5139 
5140 /* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5141 void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5142 {
5143 	ssl_sock_free_ca(bind_conf);
5144 	ssl_sock_free_all_ctx(bind_conf);
5145 	ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
5146 	free(bind_conf->ca_sign_file);
5147 	free(bind_conf->ca_sign_pass);
5148 	if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
5149 		free(bind_conf->keys_ref->filename);
5150 		free(bind_conf->keys_ref->tlskeys);
5151 		LIST_DEL(&bind_conf->keys_ref->list);
5152 		free(bind_conf->keys_ref);
5153 	}
5154 	bind_conf->keys_ref = NULL;
5155 	bind_conf->ca_sign_pass = NULL;
5156 	bind_conf->ca_sign_file = NULL;
5157 }
5158 
5159 /* Load CA cert file and private key used to generate certificates */
5160 int
5161 ssl_sock_load_ca(struct bind_conf *bind_conf)
5162 {
5163 	struct proxy *px = bind_conf->frontend;
5164 	FILE     *fp;
5165 	X509     *cacert = NULL;
5166 	EVP_PKEY *capkey = NULL;
5167 	int       err    = 0;
5168 
5169 	if (!bind_conf->generate_certs)
5170 		return err;
5171 
5172 #if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
5173 	if (global_ssl.ctx_cache) {
5174 		ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
5175 	}
5176 	ssl_ctx_lru_seed = (unsigned int)time(NULL);
5177 	ssl_ctx_serial   = now_ms;
5178 #endif
5179 
5180 	if (!bind_conf->ca_sign_file) {
5181 		ha_alert("Proxy '%s': cannot enable certificate generation, "
5182 			 "no CA certificate File configured at [%s:%d].\n",
5183 			 px->id, bind_conf->file, bind_conf->line);
5184 		goto load_error;
5185 	}
5186 
5187 	/* read in the CA certificate */
5188 	if (!(fp = fopen(bind_conf->ca_sign_file, "r"))) {
5189 		ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d].\n",
5190 			 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5191 		goto load_error;
5192 	}
5193 	if (!(cacert = PEM_read_X509(fp, NULL, NULL, NULL))) {
5194 		ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d].\n",
5195 			 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5196 		goto read_error;
5197 	}
5198 	rewind(fp);
5199 	if (!(capkey = PEM_read_PrivateKey(fp, NULL, NULL, bind_conf->ca_sign_pass))) {
5200 		ha_alert("Proxy '%s': Failed to read CA private key file '%s' at [%s:%d].\n",
5201 			 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5202 		goto read_error;
5203 	}
5204 
5205 	fclose (fp);
5206 	bind_conf->ca_sign_cert = cacert;
5207 	bind_conf->ca_sign_pkey = capkey;
5208 	return err;
5209 
5210  read_error:
5211 	fclose (fp);
5212 	if (capkey) EVP_PKEY_free(capkey);
5213 	if (cacert) X509_free(cacert);
5214  load_error:
5215 	bind_conf->generate_certs = 0;
5216 	err++;
5217 	return err;
5218 }
5219 
5220 /* Release CA cert and private key used to generate certificated */
5221 void
5222 ssl_sock_free_ca(struct bind_conf *bind_conf)
5223 {
5224 	if (bind_conf->ca_sign_pkey)
5225 		EVP_PKEY_free(bind_conf->ca_sign_pkey);
5226 	if (bind_conf->ca_sign_cert)
5227 		X509_free(bind_conf->ca_sign_cert);
5228 	bind_conf->ca_sign_pkey = NULL;
5229 	bind_conf->ca_sign_cert = NULL;
5230 }
5231 
5232 /*
5233  * This function is called if SSL * context is not yet allocated. The function
5234  * is designed to be called before any other data-layer operation and sets the
5235  * handshake flag on the connection. It is safe to call it multiple times.
5236  * It returns 0 on success and -1 in error case.
5237  */
5238 static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
5239 {
5240 	struct ssl_sock_ctx *ctx;
5241 	/* already initialized */
5242 	if (*xprt_ctx)
5243 		return 0;
5244 
5245 	if (!conn_ctrl_ready(conn))
5246 		return 0;
5247 
5248 	ctx = pool_alloc(ssl_sock_ctx_pool);
5249 	if (!ctx) {
5250 		conn->err_code = CO_ER_SSL_NO_MEM;
5251 		return -1;
5252 	}
5253 	ctx->wait_event.tasklet = tasklet_new();
5254 	if (!ctx->wait_event.tasklet) {
5255 		conn->err_code = CO_ER_SSL_NO_MEM;
5256 		pool_free(ssl_sock_ctx_pool, ctx);
5257 		return -1;
5258 	}
5259 	ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5260 	ctx->wait_event.tasklet->context = ctx;
5261 	ctx->wait_event.events = 0;
5262 	ctx->sent_early_data = 0;
5263 	ctx->early_buf = BUF_NULL;
5264 	ctx->conn = conn;
5265 	ctx->send_wait = NULL;
5266 	ctx->recv_wait = NULL;
5267 	ctx->xprt_st = 0;
5268 	ctx->xprt_ctx = NULL;
5269 
5270 	/* Only work with sockets for now, this should be adapted when we'll
5271 	 * add QUIC support.
5272 	 */
5273 	ctx->xprt = xprt_get(XPRT_RAW);
5274 	if (ctx->xprt->init) {
5275 		if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5276 			goto err;
5277 	}
5278 
5279 	if (global.maxsslconn && sslconns >= global.maxsslconn) {
5280 		conn->err_code = CO_ER_SSL_TOO_MANY;
5281 		goto err;
5282 	}
5283 
5284 	/* If it is in client mode initiate SSL session
5285 	   in connect state otherwise accept state */
5286 	if (objt_server(conn->target)) {
5287 		int may_retry = 1;
5288 
5289 	retry_connect:
5290 		/* Alloc a new SSL session ctx */
5291 		ctx->ssl = SSL_new(__objt_server(conn->target)->ssl_ctx.ctx);
5292 		if (!ctx->ssl) {
5293 			if (may_retry--) {
5294 				pool_gc(NULL);
5295 				goto retry_connect;
5296 			}
5297 			conn->err_code = CO_ER_SSL_NO_MEM;
5298 			goto err;
5299 		}
5300 		ctx->bio = BIO_new(ha_meth);
5301 		if (!ctx->bio) {
5302 			SSL_free(ctx->ssl);
5303 			ctx->ssl = NULL;
5304 			if (may_retry--) {
5305 				pool_gc(NULL);
5306 				goto retry_connect;
5307 			}
5308 			conn->err_code = CO_ER_SSL_NO_MEM;
5309 			goto err;
5310 		}
5311 		BIO_set_data(ctx->bio, ctx);
5312 		SSL_set_bio(ctx->ssl, ctx->bio, ctx->bio);
5313 
5314 		/* set connection pointer */
5315 		if (!SSL_set_ex_data(ctx->ssl, ssl_app_data_index, conn)) {
5316 			SSL_free(ctx->ssl);
5317 			ctx->ssl = NULL;
5318 			conn->xprt_ctx = NULL;
5319 			if (may_retry--) {
5320 				pool_gc(NULL);
5321 				goto retry_connect;
5322 			}
5323 			conn->err_code = CO_ER_SSL_NO_MEM;
5324 			goto err;
5325 		}
5326 
5327 		SSL_set_connect_state(ctx->ssl);
5328 		if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5329 			const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5330 			SSL_SESSION *sess = d2i_SSL_SESSION(NULL, &ptr, __objt_server(conn->target)->ssl_ctx.reused_sess[tid].size);
5331 			if (sess && !SSL_set_session(ctx->ssl, sess)) {
5332 				SSL_SESSION_free(sess);
5333 				free(__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
5334 				__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr = NULL;
5335 			} else if (sess) {
5336 				SSL_SESSION_free(sess);
5337 			}
5338 		}
5339 
5340 		/* leave init state and start handshake */
5341 		conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
5342 
5343 		_HA_ATOMIC_ADD(&sslconns, 1);
5344 		_HA_ATOMIC_ADD(&totalsslconns, 1);
5345 		*xprt_ctx = ctx;
5346 		/* Start the handshake */
5347 		tasklet_wakeup(ctx->wait_event.tasklet);
5348 		if (conn->flags & CO_FL_ERROR)
5349 			goto err;
5350 		return 0;
5351 	}
5352 	else if (objt_listener(conn->target)) {
5353 		int may_retry = 1;
5354 
5355 	retry_accept:
5356 		/* Alloc a new SSL session ctx */
5357 		ctx->ssl = SSL_new(__objt_listener(conn->target)->bind_conf->initial_ctx);
5358 		if (!ctx->ssl) {
5359 			if (may_retry--) {
5360 				pool_gc(NULL);
5361 				goto retry_accept;
5362 			}
5363 			conn->err_code = CO_ER_SSL_NO_MEM;
5364 			goto err;
5365 		}
5366 		ctx->bio = BIO_new(ha_meth);
5367 		if (!ctx->bio) {
5368 			SSL_free(ctx->ssl);
5369 			ctx->ssl = NULL;
5370 			if (may_retry--) {
5371 				pool_gc(NULL);
5372 				goto retry_accept;
5373 			}
5374 			conn->err_code = CO_ER_SSL_NO_MEM;
5375 			goto err;
5376 		}
5377 		BIO_set_data(ctx->bio, ctx);
5378 		SSL_set_bio(ctx->ssl, ctx->bio, ctx->bio);
5379 
5380 		/* set connection pointer */
5381 		if (!SSL_set_ex_data(ctx->ssl, ssl_app_data_index, conn)) {
5382 			SSL_free(ctx->ssl);
5383 			ctx->ssl = NULL;
5384 			if (may_retry--) {
5385 				pool_gc(NULL);
5386 				goto retry_accept;
5387 			}
5388 			conn->err_code = CO_ER_SSL_NO_MEM;
5389 			goto err;
5390 		}
5391 
5392 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5393 		if (__objt_listener(conn->target)->bind_conf->ssl_conf.early_data) {
5394 			b_alloc(&ctx->early_buf);
5395 			SSL_set_max_early_data(ctx->ssl,
5396 			    /* Only allow early data if we managed to allocate
5397 			     * a buffer.
5398 			     */
5399 			    (!b_is_null(&ctx->early_buf)) ?
5400 			    global.tune.bufsize - global.tune.maxrewrite : 0);
5401 		}
5402 #endif
5403 
5404 		SSL_set_accept_state(ctx->ssl);
5405 
5406 		/* leave init state and start handshake */
5407 		conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
5408 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5409 		conn->flags |= CO_FL_EARLY_SSL_HS;
5410 #endif
5411 
5412 		_HA_ATOMIC_ADD(&sslconns, 1);
5413 		_HA_ATOMIC_ADD(&totalsslconns, 1);
5414 		*xprt_ctx = ctx;
5415 		/* Start the handshake */
5416 		tasklet_wakeup(ctx->wait_event.tasklet);
5417 		if (conn->flags & CO_FL_ERROR)
5418 			goto err;
5419 		return 0;
5420 	}
5421 	/* don't know how to handle such a target */
5422 	conn->err_code = CO_ER_SSL_NO_TARGET;
5423 err:
5424 	if (ctx && ctx->wait_event.tasklet)
5425 		tasklet_free(ctx->wait_event.tasklet);
5426 	pool_free(ssl_sock_ctx_pool, ctx);
5427 	return -1;
5428 }
5429 
5430 
5431 /* This is the callback which is used when an SSL handshake is pending. It
5432  * updates the FD status if it wants some polling before being called again.
5433  * It returns 0 if it fails in a fatal way or needs to poll to go further,
5434  * otherwise it returns non-zero and removes itself from the connection's
5435  * flags (the bit is provided in <flag> by the caller).
5436  */
5437 static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
5438 {
5439 	struct ssl_sock_ctx *ctx = conn->xprt_ctx;
5440 	int ret;
5441 	socklen_t lskerr;
5442 	int skerr;
5443 
5444 
5445 	if (!conn_ctrl_ready(conn))
5446 		return 0;
5447 
5448 	if (!conn->xprt_ctx)
5449 		goto out_error;
5450 
5451 	/* don't start calculating a handshake on a dead connection */
5452 	if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5453 		goto out_error;
5454 
5455 	/* FIXME/WT: for now we don't have a clear way to inspect the connection
5456 	 * status from the lower layers, so let's check the FD directly. Ideally
5457 	 * the xprt layers should provide some status indicating their knowledge
5458 	 * of shutdowns or error.
5459 	 */
5460 	skerr = 0;
5461 	lskerr = sizeof(skerr);
5462 	if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5463 	    skerr != 0)
5464 		goto out_error;
5465 
5466 #if HA_OPENSSL_VERSION_NUMBER >= 0x10101000L
5467 	/*
5468 	 * Check if we have early data. If we do, we have to read them
5469 	 * before SSL_do_handshake() is called, And there's no way to
5470 	 * detect early data, except to try to read them
5471 	 */
5472 	if (conn->flags & CO_FL_EARLY_SSL_HS) {
5473 		size_t read_data = 0;
5474 
5475 		while (1) {
5476 			ret = SSL_read_early_data(ctx->ssl,
5477 			    b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5478 			    &read_data);
5479 			if (ret == SSL_READ_EARLY_DATA_ERROR)
5480 				goto check_error;
5481 			if (read_data > 0) {
5482 				conn->flags |= CO_FL_EARLY_DATA;
5483 				b_add(&ctx->early_buf, read_data);
5484 			}
5485 			if (ret == SSL_READ_EARLY_DATA_FINISH) {
5486 				conn->flags &= ~CO_FL_EARLY_SSL_HS;
5487 				if (!b_data(&ctx->early_buf))
5488 					b_free(&ctx->early_buf);
5489 				break;
5490 			}
5491 		}
5492 	}
5493 #endif
5494 	/* If we use SSL_do_handshake to process a reneg initiated by
5495 	 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5496 	 * Usually SSL_write and SSL_read are used and process implicitly
5497 	 * the reneg handshake.
5498 	 * Here we use SSL_peek as a workaround for reneg.
5499 	 */
5500 	if ((conn->flags & CO_FL_CONNECTED) && SSL_renegotiate_pending(ctx->ssl)) {
5501 		char c;
5502 
5503 		ret = SSL_peek(ctx->ssl, &c, 1);
5504 		if (ret <= 0) {
5505 			/* handshake may have not been completed, let's find why */
5506 			ret = SSL_get_error(ctx->ssl, ret);
5507 
5508 			if (ret == SSL_ERROR_WANT_WRITE) {
5509 				/* SSL handshake needs to write, L4 connection may not be ready */
5510 				if (!(ctx->wait_event.events & SUB_RETRY_SEND))
5511 					ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
5512 				return 0;
5513 			}
5514 			else if (ret == SSL_ERROR_WANT_READ) {
5515 				/* handshake may have been completed but we have
5516 				 * no more data to read.
5517                                  */
5518 				if (!SSL_renegotiate_pending(ctx->ssl)) {
5519 					ret = 1;
5520 					goto reneg_ok;
5521 				}
5522 				/* SSL handshake needs to read, L4 connection is ready */
5523 				if (!(ctx->wait_event.events & SUB_RETRY_RECV))
5524 					ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
5525 				return 0;
5526 			}
5527 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
5528 			else if (ret == SSL_ERROR_WANT_ASYNC) {
5529 				ssl_async_process_fds(ctx);
5530 				return 0;
5531 			}
5532 #endif
5533 			else if (ret == SSL_ERROR_SYSCALL) {
5534 				/* if errno is null, then connection was successfully established */
5535 				if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5536 					conn->flags &= ~CO_FL_WAIT_L4_CONN;
5537 				if (!conn->err_code) {
5538 #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5539 					/* do not handle empty handshakes in BoringSSL or LibreSSL */
5540 					conn->err_code = CO_ER_SSL_HANDSHAKE;
5541 #else
5542 					int empty_handshake;
5543 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
5544 					/* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
5545 					OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
5546 					empty_handshake = state == TLS_ST_BEFORE;
5547 #else
5548 					/* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5549 					empty_handshake = !ctx->ssl->packet_length;
5550 #endif
5551 					if (empty_handshake) {
5552 						if (!errno) {
5553 							if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
5554 								conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5555 							else
5556 								conn->err_code = CO_ER_SSL_EMPTY;
5557 						}
5558 						else {
5559 							if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
5560 								conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5561 							else
5562 								conn->err_code = CO_ER_SSL_ABORT;
5563 						}
5564 					}
5565 					else {
5566 						if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
5567 							conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5568 						else
5569 							conn->err_code = CO_ER_SSL_HANDSHAKE;
5570 					}
5571 #endif /* BoringSSL or LibreSSL */
5572 				}
5573 				goto out_error;
5574 			}
5575 			else {
5576 				/* Fail on all other handshake errors */
5577 				/* Note: OpenSSL may leave unread bytes in the socket's
5578 				 * buffer, causing an RST to be emitted upon close() on
5579 				 * TCP sockets. We first try to drain possibly pending
5580 				 * data to avoid this as much as possible.
5581 				 */
5582 				conn_sock_drain(conn);
5583 				if (!conn->err_code)
5584 					conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
5585 						CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
5586 				goto out_error;
5587 			}
5588 		}
5589 		/* read some data: consider handshake completed */
5590 		goto reneg_ok;
5591 	}
5592 	ret = SSL_do_handshake(ctx->ssl);
5593 check_error:
5594 	if (ret != 1) {
5595 		/* handshake did not complete, let's find why */
5596 		ret = SSL_get_error(ctx->ssl, ret);
5597 
5598 		if (ret == SSL_ERROR_WANT_WRITE) {
5599 			/* SSL handshake needs to write, L4 connection may not be ready */
5600 			if (!(ctx->wait_event.events & SUB_RETRY_SEND))
5601 				ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
5602 			return 0;
5603 		}
5604 		else if (ret == SSL_ERROR_WANT_READ) {
5605 			/* SSL handshake needs to read, L4 connection is ready */
5606 			if (!(ctx->wait_event.events & SUB_RETRY_RECV))
5607 				ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5608 				    SUB_RETRY_RECV, &ctx->wait_event);
5609 			return 0;
5610 		}
5611 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
5612 		else if (ret == SSL_ERROR_WANT_ASYNC) {
5613 			ssl_async_process_fds(ctx);
5614 			return 0;
5615 		}
5616 #endif
5617 		else if (ret == SSL_ERROR_SYSCALL) {
5618 			/* if errno is null, then connection was successfully established */
5619 			if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5620 				conn->flags &= ~CO_FL_WAIT_L4_CONN;
5621 			if (!conn->err_code) {
5622 #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5623 				/* do not handle empty handshakes in BoringSSL or LibreSSL */
5624 				conn->err_code = CO_ER_SSL_HANDSHAKE;
5625 #else
5626 				int empty_handshake;
5627 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
5628 				/* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
5629 				OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
5630 				empty_handshake = state == TLS_ST_BEFORE;
5631 #else
5632 				/* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5633 				empty_handshake = !ctx->ssl->packet_length;
5634 #endif
5635 				if (empty_handshake) {
5636 					if (!errno) {
5637 						if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
5638 							conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5639 						else
5640 							conn->err_code = CO_ER_SSL_EMPTY;
5641 					}
5642 					else {
5643 						if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
5644 							conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5645 						else
5646 							conn->err_code = CO_ER_SSL_ABORT;
5647 					}
5648 				}
5649 				else {
5650 					if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
5651 						conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5652 					else
5653 						conn->err_code = CO_ER_SSL_HANDSHAKE;
5654 				}
5655 #endif /* BoringSSL or LibreSSL */
5656 			}
5657 			goto out_error;
5658 		}
5659 		else {
5660 			/* Fail on all other handshake errors */
5661 			/* Note: OpenSSL may leave unread bytes in the socket's
5662 			 * buffer, causing an RST to be emitted upon close() on
5663 			 * TCP sockets. We first try to drain possibly pending
5664 			 * data to avoid this as much as possible.
5665 			 */
5666 			conn_sock_drain(conn);
5667 			if (!conn->err_code)
5668 				conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
5669 					CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
5670 			goto out_error;
5671 		}
5672 	}
5673 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5674 	else {
5675 		/*
5676 		 * If the server refused the early data, we have to send a
5677 		 * 425 to the client, as we no longer have the data to sent
5678 		 * them again.
5679 		 */
5680 		if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
5681 			if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
5682 				conn->err_code = CO_ER_SSL_EARLY_FAILED;
5683 				goto out_error;
5684 			}
5685 		}
5686 	}
5687 #endif
5688 
5689 
5690 reneg_ok:
5691 
5692 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
5693 	/* ASYNC engine API doesn't support moving read/write
5694 	 * buffers. So we disable ASYNC mode right after
5695 	 * the handshake to avoid buffer oveflows.
5696 	 */
5697 	if (global_ssl.async)
5698 		SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
5699 #endif
5700 	/* Handshake succeeded */
5701 	if (!SSL_session_reused(ctx->ssl)) {
5702 		if (objt_server(conn->target)) {
5703 			update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5704 			if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5705 				global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
5706 		}
5707 		else {
5708 			update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5709 			if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5710 				global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5711 		}
5712 	}
5713 
5714 	/* The connection is now established at both layers, it's time to leave */
5715 	conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5716 	return 1;
5717 
5718  out_error:
5719 	/* Clear openssl global errors stack */
5720 	ssl_sock_dump_errors(conn);
5721 	ERR_clear_error();
5722 
5723 	/* free resumed session if exists */
5724 	if (objt_server(conn->target) && __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5725 		free(__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
5726 		__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr = NULL;
5727 	}
5728 
5729 	/* Fail on all other handshake errors */
5730 	conn->flags |= CO_FL_ERROR;
5731 	if (!conn->err_code)
5732 		conn->err_code = CO_ER_SSL_HANDSHAKE;
5733 	return 0;
5734 }
5735 
5736 static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, void *param)
5737 {
5738 	struct wait_event *sw;
5739 	struct ssl_sock_ctx *ctx = xprt_ctx;
5740 
5741 	if (!ctx)
5742 		return -1;
5743 
5744 	if (event_type & SUB_RETRY_RECV) {
5745 		sw = param;
5746 		BUG_ON(ctx->recv_wait !=  NULL || (sw->events & SUB_RETRY_RECV));
5747 		sw->events |= SUB_RETRY_RECV;
5748 		ctx->recv_wait = sw;
5749 		if (!(conn->flags & CO_FL_SSL_WAIT_HS) &&
5750 		    !(ctx->wait_event.events & SUB_RETRY_RECV))
5751 			ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
5752 		event_type &= ~SUB_RETRY_RECV;
5753 	}
5754 	if (event_type & SUB_RETRY_SEND) {
5755 sw = param;
5756 		BUG_ON(ctx->send_wait !=  NULL || (sw->events & SUB_RETRY_SEND));
5757 		sw->events |= SUB_RETRY_SEND;
5758 		ctx->send_wait = sw;
5759 		if (!(conn->flags & CO_FL_SSL_WAIT_HS) &&
5760 		    !(ctx->wait_event.events & SUB_RETRY_SEND))
5761 			ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
5762 		event_type &= ~SUB_RETRY_SEND;
5763 
5764 	}
5765 	if (event_type != 0)
5766 		return -1;
5767 	return 0;
5768 }
5769 
5770 static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, void *param)
5771 {
5772 	struct wait_event *sw;
5773 	struct ssl_sock_ctx *ctx = xprt_ctx;
5774 
5775 	if (event_type & SUB_RETRY_RECV) {
5776 		sw = param;
5777 		BUG_ON(ctx->recv_wait != sw);
5778 		ctx->recv_wait = NULL;
5779 		sw->events &= ~SUB_RETRY_RECV;
5780 		/* If we subscribed, and we're not doing the handshake,
5781 		 * then we subscribed because the upper layer asked for it,
5782 		 * as the upper layer is no longer interested, we can
5783 		 * unsubscribe too.
5784 		 */
5785 		if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS) &&
5786 		    (ctx->wait_event.events & SUB_RETRY_RECV))
5787 			conn_unsubscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV,
5788 			                 &ctx->wait_event);
5789 	}
5790 	if (event_type & SUB_RETRY_SEND) {
5791 		sw = param;
5792 		BUG_ON(ctx->send_wait != sw);
5793 		ctx->send_wait = NULL;
5794 		sw->events &= ~SUB_RETRY_SEND;
5795 		if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS) &&
5796 		    (ctx->wait_event.events & SUB_RETRY_SEND))
5797 			conn_unsubscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND,
5798 			                 &ctx->wait_event);
5799 
5800 	}
5801 
5802 	return 0;
5803 }
5804 
5805 /* Use the provided XPRT as an underlying XPRT, and provide the old one.
5806  * Returns 0 on success, and non-zero on failure.
5807  */
5808 static int ssl_add_xprt(struct connection *conn, void *xprt_ctx, void *toadd_ctx, const struct xprt_ops *toadd_ops, void **oldxprt_ctx, const struct xprt_ops **oldxprt_ops)
5809 {
5810 	struct ssl_sock_ctx *ctx = xprt_ctx;
5811 
5812 	if (oldxprt_ops != NULL)
5813 		*oldxprt_ops = ctx->xprt;
5814 	if (oldxprt_ctx != NULL)
5815 		*oldxprt_ctx = ctx->xprt_ctx;
5816 	ctx->xprt = toadd_ops;
5817 	ctx->xprt_ctx = toadd_ctx;
5818 	return 0;
5819 }
5820 
5821 /* Remove the specified xprt. If if it our underlying XPRT, remove it and
5822  * return 0, otherwise just call the remove_xprt method from the underlying
5823  * XPRT.
5824  */
5825 static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
5826 {
5827 	struct ssl_sock_ctx *ctx = xprt_ctx;
5828 
5829 	if (ctx->xprt_ctx == toremove_ctx) {
5830 		ctx->xprt_ctx = newctx;
5831 		ctx->xprt = newops;
5832 		return 0;
5833 	}
5834 	return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
5835 }
5836 
5837 static struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned short state)
5838 {
5839 	struct ssl_sock_ctx *ctx = context;
5840 
5841 	/* First if we're doing an handshake, try that */
5842 	if (ctx->conn->flags & CO_FL_SSL_WAIT_HS)
5843 		ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
5844 	/* If we had an error, or the handshake is done and I/O is available,
5845 	 * let the upper layer know.
5846 	 * If no mux was set up yet, and nobody subscribed, then call
5847 	 * xprt_done_cb() ourself if it's set, or destroy the connection,
5848 	 * we can't be sure conn_fd_handler() will be called again.
5849 	 */
5850 	if ((ctx->conn->flags & CO_FL_ERROR) ||
5851 	    !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
5852 		int ret = 0;
5853 		int woke = 0;
5854 
5855 		/* On error, wake any waiter */
5856 		if (ctx->recv_wait) {
5857 			ctx->recv_wait->events &= ~SUB_RETRY_RECV;
5858 			tasklet_wakeup(ctx->recv_wait->tasklet);
5859 			ctx->recv_wait = NULL;
5860 			woke = 1;
5861 		}
5862 		if (ctx->send_wait) {
5863 			ctx->send_wait->events &= ~SUB_RETRY_SEND;
5864 			tasklet_wakeup(ctx->send_wait->tasklet);
5865 			ctx->send_wait = NULL;
5866 			woke = 1;
5867 		}
5868 		/* If we're the first xprt for the connection, let the
5869 		 * upper layers know. If xprt_done_cb() is set, call it,
5870 		 * otherwise, we should have a mux, so call its wake
5871 		 * method if we didn't woke a tasklet already.
5872 		 */
5873 		if (ctx->conn->xprt_ctx == ctx) {
5874 			if (ctx->conn->xprt_done_cb)
5875 				ret = ctx->conn->xprt_done_cb(ctx->conn);
5876 			if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
5877 				ctx->conn->mux->wake(ctx->conn);
5878 			return NULL;
5879 		}
5880 	}
5881 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5882 	/* If we have early data and somebody wants to receive, let them */
5883 	else if (b_data(&ctx->early_buf) && ctx->recv_wait) {
5884 		ctx->recv_wait->events &= ~SUB_RETRY_RECV;
5885 			tasklet_wakeup(ctx->recv_wait->tasklet);
5886 			ctx->recv_wait = NULL;
5887 
5888 	}
5889 #endif
5890 	return NULL;
5891 }
5892 
5893 /* Receive up to <count> bytes from connection <conn>'s socket and store them
5894  * into buffer <buf>. Only one call to recv() is performed, unless the
5895  * buffer wraps, in which case a second call may be performed. The connection's
5896  * flags are updated with whatever special event is detected (error, read0,
5897  * empty). The caller is responsible for taking care of those events and
5898  * avoiding the call if inappropriate. The function does not call the
5899  * connection's polling update function, so the caller is responsible for this.
5900  */
5901 static size_t ssl_sock_to_buf(struct connection *conn, void *xprt_ctx, struct buffer *buf, size_t count, int flags)
5902 {
5903 	struct ssl_sock_ctx *ctx = xprt_ctx;
5904 	ssize_t ret;
5905 	size_t try, done = 0;
5906 
5907 	conn_refresh_polling_flags(conn);
5908 
5909 	if (!ctx)
5910 		goto out_error;
5911 
5912 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5913 	if (b_data(&ctx->early_buf)) {
5914 		try = b_contig_space(buf);
5915 		if (try > b_data(&ctx->early_buf))
5916 			try = b_data(&ctx->early_buf);
5917 		memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
5918 		b_add(buf, try);
5919 		b_del(&ctx->early_buf, try);
5920 		if (b_data(&ctx->early_buf) == 0)
5921 			b_free(&ctx->early_buf);
5922 		return try;
5923 	}
5924 #endif
5925 
5926 	if (conn->flags & CO_FL_HANDSHAKE)
5927 		/* a handshake was requested */
5928 		return 0;
5929 
5930 	/* read the largest possible block. For this, we perform only one call
5931 	 * to recv() unless the buffer wraps and we exactly fill the first hunk,
5932 	 * in which case we accept to do it once again. A new attempt is made on
5933 	 * EINTR too.
5934 	 */
5935 	while (count > 0) {
5936 
5937 		try = b_contig_space(buf);
5938 		if (!try)
5939 			break;
5940 
5941 		if (try > count)
5942 			try = count;
5943 
5944 		ret = SSL_read(ctx->ssl, b_tail(buf), try);
5945 
5946 		if (conn->flags & CO_FL_ERROR) {
5947 			/* CO_FL_ERROR may be set by ssl_sock_infocbk */
5948 			goto out_error;
5949 		}
5950 		if (ret > 0) {
5951 			b_add(buf, ret);
5952 			done += ret;
5953 			count -= ret;
5954 		}
5955 		else {
5956 			ret =  SSL_get_error(ctx->ssl, ret);
5957 			if (ret == SSL_ERROR_WANT_WRITE) {
5958 				/* handshake is running, and it needs to enable write */
5959 				conn->flags |= CO_FL_SSL_WAIT_HS;
5960 				ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
5961 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
5962 				/* Async mode can be re-enabled, because we're leaving data state.*/
5963 				if (global_ssl.async)
5964 					SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
5965 #endif
5966 				break;
5967 			}
5968 			else if (ret == SSL_ERROR_WANT_READ) {
5969 				if (SSL_renegotiate_pending(ctx->ssl)) {
5970 					ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5971 					                     SUB_RETRY_RECV,
5972 							     &ctx->wait_event);
5973 					/* handshake is running, and it may need to re-enable read */
5974 					conn->flags |= CO_FL_SSL_WAIT_HS;
5975 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
5976 					/* Async mode can be re-enabled, because we're leaving data state.*/
5977 					if (global_ssl.async)
5978 						SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
5979 #endif
5980 					break;
5981 				}
5982 				break;
5983 			} else if (ret == SSL_ERROR_ZERO_RETURN)
5984 				goto read0;
5985 			/* For SSL_ERROR_SYSCALL, make sure to clear the error
5986 			 * stack before shutting down the connection for
5987 			 * reading. */
5988 			if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN))
5989 				goto clear_ssl_error;
5990 			/* otherwise it's a real error */
5991 			goto out_error;
5992 		}
5993 	}
5994  leave:
5995 	return done;
5996 
5997  clear_ssl_error:
5998 	/* Clear openssl global errors stack */
5999 	ssl_sock_dump_errors(conn);
6000 	ERR_clear_error();
6001  read0:
6002 	conn_sock_read0(conn);
6003 	goto leave;
6004 
6005  out_error:
6006 	conn->flags |= CO_FL_ERROR;
6007 	/* Clear openssl global errors stack */
6008 	ssl_sock_dump_errors(conn);
6009 	ERR_clear_error();
6010 	goto leave;
6011 }
6012 
6013 
6014 /* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6015  * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6016  * other pending data for example, but this flag is ignored at the moment.
6017  * Only one call to send() is performed, unless the buffer wraps, in which case
6018  * a second call may be performed. The connection's flags are updated with
6019  * whatever special event is detected (error, empty). The caller is responsible
6020  * for taking care of those events and avoiding the call if inappropriate. The
6021  * function does not call the connection's polling update function, so the caller
6022  * is responsible for this. The buffer's output is not adjusted, it's up to the
6023  * caller to take care of this. It's up to the caller to update the buffer's
6024  * contents based on the return value.
6025  */
6026 static size_t ssl_sock_from_buf(struct connection *conn, void *xprt_ctx, const struct buffer *buf, size_t count, int flags)
6027 {
6028 	struct ssl_sock_ctx *ctx = xprt_ctx;
6029 	ssize_t ret;
6030 	size_t try, done;
6031 
6032 	done = 0;
6033 	conn_refresh_polling_flags(conn);
6034 
6035 	if (!ctx)
6036 		goto out_error;
6037 
6038 	if (conn->flags & (CO_FL_HANDSHAKE | CO_FL_EARLY_SSL_HS))
6039 		/* a handshake was requested */
6040 		return 0;
6041 
6042 	/* send the largest possible block. For this we perform only one call
6043 	 * to send() unless the buffer wraps and we exactly fill the first hunk,
6044 	 * in which case we accept to do it once again.
6045 	 */
6046 	while (count) {
6047 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
6048 		size_t written_data;
6049 #endif
6050 
6051 		try = b_contig_data(buf, done);
6052 		if (try > count)
6053 			try = count;
6054 
6055 		if (!(flags & CO_SFL_STREAMER) &&
6056 		    !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
6057 		    global_ssl.max_record && try > global_ssl.max_record) {
6058 			try = global_ssl.max_record;
6059 		}
6060 		else {
6061 			/* we need to keep the information about the fact that
6062 			 * we're not limiting the upcoming send(), because if it
6063 			 * fails, we'll have to retry with at least as many data.
6064 			 */
6065 			ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
6066 		}
6067 
6068 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
6069 		if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
6070 			unsigned int max_early;
6071 
6072 			if (objt_listener(conn->target))
6073 				max_early = SSL_get_max_early_data(ctx->ssl);
6074 			else {
6075 				if (SSL_get0_session(ctx->ssl))
6076 					max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
6077 				else
6078 					max_early = 0;
6079 			}
6080 
6081 			if (try + ctx->sent_early_data > max_early) {
6082 				try -= (try + ctx->sent_early_data) - max_early;
6083 				if (try <= 0) {
6084 					conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
6085 					tasklet_wakeup(ctx->wait_event.tasklet);
6086 					break;
6087 				}
6088 			}
6089 			ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
6090 			if (ret == 1) {
6091 				ret = written_data;
6092 				ctx->sent_early_data += ret;
6093 				if (objt_server(conn->target)) {
6094 					conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
6095 					/* Initiate the handshake, now */
6096 					tasklet_wakeup(ctx->wait_event.tasklet);
6097 				}
6098 
6099 			}
6100 
6101 		} else
6102 #endif
6103 			ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
6104 
6105 		if (conn->flags & CO_FL_ERROR) {
6106 			/* CO_FL_ERROR may be set by ssl_sock_infocbk */
6107 			goto out_error;
6108 		}
6109 		if (ret > 0) {
6110 			/* A send succeeded, so we can consier ourself connected */
6111 			conn->flags |= CO_FL_CONNECTED;
6112 			ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
6113 			count -= ret;
6114 			done += ret;
6115 		}
6116 		else {
6117 			ret = SSL_get_error(ctx->ssl, ret);
6118 
6119 			if (ret == SSL_ERROR_WANT_WRITE) {
6120 				if (SSL_renegotiate_pending(ctx->ssl)) {
6121 					/* handshake is running, and it may need to re-enable write */
6122 					conn->flags |= CO_FL_SSL_WAIT_HS;
6123 					ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
6124 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
6125 					/* Async mode can be re-enabled, because we're leaving data state.*/
6126 					if (global_ssl.async)
6127 						SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
6128 #endif
6129 					break;
6130 				}
6131 
6132 				break;
6133 			}
6134 			else if (ret == SSL_ERROR_WANT_READ) {
6135 				/* handshake is running, and it needs to enable read */
6136 				conn->flags |= CO_FL_SSL_WAIT_HS;
6137 				ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6138 				                     SUB_RETRY_RECV,
6139 						     &ctx->wait_event);
6140 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
6141 				/* Async mode can be re-enabled, because we're leaving data state.*/
6142 				if (global_ssl.async)
6143 					SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
6144 #endif
6145 				break;
6146 			}
6147 			goto out_error;
6148 		}
6149 	}
6150  leave:
6151 	return done;
6152 
6153  out_error:
6154 	/* Clear openssl global errors stack */
6155 	ssl_sock_dump_errors(conn);
6156 	ERR_clear_error();
6157 
6158 	conn->flags |= CO_FL_ERROR;
6159 	goto leave;
6160 }
6161 
6162 static void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
6163 
6164 	struct ssl_sock_ctx *ctx = xprt_ctx;
6165 
6166 
6167 	if (ctx) {
6168 		if (ctx->wait_event.events != 0)
6169 			ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6170 			                       ctx->wait_event.events,
6171 					       &ctx->wait_event);
6172 		if (ctx->send_wait) {
6173 			ctx->send_wait->events &= ~SUB_RETRY_SEND;
6174 			tasklet_wakeup(ctx->send_wait->tasklet);
6175 		}
6176 		if (ctx->recv_wait) {
6177 			ctx->recv_wait->events &= ~SUB_RETRY_RECV;
6178 			tasklet_wakeup(ctx->recv_wait->tasklet);
6179 		}
6180 		if (ctx->xprt->close)
6181 			ctx->xprt->close(conn, ctx->xprt_ctx);
6182 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
6183 		if (global_ssl.async) {
6184 			OSSL_ASYNC_FD all_fd[32], afd;
6185 			size_t num_all_fds = 0;
6186 			int i;
6187 
6188 			SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
6189 			if (num_all_fds > 32) {
6190 				send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6191 				return;
6192 			}
6193 
6194 			SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
6195 
6196 			/* If an async job is pending, we must try to
6197 			   to catch the end using polling before calling
6198 			   SSL_free */
6199 			if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
6200 				for (i=0 ; i < num_all_fds ; i++) {
6201 					/* switch on an handler designed to
6202 					 * handle the SSL_free
6203 					 */
6204 					afd = all_fd[i];
6205 					fdtab[afd].iocb = ssl_async_fd_free;
6206 					fdtab[afd].owner = ctx->ssl;
6207 					fd_want_recv(afd);
6208 					/* To ensure that the fd cache won't be used
6209 					 * and we'll catch a real RD event.
6210 					 */
6211 					fd_cant_recv(afd);
6212 				}
6213 				tasklet_free(ctx->wait_event.tasklet);
6214 				pool_free(ssl_sock_ctx_pool, ctx);
6215 				_HA_ATOMIC_ADD(&jobs, 1);
6216 				return;
6217 			}
6218 			/* Else we can remove the fds from the fdtab
6219 			 * and call SSL_free.
6220 			 * note: we do a fd_remove and not a delete
6221 			 * because the fd is  owned by the engine.
6222 			 * the engine is responsible to close
6223 			 */
6224 			for (i=0 ; i < num_all_fds ; i++)
6225 				fd_remove(all_fd[i]);
6226 		}
6227 #endif
6228 		SSL_free(ctx->ssl);
6229 		b_free(&ctx->early_buf);
6230 		tasklet_free(ctx->wait_event.tasklet);
6231 		pool_free(ssl_sock_ctx_pool, ctx);
6232 		_HA_ATOMIC_SUB(&sslconns, 1);
6233 	}
6234 }
6235 
6236 /* This function tries to perform a clean shutdown on an SSL connection, and in
6237  * any case, flags the connection as reusable if no handshake was in progress.
6238  */
6239 static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
6240 {
6241 	struct ssl_sock_ctx *ctx = xprt_ctx;
6242 
6243 	if (conn->flags & CO_FL_HANDSHAKE)
6244 		return;
6245 	if (!clean)
6246 		/* don't sent notify on SSL_shutdown */
6247 		SSL_set_quiet_shutdown(ctx->ssl, 1);
6248 	/* no handshake was in progress, try a clean ssl shutdown */
6249 	if (SSL_shutdown(ctx->ssl) <= 0) {
6250 		/* Clear openssl global errors stack */
6251 		ssl_sock_dump_errors(conn);
6252 		ERR_clear_error();
6253 	}
6254 }
6255 
6256 /* used for ppv2 pkey alog (can be used for logging) */
6257 int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6258 {
6259 	struct ssl_sock_ctx *ctx;
6260 	struct pkey_info *pkinfo;
6261 	int bits = 0;
6262 	int sig = TLSEXT_signature_anonymous;
6263 	int len = -1;
6264 
6265 	if (!ssl_sock_is_ssl(conn))
6266 		return 0;
6267 	ctx = conn->xprt_ctx;
6268 	pkinfo = SSL_CTX_get_ex_data(SSL_get_SSL_CTX(ctx->ssl), ssl_pkey_info_index);
6269 	if (pkinfo) {
6270 		sig = pkinfo->sig;
6271 		bits = pkinfo->bits;
6272 	} else {
6273 		/* multicert and generated cert have no pkey info */
6274 		X509 *crt;
6275 		EVP_PKEY *pkey;
6276 		crt = SSL_get_certificate(ctx->ssl);
6277 		if (!crt)
6278 			return 0;
6279 		pkey = X509_get_pubkey(crt);
6280 		if (pkey) {
6281 			bits = EVP_PKEY_bits(pkey);
6282 			switch(EVP_PKEY_base_id(pkey)) {
6283 			case EVP_PKEY_RSA:
6284 				sig = TLSEXT_signature_rsa;
6285 				break;
6286 			case EVP_PKEY_EC:
6287 				sig = TLSEXT_signature_ecdsa;
6288 				break;
6289 			case EVP_PKEY_DSA:
6290 				sig = TLSEXT_signature_dsa;
6291 				break;
6292 			}
6293 			EVP_PKEY_free(pkey);
6294 		}
6295 	}
6296 
6297 	switch(sig) {
6298 	case TLSEXT_signature_rsa:
6299 		len = chunk_printf(out, "RSA%d", bits);
6300 		break;
6301 	case TLSEXT_signature_ecdsa:
6302 		len = chunk_printf(out, "EC%d", bits);
6303 		break;
6304 	case TLSEXT_signature_dsa:
6305 		len = chunk_printf(out, "DSA%d", bits);
6306 		break;
6307 	default:
6308 		return 0;
6309 	}
6310 	if (len < 0)
6311 		return 0;
6312 	return 1;
6313 }
6314 
6315 /* used for ppv2 cert signature (can be used for logging) */
6316 const char *ssl_sock_get_cert_sig(struct connection *conn)
6317 {
6318 	struct ssl_sock_ctx *ctx;
6319 
6320 	__OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6321 	X509 *crt;
6322 
6323 	if (!ssl_sock_is_ssl(conn))
6324 		return NULL;
6325 	ctx = conn->xprt_ctx;
6326 	crt = SSL_get_certificate(ctx->ssl);
6327 	if (!crt)
6328 		return NULL;
6329 	X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6330 	return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6331 }
6332 
6333 /* used for ppv2 authority */
6334 const char *ssl_sock_get_sni(struct connection *conn)
6335 {
6336 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
6337 	struct ssl_sock_ctx *ctx;
6338 
6339 	if (!ssl_sock_is_ssl(conn))
6340 		return NULL;
6341 	ctx = conn->xprt_ctx;
6342 	return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
6343 #else
6344 	return NULL;
6345 #endif
6346 }
6347 
6348 /* used for logging/ppv2, may be changed for a sample fetch later */
6349 const char *ssl_sock_get_cipher_name(struct connection *conn)
6350 {
6351 	struct ssl_sock_ctx *ctx;
6352 
6353 	if (!ssl_sock_is_ssl(conn))
6354 		return NULL;
6355 	ctx = conn->xprt_ctx;
6356 	return SSL_get_cipher_name(ctx->ssl);
6357 }
6358 
6359 /* used for logging/ppv2, may be changed for a sample fetch later */
6360 const char *ssl_sock_get_proto_version(struct connection *conn)
6361 {
6362 	struct ssl_sock_ctx *ctx;
6363 
6364 	if (!ssl_sock_is_ssl(conn))
6365 		return NULL;
6366 	ctx = conn->xprt_ctx;
6367 	return SSL_get_version(ctx->ssl);
6368 }
6369 
6370 /* Extract a serial from a cert, and copy it to a chunk.
6371  * Returns 1 if serial is found and copied, 0 if no serial found and
6372  * -1 if output is not large enough.
6373  */
6374 static int
6375 ssl_sock_get_serial(X509 *crt, struct buffer *out)
6376 {
6377 	ASN1_INTEGER *serial;
6378 
6379 	serial = X509_get_serialNumber(crt);
6380 	if (!serial)
6381 		return 0;
6382 
6383 	if (out->size < serial->length)
6384 		return -1;
6385 
6386 	memcpy(out->area, serial->data, serial->length);
6387 	out->data = serial->length;
6388 	return 1;
6389 }
6390 
6391 /* Extract a cert to der, and copy it to a chunk.
6392  * Returns 1 if the cert is found and copied, 0 on der conversion failure
6393  * and -1 if the output is not large enough.
6394  */
6395 static int
6396 ssl_sock_crt2der(X509 *crt, struct buffer *out)
6397 {
6398 	int len;
6399 	unsigned char *p = (unsigned char *) out->area;;
6400 
6401 	len =i2d_X509(crt, NULL);
6402 	if (len <= 0)
6403 		return 1;
6404 
6405 	if (out->size < len)
6406 		return -1;
6407 
6408 	i2d_X509(crt,&p);
6409 	out->data = len;
6410 	return 1;
6411 }
6412 
6413 
6414 /* Copy Date in ASN1_UTCTIME format in struct buffer out.
6415  * Returns 1 if serial is found and copied, 0 if no valid time found
6416  * and -1 if output is not large enough.
6417  */
6418 static int
6419 ssl_sock_get_time(ASN1_TIME *tm, struct buffer *out)
6420 {
6421 	if (tm->type == V_ASN1_GENERALIZEDTIME) {
6422 		ASN1_GENERALIZEDTIME *gentm = (ASN1_GENERALIZEDTIME *)tm;
6423 
6424 		if (gentm->length < 12)
6425 			return 0;
6426 		if (gentm->data[0] != 0x32 || gentm->data[1] != 0x30)
6427 			return 0;
6428 		if (out->size < gentm->length-2)
6429 			return -1;
6430 
6431 		memcpy(out->area, gentm->data+2, gentm->length-2);
6432 		out->data = gentm->length-2;
6433 		return 1;
6434 	}
6435 	else if (tm->type == V_ASN1_UTCTIME) {
6436 		ASN1_UTCTIME *utctm = (ASN1_UTCTIME *)tm;
6437 
6438 		if (utctm->length < 10)
6439 			return 0;
6440 		if (utctm->data[0] >= 0x35)
6441 			return 0;
6442 		if (out->size < utctm->length)
6443 			return -1;
6444 
6445 		memcpy(out->area, utctm->data, utctm->length);
6446 		out->data = utctm->length;
6447 		return 1;
6448 	}
6449 
6450 	return 0;
6451 }
6452 
6453 /* Extract an entry from a X509_NAME and copy its value to an output chunk.
6454  * Returns 1 if entry found, 0 if entry not found, or -1 if output not large enough.
6455  */
6456 static int
6457 ssl_sock_get_dn_entry(X509_NAME *a, const struct buffer *entry, int pos,
6458 		      struct buffer *out)
6459 {
6460 	X509_NAME_ENTRY *ne;
6461 	ASN1_OBJECT *obj;
6462 	ASN1_STRING *data;
6463 	const unsigned char *data_ptr;
6464 	int data_len;
6465 	int i, j, n;
6466 	int cur = 0;
6467 	const char *s;
6468 	char tmp[128];
6469 	int name_count;
6470 
6471 	name_count = X509_NAME_entry_count(a);
6472 
6473 	out->data = 0;
6474 	for (i = 0; i < name_count; i++) {
6475 		if (pos < 0)
6476 			j = (name_count-1) - i;
6477 		else
6478 			j = i;
6479 
6480 		ne = X509_NAME_get_entry(a, j);
6481 		obj = X509_NAME_ENTRY_get_object(ne);
6482 		data = X509_NAME_ENTRY_get_data(ne);
6483 		data_ptr = ASN1_STRING_get0_data(data);
6484 		data_len = ASN1_STRING_length(data);
6485 		n = OBJ_obj2nid(obj);
6486 		if ((n == NID_undef) || ((s = OBJ_nid2sn(n)) == NULL)) {
6487 			i2t_ASN1_OBJECT(tmp, sizeof(tmp), obj);
6488 			s = tmp;
6489 		}
6490 
6491 		if (chunk_strcasecmp(entry, s) != 0)
6492 			continue;
6493 
6494 		if (pos < 0)
6495 			cur--;
6496 		else
6497 			cur++;
6498 
6499 		if (cur != pos)
6500 			continue;
6501 
6502 		if (data_len > out->size)
6503 			return -1;
6504 
6505 		memcpy(out->area, data_ptr, data_len);
6506 		out->data = data_len;
6507 		return 1;
6508 	}
6509 
6510 	return 0;
6511 
6512 }
6513 
6514 /* Extract and format full DN from a X509_NAME and copy result into a chunk
6515  * Returns 1 if dn entries exits, 0 if no dn entry found or -1 if output is not large enough.
6516  */
6517 static int
6518 ssl_sock_get_dn_oneline(X509_NAME *a, struct buffer *out)
6519 {
6520 	X509_NAME_ENTRY *ne;
6521 	ASN1_OBJECT *obj;
6522 	ASN1_STRING *data;
6523 	const unsigned char *data_ptr;
6524 	int data_len;
6525 	int i, n, ln;
6526 	int l = 0;
6527 	const char *s;
6528 	char *p;
6529 	char tmp[128];
6530 	int name_count;
6531 
6532 
6533 	name_count = X509_NAME_entry_count(a);
6534 
6535 	out->data = 0;
6536 	p = out->area;
6537 	for (i = 0; i < name_count; i++) {
6538 		ne = X509_NAME_get_entry(a, i);
6539 		obj = X509_NAME_ENTRY_get_object(ne);
6540 		data = X509_NAME_ENTRY_get_data(ne);
6541 		data_ptr = ASN1_STRING_get0_data(data);
6542 		data_len = ASN1_STRING_length(data);
6543 		n = OBJ_obj2nid(obj);
6544 		if ((n == NID_undef) || ((s = OBJ_nid2sn(n)) == NULL)) {
6545 			i2t_ASN1_OBJECT(tmp, sizeof(tmp), obj);
6546 			s = tmp;
6547 		}
6548 		ln = strlen(s);
6549 
6550 		l += 1 + ln + 1 + data_len;
6551 		if (l > out->size)
6552 			return -1;
6553 		out->data = l;
6554 
6555 		*(p++)='/';
6556 		memcpy(p, s, ln);
6557 		p += ln;
6558 		*(p++)='=';
6559 		memcpy(p, data_ptr, data_len);
6560 		p += data_len;
6561 	}
6562 
6563 	if (!out->data)
6564 		return 0;
6565 
6566 	return 1;
6567 }
6568 
6569 void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6570 {
6571 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
6572 	struct ssl_sock_ctx *ctx;
6573 
6574 	if (!ssl_sock_is_ssl(conn))
6575 		return;
6576 	ctx = conn->xprt_ctx;
6577 	SSL_set_alpn_protos(ctx->ssl, alpn, len);
6578 #endif
6579 }
6580 
6581 /* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6582  * to disable SNI.
6583  */
6584 void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6585 {
6586 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
6587 	struct ssl_sock_ctx *ctx;
6588 	struct server *s;
6589 	char *prev_name;
6590 
6591 	if (!ssl_sock_is_ssl(conn))
6592 		return;
6593 	ctx = conn->xprt_ctx;
6594 	s = __objt_server(conn->target);
6595 
6596 	/* if the SNI changes, we must destroy the reusable context so that a
6597 	 * new connection will present a new SNI. compare with the SNI
6598 	 * previously stored in the reused_sess */
6599 	/* the RWLOCK is used to ensure that we are not trying to flush the
6600 	 * cache from the CLI */
6601 
6602 	prev_name = s->ssl_ctx.reused_sess[tid].sni;
6603 	if ((!prev_name && hostname) ||
6604 	    (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
6605 		SSL_set_session(ctx->ssl, NULL);
6606 
6607 	SSL_set_tlsext_host_name(ctx->ssl, hostname);
6608 #endif
6609 }
6610 
6611 /* Extract peer certificate's common name into the chunk dest
6612  * Returns
6613  *  the len of the extracted common name
6614  *  or 0 if no CN found in DN
6615  *  or -1 on error case (i.e. no peer certificate)
6616  */
6617 int ssl_sock_get_remote_common_name(struct connection *conn,
6618 				    struct buffer *dest)
6619 {
6620 	struct ssl_sock_ctx *ctx;
6621 	X509 *crt = NULL;
6622 	X509_NAME *name;
6623 	const char find_cn[] = "CN";
6624 	const struct buffer find_cn_chunk = {
6625 		.area = (char *)&find_cn,
6626 		.data = sizeof(find_cn)-1
6627 	};
6628 	int result = -1;
6629 
6630 	if (!ssl_sock_is_ssl(conn))
6631 		goto out;
6632 	ctx = conn->xprt_ctx;
6633 
6634 	/* SSL_get_peer_certificate, it increase X509 * ref count */
6635 	crt = SSL_get_peer_certificate(ctx->ssl);
6636 	if (!crt)
6637 		goto out;
6638 
6639 	name = X509_get_subject_name(crt);
6640 	if (!name)
6641 		goto out;
6642 
6643 	result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6644 out:
6645 	if (crt)
6646 		X509_free(crt);
6647 
6648 	return result;
6649 }
6650 
6651 /* returns 1 if client passed a certificate for this session, 0 if not */
6652 int ssl_sock_get_cert_used_sess(struct connection *conn)
6653 {
6654 	struct ssl_sock_ctx *ctx;
6655 	X509 *crt = NULL;
6656 
6657 	if (!ssl_sock_is_ssl(conn))
6658 		return 0;
6659 	ctx = conn->xprt_ctx;
6660 
6661 	/* SSL_get_peer_certificate, it increase X509 * ref count */
6662 	crt = SSL_get_peer_certificate(ctx->ssl);
6663 	if (!crt)
6664 		return 0;
6665 
6666 	X509_free(crt);
6667 	return 1;
6668 }
6669 
6670 /* returns 1 if client passed a certificate for this connection, 0 if not */
6671 int ssl_sock_get_cert_used_conn(struct connection *conn)
6672 {
6673 	struct ssl_sock_ctx *ctx;
6674 
6675 	if (!ssl_sock_is_ssl(conn))
6676 		return 0;
6677 	ctx = conn->xprt_ctx;
6678 	return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
6679 }
6680 
6681 /* returns result from SSL verify */
6682 unsigned int ssl_sock_get_verify_result(struct connection *conn)
6683 {
6684 	struct ssl_sock_ctx *ctx;
6685 
6686 	if (!ssl_sock_is_ssl(conn))
6687 		return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
6688 	ctx = conn->xprt_ctx;
6689 	return (unsigned int)SSL_get_verify_result(ctx->ssl);
6690 }
6691 
6692 /* Returns the application layer protocol name in <str> and <len> when known.
6693  * Zero is returned if the protocol name was not found, otherwise non-zero is
6694  * returned. The string is allocated in the SSL context and doesn't have to be
6695  * freed by the caller. NPN is also checked if available since older versions
6696  * of openssl (1.0.1) which are more common in field only support this one.
6697  */
6698 static int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
6699 {
6700 #if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6701 	defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
6702 	struct ssl_sock_ctx *ctx = xprt_ctx;
6703 	if (!ctx)
6704 		return 0;
6705 
6706 	*str = NULL;
6707 
6708 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
6709 	SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
6710 	if (*str)
6711 		return 1;
6712 #endif
6713 #if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
6714 	SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
6715 	if (*str)
6716 		return 1;
6717 #endif
6718 #endif
6719 	return 0;
6720 }
6721 
6722 /***** Below are some sample fetching functions for ACL/patterns *****/
6723 
6724 static int
6725 smp_fetch_ssl_fc_has_early(const struct arg *args, struct sample *smp, const char *kw, void *private)
6726 {
6727 	struct connection *conn;
6728 
6729 	conn = objt_conn(smp->sess->origin);
6730 	if (!conn || conn->xprt != &ssl_sock)
6731 		return 0;
6732 
6733 	smp->flags = 0;
6734 	smp->data.type = SMP_T_BOOL;
6735 #ifdef OPENSSL_IS_BORINGSSL
6736 	{
6737 		struct ssl_sock_ctx *ctx = conn->xprt_ctx;
6738 		smp->data.u.sint = (SSL_in_early_data(ctx->ssl) &&
6739 				    SSL_early_data_accepted(ctx->ssl));
6740 	}
6741 #else
6742 	smp->data.u.sint = ((conn->flags & CO_FL_EARLY_DATA)  &&
6743 	    (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS))) ? 1 : 0;
6744 #endif
6745 	return 1;
6746 }
6747 
6748 /* boolean, returns true if client cert was present */
6749 static int
6750 smp_fetch_ssl_fc_has_crt(const struct arg *args, struct sample *smp, const char *kw, void *private)
6751 {
6752 	struct connection *conn;
6753 	struct ssl_sock_ctx *ctx;
6754 
6755 	conn = objt_conn(smp->sess->origin);
6756 	if (!conn || conn->xprt != &ssl_sock)
6757 		return 0;
6758 
6759 	ctx = conn->xprt_ctx;
6760 
6761 	if (!(conn->flags & CO_FL_CONNECTED)) {
6762 		smp->flags |= SMP_F_MAY_CHANGE;
6763 		return 0;
6764 	}
6765 
6766 	smp->flags = 0;
6767 	smp->data.type = SMP_T_BOOL;
6768 	smp->data.u.sint = SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
6769 
6770 	return 1;
6771 }
6772 
6773 /* binary, returns a certificate in a binary chunk (der/raw).
6774  * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
6775  * should be use.
6776  */
6777 static int
6778 smp_fetch_ssl_x_der(const struct arg *args, struct sample *smp, const char *kw, void *private)
6779 {
6780 	int cert_peer = (kw[4] == 'c') ? 1 : 0;
6781 	X509 *crt = NULL;
6782 	int ret = 0;
6783 	struct buffer *smp_trash;
6784 	struct connection *conn;
6785 	struct ssl_sock_ctx *ctx;
6786 
6787 	conn = objt_conn(smp->sess->origin);
6788 	if (!conn || conn->xprt != &ssl_sock)
6789 		return 0;
6790 	ctx = conn->xprt_ctx;
6791 
6792 	if (!(conn->flags & CO_FL_CONNECTED)) {
6793 		smp->flags |= SMP_F_MAY_CHANGE;
6794 		return 0;
6795 	}
6796 
6797 	if (cert_peer)
6798 		crt = SSL_get_peer_certificate(ctx->ssl);
6799 	else
6800 		crt = SSL_get_certificate(ctx->ssl);
6801 
6802 	if (!crt)
6803 		goto out;
6804 
6805 	smp_trash = get_trash_chunk();
6806 	if (ssl_sock_crt2der(crt, smp_trash) <= 0)
6807 		goto out;
6808 
6809 	smp->data.u.str = *smp_trash;
6810 	smp->data.type = SMP_T_BIN;
6811 	ret = 1;
6812 out:
6813 	/* SSL_get_peer_certificate, it increase X509 * ref count */
6814 	if (cert_peer && crt)
6815 		X509_free(crt);
6816 	return ret;
6817 }
6818 
6819 /* binary, returns serial of certificate in a binary chunk.
6820  * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
6821  * should be use.
6822  */
6823 static int
6824 smp_fetch_ssl_x_serial(const struct arg *args, struct sample *smp, const char *kw, void *private)
6825 {
6826 	int cert_peer = (kw[4] == 'c') ? 1 : 0;
6827 	X509 *crt = NULL;
6828 	int ret = 0;
6829 	struct buffer *smp_trash;
6830 	struct connection *conn;
6831 	struct ssl_sock_ctx *ctx;
6832 
6833 	conn = objt_conn(smp->sess->origin);
6834 	if (!conn || conn->xprt != &ssl_sock)
6835 		return 0;
6836 
6837 	ctx = conn->xprt_ctx;
6838 
6839 	if (!(conn->flags & CO_FL_CONNECTED)) {
6840 		smp->flags |= SMP_F_MAY_CHANGE;
6841 		return 0;
6842 	}
6843 
6844 	if (cert_peer)
6845 		crt = SSL_get_peer_certificate(ctx->ssl);
6846 	else
6847 		crt = SSL_get_certificate(ctx->ssl);
6848 
6849 	if (!crt)
6850 		goto out;
6851 
6852 	smp_trash = get_trash_chunk();
6853 	if (ssl_sock_get_serial(crt, smp_trash) <= 0)
6854 		goto out;
6855 
6856 	smp->data.u.str = *smp_trash;
6857 	smp->data.type = SMP_T_BIN;
6858 	ret = 1;
6859 out:
6860 	/* SSL_get_peer_certificate, it increase X509 * ref count */
6861 	if (cert_peer && crt)
6862 		X509_free(crt);
6863 	return ret;
6864 }
6865 
6866 /* binary, returns the client certificate's SHA-1 fingerprint (SHA-1 hash of DER-encoded certificate) in a binary chunk.
6867  * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
6868  * should be use.
6869  */
6870 static int
6871 smp_fetch_ssl_x_sha1(const struct arg *args, struct sample *smp, const char *kw, void *private)
6872 {
6873 	int cert_peer = (kw[4] == 'c') ? 1 : 0;
6874 	X509 *crt = NULL;
6875 	const EVP_MD *digest;
6876 	int ret = 0;
6877 	unsigned int len = 0;
6878 	struct buffer *smp_trash;
6879 	struct connection *conn;
6880 	struct ssl_sock_ctx *ctx;
6881 
6882 	conn = objt_conn(smp->sess->origin);
6883 	if (!conn || conn->xprt != &ssl_sock)
6884 		return 0;
6885 	ctx = conn->xprt_ctx;
6886 
6887 	if (!(conn->flags & CO_FL_CONNECTED)) {
6888 		smp->flags |= SMP_F_MAY_CHANGE;
6889 		return 0;
6890 	}
6891 
6892 	if (cert_peer)
6893 		crt = SSL_get_peer_certificate(ctx->ssl);
6894 	else
6895 		crt = SSL_get_certificate(ctx->ssl);
6896 	if (!crt)
6897 		goto out;
6898 
6899 	smp_trash = get_trash_chunk();
6900 	digest = EVP_sha1();
6901 	X509_digest(crt, digest, (unsigned char *) smp_trash->area, &len);
6902 	smp_trash->data = len;
6903 	smp->data.u.str = *smp_trash;
6904 	smp->data.type = SMP_T_BIN;
6905 	ret = 1;
6906 out:
6907 	/* SSL_get_peer_certificate, it increase X509 * ref count */
6908 	if (cert_peer && crt)
6909 		X509_free(crt);
6910 	return ret;
6911 }
6912 
6913 /* string, returns certificate's notafter date in ASN1_UTCTIME format.
6914  * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
6915  * should be use.
6916  */
6917 static int
6918 smp_fetch_ssl_x_notafter(const struct arg *args, struct sample *smp, const char *kw, void *private)
6919 {
6920 	int cert_peer = (kw[4] == 'c') ? 1 : 0;
6921 	X509 *crt = NULL;
6922 	int ret = 0;
6923 	struct buffer *smp_trash;
6924 	struct connection *conn;
6925 	struct ssl_sock_ctx *ctx;
6926 
6927 	conn = objt_conn(smp->sess->origin);
6928 	if (!conn || conn->xprt != &ssl_sock)
6929 		return 0;
6930 	ctx = conn->xprt_ctx;
6931 
6932 	if (!(conn->flags & CO_FL_CONNECTED)) {
6933 		smp->flags |= SMP_F_MAY_CHANGE;
6934 		return 0;
6935 	}
6936 
6937 	if (cert_peer)
6938 		crt = SSL_get_peer_certificate(ctx->ssl);
6939 	else
6940 		crt = SSL_get_certificate(ctx->ssl);
6941 	if (!crt)
6942 		goto out;
6943 
6944 	smp_trash = get_trash_chunk();
6945 	if (ssl_sock_get_time(X509_getm_notAfter(crt), smp_trash) <= 0)
6946 		goto out;
6947 
6948 	smp->data.u.str = *smp_trash;
6949 	smp->data.type = SMP_T_STR;
6950 	ret = 1;
6951 out:
6952 	/* SSL_get_peer_certificate, it increase X509 * ref count */
6953 	if (cert_peer && crt)
6954 		X509_free(crt);
6955 	return ret;
6956 }
6957 
6958 /* string, returns a string of a formatted full dn \C=..\O=..\OU=.. \CN=.. of certificate's issuer
6959  * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
6960  * should be use.
6961  */
6962 static int
6963 smp_fetch_ssl_x_i_dn(const struct arg *args, struct sample *smp, const char *kw, void *private)
6964 {
6965 	int cert_peer = (kw[4] == 'c') ? 1 : 0;
6966 	X509 *crt = NULL;
6967 	X509_NAME *name;
6968 	int ret = 0;
6969 	struct buffer *smp_trash;
6970 	struct connection *conn;
6971 	struct ssl_sock_ctx *ctx;
6972 
6973 	conn = objt_conn(smp->sess->origin);
6974 	if (!conn || conn->xprt != &ssl_sock)
6975 		return 0;
6976 	ctx = conn->xprt_ctx;
6977 
6978 	if (!(conn->flags & CO_FL_CONNECTED)) {
6979 		smp->flags |= SMP_F_MAY_CHANGE;
6980 		return 0;
6981 	}
6982 
6983 	if (cert_peer)
6984 		crt = SSL_get_peer_certificate(ctx->ssl);
6985 	else
6986 		crt = SSL_get_certificate(ctx->ssl);
6987 	if (!crt)
6988 		goto out;
6989 
6990 	name = X509_get_issuer_name(crt);
6991 	if (!name)
6992 		goto out;
6993 
6994 	smp_trash = get_trash_chunk();
6995 	if (args && args[0].type == ARGT_STR) {
6996 		int pos = 1;
6997 
6998 		if (args[1].type == ARGT_SINT)
6999 			pos = args[1].data.sint;
7000 
7001 		if (ssl_sock_get_dn_entry(name, &args[0].data.str, pos, smp_trash) <= 0)
7002 			goto out;
7003 	}
7004 	else if (ssl_sock_get_dn_oneline(name, smp_trash) <= 0)
7005 		goto out;
7006 
7007 	smp->data.type = SMP_T_STR;
7008 	smp->data.u.str = *smp_trash;
7009 	ret = 1;
7010 out:
7011 	/* SSL_get_peer_certificate, it increase X509 * ref count */
7012 	if (cert_peer && crt)
7013 		X509_free(crt);
7014 	return ret;
7015 }
7016 
7017 /* string, returns notbefore date in ASN1_UTCTIME format.
7018  * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
7019  * should be use.
7020  */
7021 static int
7022 smp_fetch_ssl_x_notbefore(const struct arg *args, struct sample *smp, const char *kw, void *private)
7023 {
7024 	int cert_peer = (kw[4] == 'c') ? 1 : 0;
7025 	X509 *crt = NULL;
7026 	int ret = 0;
7027 	struct buffer *smp_trash;
7028 	struct connection *conn;
7029 	struct ssl_sock_ctx *ctx;
7030 
7031 	conn = objt_conn(smp->sess->origin);
7032 	if (!conn || conn->xprt != &ssl_sock)
7033 		return 0;
7034 	ctx = conn->xprt_ctx;
7035 
7036 	if (!(conn->flags & CO_FL_CONNECTED)) {
7037 		smp->flags |= SMP_F_MAY_CHANGE;
7038 		return 0;
7039 	}
7040 
7041 	if (cert_peer)
7042 		crt = SSL_get_peer_certificate(ctx->ssl);
7043 	else
7044 		crt = SSL_get_certificate(ctx->ssl);
7045 	if (!crt)
7046 		goto out;
7047 
7048 	smp_trash = get_trash_chunk();
7049 	if (ssl_sock_get_time(X509_getm_notBefore(crt), smp_trash) <= 0)
7050 		goto out;
7051 
7052 	smp->data.u.str = *smp_trash;
7053 	smp->data.type = SMP_T_STR;
7054 	ret = 1;
7055 out:
7056 	/* SSL_get_peer_certificate, it increase X509 * ref count */
7057 	if (cert_peer && crt)
7058 		X509_free(crt);
7059 	return ret;
7060 }
7061 
7062 /* string, returns a string of a formatted full dn \C=..\O=..\OU=.. \CN=.. of certificate's subject
7063  * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
7064  * should be use.
7065  */
7066 static int
7067 smp_fetch_ssl_x_s_dn(const struct arg *args, struct sample *smp, const char *kw, void *private)
7068 {
7069 	int cert_peer = (kw[4] == 'c') ? 1 : 0;
7070 	X509 *crt = NULL;
7071 	X509_NAME *name;
7072 	int ret = 0;
7073 	struct buffer *smp_trash;
7074 	struct connection *conn;
7075 	struct ssl_sock_ctx *ctx;
7076 
7077 	conn = objt_conn(smp->sess->origin);
7078 	if (!conn || conn->xprt != &ssl_sock)
7079 		return 0;
7080 	ctx = conn->xprt_ctx;
7081 
7082 	if (!(conn->flags & CO_FL_CONNECTED)) {
7083 		smp->flags |= SMP_F_MAY_CHANGE;
7084 		return 0;
7085 	}
7086 
7087 	if (cert_peer)
7088 		crt = SSL_get_peer_certificate(ctx->ssl);
7089 	else
7090 		crt = SSL_get_certificate(ctx->ssl);
7091 	if (!crt)
7092 		goto out;
7093 
7094 	name = X509_get_subject_name(crt);
7095 	if (!name)
7096 		goto out;
7097 
7098 	smp_trash = get_trash_chunk();
7099 	if (args && args[0].type == ARGT_STR) {
7100 		int pos = 1;
7101 
7102 		if (args[1].type == ARGT_SINT)
7103 			pos = args[1].data.sint;
7104 
7105 		if (ssl_sock_get_dn_entry(name, &args[0].data.str, pos, smp_trash) <= 0)
7106 			goto out;
7107 	}
7108 	else if (ssl_sock_get_dn_oneline(name, smp_trash) <= 0)
7109 		goto out;
7110 
7111 	smp->data.type = SMP_T_STR;
7112 	smp->data.u.str = *smp_trash;
7113 	ret = 1;
7114 out:
7115 	/* SSL_get_peer_certificate, it increase X509 * ref count */
7116 	if (cert_peer && crt)
7117 		X509_free(crt);
7118 	return ret;
7119 }
7120 
7121 /* integer, returns true if current session use a client certificate */
7122 static int
7123 smp_fetch_ssl_c_used(const struct arg *args, struct sample *smp, const char *kw, void *private)
7124 {
7125 	X509 *crt;
7126 	struct connection *conn;
7127 	struct ssl_sock_ctx *ctx;
7128 
7129 	conn = objt_conn(smp->sess->origin);
7130 	if (!conn || conn->xprt != &ssl_sock)
7131 		return 0;
7132 	ctx = conn->xprt_ctx;
7133 
7134 	if (!(conn->flags & CO_FL_CONNECTED)) {
7135 		smp->flags |= SMP_F_MAY_CHANGE;
7136 		return 0;
7137 	}
7138 
7139 	/* SSL_get_peer_certificate returns a ptr on allocated X509 struct */
7140 	crt = SSL_get_peer_certificate(ctx->ssl);
7141 	if (crt) {
7142 		X509_free(crt);
7143 	}
7144 
7145 	smp->data.type = SMP_T_BOOL;
7146 	smp->data.u.sint = (crt != NULL);
7147 	return 1;
7148 }
7149 
7150 /* integer, returns the certificate version
7151  * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
7152  * should be use.
7153  */
7154 static int
7155 smp_fetch_ssl_x_version(const struct arg *args, struct sample *smp, const char *kw, void *private)
7156 {
7157 	int cert_peer = (kw[4] == 'c') ? 1 : 0;
7158 	X509 *crt;
7159 	struct connection *conn;
7160 	struct ssl_sock_ctx *ctx;
7161 
7162 	conn = objt_conn(smp->sess->origin);
7163 	if (!conn || conn->xprt != &ssl_sock)
7164 		return 0;
7165 	ctx = conn->xprt_ctx;
7166 
7167 	if (!(conn->flags & CO_FL_CONNECTED)) {
7168 		smp->flags |= SMP_F_MAY_CHANGE;
7169 		return 0;
7170 	}
7171 
7172 	if (cert_peer)
7173 		crt = SSL_get_peer_certificate(ctx->ssl);
7174 	else
7175 		crt = SSL_get_certificate(ctx->ssl);
7176 	if (!crt)
7177 		return 0;
7178 
7179 	smp->data.u.sint = (unsigned int)(1 + X509_get_version(crt));
7180 	/* SSL_get_peer_certificate increase X509 * ref count  */
7181 	if (cert_peer)
7182 		X509_free(crt);
7183 	smp->data.type = SMP_T_SINT;
7184 
7185 	return 1;
7186 }
7187 
7188 /* string, returns the certificate's signature algorithm.
7189  * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
7190  * should be use.
7191  */
7192 static int
7193 smp_fetch_ssl_x_sig_alg(const struct arg *args, struct sample *smp, const char *kw, void *private)
7194 {
7195 	int cert_peer = (kw[4] == 'c') ? 1 : 0;
7196 	X509 *crt;
7197 	__OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
7198 	int nid;
7199 	struct connection *conn;
7200 	struct ssl_sock_ctx *ctx;
7201 
7202 	conn = objt_conn(smp->sess->origin);
7203 	if (!conn || conn->xprt != &ssl_sock)
7204 		return 0;
7205 	ctx = conn->xprt_ctx;
7206 
7207 	if (!(conn->flags & CO_FL_CONNECTED)) {
7208 		smp->flags |= SMP_F_MAY_CHANGE;
7209 		return 0;
7210 	}
7211 
7212 	if (cert_peer)
7213 		crt = SSL_get_peer_certificate(ctx->ssl);
7214 	else
7215 		crt = SSL_get_certificate(ctx->ssl);
7216 	if (!crt)
7217 		return 0;
7218 
7219 	X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
7220 	nid = OBJ_obj2nid(algorithm);
7221 
7222 	smp->data.u.str.area = (char *)OBJ_nid2sn(nid);
7223 	if (!smp->data.u.str.area) {
7224 		/* SSL_get_peer_certificate increase X509 * ref count  */
7225 		if (cert_peer)
7226 			X509_free(crt);
7227 		return 0;
7228 	}
7229 
7230 	smp->data.type = SMP_T_STR;
7231 	smp->flags |= SMP_F_CONST;
7232 	smp->data.u.str.data = strlen(smp->data.u.str.area);
7233 	/* SSL_get_peer_certificate increase X509 * ref count  */
7234 	if (cert_peer)
7235 		X509_free(crt);
7236 
7237 	return 1;
7238 }
7239 
7240 /* string, returns the certificate's key algorithm.
7241  * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
7242  * should be use.
7243  */
7244 static int
7245 smp_fetch_ssl_x_key_alg(const struct arg *args, struct sample *smp, const char *kw, void *private)
7246 {
7247 	int cert_peer = (kw[4] == 'c') ? 1 : 0;
7248 	X509 *crt;
7249 	ASN1_OBJECT *algorithm;
7250 	int nid;
7251 	struct connection *conn;
7252 	struct ssl_sock_ctx *ctx;
7253 
7254 	conn = objt_conn(smp->sess->origin);
7255 	if (!conn || conn->xprt != &ssl_sock)
7256 		return 0;
7257 	ctx = conn->xprt_ctx;
7258 
7259 	if (!(conn->flags & CO_FL_CONNECTED)) {
7260 		smp->flags |= SMP_F_MAY_CHANGE;
7261 		return 0;
7262 	}
7263 
7264 	if (cert_peer)
7265 		crt = SSL_get_peer_certificate(ctx->ssl);
7266 	else
7267 		crt = SSL_get_certificate(ctx->ssl);
7268 	if (!crt)
7269 		return 0;
7270 
7271 	X509_PUBKEY_get0_param(&algorithm, NULL, NULL, NULL, X509_get_X509_PUBKEY(crt));
7272 	nid = OBJ_obj2nid(algorithm);
7273 
7274 	smp->data.u.str.area = (char *)OBJ_nid2sn(nid);
7275 	if (!smp->data.u.str.area) {
7276 		/* SSL_get_peer_certificate increase X509 * ref count  */
7277 		if (cert_peer)
7278 			X509_free(crt);
7279 		return 0;
7280 	}
7281 
7282 	smp->data.type = SMP_T_STR;
7283 	smp->flags |= SMP_F_CONST;
7284 	smp->data.u.str.data = strlen(smp->data.u.str.area);
7285 	if (cert_peer)
7286 		X509_free(crt);
7287 
7288 	return 1;
7289 }
7290 
7291 /* boolean, returns true if front conn. transport layer is SSL.
7292  * This function is also usable on backend conn if the fetch keyword 5th
7293  * char is 'b'.
7294  */
7295 static int
7296 smp_fetch_ssl_fc(const struct arg *args, struct sample *smp, const char *kw, void *private)
7297 {
7298 	struct connection *conn = (kw[4] != 'b') ? objt_conn(smp->sess->origin) :
7299 	                                    smp->strm ? cs_conn(objt_cs(smp->strm->si[1].end)) : NULL;
7300 
7301 	smp->data.type = SMP_T_BOOL;
7302 	smp->data.u.sint = (conn && conn->xprt == &ssl_sock);
7303 	return 1;
7304 }
7305 
7306 /* boolean, returns true if client present a SNI */
7307 static int
7308 smp_fetch_ssl_fc_has_sni(const struct arg *args, struct sample *smp, const char *kw, void *private)
7309 {
7310 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
7311 	struct connection *conn = objt_conn(smp->sess->origin);
7312 	struct ssl_sock_ctx *ctx = conn ? conn->xprt_ctx : NULL;
7313 
7314 	smp->data.type = SMP_T_BOOL;
7315 	smp->data.u.sint = (conn && conn->xprt == &ssl_sock) &&
7316 		conn->xprt_ctx &&
7317 		SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name) != NULL;
7318 	return 1;
7319 #else
7320 	return 0;
7321 #endif
7322 }
7323 
7324 /* boolean, returns true if client session has been resumed.
7325  * This function is also usable on backend conn if the fetch keyword 5th
7326  * char is 'b'.
7327  */
7328 static int
7329 smp_fetch_ssl_fc_is_resumed(const struct arg *args, struct sample *smp, const char *kw, void *private)
7330 {
7331 	struct connection *conn = (kw[4] != 'b') ? objt_conn(smp->sess->origin) :
7332 	                                    smp->strm ? cs_conn(objt_cs(smp->strm->si[1].end)) : NULL;
7333 	struct ssl_sock_ctx *ctx = conn ? conn->xprt_ctx : NULL;
7334 
7335 
7336 	smp->data.type = SMP_T_BOOL;
7337 	smp->data.u.sint = (conn && conn->xprt == &ssl_sock) &&
7338 		conn->xprt_ctx &&
7339 		SSL_session_reused(ctx->ssl);
7340 	return 1;
7341 }
7342 
7343 /* string, returns the used cipher if front conn. transport layer is SSL.
7344  * This function is also usable on backend conn if the fetch keyword 5th
7345  * char is 'b'.
7346  */
7347 static int
7348 smp_fetch_ssl_fc_cipher(const struct arg *args, struct sample *smp, const char *kw, void *private)
7349 {
7350 	struct connection *conn = (kw[4] != 'b') ? objt_conn(smp->sess->origin) :
7351 	                                    smp->strm ? cs_conn(objt_cs(smp->strm->si[1].end)) : NULL;
7352 	struct ssl_sock_ctx *ctx;
7353 
7354 	smp->flags = 0;
7355 	if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
7356 		return 0;
7357 	ctx = conn->xprt_ctx;
7358 
7359 	smp->data.u.str.area = (char *)SSL_get_cipher_name(ctx->ssl);
7360 	if (!smp->data.u.str.area)
7361 		return 0;
7362 
7363 	smp->data.type = SMP_T_STR;
7364 	smp->flags |= SMP_F_CONST;
7365 	smp->data.u.str.data = strlen(smp->data.u.str.area);
7366 
7367 	return 1;
7368 }
7369 
7370 /* integer, returns the algoritm's keysize if front conn. transport layer
7371  * is SSL.
7372  * This function is also usable on backend conn if the fetch keyword 5th
7373  * char is 'b'.
7374  */
7375 static int
7376 smp_fetch_ssl_fc_alg_keysize(const struct arg *args, struct sample *smp, const char *kw, void *private)
7377 {
7378 	struct connection *conn = (kw[4] != 'b') ? objt_conn(smp->sess->origin) :
7379 	                                    smp->strm ? cs_conn(objt_cs(smp->strm->si[1].end)) : NULL;
7380 	struct ssl_sock_ctx *ctx;
7381 	int sint;
7382 
7383 	smp->flags = 0;
7384 	if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
7385 		return 0;
7386 	ctx = conn->xprt_ctx;
7387 
7388 	if (!SSL_get_cipher_bits(ctx->ssl, &sint))
7389 		return 0;
7390 
7391 	smp->data.u.sint = sint;
7392 	smp->data.type = SMP_T_SINT;
7393 
7394 	return 1;
7395 }
7396 
7397 /* integer, returns the used keysize if front conn. transport layer is SSL.
7398  * This function is also usable on backend conn if the fetch keyword 5th
7399  * char is 'b'.
7400  */
7401 static int
7402 smp_fetch_ssl_fc_use_keysize(const struct arg *args, struct sample *smp, const char *kw, void *private)
7403 {
7404 	struct connection *conn = (kw[4] != 'b') ? objt_conn(smp->sess->origin) :
7405 	                                    smp->strm ? cs_conn(objt_cs(smp->strm->si[1].end)) : NULL;
7406 	struct ssl_sock_ctx *ctx;
7407 
7408 	smp->flags = 0;
7409 	if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
7410 		return 0;
7411 	ctx = conn->xprt_ctx;
7412 
7413 	smp->data.u.sint = (unsigned int)SSL_get_cipher_bits(ctx->ssl, NULL);
7414 	if (!smp->data.u.sint)
7415 		return 0;
7416 
7417 	smp->data.type = SMP_T_SINT;
7418 
7419 	return 1;
7420 }
7421 
7422 #if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
7423 static int
7424 smp_fetch_ssl_fc_npn(const struct arg *args, struct sample *smp, const char *kw, void *private)
7425 {
7426 	struct connection *conn;
7427 	struct ssl_sock_ctx *ctx;
7428 	unsigned int len = 0;
7429 
7430 	smp->flags = SMP_F_CONST;
7431 	smp->data.type = SMP_T_STR;
7432 
7433 	conn = (kw[4] != 'b' ) ? objt_conn(smp->sess->origin) :
7434 	    smp->strm ? cs_conn(objt_cs(smp->strm->si[1].end)) : NULL;
7435 	if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
7436 		return 0;
7437 	ctx = conn->xprt_ctx;
7438 
7439 	smp->data.u.str.area = NULL;
7440 	SSL_get0_next_proto_negotiated(ctx->ssl,
7441 	                               (const unsigned char **)&smp->data.u.str.area,
7442 	                               &len);
7443 
7444 	if (!smp->data.u.str.area)
7445 		return 0;
7446 
7447 	smp->data.u.str.data = len;
7448 	return 1;
7449 }
7450 #endif
7451 
7452 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
7453 static int
7454 smp_fetch_ssl_fc_alpn(const struct arg *args, struct sample *smp, const char *kw, void *private)
7455 {
7456 	struct connection *conn;
7457 	struct ssl_sock_ctx *ctx;
7458 	unsigned int len = 0;
7459 
7460 	smp->flags = SMP_F_CONST;
7461 	smp->data.type = SMP_T_STR;
7462 
7463 	conn = (kw[4] != 'b' ) ? objt_conn(smp->sess->origin) :
7464 	    smp->strm ? cs_conn(objt_cs(smp->strm->si[1].end)) : NULL;
7465 
7466 	if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
7467 		return 0;
7468 	ctx = conn->xprt_ctx;
7469 
7470 	smp->data.u.str.area = NULL;
7471 	SSL_get0_alpn_selected(ctx->ssl,
7472 	                       (const unsigned char **)&smp->data.u.str.area,
7473 	                       &len);
7474 
7475 	if (!smp->data.u.str.area)
7476 		return 0;
7477 
7478 	smp->data.u.str.data = len;
7479 	return 1;
7480 }
7481 #endif
7482 
7483 /* string, returns the used protocol if front conn. transport layer is SSL.
7484  * This function is also usable on backend conn if the fetch keyword 5th
7485  * char is 'b'.
7486  */
7487 static int
7488 smp_fetch_ssl_fc_protocol(const struct arg *args, struct sample *smp, const char *kw, void *private)
7489 {
7490 	struct connection *conn = (kw[4] != 'b') ? objt_conn(smp->sess->origin) :
7491 	                                    smp->strm ? cs_conn(objt_cs(smp->strm->si[1].end)) : NULL;
7492 	struct ssl_sock_ctx *ctx;
7493 
7494 	smp->flags = 0;
7495 	if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
7496 		return 0;
7497 	ctx = conn->xprt_ctx;
7498 
7499 	smp->data.u.str.area = (char *)SSL_get_version(ctx->ssl);
7500 	if (!smp->data.u.str.area)
7501 		return 0;
7502 
7503 	smp->data.type = SMP_T_STR;
7504 	smp->flags = SMP_F_CONST;
7505 	smp->data.u.str.data = strlen(smp->data.u.str.area);
7506 
7507 	return 1;
7508 }
7509 
7510 /* binary, returns the SSL stream id if front conn. transport layer is SSL.
7511  * This function is also usable on backend conn if the fetch keyword 5th
7512  * char is 'b'.
7513  */
7514 #if HA_OPENSSL_VERSION_NUMBER > 0x0090800fL
7515 static int
7516 smp_fetch_ssl_fc_session_id(const struct arg *args, struct sample *smp, const char *kw, void *private)
7517 {
7518 	struct connection *conn = (kw[4] != 'b') ? objt_conn(smp->sess->origin) :
7519 	                                    smp->strm ? cs_conn(objt_cs(smp->strm->si[1].end)) : NULL;
7520 	SSL_SESSION *ssl_sess;
7521 	struct ssl_sock_ctx *ctx;
7522 	unsigned int len = 0;
7523 
7524 	smp->flags = SMP_F_CONST;
7525 	smp->data.type = SMP_T_BIN;
7526 
7527 	if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
7528 		return 0;
7529 	ctx = conn->xprt_ctx;
7530 
7531 	ssl_sess = SSL_get_session(ctx->ssl);
7532 	if (!ssl_sess)
7533 		return 0;
7534 
7535 	smp->data.u.str.area = (char *)SSL_SESSION_get_id(ssl_sess, &len);
7536 	if (!smp->data.u.str.area || !len)
7537 		return 0;
7538 
7539 	smp->data.u.str.data = len;
7540 	return 1;
7541 }
7542 #endif
7543 
7544 
7545 #if HA_OPENSSL_VERSION_NUMBER >= 0x10100000L
7546 static int
7547 smp_fetch_ssl_fc_random(const struct arg *args, struct sample *smp, const char *kw, void *private)
7548 {
7549 	struct connection *conn = (kw[4] != 'b') ? objt_conn(smp->sess->origin) :
7550 	                                           smp->strm ? cs_conn(objt_cs(smp->strm->si[1].end)) : NULL;
7551 	struct buffer *data;
7552 	struct ssl_sock_ctx *ctx;
7553 
7554 	if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
7555 		return 0;
7556 	ctx = conn->xprt_ctx;
7557 
7558 	data = get_trash_chunk();
7559 	if (kw[7] == 'c')
7560 		data->data = SSL_get_client_random(ctx->ssl,
7561 		                                   (unsigned char *) data->area,
7562 		                                   data->size);
7563 	else
7564 		data->data = SSL_get_server_random(ctx->ssl,
7565 		                                   (unsigned char *) data->area,
7566 		                                   data->size);
7567 	if (!data->data)
7568 		return 0;
7569 
7570 	smp->flags = 0;
7571 	smp->data.type = SMP_T_BIN;
7572 	smp->data.u.str = *data;
7573 
7574 	return 1;
7575 }
7576 
7577 static int
7578 smp_fetch_ssl_fc_session_key(const struct arg *args, struct sample *smp, const char *kw, void *private)
7579 {
7580 	struct connection *conn = (kw[4] != 'b') ? objt_conn(smp->sess->origin) :
7581 	                                    smp->strm ? cs_conn(objt_cs(smp->strm->si[1].end)) : NULL;
7582 	SSL_SESSION *ssl_sess;
7583 	struct buffer *data;
7584 	struct ssl_sock_ctx *ctx;
7585 
7586 	if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
7587 		return 0;
7588 	ctx = conn->xprt_ctx;
7589 
7590 	ssl_sess = SSL_get_session(ctx->ssl);
7591 	if (!ssl_sess)
7592 		return 0;
7593 
7594 	data = get_trash_chunk();
7595 	data->data = SSL_SESSION_get_master_key(ssl_sess,
7596 					       (unsigned char *) data->area,
7597 					       data->size);
7598 	if (!data->data)
7599 		return 0;
7600 
7601 	smp->flags = 0;
7602 	smp->data.type = SMP_T_BIN;
7603 	smp->data.u.str = *data;
7604 
7605 	return 1;
7606 }
7607 #endif
7608 
7609 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
7610 static int
7611 smp_fetch_ssl_fc_sni(const struct arg *args, struct sample *smp, const char *kw, void *private)
7612 {
7613 	struct connection *conn;
7614 	struct ssl_sock_ctx *ctx;
7615 
7616 	smp->flags = SMP_F_CONST;
7617 	smp->data.type = SMP_T_STR;
7618 
7619 	conn = objt_conn(smp->sess->origin);
7620 	if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
7621 		return 0;
7622 	ctx = conn->xprt_ctx;
7623 
7624 	smp->data.u.str.area = (char *)SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
7625 	if (!smp->data.u.str.area)
7626 		return 0;
7627 
7628 	smp->data.u.str.data = strlen(smp->data.u.str.area);
7629 	return 1;
7630 }
7631 #endif
7632 
7633 static int
7634 smp_fetch_ssl_fc_cl_bin(const struct arg *args, struct sample *smp, const char *kw, void *private)
7635 {
7636 	struct connection *conn;
7637 	struct ssl_capture *capture;
7638 	struct ssl_sock_ctx *ctx;
7639 
7640 	conn = objt_conn(smp->sess->origin);
7641 	if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
7642 		return 0;
7643 	ctx = conn->xprt_ctx;
7644 
7645 	capture = SSL_get_ex_data(ctx->ssl, ssl_capture_ptr_index);
7646 	if (!capture)
7647 		return 0;
7648 
7649 	smp->flags = SMP_F_CONST;
7650 	smp->data.type = SMP_T_BIN;
7651 	smp->data.u.str.area = capture->ciphersuite;
7652 	smp->data.u.str.data = capture->ciphersuite_len;
7653 	return 1;
7654 }
7655 
7656 static int
7657 smp_fetch_ssl_fc_cl_hex(const struct arg *args, struct sample *smp, const char *kw, void *private)
7658 {
7659 	struct buffer *data;
7660 
7661 	if (!smp_fetch_ssl_fc_cl_bin(args, smp, kw, private))
7662 		return 0;
7663 
7664 	data = get_trash_chunk();
7665 	dump_binary(data, smp->data.u.str.area, smp->data.u.str.data);
7666 	smp->data.type = SMP_T_BIN;
7667 	smp->data.u.str = *data;
7668 	return 1;
7669 }
7670 
7671 static int
7672 smp_fetch_ssl_fc_cl_xxh64(const struct arg *args, struct sample *smp, const char *kw, void *private)
7673 {
7674 	struct connection *conn;
7675 	struct ssl_capture *capture;
7676 	struct ssl_sock_ctx *ctx;
7677 
7678 	conn = objt_conn(smp->sess->origin);
7679 	if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
7680 		return 0;
7681 	ctx = conn->xprt_ctx;
7682 
7683 	capture = SSL_get_ex_data(ctx->ssl, ssl_capture_ptr_index);
7684 	if (!capture)
7685 		return 0;
7686 
7687 	smp->data.type = SMP_T_SINT;
7688 	smp->data.u.sint = capture->xxh64;
7689 	return 1;
7690 }
7691 
7692 static int
7693 smp_fetch_ssl_fc_cl_str(const struct arg *args, struct sample *smp, const char *kw, void *private)
7694 {
7695 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL)
7696 	struct buffer *data;
7697 	int i;
7698 
7699 	if (!smp_fetch_ssl_fc_cl_bin(args, smp, kw, private))
7700 		return 0;
7701 
7702 	data = get_trash_chunk();
7703 	for (i = 0; i + 1 < smp->data.u.str.data; i += 2) {
7704 		const char *str;
7705 		const SSL_CIPHER *cipher;
7706 		const unsigned char *bin = (const unsigned char *) smp->data.u.str.area + i;
7707 		uint16_t id = (bin[0] << 8) | bin[1];
7708 #if defined(OPENSSL_IS_BORINGSSL)
7709 		cipher = SSL_get_cipher_by_value(id);
7710 #else
7711 		struct connection *conn = __objt_conn(smp->sess->origin);
7712 		struct ssl_sock_ctx *ctx = conn->xprt_ctx;
7713 		cipher = SSL_CIPHER_find(ctx->ssl, bin);
7714 #endif
7715 		str = SSL_CIPHER_get_name(cipher);
7716 		if (!str || strcmp(str, "(NONE)") == 0)
7717 			chunk_appendf(data, "%sUNKNOWN(%04x)", i == 0 ? "" : ",", id);
7718 		else
7719 			chunk_appendf(data, "%s%s", i == 0 ? "" : ",", str);
7720 	}
7721 	smp->data.type = SMP_T_STR;
7722 	smp->data.u.str = *data;
7723 	return 1;
7724 #else
7725 	return smp_fetch_ssl_fc_cl_xxh64(args, smp, kw, private);
7726 #endif
7727 }
7728 
7729 #if HA_OPENSSL_VERSION_NUMBER > 0x0090800fL
7730 static int
7731 smp_fetch_ssl_fc_unique_id(const struct arg *args, struct sample *smp, const char *kw, void *private)
7732 {
7733 	struct connection *conn = (kw[4] != 'b') ? objt_conn(smp->sess->origin) :
7734 	                                    smp->strm ? cs_conn(objt_cs(smp->strm->si[1].end)) : NULL;
7735 	int finished_len;
7736 	struct buffer *finished_trash;
7737 	struct ssl_sock_ctx *ctx;
7738 
7739 	smp->flags = 0;
7740 	if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
7741 		return 0;
7742 	ctx = conn->xprt_ctx;
7743 
7744 	if (!(conn->flags & CO_FL_CONNECTED)) {
7745 		smp->flags |= SMP_F_MAY_CHANGE;
7746 		return 0;
7747 	}
7748 
7749 	finished_trash = get_trash_chunk();
7750 	if (!SSL_session_reused(ctx->ssl))
7751 		finished_len = SSL_get_peer_finished(ctx->ssl,
7752 						     finished_trash->area,
7753 						     finished_trash->size);
7754 	else
7755 		finished_len = SSL_get_finished(ctx->ssl,
7756 						finished_trash->area,
7757 						finished_trash->size);
7758 
7759 	if (!finished_len)
7760 		return 0;
7761 
7762 	finished_trash->data = finished_len;
7763 	smp->data.u.str = *finished_trash;
7764 	smp->data.type = SMP_T_BIN;
7765 
7766 	return 1;
7767 }
7768 #endif
7769 
7770 /* integer, returns the first verify error in CA chain of client certificate chain. */
7771 static int
7772 smp_fetch_ssl_c_ca_err(const struct arg *args, struct sample *smp, const char *kw, void *private)
7773 {
7774 	struct connection *conn;
7775 	struct ssl_sock_ctx *ctx;
7776 
7777 	conn = objt_conn(smp->sess->origin);
7778 	if (!conn || conn->xprt != &ssl_sock)
7779 		return 0;
7780 	ctx = conn->xprt_ctx;
7781 
7782 	if (!(conn->flags & CO_FL_CONNECTED)) {
7783 		smp->flags = SMP_F_MAY_CHANGE;
7784 		return 0;
7785 	}
7786 
7787 	smp->data.type = SMP_T_SINT;
7788 	smp->data.u.sint = (unsigned long long int)SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st);
7789 	smp->flags = 0;
7790 
7791 	return 1;
7792 }
7793 
7794 /* integer, returns the depth of the first verify error in CA chain of client certificate chain. */
7795 static int
7796 smp_fetch_ssl_c_ca_err_depth(const struct arg *args, struct sample *smp, const char *kw, void *private)
7797 {
7798 	struct connection *conn;
7799 	struct ssl_sock_ctx *ctx;
7800 
7801 	conn = objt_conn(smp->sess->origin);
7802 	if (!conn || conn->xprt != &ssl_sock)
7803 		return 0;
7804 
7805 	if (!(conn->flags & CO_FL_CONNECTED)) {
7806 		smp->flags = SMP_F_MAY_CHANGE;
7807 		return 0;
7808 	}
7809 	ctx = conn->xprt_ctx;
7810 
7811 	smp->data.type = SMP_T_SINT;
7812 	smp->data.u.sint = (long long int)SSL_SOCK_ST_TO_CAEDEPTH(ctx->xprt_st);
7813 	smp->flags = 0;
7814 
7815 	return 1;
7816 }
7817 
7818 /* integer, returns the first verify error on client certificate */
7819 static int
7820 smp_fetch_ssl_c_err(const struct arg *args, struct sample *smp, const char *kw, void *private)
7821 {
7822 	struct connection *conn;
7823 	struct ssl_sock_ctx *ctx;
7824 
7825 	conn = objt_conn(smp->sess->origin);
7826 	if (!conn || conn->xprt != &ssl_sock)
7827 		return 0;
7828 
7829 	if (!(conn->flags & CO_FL_CONNECTED)) {
7830 		smp->flags = SMP_F_MAY_CHANGE;
7831 		return 0;
7832 	}
7833 
7834 	ctx = conn->xprt_ctx;
7835 
7836 	smp->data.type = SMP_T_SINT;
7837 	smp->data.u.sint = (long long int)SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st);
7838 	smp->flags = 0;
7839 
7840 	return 1;
7841 }
7842 
7843 /* integer, returns the verify result on client cert */
7844 static int
7845 smp_fetch_ssl_c_verify(const struct arg *args, struct sample *smp, const char *kw, void *private)
7846 {
7847 	struct connection *conn;
7848 	struct ssl_sock_ctx *ctx;
7849 
7850 	conn = objt_conn(smp->sess->origin);
7851 	if (!conn || conn->xprt != &ssl_sock)
7852 		return 0;
7853 
7854 	if (!(conn->flags & CO_FL_CONNECTED)) {
7855 		smp->flags = SMP_F_MAY_CHANGE;
7856 		return 0;
7857 	}
7858 
7859 	if (!conn->xprt_ctx)
7860 		return 0;
7861 	ctx = conn->xprt_ctx;
7862 
7863 	smp->data.type = SMP_T_SINT;
7864 	smp->data.u.sint = (long long int)SSL_get_verify_result(ctx->ssl);
7865 	smp->flags = 0;
7866 
7867 	return 1;
7868 }
7869 
7870 /* parse the "ca-file" bind keyword */
7871 static int ssl_bind_parse_ca_file(char **args, int cur_arg, struct proxy *px, struct ssl_bind_conf *conf, char **err)
7872 {
7873 	if (!*args[cur_arg + 1]) {
7874 		if (err)
7875 			memprintf(err, "'%s' : missing CAfile path", args[cur_arg]);
7876 		return ERR_ALERT | ERR_FATAL;
7877 	}
7878 
7879 	if ((*args[cur_arg + 1] != '/') && global_ssl.ca_base)
7880 		memprintf(&conf->ca_file, "%s/%s", global_ssl.ca_base, args[cur_arg + 1]);
7881 	else
7882 		memprintf(&conf->ca_file, "%s", args[cur_arg + 1]);
7883 
7884 	return 0;
7885 }
7886 static int bind_parse_ca_file(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
7887 {
7888 	return ssl_bind_parse_ca_file(args, cur_arg, px, &conf->ssl_conf, err);
7889 }
7890 
7891 /* parse the "ca-sign-file" bind keyword */
7892 static int bind_parse_ca_sign_file(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
7893 {
7894 	if (!*args[cur_arg + 1]) {
7895 		if (err)
7896 			memprintf(err, "'%s' : missing CAfile path", args[cur_arg]);
7897 		return ERR_ALERT | ERR_FATAL;
7898 	}
7899 
7900 	if ((*args[cur_arg + 1] != '/') && global_ssl.ca_base)
7901 		memprintf(&conf->ca_sign_file, "%s/%s", global_ssl.ca_base, args[cur_arg + 1]);
7902 	else
7903 		memprintf(&conf->ca_sign_file, "%s", args[cur_arg + 1]);
7904 
7905 	return 0;
7906 }
7907 
7908 /* parse the "ca-sign-pass" bind keyword */
7909 static int bind_parse_ca_sign_pass(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
7910 {
7911 	if (!*args[cur_arg + 1]) {
7912 		if (err)
7913 			memprintf(err, "'%s' : missing CAkey password", args[cur_arg]);
7914 		return ERR_ALERT | ERR_FATAL;
7915 	}
7916 	memprintf(&conf->ca_sign_pass, "%s", args[cur_arg + 1]);
7917 	return 0;
7918 }
7919 
7920 /* parse the "ciphers" bind keyword */
7921 static int ssl_bind_parse_ciphers(char **args, int cur_arg, struct proxy *px, struct ssl_bind_conf *conf, char **err)
7922 {
7923 	if (!*args[cur_arg + 1]) {
7924 		memprintf(err, "'%s' : missing cipher suite", args[cur_arg]);
7925 		return ERR_ALERT | ERR_FATAL;
7926 	}
7927 
7928 	free(conf->ciphers);
7929 	conf->ciphers = strdup(args[cur_arg + 1]);
7930 	return 0;
7931 }
7932 static int bind_parse_ciphers(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
7933 {
7934 	return ssl_bind_parse_ciphers(args, cur_arg, px, &conf->ssl_conf, err);
7935 }
7936 
7937 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
7938 /* parse the "ciphersuites" bind keyword */
7939 static int ssl_bind_parse_ciphersuites(char **args, int cur_arg, struct proxy *px, struct ssl_bind_conf *conf, char **err)
7940 {
7941 	if (!*args[cur_arg + 1]) {
7942 		memprintf(err, "'%s' : missing cipher suite", args[cur_arg]);
7943 		return ERR_ALERT | ERR_FATAL;
7944 	}
7945 
7946 	free(conf->ciphersuites);
7947 	conf->ciphersuites = strdup(args[cur_arg + 1]);
7948 	return 0;
7949 }
7950 static int bind_parse_ciphersuites(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
7951 {
7952 	return ssl_bind_parse_ciphersuites(args, cur_arg, px, &conf->ssl_conf, err);
7953 }
7954 #endif
7955 
7956 /* parse the "crt" bind keyword. Returns a set of ERR_* flags possibly with an error in <err>. */
7957 static int bind_parse_crt(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
7958 {
7959 	char path[MAXPATHLEN];
7960 
7961 	if (!*args[cur_arg + 1]) {
7962 		memprintf(err, "'%s' : missing certificate location", args[cur_arg]);
7963 		return ERR_ALERT | ERR_FATAL;
7964 	}
7965 
7966 	if ((*args[cur_arg + 1] != '/' ) && global_ssl.crt_base) {
7967 		if ((strlen(global_ssl.crt_base) + 1 + strlen(args[cur_arg + 1]) + 1) > MAXPATHLEN) {
7968 			memprintf(err, "'%s' : path too long", args[cur_arg]);
7969 			return ERR_ALERT | ERR_FATAL;
7970 		}
7971 		snprintf(path, sizeof(path), "%s/%s",  global_ssl.crt_base, args[cur_arg + 1]);
7972 		return ssl_sock_load_cert(path, conf, err);
7973 	}
7974 
7975 	return ssl_sock_load_cert(args[cur_arg + 1], conf, err);
7976 }
7977 
7978 /* parse the "crt-list" bind keyword. Returns a set of ERR_* flags possibly with an error in <err>. */
7979 static int bind_parse_crt_list(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
7980 {
7981 	int err_code;
7982 
7983 	if (!*args[cur_arg + 1]) {
7984 		memprintf(err, "'%s' : missing certificate location", args[cur_arg]);
7985 		return ERR_ALERT | ERR_FATAL;
7986 	}
7987 
7988 	err_code = ssl_sock_load_cert_list_file(args[cur_arg + 1], conf, px, err);
7989 	if (err_code)
7990 		memprintf(err, "'%s' : %s", args[cur_arg], *err);
7991 
7992 	return err_code;
7993 }
7994 
7995 /* parse the "crl-file" bind keyword */
7996 static int ssl_bind_parse_crl_file(char **args, int cur_arg, struct proxy *px, struct ssl_bind_conf *conf, char **err)
7997 {
7998 #ifndef X509_V_FLAG_CRL_CHECK
7999 	if (err)
8000 		memprintf(err, "'%s' : library does not support CRL verify", args[cur_arg]);
8001 	return ERR_ALERT | ERR_FATAL;
8002 #else
8003 	if (!*args[cur_arg + 1]) {
8004 		if (err)
8005 			memprintf(err, "'%s' : missing CRLfile path", args[cur_arg]);
8006 		return ERR_ALERT | ERR_FATAL;
8007 	}
8008 
8009 	if ((*args[cur_arg + 1] != '/') && global_ssl.ca_base)
8010 		memprintf(&conf->crl_file, "%s/%s", global_ssl.ca_base, args[cur_arg + 1]);
8011 	else
8012 		memprintf(&conf->crl_file, "%s", args[cur_arg + 1]);
8013 
8014 	return 0;
8015 #endif
8016 }
8017 static int bind_parse_crl_file(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
8018 {
8019 	return ssl_bind_parse_crl_file(args, cur_arg, px, &conf->ssl_conf, err);
8020 }
8021 
8022 /* parse the "curves" bind keyword keyword */
8023 static int ssl_bind_parse_curves(char **args, int cur_arg, struct proxy *px, struct ssl_bind_conf *conf, char **err)
8024 {
8025 #if ((HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL) || defined(LIBRESSL_VERSION_NUMBER))
8026 	if (!*args[cur_arg + 1]) {
8027 		if (err)
8028 			memprintf(err, "'%s' : missing curve suite", args[cur_arg]);
8029 		return ERR_ALERT | ERR_FATAL;
8030 	}
8031 	conf->curves = strdup(args[cur_arg + 1]);
8032 	return 0;
8033 #else
8034 	if (err)
8035 		memprintf(err, "'%s' : library does not support curve suite", args[cur_arg]);
8036 	return ERR_ALERT | ERR_FATAL;
8037 #endif
8038 }
8039 static int bind_parse_curves(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
8040 {
8041 	return ssl_bind_parse_curves(args, cur_arg, px, &conf->ssl_conf, err);
8042 }
8043 
8044 /* parse the "ecdhe" bind keyword keyword */
8045 static int ssl_bind_parse_ecdhe(char **args, int cur_arg, struct proxy *px, struct ssl_bind_conf *conf, char **err)
8046 {
8047 #if HA_OPENSSL_VERSION_NUMBER < 0x0090800fL
8048 	if (err)
8049 		memprintf(err, "'%s' : library does not support elliptic curve Diffie-Hellman (too old)", args[cur_arg]);
8050 	return ERR_ALERT | ERR_FATAL;
8051 #elif defined(OPENSSL_NO_ECDH)
8052 	if (err)
8053 		memprintf(err, "'%s' : library does not support elliptic curve Diffie-Hellman (disabled via OPENSSL_NO_ECDH)", args[cur_arg]);
8054 	return ERR_ALERT | ERR_FATAL;
8055 #else
8056 	if (!*args[cur_arg + 1]) {
8057 		if (err)
8058 			memprintf(err, "'%s' : missing named curve", args[cur_arg]);
8059 		return ERR_ALERT | ERR_FATAL;
8060 	}
8061 
8062 	conf->ecdhe = strdup(args[cur_arg + 1]);
8063 
8064 	return 0;
8065 #endif
8066 }
8067 static int bind_parse_ecdhe(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
8068 {
8069 	return ssl_bind_parse_ecdhe(args, cur_arg, px, &conf->ssl_conf, err);
8070 }
8071 
8072 /* parse the "crt-ignore-err" and "ca-ignore-err" bind keywords */
8073 static int bind_parse_ignore_err(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
8074 {
8075 	int code;
8076 	char *p = args[cur_arg + 1];
8077 	unsigned long long *ignerr = &conf->crt_ignerr;
8078 
8079 	if (!*p) {
8080 		if (err)
8081 			memprintf(err, "'%s' : missing error IDs list", args[cur_arg]);
8082 		return ERR_ALERT | ERR_FATAL;
8083 	}
8084 
8085 	if (strcmp(args[cur_arg], "ca-ignore-err") == 0)
8086 		ignerr = &conf->ca_ignerr;
8087 
8088 	if (strcmp(p, "all") == 0) {
8089 		*ignerr = ~0ULL;
8090 		return 0;
8091 	}
8092 
8093 	while (p) {
8094 		code = atoi(p);
8095 		if ((code <= 0) || (code > 63)) {
8096 			if (err)
8097 				memprintf(err, "'%s' : ID '%d' out of range (1..63) in error IDs list '%s'",
8098 				          args[cur_arg], code, args[cur_arg + 1]);
8099 			return ERR_ALERT | ERR_FATAL;
8100 		}
8101 		*ignerr |= 1ULL << code;
8102 		p = strchr(p, ',');
8103 		if (p)
8104 			p++;
8105 	}
8106 
8107 	return 0;
8108 }
8109 
8110 /* parse tls_method_options "no-xxx" and "force-xxx" */
8111 static int parse_tls_method_options(char *arg, struct tls_version_filter *methods, char **err)
8112 {
8113 	uint16_t v;
8114 	char *p;
8115 	p = strchr(arg, '-');
8116 	if (!p)
8117 		goto fail;
8118 	p++;
8119 	if (!strcmp(p, "sslv3"))
8120 		v = CONF_SSLV3;
8121 	else if (!strcmp(p, "tlsv10"))
8122 		v = CONF_TLSV10;
8123 	else if (!strcmp(p, "tlsv11"))
8124 		v = CONF_TLSV11;
8125 	else if (!strcmp(p, "tlsv12"))
8126 		v = CONF_TLSV12;
8127 	else if (!strcmp(p, "tlsv13"))
8128 		v = CONF_TLSV13;
8129 	else
8130 		goto fail;
8131 	if (!strncmp(arg, "no-", 3))
8132 		methods->flags |= methodVersions[v].flag;
8133 	else if (!strncmp(arg, "force-", 6))
8134 		methods->min = methods->max = v;
8135 	else
8136 		goto fail;
8137 	return 0;
8138  fail:
8139 	if (err)
8140 		memprintf(err, "'%s' : option not implemented", arg);
8141 	return ERR_ALERT | ERR_FATAL;
8142 }
8143 
8144 static int bind_parse_tls_method_options(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
8145 {
8146 	return parse_tls_method_options(args[cur_arg], &conf->ssl_conf.ssl_methods, err);
8147 }
8148 
8149 static int srv_parse_tls_method_options(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8150 {
8151 	return parse_tls_method_options(args[*cur_arg], &newsrv->ssl_ctx.methods, err);
8152 }
8153 
8154 /* parse tls_method min/max: "ssl-min-ver" and "ssl-max-ver" */
8155 static int parse_tls_method_minmax(char **args, int cur_arg, struct tls_version_filter *methods, char **err)
8156 {
8157 	uint16_t i, v = 0;
8158 	char *argv = args[cur_arg + 1];
8159 	if (!*argv) {
8160 		if (err)
8161 			memprintf(err, "'%s' : missing the ssl/tls version", args[cur_arg]);
8162 		return ERR_ALERT | ERR_FATAL;
8163 	}
8164 	for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
8165 		if (!strcmp(argv, methodVersions[i].name))
8166 			v = i;
8167 	if (!v) {
8168 		if (err)
8169 			memprintf(err, "'%s' : unknown ssl/tls version", args[cur_arg + 1]);
8170 		return ERR_ALERT | ERR_FATAL;
8171 	}
8172 	if (!strcmp("ssl-min-ver", args[cur_arg]))
8173 		methods->min = v;
8174 	else if (!strcmp("ssl-max-ver", args[cur_arg]))
8175 		methods->max = v;
8176 	else {
8177 		if (err)
8178 			memprintf(err, "'%s' : option not implemented", args[cur_arg]);
8179 		return ERR_ALERT | ERR_FATAL;
8180 	}
8181 	return 0;
8182 }
8183 
8184 static int ssl_bind_parse_tls_method_minmax(char **args, int cur_arg, struct proxy *px, struct ssl_bind_conf *conf, char **err)
8185 {
8186 #if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L) && !defined(OPENSSL_IS_BORINGSSL)
8187 	ha_warning("crt-list: ssl-min-ver and ssl-max-ver are not supported with this Openssl version (skipped).\n");
8188 #endif
8189 	return parse_tls_method_minmax(args, cur_arg, &conf->ssl_methods, err);
8190 }
8191 
8192 static int bind_parse_tls_method_minmax(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
8193 {
8194 	return parse_tls_method_minmax(args, cur_arg, &conf->ssl_conf.ssl_methods, err);
8195 }
8196 
8197 static int srv_parse_tls_method_minmax(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8198 {
8199 	return parse_tls_method_minmax(args, *cur_arg, &newsrv->ssl_ctx.methods, err);
8200 }
8201 
8202 /* parse the "no-tls-tickets" bind keyword */
8203 static int bind_parse_no_tls_tickets(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
8204 {
8205 	conf->ssl_options |= BC_SSL_O_NO_TLS_TICKETS;
8206 	return 0;
8207 }
8208 
8209 /* parse the "allow-0rtt" bind keyword */
8210 static int ssl_bind_parse_allow_0rtt(char **args, int cur_arg, struct proxy *px, struct ssl_bind_conf *conf, char **err)
8211 {
8212 	conf->early_data = 1;
8213 	return 0;
8214 }
8215 
8216 static int bind_parse_allow_0rtt(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
8217 {
8218 	conf->ssl_conf.early_data = 1;
8219 	return 0;
8220 }
8221 
8222 /* parse the "npn" bind keyword */
8223 static int ssl_bind_parse_npn(char **args, int cur_arg, struct proxy *px, struct ssl_bind_conf *conf, char **err)
8224 {
8225 #if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
8226 	char *p1, *p2;
8227 
8228 	if (!*args[cur_arg + 1]) {
8229 		memprintf(err, "'%s' : missing the comma-delimited NPN protocol suite", args[cur_arg]);
8230 		return ERR_ALERT | ERR_FATAL;
8231 	}
8232 
8233 	free(conf->npn_str);
8234 
8235 	/* the NPN string is built as a suite of (<len> <name>)*,
8236 	 * so we reuse each comma to store the next <len> and need
8237 	 * one more for the end of the string.
8238 	 */
8239 	conf->npn_len = strlen(args[cur_arg + 1]) + 1;
8240 	conf->npn_str = calloc(1, conf->npn_len + 1);
8241 	memcpy(conf->npn_str + 1, args[cur_arg + 1], conf->npn_len);
8242 
8243 	/* replace commas with the name length */
8244 	p1 = conf->npn_str;
8245 	p2 = p1 + 1;
8246 	while (1) {
8247 		p2 = memchr(p1 + 1, ',', conf->npn_str + conf->npn_len - (p1 + 1));
8248 		if (!p2)
8249 			p2 = p1 + 1 + strlen(p1 + 1);
8250 
8251 		if (p2 - (p1 + 1) > 255) {
8252 			*p2 = '\0';
8253 			memprintf(err, "'%s' : NPN protocol name too long : '%s'", args[cur_arg], p1 + 1);
8254 			return ERR_ALERT | ERR_FATAL;
8255 		}
8256 
8257 		*p1 = p2 - (p1 + 1);
8258 		p1 = p2;
8259 
8260 		if (!*p2)
8261 			break;
8262 
8263 		*(p2++) = '\0';
8264 	}
8265 	return 0;
8266 #else
8267 	if (err)
8268 		memprintf(err, "'%s' : library does not support TLS NPN extension", args[cur_arg]);
8269 	return ERR_ALERT | ERR_FATAL;
8270 #endif
8271 }
8272 
8273 static int bind_parse_npn(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
8274 {
8275 	return ssl_bind_parse_npn(args, cur_arg, px, &conf->ssl_conf, err);
8276 }
8277 
8278 /* parse the "alpn" bind keyword */
8279 static int ssl_bind_parse_alpn(char **args, int cur_arg, struct proxy *px, struct ssl_bind_conf *conf, char **err)
8280 {
8281 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
8282 	char *p1, *p2;
8283 
8284 	if (!*args[cur_arg + 1]) {
8285 		memprintf(err, "'%s' : missing the comma-delimited ALPN protocol suite", args[cur_arg]);
8286 		return ERR_ALERT | ERR_FATAL;
8287 	}
8288 
8289 	free(conf->alpn_str);
8290 
8291 	/* the ALPN string is built as a suite of (<len> <name>)*,
8292 	 * so we reuse each comma to store the next <len> and need
8293 	 * one more for the end of the string.
8294 	 */
8295 	conf->alpn_len = strlen(args[cur_arg + 1]) + 1;
8296 	conf->alpn_str = calloc(1, conf->alpn_len + 1);
8297 	memcpy(conf->alpn_str + 1, args[cur_arg + 1], conf->alpn_len);
8298 
8299 	/* replace commas with the name length */
8300 	p1 = conf->alpn_str;
8301 	p2 = p1 + 1;
8302 	while (1) {
8303 		p2 = memchr(p1 + 1, ',', conf->alpn_str + conf->alpn_len - (p1 + 1));
8304 		if (!p2)
8305 			p2 = p1 + 1 + strlen(p1 + 1);
8306 
8307 		if (p2 - (p1 + 1) > 255) {
8308 			*p2 = '\0';
8309 			memprintf(err, "'%s' : ALPN protocol name too long : '%s'", args[cur_arg], p1 + 1);
8310 			return ERR_ALERT | ERR_FATAL;
8311 		}
8312 
8313 		*p1 = p2 - (p1 + 1);
8314 		p1 = p2;
8315 
8316 		if (!*p2)
8317 			break;
8318 
8319 		*(p2++) = '\0';
8320 	}
8321 	return 0;
8322 #else
8323 	if (err)
8324 		memprintf(err, "'%s' : library does not support TLS ALPN extension", args[cur_arg]);
8325 	return ERR_ALERT | ERR_FATAL;
8326 #endif
8327 }
8328 
8329 static int bind_parse_alpn(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
8330 {
8331 	return ssl_bind_parse_alpn(args, cur_arg, px, &conf->ssl_conf, err);
8332 }
8333 
8334 /* parse the "ssl" bind keyword */
8335 static int bind_parse_ssl(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
8336 {
8337 	conf->xprt = &ssl_sock;
8338 	conf->is_ssl = 1;
8339 
8340 	if (global_ssl.listen_default_ciphers && !conf->ssl_conf.ciphers)
8341 		conf->ssl_conf.ciphers = strdup(global_ssl.listen_default_ciphers);
8342 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
8343 	if (global_ssl.listen_default_ciphersuites && !conf->ssl_conf.ciphersuites)
8344 		conf->ssl_conf.ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
8345 #endif
8346 	conf->ssl_options |= global_ssl.listen_default_ssloptions;
8347 	conf->ssl_conf.ssl_methods.flags |= global_ssl.listen_default_sslmethods.flags;
8348 	if (!conf->ssl_conf.ssl_methods.min)
8349 		conf->ssl_conf.ssl_methods.min = global_ssl.listen_default_sslmethods.min;
8350 	if (!conf->ssl_conf.ssl_methods.max)
8351 		conf->ssl_conf.ssl_methods.max = global_ssl.listen_default_sslmethods.max;
8352 
8353 	return 0;
8354 }
8355 
8356 /* parse the "prefer-client-ciphers" bind keyword */
8357 static int bind_parse_pcc(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
8358 {
8359         conf->ssl_options |= BC_SSL_O_PREF_CLIE_CIPH;
8360         return 0;
8361 }
8362 
8363 /* parse the "generate-certificates" bind keyword */
8364 static int bind_parse_generate_certs(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
8365 {
8366 #if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
8367 	conf->generate_certs = 1;
8368 #else
8369 	memprintf(err, "%sthis version of openssl cannot generate SSL certificates.\n",
8370 		  err && *err ? *err : "");
8371 #endif
8372 	return 0;
8373 }
8374 
8375 /* parse the "strict-sni" bind keyword */
8376 static int bind_parse_strict_sni(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
8377 {
8378 	conf->strict_sni = 1;
8379 	return 0;
8380 }
8381 
8382 /* parse the "tls-ticket-keys" bind keyword */
8383 static int bind_parse_tls_ticket_keys(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
8384 {
8385 #if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
8386 	FILE *f = NULL;
8387 	int i = 0;
8388 	char thisline[LINESIZE];
8389 	struct tls_keys_ref *keys_ref = NULL;
8390 
8391 	if (!*args[cur_arg + 1]) {
8392 		if (err)
8393 			memprintf(err, "'%s' : missing TLS ticket keys file path", args[cur_arg]);
8394 		goto fail;
8395 	}
8396 
8397 	keys_ref = tlskeys_ref_lookup(args[cur_arg + 1]);
8398 	if (keys_ref) {
8399 		keys_ref->refcount++;
8400 		conf->keys_ref = keys_ref;
8401 		return 0;
8402 	}
8403 
8404 	keys_ref = calloc(1, sizeof(*keys_ref));
8405 	if (!keys_ref) {
8406 		if (err)
8407 			 memprintf(err, "'%s' : allocation error", args[cur_arg+1]);
8408 		goto fail;
8409 	}
8410 
8411 	keys_ref->tlskeys = malloc(TLS_TICKETS_NO * sizeof(union tls_sess_key));
8412 	if (!keys_ref->tlskeys) {
8413 		if (err)
8414 			 memprintf(err, "'%s' : allocation error", args[cur_arg+1]);
8415 		goto fail;
8416 	}
8417 
8418 	if ((f = fopen(args[cur_arg + 1], "r")) == NULL) {
8419 		if (err)
8420 			memprintf(err, "'%s' : unable to load ssl tickets keys file", args[cur_arg+1]);
8421 		goto fail;
8422 	}
8423 
8424 	keys_ref->filename = strdup(args[cur_arg + 1]);
8425 	if (!keys_ref->filename) {
8426 		if (err)
8427 			 memprintf(err, "'%s' : allocation error", args[cur_arg+1]);
8428 		goto fail;
8429 	}
8430 
8431 	keys_ref->key_size_bits = 0;
8432 	while (fgets(thisline, sizeof(thisline), f) != NULL) {
8433 		int len = strlen(thisline);
8434 		int dec_size;
8435 
8436 		/* Strip newline characters from the end */
8437 		if(thisline[len - 1] == '\n')
8438 			thisline[--len] = 0;
8439 
8440 		if(thisline[len - 1] == '\r')
8441 			thisline[--len] = 0;
8442 
8443 		dec_size = base64dec(thisline, len, (char *) (keys_ref->tlskeys + i % TLS_TICKETS_NO), sizeof(union tls_sess_key));
8444 		if (dec_size < 0) {
8445 			if (err)
8446 				memprintf(err, "'%s' : unable to decode base64 key on line %d", args[cur_arg+1], i + 1);
8447 			goto fail;
8448 		}
8449 		else if (!keys_ref->key_size_bits && (dec_size == sizeof(struct tls_sess_key_128))) {
8450 			keys_ref->key_size_bits = 128;
8451 		}
8452 		else if (!keys_ref->key_size_bits && (dec_size == sizeof(struct tls_sess_key_256))) {
8453 			keys_ref->key_size_bits = 256;
8454 		}
8455 		else if (((dec_size != sizeof(struct tls_sess_key_128)) && (dec_size != sizeof(struct tls_sess_key_256)))
8456 			 || ((dec_size == sizeof(struct tls_sess_key_128) && (keys_ref->key_size_bits != 128)))
8457 			 || ((dec_size == sizeof(struct tls_sess_key_256) && (keys_ref->key_size_bits != 256)))) {
8458 			if (err)
8459 				memprintf(err, "'%s' : wrong sized key on line %d", args[cur_arg+1], i + 1);
8460 			goto fail;
8461 		}
8462 		i++;
8463 	}
8464 
8465 	if (i < TLS_TICKETS_NO) {
8466 		if (err)
8467 			memprintf(err, "'%s' : please supply at least %d keys in the tls-tickets-file", args[cur_arg+1], TLS_TICKETS_NO);
8468 		goto fail;
8469 	}
8470 
8471 	fclose(f);
8472 
8473 	/* Use penultimate key for encryption, handle when TLS_TICKETS_NO = 1 */
8474 	i -= 2;
8475 	keys_ref->tls_ticket_enc_index = i < 0 ? 0 : i % TLS_TICKETS_NO;
8476 	keys_ref->unique_id = -1;
8477 	keys_ref->refcount = 1;
8478 	HA_RWLOCK_INIT(&keys_ref->lock);
8479 	conf->keys_ref = keys_ref;
8480 
8481 	LIST_ADD(&tlskeys_reference, &keys_ref->list);
8482 
8483 	return 0;
8484 
8485   fail:
8486 	if (f)
8487 		fclose(f);
8488 	if (keys_ref) {
8489 		free(keys_ref->filename);
8490 		free(keys_ref->tlskeys);
8491 		free(keys_ref);
8492 	}
8493 	return ERR_ALERT | ERR_FATAL;
8494 
8495 #else
8496 	if (err)
8497 		memprintf(err, "'%s' : TLS ticket callback extension not supported", args[cur_arg]);
8498 	return ERR_ALERT | ERR_FATAL;
8499 #endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
8500 }
8501 
8502 /* parse the "verify" bind keyword */
8503 static int ssl_bind_parse_verify(char **args, int cur_arg, struct proxy *px, struct ssl_bind_conf *conf, char **err)
8504 {
8505 	if (!*args[cur_arg + 1]) {
8506 		if (err)
8507 			memprintf(err, "'%s' : missing verify method", args[cur_arg]);
8508 		return ERR_ALERT | ERR_FATAL;
8509 	}
8510 
8511 	if (strcmp(args[cur_arg + 1], "none") == 0)
8512 		conf->verify = SSL_SOCK_VERIFY_NONE;
8513 	else if (strcmp(args[cur_arg + 1], "optional") == 0)
8514 		conf->verify = SSL_SOCK_VERIFY_OPTIONAL;
8515 	else if (strcmp(args[cur_arg + 1], "required") == 0)
8516 		conf->verify = SSL_SOCK_VERIFY_REQUIRED;
8517 	else {
8518 		if (err)
8519 			memprintf(err, "'%s' : unknown verify method '%s', only 'none', 'optional', and 'required' are supported\n",
8520 			          args[cur_arg], args[cur_arg + 1]);
8521 		return ERR_ALERT | ERR_FATAL;
8522 	}
8523 
8524 	return 0;
8525 }
8526 static int bind_parse_verify(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
8527 {
8528 	return ssl_bind_parse_verify(args, cur_arg, px, &conf->ssl_conf, err);
8529 }
8530 
8531 /* parse the "no-ca-names" bind keyword */
8532 static int ssl_bind_parse_no_ca_names(char **args, int cur_arg, struct proxy *px, struct ssl_bind_conf *conf, char **err)
8533 {
8534 	conf->no_ca_names = 1;
8535 	return 0;
8536 }
8537 static int bind_parse_no_ca_names(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
8538 {
8539 	return ssl_bind_parse_no_ca_names(args, cur_arg, px, &conf->ssl_conf, err);
8540 }
8541 
8542 /************** "server" keywords ****************/
8543 
8544 /* parse the "npn" bind keyword */
8545 static int srv_parse_npn(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8546 {
8547 #if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
8548 	char *p1, *p2;
8549 
8550 	if (!*args[*cur_arg + 1]) {
8551 		memprintf(err, "'%s' : missing the comma-delimited NPN protocol suite", args[*cur_arg]);
8552 		return ERR_ALERT | ERR_FATAL;
8553 	}
8554 
8555 	free(newsrv->ssl_ctx.npn_str);
8556 
8557 	/* the NPN string is built as a suite of (<len> <name>)*,
8558 	 * so we reuse each comma to store the next <len> and need
8559 	 * one more for the end of the string.
8560 	 */
8561 	newsrv->ssl_ctx.npn_len = strlen(args[*cur_arg + 1]) + 1;
8562 	newsrv->ssl_ctx.npn_str = calloc(1, newsrv->ssl_ctx.npn_len + 1);
8563 	memcpy(newsrv->ssl_ctx.npn_str + 1, args[*cur_arg + 1],
8564 	    newsrv->ssl_ctx.npn_len);
8565 
8566 	/* replace commas with the name length */
8567 	p1 = newsrv->ssl_ctx.npn_str;
8568 	p2 = p1 + 1;
8569 	while (1) {
8570 		p2 = memchr(p1 + 1, ',', newsrv->ssl_ctx.npn_str +
8571 		    newsrv->ssl_ctx.npn_len - (p1 + 1));
8572 		if (!p2)
8573 			p2 = p1 + 1 + strlen(p1 + 1);
8574 
8575 		if (p2 - (p1 + 1) > 255) {
8576 			*p2 = '\0';
8577 			memprintf(err, "'%s' : NPN protocol name too long : '%s'", args[*cur_arg], p1 + 1);
8578 			return ERR_ALERT | ERR_FATAL;
8579 		}
8580 
8581 		*p1 = p2 - (p1 + 1);
8582 		p1 = p2;
8583 
8584 		if (!*p2)
8585 			break;
8586 
8587 		*(p2++) = '\0';
8588 	}
8589 	return 0;
8590 #else
8591 	if (err)
8592 		memprintf(err, "'%s' : library does not support TLS NPN extension", args[*cur_arg]);
8593 	return ERR_ALERT | ERR_FATAL;
8594 #endif
8595 }
8596 
8597 /* parse the "alpn" or the "check-alpn" server keyword */
8598 static int srv_parse_alpn(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8599 {
8600 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
8601 	char *p1, *p2;
8602 	char **alpn_str;
8603 	int *alpn_len;
8604 
8605 	if (*args[*cur_arg] == 'c') {
8606 		alpn_str = &newsrv->check.alpn_str;
8607 		alpn_len = &newsrv->check.alpn_len;
8608 	} else {
8609 		alpn_str = &newsrv->ssl_ctx.alpn_str;
8610 		alpn_len = &newsrv->ssl_ctx.alpn_len;
8611 
8612 	}
8613 	if (!*args[*cur_arg + 1]) {
8614 		memprintf(err, "'%s' : missing the comma-delimited ALPN protocol suite", args[*cur_arg]);
8615 		return ERR_ALERT | ERR_FATAL;
8616 	}
8617 
8618 	free(*alpn_str);
8619 
8620 	/* the ALPN string is built as a suite of (<len> <name>)*,
8621 	 * so we reuse each comma to store the next <len> and need
8622 	 * one more for the end of the string.
8623 	 */
8624 	*alpn_len = strlen(args[*cur_arg + 1]) + 1;
8625 	*alpn_str = calloc(1, *alpn_len + 1);
8626 	memcpy(*alpn_str + 1, args[*cur_arg + 1], *alpn_len);
8627 
8628 	/* replace commas with the name length */
8629 	p1 = *alpn_str;
8630 	p2 = p1 + 1;
8631 	while (1) {
8632 		p2 = memchr(p1 + 1, ',', *alpn_str + *alpn_len - (p1 + 1));
8633 		if (!p2)
8634 			p2 = p1 + 1 + strlen(p1 + 1);
8635 
8636 		if (p2 - (p1 + 1) > 255) {
8637 			*p2 = '\0';
8638 			memprintf(err, "'%s' : ALPN protocol name too long : '%s'", args[*cur_arg], p1 + 1);
8639 			return ERR_ALERT | ERR_FATAL;
8640 		}
8641 
8642 		*p1 = p2 - (p1 + 1);
8643 		p1 = p2;
8644 
8645 		if (!*p2)
8646 			break;
8647 
8648 		*(p2++) = '\0';
8649 	}
8650 	return 0;
8651 #else
8652 	if (err)
8653 		memprintf(err, "'%s' : library does not support TLS ALPN extension", args[*cur_arg]);
8654 	return ERR_ALERT | ERR_FATAL;
8655 #endif
8656 }
8657 
8658 /* parse the "ca-file" server keyword */
8659 static int srv_parse_ca_file(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8660 {
8661 	if (!*args[*cur_arg + 1]) {
8662 		if (err)
8663 			memprintf(err, "'%s' : missing CAfile path", args[*cur_arg]);
8664 		return ERR_ALERT | ERR_FATAL;
8665 	}
8666 
8667 	if ((*args[*cur_arg + 1] != '/') && global_ssl.ca_base)
8668 		memprintf(&newsrv->ssl_ctx.ca_file, "%s/%s", global_ssl.ca_base, args[*cur_arg + 1]);
8669 	else
8670 		memprintf(&newsrv->ssl_ctx.ca_file, "%s", args[*cur_arg + 1]);
8671 
8672 	return 0;
8673 }
8674 
8675 /* parse the "check-sni" server keyword */
8676 static int srv_parse_check_sni(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8677 {
8678 	if (!*args[*cur_arg + 1]) {
8679 		if (err)
8680 			memprintf(err, "'%s' : missing SNI", args[*cur_arg]);
8681 		return ERR_ALERT | ERR_FATAL;
8682 	}
8683 
8684 	newsrv->check.sni = strdup(args[*cur_arg + 1]);
8685 	if (!newsrv->check.sni) {
8686 		memprintf(err, "'%s' : failed to allocate memory", args[*cur_arg]);
8687 		return ERR_ALERT | ERR_FATAL;
8688 	}
8689 	return 0;
8690 
8691 }
8692 
8693 /* parse the "check-ssl" server keyword */
8694 static int srv_parse_check_ssl(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8695 {
8696 	newsrv->check.use_ssl = 1;
8697 	if (global_ssl.connect_default_ciphers && !newsrv->ssl_ctx.ciphers)
8698 		newsrv->ssl_ctx.ciphers = strdup(global_ssl.connect_default_ciphers);
8699 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
8700 	if (global_ssl.connect_default_ciphersuites && !newsrv->ssl_ctx.ciphersuites)
8701 		newsrv->ssl_ctx.ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
8702 #endif
8703 	newsrv->ssl_ctx.options |= global_ssl.connect_default_ssloptions;
8704 	newsrv->ssl_ctx.methods.flags |= global_ssl.connect_default_sslmethods.flags;
8705 	if (!newsrv->ssl_ctx.methods.min)
8706 		newsrv->ssl_ctx.methods.min = global_ssl.connect_default_sslmethods.min;
8707 	if (!newsrv->ssl_ctx.methods.max)
8708 		newsrv->ssl_ctx.methods.max = global_ssl.connect_default_sslmethods.max;
8709 
8710 	return 0;
8711 }
8712 
8713 /* parse the "ciphers" server keyword */
8714 static int srv_parse_ciphers(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8715 {
8716 	if (!*args[*cur_arg + 1]) {
8717 		memprintf(err, "'%s' : missing cipher suite", args[*cur_arg]);
8718 		return ERR_ALERT | ERR_FATAL;
8719 	}
8720 
8721 	free(newsrv->ssl_ctx.ciphers);
8722 	newsrv->ssl_ctx.ciphers = strdup(args[*cur_arg + 1]);
8723 	return 0;
8724 }
8725 
8726 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
8727 /* parse the "ciphersuites" server keyword */
8728 static int srv_parse_ciphersuites(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8729 {
8730 	if (!*args[*cur_arg + 1]) {
8731 		memprintf(err, "'%s' : missing cipher suite", args[*cur_arg]);
8732 		return ERR_ALERT | ERR_FATAL;
8733 	}
8734 
8735 	free(newsrv->ssl_ctx.ciphersuites);
8736 	newsrv->ssl_ctx.ciphersuites = strdup(args[*cur_arg + 1]);
8737 	return 0;
8738 }
8739 #endif
8740 
8741 /* parse the "crl-file" server keyword */
8742 static int srv_parse_crl_file(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8743 {
8744 #ifndef X509_V_FLAG_CRL_CHECK
8745 	if (err)
8746 		memprintf(err, "'%s' : library does not support CRL verify", args[*cur_arg]);
8747 	return ERR_ALERT | ERR_FATAL;
8748 #else
8749 	if (!*args[*cur_arg + 1]) {
8750 		if (err)
8751 			memprintf(err, "'%s' : missing CRLfile path", args[*cur_arg]);
8752 		return ERR_ALERT | ERR_FATAL;
8753 	}
8754 
8755 	if ((*args[*cur_arg + 1] != '/') && global_ssl.ca_base)
8756 		memprintf(&newsrv->ssl_ctx.crl_file, "%s/%s", global_ssl.ca_base, args[*cur_arg + 1]);
8757 	else
8758 		memprintf(&newsrv->ssl_ctx.crl_file, "%s", args[*cur_arg + 1]);
8759 
8760 	return 0;
8761 #endif
8762 }
8763 
8764 /* parse the "crt" server keyword */
8765 static int srv_parse_crt(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8766 {
8767 	if (!*args[*cur_arg + 1]) {
8768 		if (err)
8769 			memprintf(err, "'%s' : missing certificate file path", args[*cur_arg]);
8770 		return ERR_ALERT | ERR_FATAL;
8771 	}
8772 
8773 	if ((*args[*cur_arg + 1] != '/') && global_ssl.crt_base)
8774 		memprintf(&newsrv->ssl_ctx.client_crt, "%s/%s", global_ssl.crt_base, args[*cur_arg + 1]);
8775 	else
8776 		memprintf(&newsrv->ssl_ctx.client_crt, "%s", args[*cur_arg + 1]);
8777 
8778 	return 0;
8779 }
8780 
8781 /* parse the "no-check-ssl" server keyword */
8782 static int srv_parse_no_check_ssl(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8783 {
8784 	newsrv->check.use_ssl = -1;
8785 	free(newsrv->ssl_ctx.ciphers);
8786 	newsrv->ssl_ctx.ciphers = NULL;
8787 	newsrv->ssl_ctx.options &= ~global_ssl.connect_default_ssloptions;
8788 	return 0;
8789 }
8790 
8791 /* parse the "no-send-proxy-v2-ssl" server keyword */
8792 static int srv_parse_no_send_proxy_ssl(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8793 {
8794 	newsrv->pp_opts &= ~SRV_PP_V2;
8795 	newsrv->pp_opts &= ~SRV_PP_V2_SSL;
8796 	return 0;
8797 }
8798 
8799 /* parse the "no-send-proxy-v2-ssl-cn" server keyword */
8800 static int srv_parse_no_send_proxy_cn(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8801 {
8802 	newsrv->pp_opts &= ~SRV_PP_V2;
8803 	newsrv->pp_opts &= ~SRV_PP_V2_SSL;
8804 	newsrv->pp_opts &= ~SRV_PP_V2_SSL_CN;
8805 	return 0;
8806 }
8807 
8808 /* parse the "no-ssl" server keyword */
8809 static int srv_parse_no_ssl(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8810 {
8811 	newsrv->use_ssl = -1;
8812 	free(newsrv->ssl_ctx.ciphers);
8813 	newsrv->ssl_ctx.ciphers = NULL;
8814 	return 0;
8815 }
8816 
8817 /* parse the "allow-0rtt" server keyword */
8818 static int srv_parse_allow_0rtt(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8819 {
8820 	newsrv->ssl_ctx.options |= SRV_SSL_O_EARLY_DATA;
8821 	return 0;
8822 }
8823 
8824 /* parse the "no-ssl-reuse" server keyword */
8825 static int srv_parse_no_ssl_reuse(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8826 {
8827 	newsrv->ssl_ctx.options |= SRV_SSL_O_NO_REUSE;
8828 	return 0;
8829 }
8830 
8831 /* parse the "no-tls-tickets" server keyword */
8832 static int srv_parse_no_tls_tickets(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8833 {
8834 	newsrv->ssl_ctx.options |= SRV_SSL_O_NO_TLS_TICKETS;
8835 	return 0;
8836 }
8837 /* parse the "send-proxy-v2-ssl" server keyword */
8838 static int srv_parse_send_proxy_ssl(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8839 {
8840 	newsrv->pp_opts |= SRV_PP_V2;
8841 	newsrv->pp_opts |= SRV_PP_V2_SSL;
8842 	return 0;
8843 }
8844 
8845 /* parse the "send-proxy-v2-ssl-cn" server keyword */
8846 static int srv_parse_send_proxy_cn(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8847 {
8848 	newsrv->pp_opts |= SRV_PP_V2;
8849 	newsrv->pp_opts |= SRV_PP_V2_SSL;
8850 	newsrv->pp_opts |= SRV_PP_V2_SSL_CN;
8851 	return 0;
8852 }
8853 
8854 /* parse the "sni" server keyword */
8855 static int srv_parse_sni(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8856 {
8857 #ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
8858 	memprintf(err, "'%s' : the current SSL library doesn't support the SNI TLS extension", args[*cur_arg]);
8859 	return ERR_ALERT | ERR_FATAL;
8860 #else
8861 	char *arg;
8862 
8863 	arg = args[*cur_arg + 1];
8864 	if (!*arg) {
8865 		memprintf(err, "'%s' : missing sni expression", args[*cur_arg]);
8866 		return ERR_ALERT | ERR_FATAL;
8867 	}
8868 
8869 	free(newsrv->sni_expr);
8870 	newsrv->sni_expr = strdup(arg);
8871 
8872 	return 0;
8873 #endif
8874 }
8875 
8876 /* parse the "ssl" server keyword */
8877 static int srv_parse_ssl(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8878 {
8879 	newsrv->use_ssl = 1;
8880 	if (global_ssl.connect_default_ciphers && !newsrv->ssl_ctx.ciphers)
8881 		newsrv->ssl_ctx.ciphers = strdup(global_ssl.connect_default_ciphers);
8882 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
8883 	if (global_ssl.connect_default_ciphersuites && !newsrv->ssl_ctx.ciphersuites)
8884 		newsrv->ssl_ctx.ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
8885 #endif
8886 	newsrv->ssl_ctx.options |= global_ssl.connect_default_ssloptions;
8887 	newsrv->ssl_ctx.methods.flags |= global_ssl.connect_default_sslmethods.flags;
8888 
8889 	if (!newsrv->ssl_ctx.methods.min)
8890 		newsrv->ssl_ctx.methods.min = global_ssl.connect_default_sslmethods.min;
8891 
8892 	if (!newsrv->ssl_ctx.methods.max)
8893 		newsrv->ssl_ctx.methods.max = global_ssl.connect_default_sslmethods.max;
8894 
8895 
8896 	return 0;
8897 }
8898 
8899 /* parse the "ssl-reuse" server keyword */
8900 static int srv_parse_ssl_reuse(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8901 {
8902 	newsrv->ssl_ctx.options &= ~SRV_SSL_O_NO_REUSE;
8903 	return 0;
8904 }
8905 
8906 /* parse the "tls-tickets" server keyword */
8907 static int srv_parse_tls_tickets(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8908 {
8909 	newsrv->ssl_ctx.options &= ~SRV_SSL_O_NO_TLS_TICKETS;
8910 	return 0;
8911 }
8912 
8913 /* parse the "verify" server keyword */
8914 static int srv_parse_verify(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8915 {
8916 	if (!*args[*cur_arg + 1]) {
8917 		if (err)
8918 			memprintf(err, "'%s' : missing verify method", args[*cur_arg]);
8919 		return ERR_ALERT | ERR_FATAL;
8920 	}
8921 
8922 	if (strcmp(args[*cur_arg + 1], "none") == 0)
8923 		newsrv->ssl_ctx.verify = SSL_SOCK_VERIFY_NONE;
8924 	else if (strcmp(args[*cur_arg + 1], "required") == 0)
8925 		newsrv->ssl_ctx.verify = SSL_SOCK_VERIFY_REQUIRED;
8926 	else {
8927 		if (err)
8928 			memprintf(err, "'%s' : unknown verify method '%s', only 'none' and 'required' are supported\n",
8929 			          args[*cur_arg], args[*cur_arg + 1]);
8930 		return ERR_ALERT | ERR_FATAL;
8931 	}
8932 
8933 	return 0;
8934 }
8935 
8936 /* parse the "verifyhost" server keyword */
8937 static int srv_parse_verifyhost(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
8938 {
8939 	if (!*args[*cur_arg + 1]) {
8940 		if (err)
8941 			memprintf(err, "'%s' : missing hostname to verify against", args[*cur_arg]);
8942 		return ERR_ALERT | ERR_FATAL;
8943 	}
8944 
8945 	free(newsrv->ssl_ctx.verify_host);
8946 	newsrv->ssl_ctx.verify_host = strdup(args[*cur_arg + 1]);
8947 
8948 	return 0;
8949 }
8950 
8951 /* parse the "ssl-default-bind-options" keyword in global section */
8952 static int ssl_parse_default_bind_options(char **args, int section_type, struct proxy *curpx,
8953                                           struct proxy *defpx, const char *file, int line,
8954                                           char **err) {
8955 	int i = 1;
8956 
8957 	if (*(args[i]) == 0) {
8958 		memprintf(err, "global statement '%s' expects an option as an argument.", args[0]);
8959 		return -1;
8960 	}
8961 	while (*(args[i])) {
8962 		if (!strcmp(args[i], "no-tls-tickets"))
8963 			global_ssl.listen_default_ssloptions |= BC_SSL_O_NO_TLS_TICKETS;
8964 		else if (!strcmp(args[i], "prefer-client-ciphers"))
8965 			global_ssl.listen_default_ssloptions |= BC_SSL_O_PREF_CLIE_CIPH;
8966 		else if (!strcmp(args[i], "ssl-min-ver") || !strcmp(args[i], "ssl-max-ver")) {
8967 			if (!parse_tls_method_minmax(args, i, &global_ssl.listen_default_sslmethods, err))
8968 				i++;
8969 			else {
8970 				memprintf(err, "%s on global statement '%s'.", *err, args[0]);
8971 				return -1;
8972 			}
8973 		}
8974 		else if (parse_tls_method_options(args[i], &global_ssl.listen_default_sslmethods, err)) {
8975 			memprintf(err, "unknown option '%s' on global statement '%s'.", args[i], args[0]);
8976 			return -1;
8977 		}
8978 		i++;
8979 	}
8980 	return 0;
8981 }
8982 
8983 /* parse the "ssl-default-server-options" keyword in global section */
8984 static int ssl_parse_default_server_options(char **args, int section_type, struct proxy *curpx,
8985                                             struct proxy *defpx, const char *file, int line,
8986                                             char **err) {
8987 	int i = 1;
8988 
8989 	if (*(args[i]) == 0) {
8990 		memprintf(err, "global statement '%s' expects an option as an argument.", args[0]);
8991 		return -1;
8992 	}
8993 	while (*(args[i])) {
8994 		if (!strcmp(args[i], "no-tls-tickets"))
8995 			global_ssl.connect_default_ssloptions |= SRV_SSL_O_NO_TLS_TICKETS;
8996 		else if (!strcmp(args[i], "ssl-min-ver") || !strcmp(args[i], "ssl-max-ver")) {
8997 			if (!parse_tls_method_minmax(args, i, &global_ssl.connect_default_sslmethods, err))
8998 				i++;
8999 			else {
9000 				memprintf(err, "%s on global statement '%s'.", *err, args[0]);
9001 				return -1;
9002 			}
9003 		}
9004 		else if (parse_tls_method_options(args[i], &global_ssl.connect_default_sslmethods, err)) {
9005 			memprintf(err, "unknown option '%s' on global statement '%s'.", args[i], args[0]);
9006 			return -1;
9007 		}
9008 		i++;
9009 	}
9010 	return 0;
9011 }
9012 
9013 /* parse the "ca-base" / "crt-base" keywords in global section.
9014  * Returns <0 on alert, >0 on warning, 0 on success.
9015  */
9016 static int ssl_parse_global_ca_crt_base(char **args, int section_type, struct proxy *curpx,
9017                                         struct proxy *defpx, const char *file, int line,
9018                                         char **err)
9019 {
9020 	char **target;
9021 
9022 	target = (args[0][1] == 'a') ? &global_ssl.ca_base : &global_ssl.crt_base;
9023 
9024 	if (too_many_args(1, args, err, NULL))
9025 		return -1;
9026 
9027 	if (*target) {
9028 		memprintf(err, "'%s' already specified.", args[0]);
9029 		return -1;
9030 	}
9031 
9032 	if (*(args[1]) == 0) {
9033 		memprintf(err, "global statement '%s' expects a directory path as an argument.", args[0]);
9034 		return -1;
9035 	}
9036 	*target = strdup(args[1]);
9037 	return 0;
9038 }
9039 
9040 /* parse the "ssl-mode-async" keyword in global section.
9041  * Returns <0 on alert, >0 on warning, 0 on success.
9042  */
9043 static int ssl_parse_global_ssl_async(char **args, int section_type, struct proxy *curpx,
9044                                        struct proxy *defpx, const char *file, int line,
9045                                        char **err)
9046 {
9047 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
9048 	global_ssl.async = 1;
9049 	global.ssl_used_async_engines = nb_engines;
9050 	return 0;
9051 #else
9052 	memprintf(err, "'%s': openssl library does not support async mode", args[0]);
9053 	return -1;
9054 #endif
9055 }
9056 
9057 #ifndef OPENSSL_NO_ENGINE
9058 static int ssl_check_async_engine_count(void) {
9059 	int err_code = 0;
9060 
9061 	if (global_ssl.async && (openssl_engines_initialized > 32)) {
9062 		ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
9063 		err_code = ERR_ABORT;
9064 	}
9065 	return err_code;
9066 }
9067 
9068 /* parse the "ssl-engine" keyword in global section.
9069  * Returns <0 on alert, >0 on warning, 0 on success.
9070  */
9071 static int ssl_parse_global_ssl_engine(char **args, int section_type, struct proxy *curpx,
9072                                        struct proxy *defpx, const char *file, int line,
9073                                        char **err)
9074 {
9075 	char *algo;
9076 	int ret = -1;
9077 
9078 	if (*(args[1]) == 0) {
9079 		memprintf(err, "global statement '%s' expects a valid engine name as an argument.", args[0]);
9080 		return ret;
9081 	}
9082 
9083 	if (*(args[2]) == 0) {
9084 		/* if no list of algorithms is given, it defaults to ALL */
9085 		algo = strdup("ALL");
9086 		goto add_engine;
9087 	}
9088 
9089 	/* otherwise the expected format is ssl-engine <engine_name> algo <list of algo> */
9090 	if (strcmp(args[2], "algo") != 0) {
9091 		memprintf(err, "global statement '%s' expects to have algo keyword.", args[0]);
9092 		return ret;
9093 	}
9094 
9095 	if (*(args[3]) == 0) {
9096 		memprintf(err, "global statement '%s' expects algorithm names as an argument.", args[0]);
9097 		return ret;
9098 	}
9099 	algo = strdup(args[3]);
9100 
9101 add_engine:
9102 	if (ssl_init_single_engine(args[1], algo)==0) {
9103 		openssl_engines_initialized++;
9104 		ret = 0;
9105 	}
9106 	free(algo);
9107 	return ret;
9108 }
9109 #endif
9110 
9111 /* parse the "ssl-default-bind-ciphers" / "ssl-default-server-ciphers" keywords
9112  * in global section. Returns <0 on alert, >0 on warning, 0 on success.
9113  */
9114 static int ssl_parse_global_ciphers(char **args, int section_type, struct proxy *curpx,
9115                                     struct proxy *defpx, const char *file, int line,
9116                                     char **err)
9117 {
9118 	char **target;
9119 
9120 	target = (args[0][12] == 'b') ? &global_ssl.listen_default_ciphers : &global_ssl.connect_default_ciphers;
9121 
9122 	if (too_many_args(1, args, err, NULL))
9123 		return -1;
9124 
9125 	if (*(args[1]) == 0) {
9126 		memprintf(err, "global statement '%s' expects a cipher suite as an argument.", args[0]);
9127 		return -1;
9128 	}
9129 
9130 	free(*target);
9131 	*target = strdup(args[1]);
9132 	return 0;
9133 }
9134 
9135 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
9136 /* parse the "ssl-default-bind-ciphersuites" / "ssl-default-server-ciphersuites" keywords
9137  * in global section. Returns <0 on alert, >0 on warning, 0 on success.
9138  */
9139 static int ssl_parse_global_ciphersuites(char **args, int section_type, struct proxy *curpx,
9140                                     struct proxy *defpx, const char *file, int line,
9141                                     char **err)
9142 {
9143 	char **target;
9144 
9145 	target = (args[0][12] == 'b') ? &global_ssl.listen_default_ciphersuites : &global_ssl.connect_default_ciphersuites;
9146 
9147 	if (too_many_args(1, args, err, NULL))
9148 		return -1;
9149 
9150 	if (*(args[1]) == 0) {
9151 		memprintf(err, "global statement '%s' expects a cipher suite as an argument.", args[0]);
9152 		return -1;
9153 	}
9154 
9155 	free(*target);
9156 	*target = strdup(args[1]);
9157 	return 0;
9158 }
9159 #endif
9160 
9161 /* parse various global tune.ssl settings consisting in positive integers.
9162  * Returns <0 on alert, >0 on warning, 0 on success.
9163  */
9164 static int ssl_parse_global_int(char **args, int section_type, struct proxy *curpx,
9165                                 struct proxy *defpx, const char *file, int line,
9166                                 char **err)
9167 {
9168 	int *target;
9169 
9170 	if (strcmp(args[0], "tune.ssl.cachesize") == 0)
9171 		target = &global.tune.sslcachesize;
9172 	else if (strcmp(args[0], "tune.ssl.maxrecord") == 0)
9173 		target = (int *)&global_ssl.max_record;
9174 	else if (strcmp(args[0], "tune.ssl.ssl-ctx-cache-size") == 0)
9175 		target = &global_ssl.ctx_cache;
9176 	else if (strcmp(args[0], "maxsslconn") == 0)
9177 		target = &global.maxsslconn;
9178 	else if (strcmp(args[0], "tune.ssl.capture-cipherlist-size") == 0)
9179 		target = &global_ssl.capture_cipherlist;
9180 	else {
9181 		memprintf(err, "'%s' keyword not unhandled (please report this bug).", args[0]);
9182 		return -1;
9183 	}
9184 
9185 	if (too_many_args(1, args, err, NULL))
9186 		return -1;
9187 
9188 	if (*(args[1]) == 0) {
9189 		memprintf(err, "'%s' expects an integer argument.", args[0]);
9190 		return -1;
9191 	}
9192 
9193 	*target = atoi(args[1]);
9194 	if (*target < 0) {
9195 		memprintf(err, "'%s' expects a positive numeric value.", args[0]);
9196 		return -1;
9197 	}
9198 	return 0;
9199 }
9200 
9201 static int ssl_parse_global_capture_cipherlist(char **args, int section_type, struct proxy *curpx,
9202                                                struct proxy *defpx, const char *file, int line,
9203                                                char **err)
9204 {
9205 	int ret;
9206 
9207 	ret = ssl_parse_global_int(args, section_type, curpx, defpx, file, line, err);
9208 	if (ret != 0)
9209 		return ret;
9210 
9211 	if (pool_head_ssl_capture) {
9212 		memprintf(err, "'%s' is already configured.", args[0]);
9213 		return -1;
9214 	}
9215 
9216 	pool_head_ssl_capture = create_pool("ssl-capture", sizeof(struct ssl_capture) + global_ssl.capture_cipherlist, MEM_F_SHARED);
9217 	if (!pool_head_ssl_capture) {
9218 		memprintf(err, "Out of memory error.");
9219 		return -1;
9220 	}
9221 	return 0;
9222 }
9223 
9224 /* parse "ssl.force-private-cache".
9225  * Returns <0 on alert, >0 on warning, 0 on success.
9226  */
9227 static int ssl_parse_global_private_cache(char **args, int section_type, struct proxy *curpx,
9228                                           struct proxy *defpx, const char *file, int line,
9229                                           char **err)
9230 {
9231 	if (too_many_args(0, args, err, NULL))
9232 		return -1;
9233 
9234 	global_ssl.private_cache = 1;
9235 	return 0;
9236 }
9237 
9238 /* parse "ssl.lifetime".
9239  * Returns <0 on alert, >0 on warning, 0 on success.
9240  */
9241 static int ssl_parse_global_lifetime(char **args, int section_type, struct proxy *curpx,
9242                                      struct proxy *defpx, const char *file, int line,
9243                                      char **err)
9244 {
9245 	const char *res;
9246 
9247 	if (too_many_args(1, args, err, NULL))
9248 		return -1;
9249 
9250 	if (*(args[1]) == 0) {
9251 		memprintf(err, "'%s' expects ssl sessions <lifetime> in seconds as argument.", args[0]);
9252 		return -1;
9253 	}
9254 
9255 	res = parse_time_err(args[1], &global_ssl.life_time, TIME_UNIT_S);
9256 	if (res == PARSE_TIME_OVER) {
9257 		memprintf(err, "timer overflow in argument '%s' to <%s> (maximum value is 2147483647 s or ~68 years).",
9258 			  args[1], args[0]);
9259 		return -1;
9260 	}
9261 	else if (res == PARSE_TIME_UNDER) {
9262 		memprintf(err, "timer underflow in argument '%s' to <%s> (minimum non-null value is 1 s).",
9263 			  args[1], args[0]);
9264 		return -1;
9265 	}
9266 	else if (res) {
9267 		memprintf(err, "unexpected character '%c' in argument to <%s>.", *res, args[0]);
9268 		return -1;
9269 	}
9270 	return 0;
9271 }
9272 
9273 #ifndef OPENSSL_NO_DH
9274 /* parse "ssl-dh-param-file".
9275  * Returns <0 on alert, >0 on warning, 0 on success.
9276  */
9277 static int ssl_parse_global_dh_param_file(char **args, int section_type, struct proxy *curpx,
9278                                        struct proxy *defpx, const char *file, int line,
9279                                        char **err)
9280 {
9281 	if (too_many_args(1, args, err, NULL))
9282 		return -1;
9283 
9284 	if (*(args[1]) == 0) {
9285 		memprintf(err, "'%s' expects a file path as an argument.", args[0]);
9286 		return -1;
9287 	}
9288 
9289 	if (ssl_sock_load_global_dh_param_from_file(args[1])) {
9290 		memprintf(err, "'%s': unable to load DH parameters from file <%s>.", args[0], args[1]);
9291 		return -1;
9292 	}
9293 	return 0;
9294 }
9295 
9296 /* parse "ssl.default-dh-param".
9297  * Returns <0 on alert, >0 on warning, 0 on success.
9298  */
9299 static int ssl_parse_global_default_dh(char **args, int section_type, struct proxy *curpx,
9300                                        struct proxy *defpx, const char *file, int line,
9301                                        char **err)
9302 {
9303 	if (too_many_args(1, args, err, NULL))
9304 		return -1;
9305 
9306 	if (*(args[1]) == 0) {
9307 		memprintf(err, "'%s' expects an integer argument.", args[0]);
9308 		return -1;
9309 	}
9310 
9311 	global_ssl.default_dh_param = atoi(args[1]);
9312 	if (global_ssl.default_dh_param < 1024) {
9313 		memprintf(err, "'%s' expects a value >= 1024.", args[0]);
9314 		return -1;
9315 	}
9316 	return 0;
9317 }
9318 #endif
9319 
9320 
9321 /* This function is used with TLS ticket keys management. It permits to browse
9322  * each reference. The variable <getnext> must contain the current node,
9323  * <end> point to the root node.
9324  */
9325 #if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
9326 static inline
9327 struct tls_keys_ref *tlskeys_list_get_next(struct tls_keys_ref *getnext, struct list *end)
9328 {
9329 	struct tls_keys_ref *ref = getnext;
9330 
9331 	while (1) {
9332 
9333 		/* Get next list entry. */
9334 		ref = LIST_NEXT(&ref->list, struct tls_keys_ref *, list);
9335 
9336 		/* If the entry is the last of the list, return NULL. */
9337 		if (&ref->list == end)
9338 			return NULL;
9339 
9340 		return ref;
9341 	}
9342 }
9343 
9344 static inline
9345 struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
9346 {
9347 	int id;
9348 	char *error;
9349 
9350 	/* If the reference starts by a '#', this is numeric id. */
9351 	if (reference[0] == '#') {
9352 		/* Try to convert the numeric id. If the conversion fails, the lookup fails. */
9353 		id = strtol(reference + 1, &error, 10);
9354 		if (*error != '\0')
9355 			return NULL;
9356 
9357 		/* Perform the unique id lookup. */
9358 		return tlskeys_ref_lookupid(id);
9359 	}
9360 
9361 	/* Perform the string lookup. */
9362 	return tlskeys_ref_lookup(reference);
9363 }
9364 #endif
9365 
9366 
9367 #if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
9368 
9369 static int cli_io_handler_tlskeys_files(struct appctx *appctx);
9370 
9371 static inline int cli_io_handler_tlskeys_entries(struct appctx *appctx) {
9372 	return cli_io_handler_tlskeys_files(appctx);
9373 }
9374 
9375 /* dumps all tls keys. Relies on cli.i0 (non-null = only list file names), cli.i1
9376  * (next index to be dumped), and cli.p0 (next key reference).
9377  */
9378 static int cli_io_handler_tlskeys_files(struct appctx *appctx) {
9379 
9380 	struct stream_interface *si = appctx->owner;
9381 
9382 	switch (appctx->st2) {
9383 	case STAT_ST_INIT:
9384 		/* Display the column headers. If the message cannot be sent,
9385 		 * quit the function with returning 0. The function is called
9386 		 * later and restart at the state "STAT_ST_INIT".
9387 		 */
9388 		chunk_reset(&trash);
9389 
9390 		if (appctx->io_handler == cli_io_handler_tlskeys_entries)
9391 			chunk_appendf(&trash, "# id secret\n");
9392 		else
9393 			chunk_appendf(&trash, "# id (file)\n");
9394 
9395 		if (ci_putchk(si_ic(si), &trash) == -1) {
9396 			si_rx_room_blk(si);
9397 			return 0;
9398 		}
9399 
9400 		/* Now, we start the browsing of the references lists.
9401 		 * Note that the following call to LIST_ELEM return bad pointer. The only
9402 		 * available field of this pointer is <list>. It is used with the function
9403 		 * tlskeys_list_get_next() for retruning the first available entry
9404 		 */
9405 		if (appctx->ctx.cli.p0 == NULL) {
9406 			appctx->ctx.cli.p0 = LIST_ELEM(&tlskeys_reference, struct tls_keys_ref *, list);
9407 			appctx->ctx.cli.p0 = tlskeys_list_get_next(appctx->ctx.cli.p0, &tlskeys_reference);
9408 		}
9409 
9410 		appctx->st2 = STAT_ST_LIST;
9411 		/* fall through */
9412 
9413 	case STAT_ST_LIST:
9414 		while (appctx->ctx.cli.p0) {
9415 			struct tls_keys_ref *ref = appctx->ctx.cli.p0;
9416 
9417 			chunk_reset(&trash);
9418 			if (appctx->io_handler == cli_io_handler_tlskeys_entries && appctx->ctx.cli.i1 == 0)
9419 				chunk_appendf(&trash, "# ");
9420 
9421 			if (appctx->ctx.cli.i1 == 0)
9422 				chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
9423 
9424 			if (appctx->io_handler == cli_io_handler_tlskeys_entries) {
9425 				int head;
9426 
9427 				HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
9428 				head = ref->tls_ticket_enc_index;
9429 				while (appctx->ctx.cli.i1 < TLS_TICKETS_NO) {
9430 					struct buffer *t2 = get_trash_chunk();
9431 
9432 					chunk_reset(t2);
9433 					/* should never fail here because we dump only a key in the t2 buffer */
9434 					if (ref->key_size_bits == 128) {
9435 						t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
9436 						                   sizeof(struct tls_sess_key_128),
9437 						                   t2->area, t2->size);
9438 						chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
9439 							      t2->area);
9440 					}
9441 					else if (ref->key_size_bits == 256) {
9442 						t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
9443 						                   sizeof(struct tls_sess_key_256),
9444 						                   t2->area, t2->size);
9445 						chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
9446 							      t2->area);
9447 					}
9448 					else {
9449 						/* This case should never happen */
9450 						chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, appctx->ctx.cli.i1);
9451 					}
9452 
9453 					if (ci_putchk(si_ic(si), &trash) == -1) {
9454 						/* let's try again later from this stream. We add ourselves into
9455 						 * this stream's users so that it can remove us upon termination.
9456 						 */
9457 						HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
9458 						si_rx_room_blk(si);
9459 						return 0;
9460 					}
9461 					appctx->ctx.cli.i1++;
9462 				}
9463 				HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
9464 				appctx->ctx.cli.i1 = 0;
9465 			}
9466 			if (ci_putchk(si_ic(si), &trash) == -1) {
9467 				/* let's try again later from this stream. We add ourselves into
9468 				 * this stream's users so that it can remove us upon termination.
9469 				 */
9470 				si_rx_room_blk(si);
9471 				return 0;
9472 			}
9473 
9474 			if (appctx->ctx.cli.i0 == 0) /* don't display everything if not necessary */
9475 				break;
9476 
9477 			/* get next list entry and check the end of the list */
9478 			appctx->ctx.cli.p0 = tlskeys_list_get_next(appctx->ctx.cli.p0, &tlskeys_reference);
9479 		}
9480 
9481 		appctx->st2 = STAT_ST_FIN;
9482 		/* fall through */
9483 
9484 	default:
9485 		appctx->st2 = STAT_ST_FIN;
9486 		return 1;
9487 	}
9488 	return 0;
9489 }
9490 
9491 /* sets cli.i0 to non-zero if only file lists should be dumped */
9492 static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
9493 {
9494 	/* no parameter, shows only file list */
9495 	if (!*args[2]) {
9496 		appctx->ctx.cli.i0 = 1;
9497 		appctx->io_handler = cli_io_handler_tlskeys_files;
9498 		return 0;
9499 	}
9500 
9501 	if (args[2][0] == '*') {
9502 		/* list every TLS ticket keys */
9503 		appctx->ctx.cli.i0 = 1;
9504 	} else {
9505 		appctx->ctx.cli.p0 = tlskeys_ref_lookup_ref(args[2]);
9506 		if (!appctx->ctx.cli.p0) {
9507 			appctx->ctx.cli.severity = LOG_ERR;
9508 			appctx->ctx.cli.msg = "'show tls-keys' unable to locate referenced filename\n";
9509 			appctx->st0 = CLI_ST_PRINT;
9510 			return 1;
9511 		}
9512 	}
9513 	appctx->io_handler = cli_io_handler_tlskeys_entries;
9514 	return 0;
9515 }
9516 
9517 static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
9518 {
9519 	struct tls_keys_ref *ref;
9520 	int ret;
9521 
9522 	/* Expect two parameters: the filename and the new new TLS key in encoding */
9523 	if (!*args[3] || !*args[4]) {
9524 		appctx->ctx.cli.severity = LOG_ERR;
9525 		appctx->ctx.cli.msg = "'set ssl tls-key' expects a filename and the new TLS key in base64 encoding.\n";
9526 		appctx->st0 = CLI_ST_PRINT;
9527 		return 1;
9528 	}
9529 
9530 	ref = tlskeys_ref_lookup_ref(args[3]);
9531 	if (!ref) {
9532 		appctx->ctx.cli.severity = LOG_ERR;
9533 		appctx->ctx.cli.msg = "'set ssl tls-key' unable to locate referenced filename\n";
9534 		appctx->st0 = CLI_ST_PRINT;
9535 		return 1;
9536 	}
9537 
9538 	ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
9539 	if (ret < 0) {
9540 		appctx->ctx.cli.severity = LOG_ERR;
9541 		appctx->ctx.cli.msg = "'set ssl tls-key' received invalid base64 encoded TLS key.\n";
9542 		appctx->st0 = CLI_ST_PRINT;
9543 		return 1;
9544 	}
9545 
9546 	trash.data = ret;
9547 	if (ssl_sock_update_tlskey_ref(ref, &trash) < 0) {
9548 		appctx->ctx.cli.severity = LOG_ERR;
9549 		appctx->ctx.cli.msg = "'set ssl tls-key' received a key of wrong size.\n";
9550 		appctx->st0 = CLI_ST_PRINT;
9551 		return 1;
9552 	}
9553 	appctx->ctx.cli.severity = LOG_INFO;
9554 	appctx->ctx.cli.msg = "TLS ticket key updated!\n";
9555 	appctx->st0 = CLI_ST_PRINT;
9556 	return 1;
9557 
9558 }
9559 #endif
9560 
9561 static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
9562 {
9563 #if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
9564 	char *err = NULL;
9565 	int i, j, ret;
9566 
9567 	if (!payload)
9568 		payload = args[3];
9569 
9570 	/* Expect one parameter: the new response in base64 encoding */
9571 	if (!*payload) {
9572 		appctx->ctx.cli.severity = LOG_ERR;
9573 		appctx->ctx.cli.msg = "'set ssl ocsp-response' expects response in base64 encoding.\n";
9574 		appctx->st0 = CLI_ST_PRINT;
9575 		return 1;
9576 	}
9577 
9578 	/* remove \r and \n from the payload */
9579 	for (i = 0, j = 0; payload[i]; i++) {
9580 		if (payload[i] == '\r' || payload[i] == '\n')
9581 			continue;
9582 		payload[j++] = payload[i];
9583 	}
9584 	payload[j] = 0;
9585 
9586 	ret = base64dec(payload, j, trash.area, trash.size);
9587 	if (ret < 0) {
9588 		appctx->ctx.cli.severity = LOG_ERR;
9589 		appctx->ctx.cli.msg = "'set ssl ocsp-response' received invalid base64 encoded response.\n";
9590 		appctx->st0 = CLI_ST_PRINT;
9591 		return 1;
9592 	}
9593 
9594 	trash.data = ret;
9595 	if (ssl_sock_update_ocsp_response(&trash, &err)) {
9596 		if (err) {
9597 			memprintf(&err, "%s.\n", err);
9598 			appctx->ctx.cli.err = err;
9599 			appctx->st0 = CLI_ST_PRINT_FREE;
9600 		}
9601 		else {
9602 			appctx->ctx.cli.severity = LOG_ERR;
9603 			appctx->ctx.cli.msg = "Failed to update OCSP response.\n";
9604 			appctx->st0 = CLI_ST_PRINT;
9605 		}
9606 		return 1;
9607 	}
9608 	appctx->ctx.cli.severity = LOG_INFO;
9609 	appctx->ctx.cli.msg = "OCSP Response updated!\n";
9610 	appctx->st0 = CLI_ST_PRINT;
9611 	return 1;
9612 #else
9613 	appctx->ctx.cli.severity = LOG_ERR;
9614 	appctx->ctx.cli.msg = "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n";
9615 	appctx->st0 = CLI_ST_PRINT;
9616 	return 1;
9617 #endif
9618 
9619 }
9620 
9621 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1000100fL)
9622 /* This function checks an <arg> and fills it with a variable type if the
9623  * <arg> string contains a valid variable name. If failed, the function
9624  * tries to perform a base64 decode operation on the same string, and
9625  * fills the <arg> with the decoded content.
9626  *
9627  * Validation is skipped if the <arg> string is empty.
9628  *
9629  * This function returns 0 if the variable lookup fails and the specified
9630  * <arg> string is not a valid base64 encoded string, as well if
9631  * unexpected argument type is specified or memory allocation error
9632  * occurs. Otherwise it returns 1.
9633  */
9634 static inline int sample_check_arg_base64(struct arg *arg, char **err)
9635 {
9636 	char *dec = NULL;
9637 	int dec_size;
9638 
9639 	if (arg->type != ARGT_STR) {
9640 		memprintf(err, "unexpected argument type");
9641 		return 0;
9642 	}
9643 
9644 	if (arg->data.str.data == 0) /* empty */
9645 		return 1;
9646 
9647 	if (vars_check_arg(arg, NULL))
9648 		return 1;
9649 
9650 	if (arg->data.str.data % 4) {
9651 		memprintf(err, "argument needs to be base64 encoded, and "
9652 		               "can either be a string or a variable");
9653 		return 0;
9654 	}
9655 
9656 	dec_size = (arg->data.str.data / 4 * 3)
9657 	           - (arg->data.str.area[arg->data.str.data-1] == '=' ? 1 : 0)
9658 	           - (arg->data.str.area[arg->data.str.data-2] == '=' ? 1 : 0);
9659 
9660 	if ((dec = malloc(dec_size)) == NULL) {
9661 		memprintf(err, "memory allocation error");
9662 		return 0;
9663 	}
9664 
9665 	dec_size = base64dec(arg->data.str.area, arg->data.str.data, dec, dec_size);
9666 	if (dec_size < 0) {
9667 		memprintf(err, "argument needs to be base64 encoded, and "
9668 		               "can either be a string or a variable");
9669 		free(dec);
9670 		return 0;
9671 	}
9672 
9673 	/* base64 decoded */
9674 	chunk_destroy(&arg->data.str);
9675 	arg->data.str.area = dec;
9676 	arg->data.str.data = dec_size;
9677 	return 1;
9678 }
9679 
9680 static int check_aes_gcm(struct arg *args, struct sample_conv *conv,
9681 						  const char *file, int line, char **err)
9682 {
9683 	switch(args[0].data.sint) {
9684 	case 128:
9685 	case 192:
9686 	case 256:
9687 		break;
9688 	default:
9689 		memprintf(err, "key size must be 128, 192 or 256 (bits).");
9690 		return 0;
9691 	}
9692 
9693 	/* Try to decode variables. */
9694 	if (!sample_check_arg_base64(&args[1], err)) {
9695 		memprintf(err, "failed to parse nonce : %s", *err);
9696 		return 0;
9697 	}
9698 	if (!sample_check_arg_base64(&args[2], err)) {
9699 		memprintf(err, "failed to parse key : %s", *err);
9700 		return 0;
9701 	}
9702 	if (!sample_check_arg_base64(&args[3], err)) {
9703 		memprintf(err, "failed to parse aead_tag : %s", *err);
9704 		return 0;
9705 	}
9706 
9707 	return 1;
9708 }
9709 
9710 /* Arguements: AES size in bits, nonce, key, tag. The last three arguments are base64 encoded */
9711 static int sample_conv_aes_gcm_dec(const struct arg *arg_p, struct sample *smp, void *private)
9712 {
9713 	struct sample nonce, key, aead_tag;
9714 	struct buffer *smp_trash = NULL, *smp_trash_alloc = NULL;
9715 	EVP_CIPHER_CTX *ctx;
9716 	int dec_size, ret;
9717 
9718 	smp_trash_alloc = alloc_trash_chunk();
9719 	if (!smp_trash_alloc)
9720 		return 0;
9721 
9722 	/* smp copy */
9723 	smp_trash_alloc->data = smp->data.u.str.data;
9724 	if (unlikely(smp_trash_alloc->data > smp_trash_alloc->size))
9725 		smp_trash_alloc->data = smp_trash_alloc->size;
9726 	memcpy(smp_trash_alloc->area, smp->data.u.str.area, smp_trash_alloc->data);
9727 
9728 	ctx = EVP_CIPHER_CTX_new();
9729 
9730 	if (!ctx)
9731 		goto err;
9732 
9733 	smp_trash = alloc_trash_chunk();
9734 	if (!smp_trash)
9735 		goto err;
9736 
9737 	smp_set_owner(&nonce, smp->px, smp->sess, smp->strm, smp->opt);
9738 	if (!sample_conv_var2smp_str(&arg_p[1], &nonce))
9739 		goto err;
9740 
9741 	if (arg_p[1].type == ARGT_VAR) {
9742 		dec_size = base64dec(nonce.data.u.str.area, nonce.data.u.str.data, smp_trash->area, smp_trash->size);
9743 		if (dec_size < 0)
9744 			goto err;
9745 		smp_trash->data = dec_size;
9746 		nonce.data.u.str = *smp_trash;
9747 	}
9748 
9749 	/* Set cipher type and mode */
9750 	switch(arg_p[0].data.sint) {
9751 	case 128:
9752 		EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
9753 		break;
9754 	case 192:
9755 		EVP_DecryptInit_ex(ctx, EVP_aes_192_gcm(), NULL, NULL, NULL);
9756 		break;
9757 	case 256:
9758 		EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
9759 		break;
9760 	}
9761 
9762 	EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, nonce.data.u.str.data, NULL);
9763 
9764 	/* Initialise IV */
9765 	if(!EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, (unsigned char *) nonce.data.u.str.area))
9766 		goto err;
9767 
9768 	smp_set_owner(&key, smp->px, smp->sess, smp->strm, smp->opt);
9769 	if (!sample_conv_var2smp_str(&arg_p[2], &key))
9770 		goto err;
9771 
9772 	if (arg_p[2].type == ARGT_VAR) {
9773 		dec_size = base64dec(key.data.u.str.area, key.data.u.str.data, smp_trash->area, smp_trash->size);
9774 		if (dec_size < 0)
9775 			goto err;
9776 		smp_trash->data = dec_size;
9777 		key.data.u.str = *smp_trash;
9778 	}
9779 
9780 	/* Initialise key */
9781 	if (!EVP_DecryptInit_ex(ctx, NULL, NULL, (unsigned char *) key.data.u.str.area, NULL))
9782 		goto err;
9783 
9784 	if (!EVP_DecryptUpdate(ctx, (unsigned char *) smp_trash->area, (int *) &smp_trash->data,
9785 	                       (unsigned char *) smp_trash_alloc->area, (int) smp_trash_alloc->data))
9786 		goto err;
9787 
9788 	smp_set_owner(&aead_tag, smp->px, smp->sess, smp->strm, smp->opt);
9789 	if (!sample_conv_var2smp_str(&arg_p[3], &aead_tag))
9790 		goto err;
9791 
9792 	if (arg_p[3].type == ARGT_VAR) {
9793 		dec_size = base64dec(aead_tag.data.u.str.area, aead_tag.data.u.str.data, smp_trash_alloc->area, smp_trash_alloc->size);
9794 		if (dec_size < 0)
9795 			goto err;
9796 		smp_trash_alloc->data = dec_size;
9797 		aead_tag.data.u.str = *smp_trash_alloc;
9798 	}
9799 
9800 	dec_size = smp_trash->data;
9801 
9802 	EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, aead_tag.data.u.str.data, (void *) aead_tag.data.u.str.area);
9803 	ret = EVP_DecryptFinal_ex(ctx, (unsigned char *) smp_trash->area + smp_trash->data, (int *) &smp_trash->data);
9804 
9805 	if (ret <= 0)
9806 		goto err;
9807 
9808 	smp->data.u.str.data = dec_size + smp_trash->data;
9809 	smp->data.u.str.area = smp_trash->area;
9810 	smp->data.type = SMP_T_BIN;
9811 	smp_dup(smp);
9812 	free_trash_chunk(smp_trash_alloc);
9813 	free_trash_chunk(smp_trash);
9814 	return 1;
9815 
9816 err:
9817 	free_trash_chunk(smp_trash_alloc);
9818 	free_trash_chunk(smp_trash);
9819 	return 0;
9820 }
9821 # endif
9822 
9823 /* register cli keywords */
9824 static struct cli_kw_list cli_kws = {{ },{
9825 #if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
9826 	{ { "show", "tls-keys", NULL }, "show tls-keys [id|*]: show tls keys references or dump tls ticket keys when id specified", cli_parse_show_tlskeys, NULL },
9827 	{ { "set", "ssl", "tls-key", NULL }, "set ssl tls-key [id|keyfile] <tlskey>: set the next TLS key for the <id> or <keyfile> listener to <tlskey>", cli_parse_set_tlskeys, NULL },
9828 #endif
9829 	{ { "set", "ssl", "ocsp-response", NULL }, NULL, cli_parse_set_ocspresponse, NULL },
9830 	{ { NULL }, NULL, NULL, NULL }
9831 }};
9832 
9833 INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
9834 
9835 /* Note: must not be declared <const> as its list will be overwritten.
9836  * Please take care of keeping this list alphabetically sorted.
9837  */
9838 static struct sample_fetch_kw_list sample_fetch_keywords = {ILH, {
9839 	{ "ssl_bc",                 smp_fetch_ssl_fc,             0,                   NULL,    SMP_T_BOOL, SMP_USE_L5SRV },
9840 	{ "ssl_bc_alg_keysize",     smp_fetch_ssl_fc_alg_keysize, 0,                   NULL,    SMP_T_SINT, SMP_USE_L5SRV },
9841 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
9842 	{ "ssl_bc_alpn",            smp_fetch_ssl_fc_alpn,        0,                   NULL,    SMP_T_STR,  SMP_USE_L5SRV },
9843 #endif
9844 	{ "ssl_bc_cipher",          smp_fetch_ssl_fc_cipher,      0,                   NULL,    SMP_T_STR,  SMP_USE_L5SRV },
9845 #if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
9846 	{ "ssl_bc_npn",             smp_fetch_ssl_fc_npn,         0,                   NULL,    SMP_T_STR,  SMP_USE_L5SRV },
9847 #endif
9848 	{ "ssl_bc_is_resumed",      smp_fetch_ssl_fc_is_resumed,  0,                   NULL,    SMP_T_BOOL, SMP_USE_L5SRV },
9849 	{ "ssl_bc_protocol",        smp_fetch_ssl_fc_protocol,    0,                   NULL,    SMP_T_STR,  SMP_USE_L5SRV },
9850 	{ "ssl_bc_unique_id",       smp_fetch_ssl_fc_unique_id,   0,                   NULL,    SMP_T_BIN,  SMP_USE_L5SRV },
9851 	{ "ssl_bc_use_keysize",     smp_fetch_ssl_fc_use_keysize, 0,                   NULL,    SMP_T_SINT, SMP_USE_L5SRV },
9852 #if HA_OPENSSL_VERSION_NUMBER > 0x0090800fL
9853 	{ "ssl_bc_session_id",      smp_fetch_ssl_fc_session_id,  0,                   NULL,    SMP_T_BIN,  SMP_USE_L5SRV },
9854 #endif
9855 #if HA_OPENSSL_VERSION_NUMBER >= 0x10100000L
9856 	{ "ssl_bc_client_random",   smp_fetch_ssl_fc_random,      0,                   NULL,    SMP_T_BIN,  SMP_USE_L5SRV },
9857 	{ "ssl_bc_server_random",   smp_fetch_ssl_fc_random,      0,                   NULL,    SMP_T_BIN,  SMP_USE_L5SRV },
9858 	{ "ssl_bc_session_key",     smp_fetch_ssl_fc_session_key, 0,                   NULL,    SMP_T_BIN,  SMP_USE_L5SRV },
9859 #endif
9860 	{ "ssl_c_ca_err",           smp_fetch_ssl_c_ca_err,       0,                   NULL,    SMP_T_SINT, SMP_USE_L5CLI },
9861 	{ "ssl_c_ca_err_depth",     smp_fetch_ssl_c_ca_err_depth, 0,                   NULL,    SMP_T_SINT, SMP_USE_L5CLI },
9862 	{ "ssl_c_der",              smp_fetch_ssl_x_der,          0,                   NULL,    SMP_T_BIN,  SMP_USE_L5CLI },
9863 	{ "ssl_c_err",              smp_fetch_ssl_c_err,          0,                   NULL,    SMP_T_SINT, SMP_USE_L5CLI },
9864 	{ "ssl_c_i_dn",             smp_fetch_ssl_x_i_dn,         ARG2(0,STR,SINT),    NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9865 	{ "ssl_c_key_alg",          smp_fetch_ssl_x_key_alg,      0,                   NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9866 	{ "ssl_c_notafter",         smp_fetch_ssl_x_notafter,     0,                   NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9867 	{ "ssl_c_notbefore",        smp_fetch_ssl_x_notbefore,    0,                   NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9868 	{ "ssl_c_sig_alg",          smp_fetch_ssl_x_sig_alg,      0,                   NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9869 	{ "ssl_c_s_dn",             smp_fetch_ssl_x_s_dn,         ARG2(0,STR,SINT),    NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9870 	{ "ssl_c_serial",           smp_fetch_ssl_x_serial,       0,                   NULL,    SMP_T_BIN,  SMP_USE_L5CLI },
9871 	{ "ssl_c_sha1",             smp_fetch_ssl_x_sha1,         0,                   NULL,    SMP_T_BIN,  SMP_USE_L5CLI },
9872 	{ "ssl_c_used",             smp_fetch_ssl_c_used,         0,                   NULL,    SMP_T_BOOL, SMP_USE_L5CLI },
9873 	{ "ssl_c_verify",           smp_fetch_ssl_c_verify,       0,                   NULL,    SMP_T_SINT, SMP_USE_L5CLI },
9874 	{ "ssl_c_version",          smp_fetch_ssl_x_version,      0,                   NULL,    SMP_T_SINT, SMP_USE_L5CLI },
9875 	{ "ssl_f_der",              smp_fetch_ssl_x_der,          0,                   NULL,    SMP_T_BIN,  SMP_USE_L5CLI },
9876 	{ "ssl_f_i_dn",             smp_fetch_ssl_x_i_dn,         ARG2(0,STR,SINT),    NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9877 	{ "ssl_f_key_alg",          smp_fetch_ssl_x_key_alg,      0,                   NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9878 	{ "ssl_f_notafter",         smp_fetch_ssl_x_notafter,     0,                   NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9879 	{ "ssl_f_notbefore",        smp_fetch_ssl_x_notbefore,    0,                   NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9880 	{ "ssl_f_sig_alg",          smp_fetch_ssl_x_sig_alg,      0,                   NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9881 	{ "ssl_f_s_dn",             smp_fetch_ssl_x_s_dn,         ARG2(0,STR,SINT),    NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9882 	{ "ssl_f_serial",           smp_fetch_ssl_x_serial,       0,                   NULL,    SMP_T_BIN,  SMP_USE_L5CLI },
9883 	{ "ssl_f_sha1",             smp_fetch_ssl_x_sha1,         0,                   NULL,    SMP_T_BIN,  SMP_USE_L5CLI },
9884 	{ "ssl_f_version",          smp_fetch_ssl_x_version,      0,                   NULL,    SMP_T_SINT, SMP_USE_L5CLI },
9885 	{ "ssl_fc",                 smp_fetch_ssl_fc,             0,                   NULL,    SMP_T_BOOL, SMP_USE_L5CLI },
9886 	{ "ssl_fc_alg_keysize",     smp_fetch_ssl_fc_alg_keysize, 0,                   NULL,    SMP_T_SINT, SMP_USE_L5CLI },
9887 	{ "ssl_fc_cipher",          smp_fetch_ssl_fc_cipher,      0,                   NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9888 	{ "ssl_fc_has_crt",         smp_fetch_ssl_fc_has_crt,     0,                   NULL,    SMP_T_BOOL, SMP_USE_L5CLI },
9889 	{ "ssl_fc_has_early",       smp_fetch_ssl_fc_has_early,   0,                   NULL,    SMP_T_BOOL, SMP_USE_L5CLI },
9890 	{ "ssl_fc_has_sni",         smp_fetch_ssl_fc_has_sni,     0,                   NULL,    SMP_T_BOOL, SMP_USE_L5CLI },
9891 	{ "ssl_fc_is_resumed",      smp_fetch_ssl_fc_is_resumed,  0,                   NULL,    SMP_T_BOOL, SMP_USE_L5CLI },
9892 #if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
9893 	{ "ssl_fc_npn",             smp_fetch_ssl_fc_npn,         0,                   NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9894 #endif
9895 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
9896 	{ "ssl_fc_alpn",            smp_fetch_ssl_fc_alpn,        0,                   NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9897 #endif
9898 	{ "ssl_fc_protocol",        smp_fetch_ssl_fc_protocol,    0,                   NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9899 #if HA_OPENSSL_VERSION_NUMBER > 0x0090800fL
9900 	{ "ssl_fc_unique_id",       smp_fetch_ssl_fc_unique_id,   0,                   NULL,    SMP_T_BIN,  SMP_USE_L5CLI },
9901 #endif
9902 	{ "ssl_fc_use_keysize",     smp_fetch_ssl_fc_use_keysize, 0,                   NULL,    SMP_T_SINT, SMP_USE_L5CLI },
9903 #if HA_OPENSSL_VERSION_NUMBER > 0x0090800fL
9904 	{ "ssl_fc_session_id",      smp_fetch_ssl_fc_session_id,  0,                   NULL,    SMP_T_BIN,  SMP_USE_L5CLI },
9905 #endif
9906 #if HA_OPENSSL_VERSION_NUMBER >= 0x10100000L
9907 	{ "ssl_fc_client_random",   smp_fetch_ssl_fc_random,      0,                   NULL,    SMP_T_BIN,  SMP_USE_L5CLI },
9908 	{ "ssl_fc_server_random",   smp_fetch_ssl_fc_random,      0,                   NULL,    SMP_T_BIN,  SMP_USE_L5CLI },
9909 	{ "ssl_fc_session_key",     smp_fetch_ssl_fc_session_key, 0,                   NULL,    SMP_T_BIN,  SMP_USE_L5CLI },
9910 #endif
9911 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
9912 	{ "ssl_fc_sni",             smp_fetch_ssl_fc_sni,         0,                   NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9913 #endif
9914 	{ "ssl_fc_cipherlist_bin",  smp_fetch_ssl_fc_cl_bin,      0,                   NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9915 	{ "ssl_fc_cipherlist_hex",  smp_fetch_ssl_fc_cl_hex,      0,                   NULL,    SMP_T_BIN,  SMP_USE_L5CLI },
9916 	{ "ssl_fc_cipherlist_str",  smp_fetch_ssl_fc_cl_str,      0,                   NULL,    SMP_T_STR,  SMP_USE_L5CLI },
9917 	{ "ssl_fc_cipherlist_xxh",  smp_fetch_ssl_fc_cl_xxh64,    0,                   NULL,    SMP_T_SINT, SMP_USE_L5CLI },
9918 	{ NULL, NULL, 0, 0, 0 },
9919 }};
9920 
9921 INITCALL1(STG_REGISTER, sample_register_fetches, &sample_fetch_keywords);
9922 
9923 /* Note: must not be declared <const> as its list will be overwritten.
9924  * Please take care of keeping this list alphabetically sorted.
9925  */
9926 static struct acl_kw_list acl_kws = {ILH, {
9927 	{ "ssl_fc_sni_end",         "ssl_fc_sni", PAT_MATCH_END },
9928 	{ "ssl_fc_sni_reg",         "ssl_fc_sni", PAT_MATCH_REG },
9929 	{ /* END */ },
9930 }};
9931 
9932 INITCALL1(STG_REGISTER, acl_register_keywords, &acl_kws);
9933 
9934 /* Note: must not be declared <const> as its list will be overwritten.
9935  * Please take care of keeping this list alphabetically sorted, doing so helps
9936  * all code contributors.
9937  * Optional keywords are also declared with a NULL ->parse() function so that
9938  * the config parser can report an appropriate error when a known keyword was
9939  * not enabled.
9940  */
9941 static struct ssl_bind_kw ssl_bind_kws[] = {
9942 	{ "allow-0rtt",            ssl_bind_parse_allow_0rtt,       0 }, /* allow 0-RTT */
9943 	{ "alpn",                  ssl_bind_parse_alpn,             1 }, /* set ALPN supported protocols */
9944 	{ "ca-file",               ssl_bind_parse_ca_file,          1 }, /* set CAfile to process verify on client cert */
9945 	{ "ciphers",               ssl_bind_parse_ciphers,          1 }, /* set SSL cipher suite */
9946 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
9947 	{ "ciphersuites",          ssl_bind_parse_ciphersuites,     1 }, /* set TLS 1.3 cipher suite */
9948 #endif
9949 	{ "crl-file",              ssl_bind_parse_crl_file,         1 }, /* set certificat revocation list file use on client cert verify */
9950 	{ "curves",                ssl_bind_parse_curves,           1 }, /* set SSL curve suite */
9951 	{ "ecdhe",                 ssl_bind_parse_ecdhe,            1 }, /* defines named curve for elliptic curve Diffie-Hellman */
9952 	{ "no-ca-names",           ssl_bind_parse_no_ca_names,      0 }, /* do not send ca names to clients (ca_file related) */
9953 	{ "npn",                   ssl_bind_parse_npn,              1 }, /* set NPN supported protocols */
9954 	{ "ssl-min-ver",           ssl_bind_parse_tls_method_minmax,1 }, /* minimum version */
9955 	{ "ssl-max-ver",           ssl_bind_parse_tls_method_minmax,1 }, /* maximum version */
9956 	{ "verify",                ssl_bind_parse_verify,           1 }, /* set SSL verify method */
9957 	{ NULL, NULL, 0 },
9958 };
9959 
9960 /* no initcall for ssl_bind_kws, these ones are parsed in the parser loop */
9961 
9962 static struct bind_kw_list bind_kws = { "SSL", { }, {
9963 	{ "allow-0rtt",            bind_parse_allow_0rtt,         0 }, /* Allow 0RTT */
9964 	{ "alpn",                  bind_parse_alpn,               1 }, /* set ALPN supported protocols */
9965 	{ "ca-file",               bind_parse_ca_file,            1 }, /* set CAfile to process verify on client cert */
9966 	{ "ca-ignore-err",         bind_parse_ignore_err,         1 }, /* set error IDs to ignore on verify depth > 0 */
9967 	{ "ca-sign-file",          bind_parse_ca_sign_file,       1 }, /* set CAFile used to generate and sign server certs */
9968 	{ "ca-sign-pass",          bind_parse_ca_sign_pass,       1 }, /* set CAKey passphrase */
9969 	{ "ciphers",               bind_parse_ciphers,            1 }, /* set SSL cipher suite */
9970 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
9971 	{ "ciphersuites",          bind_parse_ciphersuites,       1 }, /* set TLS 1.3 cipher suite */
9972 #endif
9973 	{ "crl-file",              bind_parse_crl_file,           1 }, /* set certificat revocation list file use on client cert verify */
9974 	{ "crt",                   bind_parse_crt,                1 }, /* load SSL certificates from this location */
9975 	{ "crt-ignore-err",        bind_parse_ignore_err,         1 }, /* set error IDs to ingore on verify depth == 0 */
9976 	{ "crt-list",              bind_parse_crt_list,           1 }, /* load a list of crt from this location */
9977 	{ "curves",                bind_parse_curves,             1 }, /* set SSL curve suite */
9978 	{ "ecdhe",                 bind_parse_ecdhe,              1 }, /* defines named curve for elliptic curve Diffie-Hellman */
9979 	{ "force-sslv3",           bind_parse_tls_method_options, 0 }, /* force SSLv3 */
9980 	{ "force-tlsv10",          bind_parse_tls_method_options, 0 }, /* force TLSv10 */
9981 	{ "force-tlsv11",          bind_parse_tls_method_options, 0 }, /* force TLSv11 */
9982 	{ "force-tlsv12",          bind_parse_tls_method_options, 0 }, /* force TLSv12 */
9983 	{ "force-tlsv13",          bind_parse_tls_method_options, 0 }, /* force TLSv13 */
9984 	{ "generate-certificates", bind_parse_generate_certs,     0 }, /* enable the server certificates generation */
9985 	{ "no-ca-names",           bind_parse_no_ca_names,        0 }, /* do not send ca names to clients (ca_file related) */
9986 	{ "no-sslv3",              bind_parse_tls_method_options, 0 }, /* disable SSLv3 */
9987 	{ "no-tlsv10",             bind_parse_tls_method_options, 0 }, /* disable TLSv10 */
9988 	{ "no-tlsv11",             bind_parse_tls_method_options, 0 }, /* disable TLSv11 */
9989 	{ "no-tlsv12",             bind_parse_tls_method_options, 0 }, /* disable TLSv12 */
9990 	{ "no-tlsv13",             bind_parse_tls_method_options, 0 }, /* disable TLSv13 */
9991 	{ "no-tls-tickets",        bind_parse_no_tls_tickets,     0 }, /* disable session resumption tickets */
9992 	{ "ssl",                   bind_parse_ssl,                0 }, /* enable SSL processing */
9993 	{ "ssl-min-ver",           bind_parse_tls_method_minmax,  1 }, /* minimum version */
9994 	{ "ssl-max-ver",           bind_parse_tls_method_minmax,  1 }, /* maximum version */
9995 	{ "strict-sni",            bind_parse_strict_sni,         0 }, /* refuse negotiation if sni doesn't match a certificate */
9996 	{ "tls-ticket-keys",       bind_parse_tls_ticket_keys,    1 }, /* set file to load TLS ticket keys from */
9997 	{ "verify",                bind_parse_verify,             1 }, /* set SSL verify method */
9998 	{ "npn",                   bind_parse_npn,                1 }, /* set NPN supported protocols */
9999 	{ "prefer-client-ciphers", bind_parse_pcc,                0 }, /* prefer client ciphers */
10000 	{ NULL, NULL, 0 },
10001 }};
10002 
10003 INITCALL1(STG_REGISTER, bind_register_keywords, &bind_kws);
10004 
10005 /* Note: must not be declared <const> as its list will be overwritten.
10006  * Please take care of keeping this list alphabetically sorted, doing so helps
10007  * all code contributors.
10008  * Optional keywords are also declared with a NULL ->parse() function so that
10009  * the config parser can report an appropriate error when a known keyword was
10010  * not enabled.
10011  */
10012 static struct srv_kw_list srv_kws = { "SSL", { }, {
10013 	{ "allow-0rtt",              srv_parse_allow_0rtt,         0, 1 }, /* Allow using early data on this server */
10014 	{ "alpn",                    srv_parse_alpn,               1, 1 }, /* Set ALPN supported protocols */
10015 	{ "ca-file",                 srv_parse_ca_file,            1, 1 }, /* set CAfile to process verify server cert */
10016 	{ "check-alpn",              srv_parse_alpn,               1, 1 }, /* Set ALPN used for checks */
10017 	{ "check-sni",               srv_parse_check_sni,          1, 1 }, /* set SNI */
10018 	{ "check-ssl",               srv_parse_check_ssl,          0, 1 }, /* enable SSL for health checks */
10019 	{ "ciphers",                 srv_parse_ciphers,            1, 1 }, /* select the cipher suite */
10020 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
10021 	{ "ciphersuites",            srv_parse_ciphersuites,       1, 1 }, /* select the cipher suite */
10022 #endif
10023 	{ "crl-file",                srv_parse_crl_file,           1, 1 }, /* set certificate revocation list file use on server cert verify */
10024 	{ "crt",                     srv_parse_crt,                1, 1 }, /* set client certificate */
10025 	{ "force-sslv3",             srv_parse_tls_method_options, 0, 1 }, /* force SSLv3 */
10026 	{ "force-tlsv10",            srv_parse_tls_method_options, 0, 1 }, /* force TLSv10 */
10027 	{ "force-tlsv11",            srv_parse_tls_method_options, 0, 1 }, /* force TLSv11 */
10028 	{ "force-tlsv12",            srv_parse_tls_method_options, 0, 1 }, /* force TLSv12 */
10029 	{ "force-tlsv13",            srv_parse_tls_method_options, 0, 1 }, /* force TLSv13 */
10030 	{ "no-check-ssl",            srv_parse_no_check_ssl,       0, 1 }, /* disable SSL for health checks */
10031 	{ "no-send-proxy-v2-ssl",    srv_parse_no_send_proxy_ssl,  0, 1 }, /* do not send PROXY protocol header v2 with SSL info */
10032 	{ "no-send-proxy-v2-ssl-cn", srv_parse_no_send_proxy_cn,   0, 1 }, /* do not send PROXY protocol header v2 with CN */
10033 	{ "no-ssl",                  srv_parse_no_ssl,             0, 1 }, /* disable SSL processing */
10034 	{ "no-ssl-reuse",            srv_parse_no_ssl_reuse,       0, 1 }, /* disable session reuse */
10035 	{ "no-sslv3",                srv_parse_tls_method_options, 0, 0 }, /* disable SSLv3 */
10036 	{ "no-tlsv10",               srv_parse_tls_method_options, 0, 0 }, /* disable TLSv10 */
10037 	{ "no-tlsv11",               srv_parse_tls_method_options, 0, 0 }, /* disable TLSv11 */
10038 	{ "no-tlsv12",               srv_parse_tls_method_options, 0, 0 }, /* disable TLSv12 */
10039 	{ "no-tlsv13",               srv_parse_tls_method_options, 0, 0 }, /* disable TLSv13 */
10040 	{ "no-tls-tickets",          srv_parse_no_tls_tickets,     0, 1 }, /* disable session resumption tickets */
10041 	{ "npn",                     srv_parse_npn,                1, 1 }, /* Set NPN supported protocols */
10042 	{ "send-proxy-v2-ssl",       srv_parse_send_proxy_ssl,     0, 1 }, /* send PROXY protocol header v2 with SSL info */
10043 	{ "send-proxy-v2-ssl-cn",    srv_parse_send_proxy_cn,      0, 1 }, /* send PROXY protocol header v2 with CN */
10044 	{ "sni",                     srv_parse_sni,                1, 1 }, /* send SNI extension */
10045 	{ "ssl",                     srv_parse_ssl,                0, 1 }, /* enable SSL processing */
10046 	{ "ssl-min-ver",             srv_parse_tls_method_minmax,  1, 1 }, /* minimum version */
10047 	{ "ssl-max-ver",             srv_parse_tls_method_minmax,  1, 1 }, /* maximum version */
10048 	{ "ssl-reuse",               srv_parse_ssl_reuse,          0, 1 }, /* enable session reuse */
10049 	{ "tls-tickets",             srv_parse_tls_tickets,        0, 1 }, /* enable session resumption tickets */
10050 	{ "verify",                  srv_parse_verify,             1, 1 }, /* set SSL verify method */
10051 	{ "verifyhost",              srv_parse_verifyhost,         1, 1 }, /* require that SSL cert verifies for hostname */
10052 	{ NULL, NULL, 0, 0 },
10053 }};
10054 
10055 INITCALL1(STG_REGISTER, srv_register_keywords, &srv_kws);
10056 
10057 static struct cfg_kw_list cfg_kws = {ILH, {
10058 	{ CFG_GLOBAL, "ca-base",  ssl_parse_global_ca_crt_base },
10059 	{ CFG_GLOBAL, "crt-base", ssl_parse_global_ca_crt_base },
10060 	{ CFG_GLOBAL, "maxsslconn", ssl_parse_global_int },
10061 	{ CFG_GLOBAL, "ssl-default-bind-options", ssl_parse_default_bind_options },
10062 	{ CFG_GLOBAL, "ssl-default-server-options", ssl_parse_default_server_options },
10063 #ifndef OPENSSL_NO_DH
10064 	{ CFG_GLOBAL, "ssl-dh-param-file", ssl_parse_global_dh_param_file },
10065 #endif
10066 	{ CFG_GLOBAL, "ssl-mode-async",  ssl_parse_global_ssl_async },
10067 #ifndef OPENSSL_NO_ENGINE
10068 	{ CFG_GLOBAL, "ssl-engine",  ssl_parse_global_ssl_engine },
10069 #endif
10070 	{ CFG_GLOBAL, "tune.ssl.cachesize", ssl_parse_global_int },
10071 #ifndef OPENSSL_NO_DH
10072 	{ CFG_GLOBAL, "tune.ssl.default-dh-param", ssl_parse_global_default_dh },
10073 #endif
10074 	{ CFG_GLOBAL, "tune.ssl.force-private-cache",  ssl_parse_global_private_cache },
10075 	{ CFG_GLOBAL, "tune.ssl.lifetime", ssl_parse_global_lifetime },
10076 	{ CFG_GLOBAL, "tune.ssl.maxrecord", ssl_parse_global_int },
10077 	{ CFG_GLOBAL, "tune.ssl.ssl-ctx-cache-size", ssl_parse_global_int },
10078 	{ CFG_GLOBAL, "tune.ssl.capture-cipherlist-size", ssl_parse_global_capture_cipherlist },
10079 	{ CFG_GLOBAL, "ssl-default-bind-ciphers", ssl_parse_global_ciphers },
10080 	{ CFG_GLOBAL, "ssl-default-server-ciphers", ssl_parse_global_ciphers },
10081 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
10082 	{ CFG_GLOBAL, "ssl-default-bind-ciphersuites", ssl_parse_global_ciphersuites },
10083 	{ CFG_GLOBAL, "ssl-default-server-ciphersuites", ssl_parse_global_ciphersuites },
10084 #endif
10085 	{ 0, NULL, NULL },
10086 }};
10087 
10088 INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
10089 
10090 /* Note: must not be declared <const> as its list will be overwritten */
10091 static struct sample_conv_kw_list conv_kws = {ILH, {
10092 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1000100fL)
10093 	{ "aes_gcm_dec", sample_conv_aes_gcm_dec, ARG4(4,SINT,STR,STR,STR), check_aes_gcm, SMP_T_BIN, SMP_T_BIN },
10094 #endif
10095 	{ NULL, NULL, 0, 0, 0 },
10096 }};
10097 
10098 INITCALL1(STG_REGISTER, sample_register_convs, &conv_kws);
10099 
10100 /* transport-layer operations for SSL sockets */
10101 static struct xprt_ops ssl_sock = {
10102 	.snd_buf  = ssl_sock_from_buf,
10103 	.rcv_buf  = ssl_sock_to_buf,
10104 	.subscribe = ssl_subscribe,
10105 	.unsubscribe = ssl_unsubscribe,
10106 	.remove_xprt = ssl_remove_xprt,
10107 	.add_xprt = ssl_add_xprt,
10108 	.rcv_pipe = NULL,
10109 	.snd_pipe = NULL,
10110 	.shutr    = NULL,
10111 	.shutw    = ssl_sock_shutw,
10112 	.close    = ssl_sock_close,
10113 	.init     = ssl_sock_init,
10114 	.prepare_bind_conf = ssl_sock_prepare_bind_conf,
10115 	.destroy_bind_conf = ssl_sock_destroy_bind_conf,
10116 	.prepare_srv = ssl_sock_prepare_srv_ctx,
10117 	.destroy_srv = ssl_sock_free_srv_ctx,
10118 	.get_alpn = ssl_sock_get_alpn,
10119 	.name     = "SSL",
10120 };
10121 
10122 enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
10123                                        struct session *sess, struct stream *s, int flags)
10124 {
10125 	struct connection *conn;
10126 	struct conn_stream *cs;
10127 
10128 	conn = objt_conn(sess->origin);
10129 	cs = objt_cs(s->si[0].end);
10130 
10131 	if (conn && cs) {
10132 		if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
10133 			cs->flags |= CS_FL_WAIT_FOR_HS;
10134 			s->req.flags |= CF_READ_NULL;
10135 			return ACT_RET_YIELD;
10136 		}
10137 	}
10138 	return (ACT_RET_CONT);
10139 }
10140 
10141 static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
10142 {
10143 	rule->action_ptr = ssl_action_wait_for_hs;
10144 
10145 	return ACT_RET_PRS_OK;
10146 }
10147 
10148 static struct action_kw_list http_req_actions = {ILH, {
10149 	{ "wait-for-handshake", ssl_parse_wait_for_hs },
10150 	{ /* END */ }
10151 }};
10152 
10153 INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
10154 
10155 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
10156 
10157 static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
10158 {
10159 	if (ptr) {
10160 		chunk_destroy(ptr);
10161 		free(ptr);
10162 	}
10163 }
10164 
10165 #endif
10166 static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
10167 {
10168 	pool_free(pool_head_ssl_capture, ptr);
10169 }
10170 
10171 __attribute__((constructor))
10172 static void __ssl_sock_init(void)
10173 {
10174 #if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
10175 	STACK_OF(SSL_COMP)* cm;
10176 	int n;
10177 #endif
10178 
10179 	if (global_ssl.listen_default_ciphers)
10180 		global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
10181 	if (global_ssl.connect_default_ciphers)
10182 		global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
10183 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
10184 	if (global_ssl.listen_default_ciphersuites)
10185 		global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
10186 	if (global_ssl.connect_default_ciphersuites)
10187 		global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
10188 #endif
10189 
10190 	xprt_register(XPRT_SSL, &ssl_sock);
10191 #if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
10192 	SSL_library_init();
10193 #endif
10194 #if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
10195 	cm = SSL_COMP_get_compression_methods();
10196 	n = sk_SSL_COMP_num(cm);
10197 	while (n--) {
10198 		(void) sk_SSL_COMP_pop(cm);
10199 	}
10200 #endif
10201 
10202 #if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
10203 	ssl_locking_init();
10204 #endif
10205 #if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
10206 	sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
10207 #endif
10208 	ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
10209 	ssl_capture_ptr_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_capture_free_func);
10210 	ssl_pkey_info_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
10211 #ifndef OPENSSL_NO_ENGINE
10212 	ENGINE_load_builtin_engines();
10213 	hap_register_post_check(ssl_check_async_engine_count);
10214 #endif
10215 #if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
10216 	hap_register_post_check(tlskeys_finalize_config);
10217 #endif
10218 
10219 	global.ssl_session_max_cost   = SSL_SESSION_MAX_COST;
10220 	global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
10221 
10222 #ifndef OPENSSL_NO_DH
10223 	ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
10224 	hap_register_post_deinit(ssl_free_dh);
10225 #endif
10226 #ifndef OPENSSL_NO_ENGINE
10227 	hap_register_post_deinit(ssl_free_engines);
10228 #endif
10229 	/* Load SSL string for the verbose & debug mode. */
10230 	ERR_load_SSL_strings();
10231 	ha_meth = BIO_meth_new(0x666, "ha methods");
10232 	BIO_meth_set_write(ha_meth, ha_ssl_write);
10233 	BIO_meth_set_read(ha_meth, ha_ssl_read);
10234 	BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
10235 	BIO_meth_set_create(ha_meth, ha_ssl_new);
10236 	BIO_meth_set_destroy(ha_meth, ha_ssl_free);
10237 	BIO_meth_set_puts(ha_meth, ha_ssl_puts);
10238 	BIO_meth_set_gets(ha_meth, ha_ssl_gets);
10239 }
10240 
10241 /* Compute and register the version string */
10242 static void ssl_register_build_options()
10243 {
10244 	char *ptr = NULL;
10245 	int i;
10246 
10247 	memprintf(&ptr, "Built with OpenSSL version : "
10248 #ifdef OPENSSL_IS_BORINGSSL
10249 		"BoringSSL");
10250 #else /* OPENSSL_IS_BORINGSSL */
10251 	        OPENSSL_VERSION_TEXT
10252 		"\nRunning on OpenSSL version : %s%s",
10253 	       OpenSSL_version(OPENSSL_VERSION),
10254 	       ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
10255 #endif
10256 	memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
10257 #if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
10258 		"no (library version too old)"
10259 #elif defined(OPENSSL_NO_TLSEXT)
10260 		"no (disabled via OPENSSL_NO_TLSEXT)"
10261 #else
10262 		"yes"
10263 #endif
10264 		"", ptr);
10265 
10266 	memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
10267 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
10268 		"yes"
10269 #else
10270 #ifdef OPENSSL_NO_TLSEXT
10271 		"no (because of OPENSSL_NO_TLSEXT)"
10272 #else
10273 		"no (version might be too old, 0.9.8f min needed)"
10274 #endif
10275 #endif
10276 	       "", ptr);
10277 
10278 	memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
10279 	for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
10280 		if (methodVersions[i].option)
10281 			memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
10282 
10283 	hap_register_build_opts(ptr, 1);
10284 }
10285 
10286 INITCALL0(STG_REGISTER, ssl_register_build_options);
10287 
10288 
10289 #ifndef OPENSSL_NO_ENGINE
10290 void ssl_free_engines(void) {
10291 	struct ssl_engine_list *wl, *wlb;
10292 	/* free up engine list */
10293 	list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
10294 		ENGINE_finish(wl->e);
10295 		ENGINE_free(wl->e);
10296 		LIST_DEL(&wl->list);
10297 		free(wl);
10298 	}
10299 }
10300 #endif
10301 
10302 #ifndef OPENSSL_NO_DH
10303 void ssl_free_dh(void) {
10304 	if (local_dh_1024) {
10305 		DH_free(local_dh_1024);
10306 		local_dh_1024 = NULL;
10307 	}
10308 	if (local_dh_2048) {
10309 		DH_free(local_dh_2048);
10310 		local_dh_2048 = NULL;
10311 	}
10312 	if (local_dh_4096) {
10313 		DH_free(local_dh_4096);
10314 		local_dh_4096 = NULL;
10315 	}
10316 	if (global_dh) {
10317 		DH_free(global_dh);
10318 		global_dh = NULL;
10319 	}
10320 }
10321 #endif
10322 
10323 __attribute__((destructor))
10324 static void __ssl_sock_deinit(void)
10325 {
10326 #if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
10327 	if (ssl_ctx_lru_tree) {
10328 		lru64_destroy(ssl_ctx_lru_tree);
10329 		HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
10330 	}
10331 #endif
10332 
10333 #if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
10334         ERR_remove_state(0);
10335         ERR_free_strings();
10336 
10337         EVP_cleanup();
10338 #endif
10339 
10340 #if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
10341         CRYPTO_cleanup_all_ex_data();
10342 #endif
10343 	BIO_meth_free(ha_meth);
10344 }
10345 
10346 
10347 /*
10348  * Local variables:
10349  *  c-indent-level: 8
10350  *  c-basic-offset: 8
10351  * End:
10352  */
10353