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