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