blob: 308dbfacdb58158c363f6711e47005b11471ec02 [file] [log] [blame]
yanbzhu08ce6ab2015-12-02 13:01:29 -05001
Emeric Brun46591952012-05-18 15:47:34 +02002/*
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02003 * SSL/TLS transport layer over SOCK_STREAM sockets
Emeric Brun46591952012-05-18 15:47:34 +02004 *
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 *
Willy Tarreau69845df2012-09-10 09:43:09 +020012 * 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 *
Emeric Brun46591952012-05-18 15:47:34 +020024 */
25
Willy Tarreau8d164dc2019-05-10 09:35:00 +020026/* Note: do NOT include openssl/xxx.h here, do it in openssl-compat.h */
Emeric Brun46591952012-05-18 15:47:34 +020027#define _GNU_SOURCE
Emeric Brunfc0421f2012-09-07 17:30:07 +020028#include <ctype.h>
29#include <dirent.h>
Emeric Brun46591952012-05-18 15:47:34 +020030#include <errno.h>
31#include <fcntl.h>
32#include <stdio.h>
33#include <stdlib.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020034#include <string.h>
35#include <unistd.h>
Emeric Brun46591952012-05-18 15:47:34 +020036
37#include <sys/socket.h>
38#include <sys/stat.h>
39#include <sys/types.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020040#include <netdb.h>
Emeric Brun46591952012-05-18 15:47:34 +020041#include <netinet/tcp.h>
42
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020043#include <haproxy/api.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020044#include <import/lru.h>
45#include <import/xxhash.h>
46
Willy Tarreau2741c8c2020-06-02 11:28:02 +020047#include <haproxy/dynbuf.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020048#include <haproxy/chunk.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020049#include <haproxy/connection.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020050#include <haproxy/errors.h>
Willy Tarreau762d7a52020-06-04 11:23:07 +020051#include <haproxy/frontend.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020052#include <haproxy/global.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020053#include <haproxy/http_rules.h>
Willy Tarreau6019fab2020-05-27 16:26:00 +020054#include <haproxy/openssl-compat.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020055#include <haproxy/pattern-t.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020056#include <haproxy/shctx.h>
Willy Tarreau47d7f902020-06-04 14:25:47 +020057#include <haproxy/ssl_ckch.h>
Willy Tarreau52d88722020-06-04 14:29:23 +020058#include <haproxy/ssl_crtlist.h>
Willy Tarreaub2bd8652020-06-04 14:21:22 +020059#include <haproxy/ssl_utils.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020060#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020061#include <haproxy/tools.h>
Willy Tarreauc2f7c582020-06-02 18:15:32 +020062#include <haproxy/ticks.h>
Willy Tarreau92b4f132020-06-01 11:05:15 +020063#include <haproxy/time.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020064#include <haproxy/base64.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020065#include <haproxy/vars.h>
Emeric Brun46591952012-05-18 15:47:34 +020066
Willy Tarreau8d2b7772020-05-27 10:58:19 +020067#include <import/ebpttree.h>
68#include <import/ebsttree.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020069
William Lallemand32af2032016-10-29 18:09:35 +020070#include <types/cli.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020071#include <types/ssl_sock.h>
William Lallemand32af2032016-10-29 18:09:35 +020072#include <types/stats.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020073
Willy Tarreauaa74c4e2020-06-04 10:19:23 +020074#include <haproxy/arg.h>
William Lallemand32af2032016-10-29 18:09:35 +020075#include <proto/channel.h>
William Lallemand32af2032016-10-29 18:09:35 +020076#include <proto/cli.h>
Willy Tarreau0f6ffd62020-06-03 19:33:00 +020077#include <haproxy/fd.h>
Willy Tarreau66347942020-06-01 12:18:08 +020078#include <haproxy/freq_ctr.h>
Willy Tarreaufc774542020-06-04 17:31:04 +020079#include <haproxy/proto_tcp.h>
Christopher Fauletfc9cfe42019-07-16 14:54:53 +020080#include <proto/http_ana.h>
Willy Tarreau92faadf2012-10-10 23:04:25 +020081#include <proto/server.h>
William Lallemand32af2032016-10-29 18:09:35 +020082#include <proto/stream_interface.h>
Emeric Brun46591952012-05-18 15:47:34 +020083#include <proto/log.h>
Emeric Brun94324a42012-10-11 14:00:19 +020084#include <proto/proxy.h>
Emeric Brun46591952012-05-18 15:47:34 +020085#include <proto/ssl_sock.h>
Willy Tarreau9ad7bd42015-04-03 19:19:59 +020086#include <proto/stream.h>
Emeric Brun46591952012-05-18 15:47:34 +020087
Willy Tarreau9356dac2019-05-10 09:22:53 +020088/* ***** READ THIS before adding code here! *****
89 *
90 * Due to API incompatibilities between multiple OpenSSL versions and their
91 * derivatives, it's often tempting to add macros to (re-)define certain
92 * symbols. Please do not do this here, and do it in common/openssl-compat.h
93 * exclusively so that the whole code consistently uses the same macros.
94 *
95 * Whenever possible if a macro is missing in certain versions, it's better
96 * to conditionally define it in openssl-compat.h than using lots of ifdefs.
97 */
98
Willy Tarreau71b734c2014-01-28 15:19:44 +010099int sslconns = 0;
100int totalsslconns = 0;
Emeric Brunece0c332017-12-06 13:51:49 +0100101int nb_engines = 0;
Emeric Brune1f38db2012-09-03 20:36:47 +0200102
William Lallemande0f3fd52020-02-25 14:53:06 +0100103static struct eb_root cert_issuer_tree = EB_ROOT; /* issuers tree from "issuers-chain-path" */
104
William Lallemand7fd8b452020-05-07 15:20:43 +0200105struct global_ssl global_ssl = {
Willy Tarreauef934602016-12-22 23:12:01 +0100106#ifdef LISTEN_DEFAULT_CIPHERS
107 .listen_default_ciphers = LISTEN_DEFAULT_CIPHERS,
108#endif
109#ifdef CONNECT_DEFAULT_CIPHERS
110 .connect_default_ciphers = CONNECT_DEFAULT_CIPHERS,
111#endif
Emmanuel Hocdet839af572019-05-14 16:27:35 +0200112#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200113#ifdef LISTEN_DEFAULT_CIPHERSUITES
114 .listen_default_ciphersuites = LISTEN_DEFAULT_CIPHERSUITES,
115#endif
116#ifdef CONNECT_DEFAULT_CIPHERSUITES
117 .connect_default_ciphersuites = CONNECT_DEFAULT_CIPHERSUITES,
118#endif
119#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100120 .listen_default_ssloptions = BC_SSL_O_NONE,
121 .connect_default_ssloptions = SRV_SSL_O_NONE,
122
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +0200123 .listen_default_sslmethods.flags = MC_SSL_O_ALL,
124 .listen_default_sslmethods.min = CONF_TLSV_NONE,
125 .listen_default_sslmethods.max = CONF_TLSV_NONE,
126 .connect_default_sslmethods.flags = MC_SSL_O_ALL,
127 .connect_default_sslmethods.min = CONF_TLSV_NONE,
128 .connect_default_sslmethods.max = CONF_TLSV_NONE,
129
Willy Tarreauef934602016-12-22 23:12:01 +0100130#ifdef DEFAULT_SSL_MAX_RECORD
131 .max_record = DEFAULT_SSL_MAX_RECORD,
132#endif
133 .default_dh_param = SSL_DEFAULT_DH_PARAM,
134 .ctx_cache = DEFAULT_SSL_CTX_CACHE,
Thierry FOURNIER5bf77322017-02-25 12:45:22 +0100135 .capture_cipherlist = 0,
William Lallemand3af48e72020-02-03 17:15:52 +0100136 .extra_files = SSL_GF_ALL,
Willy Tarreauef934602016-12-22 23:12:01 +0100137};
138
Olivier Houcharda8955d52019-04-07 22:00:38 +0200139static BIO_METHOD *ha_meth;
140
Olivier Houchard66ab4982019-02-26 18:37:15 +0100141DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx_pool", sizeof(struct ssl_sock_ctx));
142
Olivier Houchardea8dd942019-05-20 14:02:16 +0200143static struct task *ssl_sock_io_cb(struct task *, void *, unsigned short);
Olivier Houchard000694c2019-05-23 14:45:12 +0200144static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
Olivier Houchardea8dd942019-05-20 14:02:16 +0200145
Olivier Houcharda8955d52019-04-07 22:00:38 +0200146/* Methods to implement OpenSSL BIO */
147static int ha_ssl_write(BIO *h, const char *buf, int num)
148{
149 struct buffer tmpbuf;
150 struct ssl_sock_ctx *ctx;
151 int ret;
152
153 ctx = BIO_get_data(h);
154 tmpbuf.size = num;
155 tmpbuf.area = (void *)(uintptr_t)buf;
156 tmpbuf.data = num;
157 tmpbuf.head = 0;
158 ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200159 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200160 BIO_set_retry_write(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200161 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200162 } else if (ret == 0)
163 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200164 return ret;
165}
166
167static int ha_ssl_gets(BIO *h, char *buf, int size)
168{
169
170 return 0;
171}
172
173static int ha_ssl_puts(BIO *h, const char *str)
174{
175
176 return ha_ssl_write(h, str, strlen(str));
177}
178
179static int ha_ssl_read(BIO *h, char *buf, int size)
180{
181 struct buffer tmpbuf;
182 struct ssl_sock_ctx *ctx;
183 int ret;
184
185 ctx = BIO_get_data(h);
186 tmpbuf.size = size;
187 tmpbuf.area = buf;
188 tmpbuf.data = 0;
189 tmpbuf.head = 0;
190 ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200191 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200192 BIO_set_retry_read(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200193 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200194 } else if (ret == 0)
195 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200196
197 return ret;
198}
199
200static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
201{
202 int ret = 0;
203 switch (cmd) {
204 case BIO_CTRL_DUP:
205 case BIO_CTRL_FLUSH:
206 ret = 1;
207 break;
208 }
209 return ret;
210}
211
212static int ha_ssl_new(BIO *h)
213{
214 BIO_set_init(h, 1);
215 BIO_set_data(h, NULL);
216 BIO_clear_flags(h, ~0);
217 return 1;
218}
219
220static int ha_ssl_free(BIO *data)
221{
222
223 return 1;
224}
225
226
Willy Tarreau5db847a2019-05-09 14:13:35 +0200227#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100228
Emeric Brun821bb9b2017-06-15 16:37:39 +0200229static HA_RWLOCK_T *ssl_rwlocks;
230
231
232unsigned long ssl_id_function(void)
233{
234 return (unsigned long)tid;
235}
236
237void ssl_locking_function(int mode, int n, const char * file, int line)
238{
239 if (mode & CRYPTO_LOCK) {
240 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100241 HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200242 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100243 HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200244 }
245 else {
246 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100247 HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200248 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100249 HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200250 }
251}
252
253static int ssl_locking_init(void)
254{
255 int i;
256
257 ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
258 if (!ssl_rwlocks)
259 return -1;
260
261 for (i = 0 ; i < CRYPTO_num_locks() ; i++)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100262 HA_RWLOCK_INIT(&ssl_rwlocks[i]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200263
264 CRYPTO_set_id_callback(ssl_id_function);
265 CRYPTO_set_locking_callback(ssl_locking_function);
266
267 return 0;
268}
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100269
Emeric Brun821bb9b2017-06-15 16:37:39 +0200270#endif
271
Willy Tarreauaf613e82020-06-05 08:40:51 +0200272__decl_thread(HA_SPINLOCK_T ckch_lock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200273
William Lallemandbc6ca7c2019-10-29 23:48:19 +0100274
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200275/*
Emmanuel Hocdetb270e812019-11-21 19:09:31 +0100276 * deduplicate cafile (and crlfile)
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200277 */
278struct cafile_entry {
279 X509_STORE *ca_store;
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200280 STACK_OF(X509_NAME) *ca_list;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200281 struct ebmb_node node;
282 char path[0];
283};
284
285static struct eb_root cafile_tree = EB_ROOT_UNIQUE;
286
287static X509_STORE* ssl_store_get0_locations_file(char *path)
288{
289 struct ebmb_node *eb;
290
291 eb = ebst_lookup(&cafile_tree, path);
292 if (eb) {
293 struct cafile_entry *ca_e;
294 ca_e = ebmb_entry(eb, struct cafile_entry, node);
295 return ca_e->ca_store;
296 }
297 return NULL;
298}
299
William Lallemanddad31052020-05-14 17:47:32 +0200300int ssl_store_load_locations_file(char *path)
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200301{
302 if (ssl_store_get0_locations_file(path) == NULL) {
303 struct cafile_entry *ca_e;
304 X509_STORE *store = X509_STORE_new();
305 if (X509_STORE_load_locations(store, path, NULL)) {
306 int pathlen;
307 pathlen = strlen(path);
308 ca_e = calloc(1, sizeof(*ca_e) + pathlen + 1);
309 if (ca_e) {
310 memcpy(ca_e->path, path, pathlen + 1);
311 ca_e->ca_store = store;
312 ebst_insert(&cafile_tree, &ca_e->node);
313 return 1;
314 }
315 }
316 X509_STORE_free(store);
317 return 0;
318 }
319 return 1;
320}
321
322/* mimic what X509_STORE_load_locations do with store_ctx */
323static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
324{
325 X509_STORE *store;
326 store = ssl_store_get0_locations_file(path);
327 if (store_ctx && store) {
328 int i;
329 X509_OBJECT *obj;
330 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
331 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
332 obj = sk_X509_OBJECT_value(objs, i);
333 switch (X509_OBJECT_get_type(obj)) {
334 case X509_LU_X509:
335 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
336 break;
337 case X509_LU_CRL:
338 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
339 break;
340 default:
341 break;
342 }
343 }
344 return 1;
345 }
346 return 0;
347}
348
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500349/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200350static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
351{
352 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
353 return ssl_set_cert_crl_file(store_ctx, path);
354}
355
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200356/*
357 Extract CA_list from CA_file already in tree.
358 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
359 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
360*/
361static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
362{
363 struct ebmb_node *eb;
364 struct cafile_entry *ca_e;
365
366 eb = ebst_lookup(&cafile_tree, path);
367 if (!eb)
368 return NULL;
369 ca_e = ebmb_entry(eb, struct cafile_entry, node);
370
371 if (ca_e->ca_list == NULL) {
372 int i;
373 unsigned long key;
374 struct eb_root ca_name_tree = EB_ROOT;
375 struct eb64_node *node, *back;
376 struct {
377 struct eb64_node node;
378 X509_NAME *xname;
379 } *ca_name;
380 STACK_OF(X509_OBJECT) *objs;
381 STACK_OF(X509_NAME) *skn;
382 X509 *x;
383 X509_NAME *xn;
384
385 skn = sk_X509_NAME_new_null();
386 /* take x509 from cafile_tree */
387 objs = X509_STORE_get0_objects(ca_e->ca_store);
388 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
389 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
390 if (!x)
391 continue;
392 xn = X509_get_subject_name(x);
393 if (!xn)
394 continue;
395 /* Check for duplicates. */
396 key = X509_NAME_hash(xn);
397 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
398 node && ca_name == NULL;
399 node = eb64_next(node)) {
400 ca_name = container_of(node, typeof(*ca_name), node);
401 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
402 ca_name = NULL;
403 }
404 /* find a duplicate */
405 if (ca_name)
406 continue;
407 ca_name = calloc(1, sizeof *ca_name);
408 xn = X509_NAME_dup(xn);
409 if (!ca_name ||
410 !xn ||
411 !sk_X509_NAME_push(skn, xn)) {
412 free(ca_name);
413 X509_NAME_free(xn);
414 sk_X509_NAME_pop_free(skn, X509_NAME_free);
415 sk_X509_NAME_free(skn);
416 skn = NULL;
417 break;
418 }
419 ca_name->node.key = key;
420 ca_name->xname = xn;
421 eb64_insert(&ca_name_tree, &ca_name->node);
422 }
423 ca_e->ca_list = skn;
424 /* remove temporary ca_name tree */
425 node = eb64_first(&ca_name_tree);
426 while (node) {
427 ca_name = container_of(node, typeof(*ca_name), node);
428 back = eb64_next(node);
429 eb64_delete(node);
430 free(ca_name);
431 node = back;
432 }
433 }
434 return ca_e->ca_list;
435}
436
Willy Tarreaubafbe012017-11-24 17:34:44 +0100437struct pool_head *pool_head_ssl_capture = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200438int ssl_capture_ptr_index = -1;
Thierry FOURNIER28962c92018-06-17 21:37:05 +0200439static int ssl_app_data_index = -1;
Willy Tarreauef934602016-12-22 23:12:01 +0100440
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200441#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
442struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
443#endif
444
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200445#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200446unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000447struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
448struct ssl_engine_list {
449 struct list list;
450 ENGINE *e;
451};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200452#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000453
Remi Gacogne8de54152014-07-15 11:36:40 +0200454#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200455static int ssl_dh_ptr_index = -1;
Remi Gacogne47783ef2015-05-29 15:53:22 +0200456static DH *global_dh = NULL;
Remi Gacogne8de54152014-07-15 11:36:40 +0200457static DH *local_dh_1024 = NULL;
458static DH *local_dh_2048 = NULL;
459static DH *local_dh_4096 = NULL;
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +0100460static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen);
Remi Gacogne8de54152014-07-15 11:36:40 +0200461#endif /* OPENSSL_NO_DH */
462
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100463#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200464/* X509V3 Extensions that will be added on generated certificates */
465#define X509V3_EXT_SIZE 5
466static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
467 "basicConstraints",
468 "nsComment",
469 "subjectKeyIdentifier",
470 "authorityKeyIdentifier",
471 "keyUsage",
472};
473static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
474 "CA:FALSE",
475 "\"OpenSSL Generated Certificate\"",
476 "hash",
477 "keyid,issuer:always",
478 "nonRepudiation,digitalSignature,keyEncipherment"
479};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200480/* LRU cache to store generated certificate */
481static struct lru64_head *ssl_ctx_lru_tree = NULL;
482static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200483static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100484__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200485
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200486#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
487
Willy Tarreau9a1ab082019-05-09 13:26:41 +0200488#if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL
yanbzhube2774d2015-12-10 15:07:30 -0500489/* The order here matters for picking a default context,
490 * keep the most common keytype at the bottom of the list
491 */
492const char *SSL_SOCK_KEYTYPE_NAMES[] = {
493 "dsa",
494 "ecdsa",
495 "rsa"
496};
yanbzhube2774d2015-12-10 15:07:30 -0500497#endif
498
William Lallemandc3cd35f2017-11-28 11:04:43 +0100499static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100500static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
501
Dragan Dosen9ac98092020-05-11 15:51:45 +0200502/* Dedicated callback functions for heartbeat and clienthello.
503 */
504#ifdef TLS1_RT_HEARTBEAT
505static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
506 int content_type, const void *buf, size_t len,
507 SSL *ssl);
508#endif
509static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
510 int content_type, const void *buf, size_t len,
511 SSL *ssl);
512
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200513/* List head of all registered SSL/TLS protocol message callbacks. */
514struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
515
516/* Registers the function <func> in order to be called on SSL/TLS protocol
517 * message processing. It will return 0 if the function <func> is not set
518 * or if it fails to allocate memory.
519 */
520int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
521{
522 struct ssl_sock_msg_callback *cbk;
523
524 if (!func)
525 return 0;
526
527 cbk = calloc(1, sizeof(*cbk));
528 if (!cbk) {
529 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
530 return 0;
531 }
532
533 cbk->func = func;
534
535 LIST_ADDQ(&ssl_sock_msg_callbacks, &cbk->list);
536
537 return 1;
538}
539
Dragan Dosen9ac98092020-05-11 15:51:45 +0200540/* Used to register dedicated SSL/TLS protocol message callbacks.
541 */
542static int ssl_sock_register_msg_callbacks(void)
543{
544#ifdef TLS1_RT_HEARTBEAT
545 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
546 return ERR_ABORT;
547#endif
548 if (global_ssl.capture_cipherlist > 0) {
549 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
550 return ERR_ABORT;
551 }
552 return 0;
553}
554
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200555/* Used to free all SSL/TLS protocol message callbacks that were
556 * registered by using ssl_sock_register_msg_callback().
557 */
558static void ssl_sock_unregister_msg_callbacks(void)
559{
560 struct ssl_sock_msg_callback *cbk, *cbkback;
561
562 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
563 LIST_DEL(&cbk->list);
564 free(cbk);
565 }
566}
567
Dragan Doseneb607fe2020-05-11 17:17:06 +0200568SSL *ssl_sock_get_ssl_object(struct connection *conn)
569{
570 if (!ssl_sock_is_ssl(conn))
571 return NULL;
572
573 return ((struct ssl_sock_ctx *)(conn->xprt_ctx))->ssl;
574}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100575/*
576 * This function gives the detail of the SSL error. It is used only
577 * if the debug mode and the verbose mode are activated. It dump all
578 * the SSL error until the stack was empty.
579 */
580static forceinline void ssl_sock_dump_errors(struct connection *conn)
581{
582 unsigned long ret;
583
584 if (unlikely(global.mode & MODE_DEBUG)) {
585 while(1) {
586 ret = ERR_get_error();
587 if (ret == 0)
588 return;
589 fprintf(stderr, "fd[%04x] OpenSSL error[0x%lx] %s: %s\n",
Willy Tarreau585744b2017-08-24 14:31:19 +0200590 (unsigned short)conn->handle.fd, ret,
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100591 ERR_func_error_string(ret), ERR_reason_error_string(ret));
592 }
593 }
594}
595
yanbzhube2774d2015-12-10 15:07:30 -0500596
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200597#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200598int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000599{
600 int err_code = ERR_ABORT;
601 ENGINE *engine;
602 struct ssl_engine_list *el;
603
604 /* grab the structural reference to the engine */
605 engine = ENGINE_by_id(engine_id);
606 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100607 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000608 goto fail_get;
609 }
610
611 if (!ENGINE_init(engine)) {
612 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100613 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000614 goto fail_init;
615 }
616
617 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100618 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000619 goto fail_set_method;
620 }
621
622 el = calloc(1, sizeof(*el));
623 el->e = engine;
624 LIST_ADD(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100625 nb_engines++;
626 if (global_ssl.async)
627 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000628 return 0;
629
630fail_set_method:
631 /* release the functional reference from ENGINE_init() */
632 ENGINE_finish(engine);
633
634fail_init:
635 /* release the structural reference from ENGINE_by_id() */
636 ENGINE_free(engine);
637
638fail_get:
639 return err_code;
640}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200641#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000642
Willy Tarreau5db847a2019-05-09 14:13:35 +0200643#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brun3854e012017-05-17 20:42:48 +0200644/*
645 * openssl async fd handler
646 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200647void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000648{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200649 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000650
Emeric Brun3854e012017-05-17 20:42:48 +0200651 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000652 * to poll this fd until it is requested
653 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000654 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000655 fd_cant_recv(fd);
656
657 /* crypto engine is available, let's notify the associated
658 * connection that it can pursue its processing.
659 */
Olivier Houchard03abf2d2019-05-28 10:12:02 +0200660 ssl_sock_io_cb(NULL, ctx, 0);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000661}
662
Emeric Brun3854e012017-05-17 20:42:48 +0200663/*
664 * openssl async delayed SSL_free handler
665 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200666void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000667{
668 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200669 OSSL_ASYNC_FD all_fd[32];
670 size_t num_all_fds = 0;
671 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000672
Emeric Brun3854e012017-05-17 20:42:48 +0200673 /* We suppose that the async job for a same SSL *
674 * are serialized. So if we are awake it is
675 * because the running job has just finished
676 * and we can remove all async fds safely
677 */
678 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
679 if (num_all_fds > 32) {
680 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
681 return;
682 }
683
684 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
685 for (i=0 ; i < num_all_fds ; i++)
686 fd_remove(all_fd[i]);
687
688 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000689 SSL_free(ssl);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +0100690 _HA_ATOMIC_SUB(&sslconns, 1);
691 _HA_ATOMIC_SUB(&jobs, 1);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000692}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000693/*
Emeric Brun3854e012017-05-17 20:42:48 +0200694 * function used to manage a returned SSL_ERROR_WANT_ASYNC
695 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000696 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200697static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000698{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100699 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200700 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200701 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000702 size_t num_add_fds = 0;
703 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200704 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000705
706 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
707 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200708 if (num_add_fds > 32 || num_del_fds > 32) {
709 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000710 return;
711 }
712
Emeric Brun3854e012017-05-17 20:42:48 +0200713 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000714
Emeric Brun3854e012017-05-17 20:42:48 +0200715 /* We remove unused fds from the fdtab */
716 for (i=0 ; i < num_del_fds ; i++)
717 fd_remove(del_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000718
Emeric Brun3854e012017-05-17 20:42:48 +0200719 /* We add new fds to the fdtab */
720 for (i=0 ; i < num_add_fds ; i++) {
Olivier Houchardea8dd942019-05-20 14:02:16 +0200721 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000722 }
723
Emeric Brun3854e012017-05-17 20:42:48 +0200724 num_add_fds = 0;
725 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
726 if (num_add_fds > 32) {
727 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
728 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000729 }
Emeric Brun3854e012017-05-17 20:42:48 +0200730
731 /* We activate the polling for all known async fds */
732 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000733 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200734 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000735 /* To ensure that the fd cache won't be used
736 * We'll prefer to catch a real RD event
737 * because handling an EAGAIN on this fd will
738 * result in a context switch and also
739 * some engines uses a fd in blocking mode.
740 */
741 fd_cant_recv(add_fd[i]);
742 }
Emeric Brun3854e012017-05-17 20:42:48 +0200743
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000744}
745#endif
746
William Lallemand104a7a62019-10-14 14:14:59 +0200747#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200748/*
749 * This function returns the number of seconds elapsed
750 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
751 * date presented un ASN1_GENERALIZEDTIME.
752 *
753 * In parsing error case, it returns -1.
754 */
755static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
756{
757 long epoch;
758 char *p, *end;
759 const unsigned short month_offset[12] = {
760 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
761 };
762 int year, month;
763
764 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
765
766 p = (char *)d->data;
767 end = p + d->length;
768
769 if (end - p < 4) return -1;
770 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
771 p += 4;
772 if (end - p < 2) return -1;
773 month = 10 * (p[0] - '0') + p[1] - '0';
774 if (month < 1 || month > 12) return -1;
775 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
776 We consider leap years and the current month (<marsh or not) */
777 epoch = ( ((year - 1970) * 365)
778 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
779 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
780 + month_offset[month-1]
781 ) * 24 * 60 * 60;
782 p += 2;
783 if (end - p < 2) return -1;
784 /* Add the number of seconds of completed days of current month */
785 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
786 p += 2;
787 if (end - p < 2) return -1;
788 /* Add the completed hours of the current day */
789 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
790 p += 2;
791 if (end - p < 2) return -1;
792 /* Add the completed minutes of the current hour */
793 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
794 p += 2;
795 if (p == end) return -1;
796 /* Test if there is available seconds */
797 if (p[0] < '0' || p[0] > '9')
798 goto nosec;
799 if (end - p < 2) return -1;
800 /* Add the seconds of the current minute */
801 epoch += 10 * (p[0] - '0') + p[1] - '0';
802 p += 2;
803 if (p == end) return -1;
804 /* Ignore seconds float part if present */
805 if (p[0] == '.') {
806 do {
807 if (++p == end) return -1;
808 } while (p[0] >= '0' && p[0] <= '9');
809 }
810
811nosec:
812 if (p[0] == 'Z') {
813 if (end - p != 1) return -1;
814 return epoch;
815 }
816 else if (p[0] == '+') {
817 if (end - p != 5) return -1;
818 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700819 return epoch - ((10 * (p[1] - '0') + p[2] - '0') * 60 * 60 + (10 * (p[3] - '0') + p[4] - '0')) * 60;
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200820 }
821 else if (p[0] == '-') {
822 if (end - p != 5) return -1;
823 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700824 return epoch + ((10 * (p[1] - '0') + p[2] - '0') * 60 * 60 + (10 * (p[3] - '0') + p[4] - '0')) * 60;
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200825 }
826
827 return -1;
828}
829
William Lallemand104a7a62019-10-14 14:14:59 +0200830/*
831 * struct alignment works here such that the key.key is the same as key_data
832 * Do not change the placement of key_data
833 */
834struct certificate_ocsp {
835 struct ebmb_node key;
836 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
837 struct buffer response;
838 long expire;
839};
840
841struct ocsp_cbk_arg {
842 int is_single;
843 int single_kt;
844 union {
845 struct certificate_ocsp *s_ocsp;
846 /*
847 * m_ocsp will have multiple entries dependent on key type
848 * Entry 0 - DSA
849 * Entry 1 - ECDSA
850 * Entry 2 - RSA
851 */
852 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
853 };
854};
855
Emeric Brun1d3865b2014-06-20 15:37:32 +0200856static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200857
858/* This function starts to check if the OCSP response (in DER format) contained
859 * in chunk 'ocsp_response' is valid (else exits on error).
860 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
861 * contained in the OCSP Response and exits on error if no match.
862 * If it's a valid OCSP Response:
863 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
864 * pointed by 'ocsp'.
865 * If 'ocsp' is NULL, the function looks up into the OCSP response's
866 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
867 * from the response) and exits on error if not found. Finally, If an OCSP response is
868 * already present in the container, it will be overwritten.
869 *
870 * Note: OCSP response containing more than one OCSP Single response is not
871 * considered valid.
872 *
873 * Returns 0 on success, 1 in error case.
874 */
Willy Tarreau83061a82018-07-13 11:56:34 +0200875static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
876 struct certificate_ocsp *ocsp,
877 OCSP_CERTID *cid, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +0200878{
879 OCSP_RESPONSE *resp;
880 OCSP_BASICRESP *bs = NULL;
881 OCSP_SINGLERESP *sr;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200882 OCSP_CERTID *id;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200883 unsigned char *p = (unsigned char *) ocsp_response->area;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200884 int rc , count_sr;
Emeric Brun13a6b482014-06-20 15:44:34 +0200885 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200886 int reason;
887 int ret = 1;
888
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200889 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
890 ocsp_response->data);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200891 if (!resp) {
892 memprintf(err, "Unable to parse OCSP response");
893 goto out;
894 }
895
896 rc = OCSP_response_status(resp);
897 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
898 memprintf(err, "OCSP response status not successful");
899 goto out;
900 }
901
902 bs = OCSP_response_get1_basic(resp);
903 if (!bs) {
904 memprintf(err, "Failed to get basic response from OCSP Response");
905 goto out;
906 }
907
908 count_sr = OCSP_resp_count(bs);
909 if (count_sr > 1) {
910 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
911 goto out;
912 }
913
914 sr = OCSP_resp_get0(bs, 0);
915 if (!sr) {
916 memprintf(err, "Failed to get OCSP single response");
917 goto out;
918 }
919
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200920 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
921
Emeric Brun4147b2e2014-06-16 18:36:30 +0200922 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
Emmanuel Hocdetef607052017-10-24 14:57:16 +0200923 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
Emmanuel Hocdet872085c2017-10-10 15:18:52 +0200924 memprintf(err, "OCSP single response: certificate status is unknown");
Emeric Brun4147b2e2014-06-16 18:36:30 +0200925 goto out;
926 }
927
Emeric Brun13a6b482014-06-20 15:44:34 +0200928 if (!nextupd) {
929 memprintf(err, "OCSP single response: missing nextupdate");
930 goto out;
931 }
932
Emeric Brunc8b27b62014-06-19 14:16:17 +0200933 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200934 if (!rc) {
935 memprintf(err, "OCSP single response: no longer valid.");
936 goto out;
937 }
938
939 if (cid) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200940 if (OCSP_id_cmp(id, cid)) {
Emeric Brun4147b2e2014-06-16 18:36:30 +0200941 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
942 goto out;
943 }
944 }
945
946 if (!ocsp) {
947 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
948 unsigned char *p;
949
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200950 rc = i2d_OCSP_CERTID(id, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200951 if (!rc) {
952 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
953 goto out;
954 }
955
956 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
957 memprintf(err, "OCSP single response: Certificate ID too long");
958 goto out;
959 }
960
961 p = key;
962 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200963 i2d_OCSP_CERTID(id, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200964 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
965 if (!ocsp) {
966 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
967 goto out;
968 }
969 }
970
971 /* According to comments on "chunk_dup", the
972 previous chunk buffer will be freed */
973 if (!chunk_dup(&ocsp->response, ocsp_response)) {
974 memprintf(err, "OCSP response: Memory allocation error");
975 goto out;
976 }
977
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200978 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
979
Emeric Brun4147b2e2014-06-16 18:36:30 +0200980 ret = 0;
981out:
Janusz Dziemidowicz8d710492017-03-08 16:59:41 +0100982 ERR_clear_error();
983
Emeric Brun4147b2e2014-06-16 18:36:30 +0200984 if (bs)
985 OCSP_BASICRESP_free(bs);
986
987 if (resp)
988 OCSP_RESPONSE_free(resp);
989
990 return ret;
991}
992/*
993 * External function use to update the OCSP response in the OCSP response's
994 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
995 * to update in DER format.
996 *
997 * Returns 0 on success, 1 in error case.
998 */
Willy Tarreau83061a82018-07-13 11:56:34 +0200999int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001000{
1001 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
1002}
1003
William Lallemand4a660132019-10-14 14:51:41 +02001004#endif
1005
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001006#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
1007static 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)
1008{
Christopher Faulet16f45c82018-02-16 11:23:49 +01001009 struct tls_keys_ref *ref;
Emeric Brun9e754772019-01-10 17:51:55 +01001010 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001011 struct connection *conn;
1012 int head;
1013 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001014 int ret = -1; /* error by default */
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001015
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001016 conn = SSL_get_ex_data(s, ssl_app_data_index);
Willy Tarreau07d94e42018-09-20 10:57:52 +02001017 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001018 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1019
1020 keys = ref->tlskeys;
1021 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001022
1023 if (enc) {
1024 memcpy(key_name, keys[head].name, 16);
1025
1026 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +01001027 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001028
Emeric Brun9e754772019-01-10 17:51:55 +01001029 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001030
Emeric Brun9e754772019-01-10 17:51:55 +01001031 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
1032 goto end;
1033
Willy Tarreau9356dac2019-05-10 09:22:53 +02001034 HMAC_Init_ex(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001035 ret = 1;
1036 }
1037 else if (ref->key_size_bits == 256 ) {
1038
1039 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
1040 goto end;
1041
Willy Tarreau9356dac2019-05-10 09:22:53 +02001042 HMAC_Init_ex(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001043 ret = 1;
1044 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001045 } else {
1046 for (i = 0; i < TLS_TICKETS_NO; i++) {
1047 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
1048 goto found;
1049 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01001050 ret = 0;
1051 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001052
Christopher Faulet16f45c82018-02-16 11:23:49 +01001053 found:
Emeric Brun9e754772019-01-10 17:51:55 +01001054 if (ref->key_size_bits == 128) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001055 HMAC_Init_ex(hctx, keys[(head + i) % TLS_TICKETS_NO].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001056 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
1057 goto end;
1058 /* 2 for key renewal, 1 if current key is still valid */
1059 ret = i ? 2 : 1;
1060 }
1061 else if (ref->key_size_bits == 256) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001062 HMAC_Init_ex(hctx, keys[(head + i) % TLS_TICKETS_NO].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001063 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
1064 goto end;
1065 /* 2 for key renewal, 1 if current key is still valid */
1066 ret = i ? 2 : 1;
1067 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001068 }
Emeric Brun9e754772019-01-10 17:51:55 +01001069
Christopher Faulet16f45c82018-02-16 11:23:49 +01001070 end:
1071 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1072 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001073}
1074
1075struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
1076{
1077 struct tls_keys_ref *ref;
1078
1079 list_for_each_entry(ref, &tlskeys_reference, list)
1080 if (ref->filename && strcmp(filename, ref->filename) == 0)
1081 return ref;
1082 return NULL;
1083}
1084
1085struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1086{
1087 struct tls_keys_ref *ref;
1088
1089 list_for_each_entry(ref, &tlskeys_reference, list)
1090 if (ref->unique_id == unique_id)
1091 return ref;
1092 return NULL;
1093}
1094
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001095/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001096 * match existing ones, this function returns -1
1097 * else it returns 0 on success.
1098 */
1099int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001100 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001101{
Emeric Brun9e754772019-01-10 17:51:55 +01001102 if (ref->key_size_bits == 128) {
1103 if (tlskey->data != sizeof(struct tls_sess_key_128))
1104 return -1;
1105 }
1106 else if (ref->key_size_bits == 256) {
1107 if (tlskey->data != sizeof(struct tls_sess_key_256))
1108 return -1;
1109 }
1110 else
1111 return -1;
1112
Christopher Faulet16f45c82018-02-16 11:23:49 +01001113 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001114 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1115 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001116 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1117 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001118
1119 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001120}
1121
Willy Tarreau83061a82018-07-13 11:56:34 +02001122int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001123{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001124 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1125
1126 if(!ref) {
1127 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1128 return 1;
1129 }
Emeric Brun9e754772019-01-10 17:51:55 +01001130 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1131 memprintf(err, "Invalid key size");
1132 return 1;
1133 }
1134
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001135 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001136}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001137
1138/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001139 * automatic ids. It's called just after the basic checks. It returns
1140 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001141 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001142static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001143{
1144 int i = 0;
1145 struct tls_keys_ref *ref, *ref2, *ref3;
1146 struct list tkr = LIST_HEAD_INIT(tkr);
1147
1148 list_for_each_entry(ref, &tlskeys_reference, list) {
1149 if (ref->unique_id == -1) {
1150 /* Look for the first free id. */
1151 while (1) {
1152 list_for_each_entry(ref2, &tlskeys_reference, list) {
1153 if (ref2->unique_id == i) {
1154 i++;
1155 break;
1156 }
1157 }
1158 if (&ref2->list == &tlskeys_reference)
1159 break;
1160 }
1161
1162 /* Uses the unique id and increment it for the next entry. */
1163 ref->unique_id = i;
1164 i++;
1165 }
1166 }
1167
1168 /* This sort the reference list by id. */
1169 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
1170 LIST_DEL(&ref->list);
1171 list_for_each_entry(ref3, &tkr, list) {
1172 if (ref->unique_id < ref3->unique_id) {
1173 LIST_ADDQ(&ref3->list, &ref->list);
1174 break;
1175 }
1176 }
1177 if (&ref3->list == &tkr)
1178 LIST_ADDQ(&tkr, &ref->list);
1179 }
1180
1181 /* swap root */
1182 LIST_ADD(&tkr, &tlskeys_reference);
1183 LIST_DEL(&tkr);
Willy Tarreaud1c57502016-12-22 22:46:15 +01001184 return 0;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001185}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001186#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1187
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001188#ifndef OPENSSL_NO_OCSP
yanbzhube2774d2015-12-10 15:07:30 -05001189int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1190{
1191 switch (evp_keytype) {
1192 case EVP_PKEY_RSA:
1193 return 2;
1194 case EVP_PKEY_DSA:
1195 return 0;
1196 case EVP_PKEY_EC:
1197 return 1;
1198 }
1199
1200 return -1;
1201}
1202
Emeric Brun4147b2e2014-06-16 18:36:30 +02001203/*
1204 * Callback used to set OCSP status extension content in server hello.
1205 */
1206int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1207{
yanbzhube2774d2015-12-10 15:07:30 -05001208 struct certificate_ocsp *ocsp;
1209 struct ocsp_cbk_arg *ocsp_arg;
1210 char *ssl_buf;
1211 EVP_PKEY *ssl_pkey;
1212 int key_type;
1213 int index;
1214
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001215 ocsp_arg = arg;
yanbzhube2774d2015-12-10 15:07:30 -05001216
1217 ssl_pkey = SSL_get_privatekey(ssl);
1218 if (!ssl_pkey)
1219 return SSL_TLSEXT_ERR_NOACK;
1220
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001221 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001222
1223 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1224 ocsp = ocsp_arg->s_ocsp;
1225 else {
1226 /* For multiple certs per context, we have to find the correct OCSP response based on
1227 * the certificate type
1228 */
1229 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1230
1231 if (index < 0)
1232 return SSL_TLSEXT_ERR_NOACK;
1233
1234 ocsp = ocsp_arg->m_ocsp[index];
1235
1236 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001237
1238 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001239 !ocsp->response.area ||
1240 !ocsp->response.data ||
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001241 (ocsp->expire < now.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001242 return SSL_TLSEXT_ERR_NOACK;
1243
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001244 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001245 if (!ssl_buf)
1246 return SSL_TLSEXT_ERR_NOACK;
1247
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001248 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
1249 SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001250
1251 return SSL_TLSEXT_ERR_OK;
1252}
1253
William Lallemand4a660132019-10-14 14:51:41 +02001254#endif
1255
1256#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001257/*
1258 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001259 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1260 * status extension, the issuer's certificate is mandatory. It should be
1261 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001262 *
William Lallemand246c0242019-10-11 08:59:13 +02001263 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1264 * OCSP response. If file is empty or content is not a valid OCSP response,
1265 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1266 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001267 *
1268 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001269 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001270 */
William Lallemand4a660132019-10-14 14:51:41 +02001271#ifndef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001272static int ssl_sock_load_ocsp(SSL_CTX *ctx, const struct cert_key_and_chain *ckch, STACK_OF(X509) *chain)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001273{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001274 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001275 OCSP_CERTID *cid = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001276 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001277 struct certificate_ocsp *ocsp = NULL, *iocsp;
1278 char *warn = NULL;
1279 unsigned char *p;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001280 void (*callback) (void);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001281
Emeric Brun4147b2e2014-06-16 18:36:30 +02001282
William Lallemand246c0242019-10-11 08:59:13 +02001283 x = ckch->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001284 if (!x)
1285 goto out;
1286
William Lallemand246c0242019-10-11 08:59:13 +02001287 issuer = ckch->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001288 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1289 if (chain) {
1290 /* check if one of the certificate of the chain is the issuer */
1291 for (i = 0; i < sk_X509_num(chain); i++) {
1292 X509 *ti = sk_X509_value(chain, i);
1293 if (X509_check_issued(ti, x) == X509_V_OK) {
1294 issuer = ti;
1295 break;
1296 }
1297 }
1298 }
William Lallemand246c0242019-10-11 08:59:13 +02001299 if (!issuer)
1300 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001301
1302 cid = OCSP_cert_to_id(0, x, issuer);
1303 if (!cid)
1304 goto out;
1305
1306 i = i2d_OCSP_CERTID(cid, NULL);
1307 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1308 goto out;
1309
Vincent Bernat02779b62016-04-03 13:48:43 +02001310 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001311 if (!ocsp)
1312 goto out;
1313
1314 p = ocsp->key_data;
1315 i2d_OCSP_CERTID(cid, &p);
1316
1317 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1318 if (iocsp == ocsp)
1319 ocsp = NULL;
1320
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001321#ifndef SSL_CTX_get_tlsext_status_cb
1322# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1323 *cb = (void (*) (void))ctx->tlsext_status_cb;
1324#endif
1325 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1326
1327 if (!callback) {
Vincent Bernat02779b62016-04-03 13:48:43 +02001328 struct ocsp_cbk_arg *cb_arg = calloc(1, sizeof(*cb_arg));
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001329 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001330
1331 cb_arg->is_single = 1;
1332 cb_arg->s_ocsp = iocsp;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001333
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001334 pkey = X509_get_pubkey(x);
1335 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1336 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001337
1338 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
1339 SSL_CTX_set_tlsext_status_arg(ctx, cb_arg);
1340 } else {
1341 /*
1342 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1343 * Update that cb_arg with the new cert's staple
1344 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001345 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001346 struct certificate_ocsp *tmp_ocsp;
1347 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001348 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001349 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001350
1351#ifdef SSL_CTX_get_tlsext_status_arg
1352 SSL_CTX_ctrl(ctx, SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB_ARG, 0, &cb_arg);
1353#else
1354 cb_arg = ctx->tlsext_status_arg;
1355#endif
yanbzhube2774d2015-12-10 15:07:30 -05001356
1357 /*
1358 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1359 * the order of operations below matter, take care when changing it
1360 */
1361 tmp_ocsp = cb_arg->s_ocsp;
1362 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1363 cb_arg->s_ocsp = NULL;
1364 cb_arg->m_ocsp[index] = tmp_ocsp;
1365 cb_arg->is_single = 0;
1366 cb_arg->single_kt = 0;
1367
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001368 pkey = X509_get_pubkey(x);
1369 key_type = EVP_PKEY_base_id(pkey);
1370 EVP_PKEY_free(pkey);
1371
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001372 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
yanbzhube2774d2015-12-10 15:07:30 -05001373 if (index >= 0 && !cb_arg->m_ocsp[index])
1374 cb_arg->m_ocsp[index] = iocsp;
1375
1376 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001377
1378 ret = 0;
1379
1380 warn = NULL;
William Lallemand246c0242019-10-11 08:59:13 +02001381 if (ssl_sock_load_ocsp_response(ckch->ocsp_response, ocsp, cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001382 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001383 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001384 }
1385
1386out:
Emeric Brun4147b2e2014-06-16 18:36:30 +02001387 if (cid)
1388 OCSP_CERTID_free(cid);
1389
1390 if (ocsp)
1391 free(ocsp);
1392
1393 if (warn)
1394 free(warn);
1395
Emeric Brun4147b2e2014-06-16 18:36:30 +02001396 return ret;
1397}
William Lallemand4a660132019-10-14 14:51:41 +02001398#else /* OPENSSL_IS_BORINGSSL */
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001399static int ssl_sock_load_ocsp(SSL_CTX *ctx, const struct cert_key_and_chain *ckch, STACK_OF(X509) *chain)
Emmanuel Hocdet2c32d8f2017-05-22 14:58:00 +02001400{
William Lallemand4a660132019-10-14 14:51:41 +02001401 return SSL_CTX_set_ocsp_response(ctx, (const uint8_t *)ckch->ocsp_response->area, ckch->ocsp_response->data);
Emmanuel Hocdet2c32d8f2017-05-22 14:58:00 +02001402}
1403#endif
1404
William Lallemand4a660132019-10-14 14:51:41 +02001405#endif
1406
1407
Willy Tarreau5db847a2019-05-09 14:13:35 +02001408#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001409
1410#define CT_EXTENSION_TYPE 18
1411
William Lallemand03c331c2020-05-13 10:10:01 +02001412int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001413
1414int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1415{
Willy Tarreau83061a82018-07-13 11:56:34 +02001416 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001417
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001418 *out = (unsigned char *) sctl->area;
1419 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001420
1421 return 1;
1422}
1423
1424int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1425{
1426 return 1;
1427}
1428
William Lallemanda17f4112019-10-10 15:16:44 +02001429static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001430{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001431 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001432
William Lallemanda17f4112019-10-10 15:16:44 +02001433 if (!SSL_CTX_add_server_custom_ext(ctx, CT_EXTENSION_TYPE, ssl_sock_sctl_add_cbk, NULL, sctl, ssl_sock_sctl_parse_cbk, NULL))
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001434 goto out;
1435
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001436 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1437
1438 ret = 0;
1439
1440out:
1441 return ret;
1442}
1443
1444#endif
1445
Emeric Brune1f38db2012-09-03 20:36:47 +02001446void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1447{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001448 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001449 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001450 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001451 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001452
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001453#ifndef SSL_OP_NO_RENEGOTIATION
1454 /* Please note that BoringSSL defines this macro to zero so don't
1455 * change this to #if and do not assign a default value to this macro!
1456 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001457 if (where & SSL_CB_HANDSHAKE_START) {
1458 /* Disable renegotiation (CVE-2009-3555) */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01001459 if ((conn->flags & (CO_FL_WAIT_L6_CONN | CO_FL_EARLY_SSL_HS | CO_FL_EARLY_DATA)) == 0) {
Emeric Brune1f38db2012-09-03 20:36:47 +02001460 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001461 conn->err_code = CO_ER_SSL_RENEG;
1462 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001463 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001464#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001465
1466 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001467 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001468 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001469 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001470 consider that the buffering was activated,
1471 so we rise the output buffer size from 4k
1472 to 16k */
1473 write_bio = SSL_get_wbio(ssl);
1474 if (write_bio != SSL_get_rbio(ssl)) {
1475 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001476 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001477 }
1478 }
1479 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001480}
1481
Emeric Brune64aef12012-09-21 13:15:06 +02001482/* Callback is called for each certificate of the chain during a verify
1483 ok is set to 1 if preverify detect no error on current certificate.
1484 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001485int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001486{
1487 SSL *ssl;
1488 struct connection *conn;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001489 struct ssl_sock_ctx *ctx;
Emeric Brun81c00f02012-09-21 14:31:21 +02001490 int err, depth;
Emeric Brune64aef12012-09-21 13:15:06 +02001491
1492 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001493 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001494
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001495 ctx = conn->xprt_ctx;
1496
1497 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001498
Emeric Brun81c00f02012-09-21 14:31:21 +02001499 if (ok) /* no errors */
1500 return ok;
1501
1502 depth = X509_STORE_CTX_get_error_depth(x_store);
1503 err = X509_STORE_CTX_get_error(x_store);
1504
1505 /* check if CA error needs to be ignored */
1506 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001507 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1508 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1509 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001510 }
1511
Willy Tarreau731248f2020-02-04 14:02:02 +01001512 if (err < 64 && __objt_listener(conn->target)->bind_conf->ca_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001513 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001514 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001515 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001516 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001517
Willy Tarreau20879a02012-12-03 16:32:10 +01001518 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001519 return 0;
1520 }
1521
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001522 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1523 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001524
Emeric Brun81c00f02012-09-21 14:31:21 +02001525 /* check if certificate error needs to be ignored */
Willy Tarreau731248f2020-02-04 14:02:02 +01001526 if (err < 64 && __objt_listener(conn->target)->bind_conf->crt_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001527 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001528 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001529 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001530 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001531
Willy Tarreau20879a02012-12-03 16:32:10 +01001532 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001533 return 0;
Emeric Brune64aef12012-09-21 13:15:06 +02001534}
1535
Dragan Dosen9ac98092020-05-11 15:51:45 +02001536#ifdef TLS1_RT_HEARTBEAT
1537static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1538 int content_type, const void *buf, size_t len,
1539 SSL *ssl)
1540{
1541 /* test heartbeat received (write_p is set to 0
1542 for a received record) */
1543 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
1544 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
1545 const unsigned char *p = buf;
1546 unsigned int payload;
1547
1548 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1549
1550 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1551 if (*p != TLS1_HB_REQUEST)
1552 return;
1553
1554 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1555 goto kill_it;
1556
1557 payload = (p[1] * 256) + p[2];
1558 if (3 + payload + 16 <= len)
1559 return; /* OK no problem */
1560 kill_it:
1561 /* We have a clear heartbleed attack (CVE-2014-0160), the
1562 * advertised payload is larger than the advertised packet
1563 * length, so we have garbage in the buffer between the
1564 * payload and the end of the buffer (p+len). We can't know
1565 * if the SSL stack is patched, and we don't know if we can
1566 * safely wipe out the area between p+3+len and payload.
1567 * So instead, we prevent the response from being sent by
1568 * setting the max_send_fragment to 0 and we report an SSL
1569 * error, which will kill this connection. It will be reported
1570 * above as SSL_ERROR_SSL while an other handshake failure with
1571 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1572 */
1573 ssl->max_send_fragment = 0;
1574 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1575 }
1576}
1577#endif
1578
1579static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1580 int content_type, const void *buf, size_t len,
1581 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001582{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001583 struct ssl_capture *capture;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001584 unsigned char *msg;
1585 unsigned char *end;
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001586 size_t rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001587
1588 /* This function is called for "from client" and "to server"
1589 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001590 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001591 */
1592
1593 /* "write_p" is set to 0 is the bytes are received messages,
1594 * otherwise it is set to 1.
1595 */
1596 if (write_p != 0)
1597 return;
1598
1599 /* content_type contains the type of message received or sent
1600 * according with the SSL/TLS protocol spec. This message is
1601 * encoded with one byte. The value 256 (two bytes) is used
1602 * for designing the SSL/TLS record layer. According with the
1603 * rfc6101, the expected message (other than 256) are:
1604 * - change_cipher_spec(20)
1605 * - alert(21)
1606 * - handshake(22)
1607 * - application_data(23)
1608 * - (255)
1609 * We are interessed by the handshake and specially the client
1610 * hello.
1611 */
1612 if (content_type != 22)
1613 return;
1614
1615 /* The message length is at least 4 bytes, containing the
1616 * message type and the message length.
1617 */
1618 if (len < 4)
1619 return;
1620
1621 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001622 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001623 * - hello_request(0)
1624 * - client_hello(1)
1625 * - server_hello(2)
1626 * - certificate(11)
1627 * - server_key_exchange (12)
1628 * - certificate_request(13)
1629 * - server_hello_done(14)
1630 * We are interested by the client hello.
1631 */
1632 msg = (unsigned char *)buf;
1633 if (msg[0] != 1)
1634 return;
1635
1636 /* Next three bytes are the length of the message. The total length
1637 * must be this decoded length + 4. If the length given as argument
1638 * is not the same, we abort the protocol dissector.
1639 */
1640 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1641 if (len < rec_len + 4)
1642 return;
1643 msg += 4;
1644 end = msg + rec_len;
1645 if (end < msg)
1646 return;
1647
1648 /* Expect 2 bytes for protocol version (1 byte for major and 1 byte
1649 * for minor, the random, composed by 4 bytes for the unix time and
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001650 * 28 bytes for unix payload. So we jump 1 + 1 + 4 + 28.
1651 */
1652 msg += 1 + 1 + 4 + 28;
1653 if (msg > end)
1654 return;
1655
1656 /* Next, is session id:
1657 * if present, we have to jump by length + 1 for the size information
1658 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001659 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001660 if (msg[0] > 0)
1661 msg += msg[0];
1662 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001663 if (msg > end)
1664 return;
1665
1666 /* Next two bytes are the ciphersuite length. */
1667 if (msg + 2 > end)
1668 return;
1669 rec_len = (msg[0] << 8) + msg[1];
1670 msg += 2;
1671 if (msg + rec_len > end || msg + rec_len < msg)
1672 return;
1673
Willy Tarreaubafbe012017-11-24 17:34:44 +01001674 capture = pool_alloc_dirty(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001675 if (!capture)
1676 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001677 /* Compute the xxh64 of the ciphersuite. */
1678 capture->xxh64 = XXH64(msg, rec_len, 0);
1679
1680 /* Capture the ciphersuite. */
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001681 capture->ciphersuite_len = (global_ssl.capture_cipherlist < rec_len) ?
1682 global_ssl.capture_cipherlist : rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001683 memcpy(capture->ciphersuite, msg, capture->ciphersuite_len);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001684
1685 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001686}
1687
Emeric Brun29f037d2014-04-25 19:05:36 +02001688/* Callback is called for ssl protocol analyse */
1689void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1690{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001691 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1692 struct ssl_sock_msg_callback *cbk;
1693
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001694 /* Try to call all callback functions that were registered by using
1695 * ssl_sock_register_msg_callback().
1696 */
1697 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1698 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1699 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001700}
1701
Bernard Spil13c53f82018-02-15 13:34:58 +01001702#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001703static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1704 const unsigned char *in, unsigned int inlen,
1705 void *arg)
1706{
1707 struct server *srv = arg;
1708
1709 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1710 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1711 return SSL_TLSEXT_ERR_OK;
1712 return SSL_TLSEXT_ERR_NOACK;
1713}
1714#endif
1715
1716#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001717/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001718 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001719 */
1720static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1721 unsigned int *len, void *arg)
1722{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001723 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001724
1725 *data = (const unsigned char *)conf->npn_str;
1726 *len = conf->npn_len;
1727 return SSL_TLSEXT_ERR_OK;
1728}
1729#endif
1730
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001731#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001732/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001733 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001734 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001735static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1736 unsigned char *outlen,
1737 const unsigned char *server,
1738 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001739{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001740 struct ssl_bind_conf *conf = arg;
Willy Tarreauab861d32013-04-02 02:30:41 +02001741
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001742 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1743 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
1744 return SSL_TLSEXT_ERR_NOACK;
1745 }
Willy Tarreauab861d32013-04-02 02:30:41 +02001746 return SSL_TLSEXT_ERR_OK;
1747}
1748#endif
1749
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001750#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001751#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001752
Christopher Faulet30548802015-06-11 13:39:32 +02001753/* Create a X509 certificate with the specified servername and serial. This
1754 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001755static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001756ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001757{
Christopher Faulet7969a332015-10-09 11:15:03 +02001758 X509 *cacert = bind_conf->ca_sign_cert;
1759 EVP_PKEY *capkey = bind_conf->ca_sign_pkey;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001760 SSL_CTX *ssl_ctx = NULL;
1761 X509 *newcrt = NULL;
1762 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001763 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001764 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001765 X509_NAME *name;
1766 const EVP_MD *digest;
1767 X509V3_CTX ctx;
1768 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001769 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001770
Christopher Faulet48a83322017-07-28 16:56:09 +02001771 /* Get the private key of the default certificate and use it */
Willy Tarreau5db847a2019-05-09 14:13:35 +02001772#if (HA_OPENSSL_VERSION_NUMBER >= 0x10002000L)
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001773 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1774#else
1775 tmp_ssl = SSL_new(bind_conf->default_ctx);
1776 if (tmp_ssl)
1777 pkey = SSL_get_privatekey(tmp_ssl);
1778#endif
1779 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001780 goto mkcert_error;
1781
1782 /* Create the certificate */
1783 if (!(newcrt = X509_new()))
1784 goto mkcert_error;
1785
1786 /* Set version number for the certificate (X509v3) and the serial
1787 * number */
1788 if (X509_set_version(newcrt, 2L) != 1)
1789 goto mkcert_error;
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01001790 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001791
1792 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001793 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1794 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001795 goto mkcert_error;
1796
1797 /* set public key in the certificate */
1798 if (X509_set_pubkey(newcrt, pkey) != 1)
1799 goto mkcert_error;
1800
1801 /* Set issuer name from the CA */
1802 if (!(name = X509_get_subject_name(cacert)))
1803 goto mkcert_error;
1804 if (X509_set_issuer_name(newcrt, name) != 1)
1805 goto mkcert_error;
1806
1807 /* Set the subject name using the same, but the CN */
1808 name = X509_NAME_dup(name);
1809 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1810 (const unsigned char *)servername,
1811 -1, -1, 0) != 1) {
1812 X509_NAME_free(name);
1813 goto mkcert_error;
1814 }
1815 if (X509_set_subject_name(newcrt, name) != 1) {
1816 X509_NAME_free(name);
1817 goto mkcert_error;
1818 }
1819 X509_NAME_free(name);
1820
1821 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001822 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001823 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1824 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1825 X509_EXTENSION *ext;
1826
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001827 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001828 goto mkcert_error;
1829 if (!X509_add_ext(newcrt, ext, -1)) {
1830 X509_EXTENSION_free(ext);
1831 goto mkcert_error;
1832 }
1833 X509_EXTENSION_free(ext);
1834 }
1835
1836 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001837
1838 key_type = EVP_PKEY_base_id(capkey);
1839
1840 if (key_type == EVP_PKEY_DSA)
1841 digest = EVP_sha1();
1842 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001843 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001844 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02001845 digest = EVP_sha256();
1846 else {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02001847#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000000fL) && !defined(OPENSSL_IS_BORINGSSL)
Christopher Faulet7969a332015-10-09 11:15:03 +02001848 int nid;
1849
1850 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
1851 goto mkcert_error;
1852 if (!(digest = EVP_get_digestbynid(nid)))
1853 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02001854#else
1855 goto mkcert_error;
1856#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02001857 }
1858
Christopher Faulet31af49d2015-06-09 17:29:50 +02001859 if (!(X509_sign(newcrt, capkey, digest)))
1860 goto mkcert_error;
1861
1862 /* Create and set the new SSL_CTX */
1863 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
1864 goto mkcert_error;
1865 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
1866 goto mkcert_error;
1867 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
1868 goto mkcert_error;
1869 if (!SSL_CTX_check_private_key(ssl_ctx))
1870 goto mkcert_error;
1871
1872 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02001873
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01001874#ifndef OPENSSL_NO_DH
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001875 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh);
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01001876#endif
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001877#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
1878 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001879 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001880 EC_KEY *ecc;
1881 int nid;
1882
1883 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
1884 goto end;
1885 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
1886 goto end;
1887 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
1888 EC_KEY_free(ecc);
1889 }
1890#endif
1891 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02001892 return ssl_ctx;
1893
1894 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001895 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001896 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001897 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
1898 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001899 return NULL;
1900}
1901
Christopher Faulet7969a332015-10-09 11:15:03 +02001902SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001903ssl_sock_create_cert(struct connection *conn, const char *servername, unsigned int key)
Christopher Faulet7969a332015-10-09 11:15:03 +02001904{
Willy Tarreau07d94e42018-09-20 10:57:52 +02001905 struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
Olivier Houchard66ab4982019-02-26 18:37:15 +01001906 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001907
Olivier Houchard66ab4982019-02-26 18:37:15 +01001908 return ssl_sock_do_create_cert(servername, bind_conf, ctx->ssl);
Christopher Faulet7969a332015-10-09 11:15:03 +02001909}
1910
Christopher Faulet30548802015-06-11 13:39:32 +02001911/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02001912 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02001913SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02001914ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02001915{
1916 struct lru64 *lru = NULL;
1917
1918 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02001919 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001920 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02001921 if (lru && lru->domain) {
1922 if (ssl)
1923 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02001924 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02001925 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02001926 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02001927 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02001928 }
1929 return NULL;
1930}
1931
Emeric Brun821bb9b2017-06-15 16:37:39 +02001932/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
1933 * function is not thread-safe, it should only be used to check if a certificate
1934 * exists in the lru cache (with no warranty it will not be removed by another
1935 * thread). It is kept for backward compatibility. */
1936SSL_CTX *
1937ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
1938{
1939 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
1940}
1941
Christopher Fauletd2cab922015-07-28 16:03:47 +02001942/* Set a certificate int the LRU cache used to store generated
1943 * certificate. Return 0 on success, otherwise -1 */
1944int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001945ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02001946{
1947 struct lru64 *lru = NULL;
1948
1949 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001950 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001951 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02001952 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001953 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02001954 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02001955 }
Christopher Faulet30548802015-06-11 13:39:32 +02001956 if (lru->domain && lru->data)
1957 lru->free((SSL_CTX *)lru->data);
Christopher Faulet7969a332015-10-09 11:15:03 +02001958 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001959 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02001960 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02001961 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02001962 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02001963}
1964
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001965/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02001966unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001967ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02001968{
1969 return XXH32(data, len, ssl_ctx_lru_seed);
1970}
1971
Willy Tarreau2f63ef42015-10-20 15:16:01 +02001972/* Generate a cert and immediately assign it to the SSL session so that the cert's
1973 * refcount is maintained regardless of the cert's presence in the LRU cache.
1974 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02001975static int
Christopher Faulet7969a332015-10-09 11:15:03 +02001976ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001977{
1978 X509 *cacert = bind_conf->ca_sign_cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001979 SSL_CTX *ssl_ctx = NULL;
1980 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001981 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001982
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001983 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001984 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001985 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001986 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001987 if (lru && lru->domain)
1988 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02001989 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001990 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001991 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02001992 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02001993 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001994 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02001995 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001996 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02001997 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001998 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02001999 SSL_set_SSL_CTX(ssl, ssl_ctx);
2000 /* No LRU cache, this CTX will be released as soon as the session dies */
2001 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002002 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002003 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002004 return 0;
2005}
2006static int
2007ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2008{
2009 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002010 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002011
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002012 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002013 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002014 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002015 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002016 }
2017 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002018}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002019#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002020
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002021#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002022
2023static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002024{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002025#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002026 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002027 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2028#endif
2029}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002030static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2031 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002032 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2033}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002034static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002035#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002036 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002037 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2038#endif
2039}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002040static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002041#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002042 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002043 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2044#endif
2045}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002046/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002047static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2048/* Unusable in this context. */
2049static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2050static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2051static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2052static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2053static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002054#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002055
2056static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2057 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002058 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2059}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002060static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2061 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2062 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2063}
2064static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2065 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002066 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2067}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002068static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2069 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2070 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2071}
2072static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2073 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002074 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2075}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002076static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2077 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2078 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2079}
2080static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2081 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002082 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2083}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002084static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2085 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2086 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2087}
2088static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002089#if SSL_OP_NO_TLSv1_3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002090 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002091 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2092#endif
2093}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002094static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
2095#if SSL_OP_NO_TLSv1_3
2096 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2097 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002098#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002099}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002100#endif
2101static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2102static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002103
William Lallemand7fd8b452020-05-07 15:20:43 +02002104struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002105 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2106 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2107 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2108 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2109 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2110 {SSL_OP_NO_TLSv1_3, MC_SSL_O_NO_TLSV13, ctx_set_TLSv13_func, ssl_set_TLSv13_func, "TLSv1.3"}, /* CONF_TLSV13 */
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002111};
2112
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002113static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2114{
2115 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2116 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2117 SSL_set_SSL_CTX(ssl, ctx);
2118}
2119
Willy Tarreau5db847a2019-05-09 14:13:35 +02002120#if ((HA_OPENSSL_VERSION_NUMBER >= 0x10101000L) || defined(OPENSSL_IS_BORINGSSL))
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002121
2122static int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
2123{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002124 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002125 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002126
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002127 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || s->generate_certs)
2128 return SSL_TLSEXT_ERR_OK;
2129 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002130}
2131
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002132#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002133static int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
2134{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002135 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002136#else
2137static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
2138{
2139#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002140 struct connection *conn;
2141 struct bind_conf *s;
2142 const uint8_t *extension_data;
2143 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002144 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002145
2146 char *wildp = NULL;
2147 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002148 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002149 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002150 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002151 int i;
2152
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002153 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreaua8825522018-10-15 13:20:07 +02002154 s = __objt_listener(conn->target)->bind_conf;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002155
Olivier Houchard9679ac92017-10-27 14:58:08 +02002156 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002157 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002158#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002159 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2160 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002161#else
2162 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2163#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002164 /*
2165 * The server_name extension was given too much extensibility when it
2166 * was written, so parsing the normal case is a bit complex.
2167 */
2168 size_t len;
2169 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002170 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002171 /* Extract the length of the supplied list of names. */
2172 len = (*extension_data++) << 8;
2173 len |= *extension_data++;
2174 if (len + 2 != extension_len)
2175 goto abort;
2176 /*
2177 * The list in practice only has a single element, so we only consider
2178 * the first one.
2179 */
2180 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2181 goto abort;
2182 extension_len = len - 1;
2183 /* Now we can finally pull out the byte array with the actual hostname. */
2184 if (extension_len <= 2)
2185 goto abort;
2186 len = (*extension_data++) << 8;
2187 len |= *extension_data++;
2188 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2189 || memchr(extension_data, 0, len) != NULL)
2190 goto abort;
2191 servername = extension_data;
2192 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002193 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002194#if (!defined SSL_NO_GENERATE_CERTIFICATES)
2195 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002196 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002197 }
2198#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002199 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002200 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002201 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002202 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002203 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002204 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002205 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002206 goto abort;
2207 }
2208
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002209 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002210#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002211 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002212#else
2213 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2214#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002215 uint8_t sign;
2216 size_t len;
2217 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002218 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002219 len = (*extension_data++) << 8;
2220 len |= *extension_data++;
2221 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002222 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002223 if (len % 2 != 0)
2224 goto abort;
2225 for (; len > 0; len -= 2) {
2226 extension_data++; /* hash */
2227 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002228 switch (sign) {
2229 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002230 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002231 break;
2232 case TLSEXT_signature_ecdsa:
2233 has_ecdsa_sig = 1;
2234 break;
2235 default:
2236 continue;
2237 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002238 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002239 break;
2240 }
2241 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002242 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002243 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002244 }
2245 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002246 const SSL_CIPHER *cipher;
2247 size_t len;
2248 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002249 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002250#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002251 len = ctx->cipher_suites_len;
2252 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002253#else
2254 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2255#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002256 if (len % 2 != 0)
2257 goto abort;
2258 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002259#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002260 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002261 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002262#else
2263 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2264#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002265 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002266 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002267 break;
2268 }
2269 }
2270 }
2271
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002272 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002273 trash.area[i] = tolower(servername[i]);
2274 if (!wildp && (trash.area[i] == '.'))
2275 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002276 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002277 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002278
William Lallemand150bfa82019-09-19 17:12:49 +02002279 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002280
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002281 for (i = 0; i < 2; i++) {
2282 if (i == 0) /* lookup in full qualified names */
2283 node = ebst_lookup(&s->sni_ctx, trash.area);
2284 else if (i == 1 && wildp) /* lookup in wildcards names */
2285 node = ebst_lookup(&s->sni_w_ctx, wildp);
2286 else
2287 break;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002288 for (n = node; n; n = ebmb_next_dup(n)) {
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002289 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002290 if (!container_of(n, struct sni_ctx, name)->neg) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002291 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002292 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002293 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002294 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002295 break;
2296 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002297 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002298 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002299 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002300 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002301 if (!node_anonymous)
2302 node_anonymous = n;
2303 break;
2304 }
2305 }
2306 }
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002307 /* select by key_signature priority order */
2308 node = (has_ecdsa_sig && node_ecdsa) ? node_ecdsa
2309 : ((has_rsa_sig && node_rsa) ? node_rsa
2310 : (node_anonymous ? node_anonymous
2311 : (node_ecdsa ? node_ecdsa /* no ecdsa signature case (< TLSv1.2) */
2312 : node_rsa /* no rsa signature case (far far away) */
2313 )));
2314 if (node) {
2315 /* switch ctx */
2316 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2317 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
Olivier Houchard35a63cc2017-11-02 19:04:38 +01002318 if (conf) {
2319 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2320 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2321 if (conf->early_data)
2322 allow_early = 1;
2323 }
William Lallemand02010472019-10-18 11:02:19 +02002324 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchard35a63cc2017-11-02 19:04:38 +01002325 goto allow_early;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002326 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002327 }
William Lallemand150bfa82019-09-19 17:12:49 +02002328
William Lallemand02010472019-10-18 11:02:19 +02002329 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002330#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002331 if (s->generate_certs && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002332 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002333 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002334 }
2335#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002336 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002337 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002338 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002339 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002340 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002341 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02002342allow_early:
2343#ifdef OPENSSL_IS_BORINGSSL
2344 if (allow_early)
2345 SSL_set_early_data_enabled(ssl, 1);
2346#else
2347 if (!allow_early)
2348 SSL_set_max_early_data(ssl, 0);
2349#endif
2350 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002351 abort:
2352 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
2353 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002354#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002355 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002356#else
2357 *al = SSL_AD_UNRECOGNIZED_NAME;
2358 return 0;
2359#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002360}
2361
2362#else /* OPENSSL_IS_BORINGSSL */
2363
Emeric Brunfc0421f2012-09-07 17:30:07 +02002364/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2365 * warning when no match is found, which implies the default (first) cert
2366 * will keep being used.
2367 */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002368static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002369{
2370 const char *servername;
2371 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002372 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002373 struct bind_conf *s = priv;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002374 int i;
2375 (void)al; /* shut gcc stupid warning */
2376
2377 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002378 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002379#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002380 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl))
2381 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002382#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002383 if (s->strict_sni)
2384 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002385 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002386 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002387 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002388 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002389 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002390
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002391 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002392 if (!servername[i])
2393 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002394 trash.area[i] = tolower(servername[i]);
2395 if (!wildp && (trash.area[i] == '.'))
2396 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002397 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002398 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002399
William Lallemand150bfa82019-09-19 17:12:49 +02002400 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002401 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002402 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002403 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2404 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002405 if (!container_of(n, struct sni_ctx, name)->neg) {
2406 node = n;
2407 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002408 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002409 }
2410 if (!node && wildp) {
2411 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002412 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2413 /* lookup a not neg filter */
2414 if (!container_of(n, struct sni_ctx, name)->neg) {
2415 node = n;
2416 break;
2417 }
2418 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002419 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002420 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002421#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002422 if (s->generate_certs && ssl_sock_generate_certificate(servername, s, ssl)) {
2423 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002424 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002425 return SSL_TLSEXT_ERR_OK;
2426 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002427#endif
William Lallemand21724f02019-11-04 17:56:13 +01002428 if (s->strict_sni) {
2429 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002430 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002431 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002432 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002433 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002434 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002435 }
2436
2437 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002438 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002439 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002440 return SSL_TLSEXT_ERR_OK;
2441}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002442#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002443#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2444
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002445#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002446
2447static DH * ssl_get_dh_1024(void)
2448{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002449 static unsigned char dh1024_p[]={
2450 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2451 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2452 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2453 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2454 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2455 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2456 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2457 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2458 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2459 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2460 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2461 };
2462 static unsigned char dh1024_g[]={
2463 0x02,
2464 };
2465
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002466 BIGNUM *p;
2467 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002468 DH *dh = DH_new();
2469 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002470 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2471 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002472
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002473 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002474 DH_free(dh);
2475 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002476 } else {
2477 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002478 }
2479 }
2480 return dh;
2481}
2482
2483static DH *ssl_get_dh_2048(void)
2484{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002485 static unsigned char dh2048_p[]={
2486 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2487 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2488 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2489 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2490 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2491 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2492 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2493 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2494 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2495 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2496 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2497 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2498 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2499 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2500 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2501 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2502 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2503 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2504 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2505 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2506 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2507 0xB7,0x1F,0x77,0xF3,
2508 };
2509 static unsigned char dh2048_g[]={
2510 0x02,
2511 };
2512
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002513 BIGNUM *p;
2514 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002515 DH *dh = DH_new();
2516 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002517 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2518 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002519
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002520 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002521 DH_free(dh);
2522 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002523 } else {
2524 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002525 }
2526 }
2527 return dh;
2528}
2529
2530static DH *ssl_get_dh_4096(void)
2531{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002532 static unsigned char dh4096_p[]={
2533 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2534 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2535 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2536 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2537 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2538 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2539 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2540 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2541 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2542 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2543 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2544 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2545 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2546 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2547 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2548 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2549 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2550 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2551 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2552 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2553 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2554 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2555 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2556 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2557 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2558 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2559 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2560 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2561 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2562 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2563 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2564 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2565 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2566 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2567 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2568 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2569 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2570 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2571 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2572 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2573 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2574 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2575 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002576 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002577 static unsigned char dh4096_g[]={
2578 0x02,
2579 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002580
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002581 BIGNUM *p;
2582 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002583 DH *dh = DH_new();
2584 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002585 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2586 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002587
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002588 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002589 DH_free(dh);
2590 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002591 } else {
2592 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002593 }
2594 }
2595 return dh;
2596}
2597
2598/* Returns Diffie-Hellman parameters matching the private key length
Willy Tarreauef934602016-12-22 23:12:01 +01002599 but not exceeding global_ssl.default_dh_param */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002600static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen)
2601{
2602 DH *dh = NULL;
2603 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002604 int type;
2605
2606 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002607
2608 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2609 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2610 */
2611 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2612 keylen = EVP_PKEY_bits(pkey);
2613 }
2614
Willy Tarreauef934602016-12-22 23:12:01 +01002615 if (keylen > global_ssl.default_dh_param) {
2616 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002617 }
2618
Remi Gacogned3a341a2015-05-29 16:26:17 +02002619 if (keylen >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002620 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002621 }
2622 else if (keylen >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002623 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002624 }
2625 else {
Remi Gacogne8de54152014-07-15 11:36:40 +02002626 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002627 }
2628
2629 return dh;
2630}
2631
Remi Gacogne47783ef2015-05-29 15:53:22 +02002632static DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002633{
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002634 DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02002635 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002636
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002637 if (in == NULL)
2638 goto end;
2639
Remi Gacogne47783ef2015-05-29 15:53:22 +02002640 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002641 goto end;
2642
Remi Gacogne47783ef2015-05-29 15:53:22 +02002643 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
2644
2645end:
2646 if (in)
2647 BIO_free(in);
2648
Emeric Brune1b4ed42018-08-16 15:14:12 +02002649 ERR_clear_error();
2650
Remi Gacogne47783ef2015-05-29 15:53:22 +02002651 return dh;
2652}
2653
2654int ssl_sock_load_global_dh_param_from_file(const char *filename)
2655{
2656 global_dh = ssl_sock_get_dh_from_file(filename);
2657
2658 if (global_dh) {
2659 return 0;
2660 }
2661
2662 return -1;
2663}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002664#endif
2665
William Lallemand9117de92019-10-04 00:29:42 +02002666/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02002667static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02002668 struct bind_conf *s, struct ssl_bind_conf *conf,
2669 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002670{
2671 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002672 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002673
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002674 if (*name == '!') {
2675 neg = 1;
2676 name++;
2677 }
2678 if (*name == '*') {
2679 wild = 1;
2680 name++;
2681 }
2682 /* !* filter is a nop */
2683 if (neg && wild)
2684 return order;
2685 if (*name) {
2686 int j, len;
2687 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002688 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002689 trash.area[j] = tolower(name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002690 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02002691 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002692 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002693
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002694 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02002695 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02002696 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002697 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02002698 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002699 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002700 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002701 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002702 sc->order = order++;
2703 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02002704 sc->wild = wild;
2705 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01002706 sc->ckch_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02002707 LIST_ADDQ(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002708 }
2709 return order;
2710}
2711
William Lallemand6af03992019-07-23 15:00:54 +02002712/*
William Lallemand1d29c742019-10-04 00:53:29 +02002713 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
2714 * This function can't return an error.
2715 *
2716 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
2717 */
William Lallemandc756bbd2020-05-13 17:23:59 +02002718void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02002719{
2720
2721 struct sni_ctx *sc0, *sc0b, *sc1;
2722 struct ebmb_node *node;
William Lallemand21724f02019-11-04 17:56:13 +01002723 int def = 0;
William Lallemand1d29c742019-10-04 00:53:29 +02002724
2725 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
2726
2727 /* ignore if sc0 was already inserted in a tree */
2728 if (sc0->name.node.leaf_p)
2729 continue;
2730
2731 /* Check for duplicates. */
2732 if (sc0->wild)
2733 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
2734 else
2735 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
2736
2737 for (; node; node = ebmb_next_dup(node)) {
2738 sc1 = ebmb_entry(node, struct sni_ctx, name);
2739 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
2740 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
2741 /* it's a duplicate, we should remove and free it */
2742 LIST_DEL(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02002743 SSL_CTX_free(sc0->ctx);
William Lallemand1d29c742019-10-04 00:53:29 +02002744 free(sc0);
2745 sc0 = NULL;
William Lallemande15029b2019-10-14 10:46:58 +02002746 break;
William Lallemand1d29c742019-10-04 00:53:29 +02002747 }
2748 }
2749
2750 /* if duplicate, ignore the insertion */
2751 if (!sc0)
2752 continue;
2753
2754 if (sc0->wild)
2755 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
2756 else
2757 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
William Lallemand21724f02019-11-04 17:56:13 +01002758
2759 /* replace the default_ctx if required with the first ctx */
2760 if (ckch_inst->is_default && !def) {
William Lallemand02e19a52020-04-08 16:11:26 +02002761 SSL_CTX_free(bind_conf->default_ctx);
2762 SSL_CTX_up_ref(sc0->ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002763 bind_conf->default_ctx = sc0->ctx;
2764 def = 1;
2765 }
William Lallemand1d29c742019-10-04 00:53:29 +02002766 }
2767}
2768
2769/*
William Lallemande3af8fb2019-10-08 11:36:53 +02002770 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02002771 */
William Lallemande3af8fb2019-10-08 11:36:53 +02002772struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02002773
William Lallemand2954c472020-03-06 21:54:13 +01002774/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02002775struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02002776
Emeric Brun7a883362019-10-17 13:27:40 +02002777/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002778 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02002779 * DH parameter is loaded into the SSL_CTX and if there is no
2780 * DH parameter available in ckchs nor in global, the default
2781 * DH parameters are applied on the SSL_CTX.
2782 * Returns a bitfield containing the flags:
2783 * ERR_FATAL in any fatal error case
2784 * ERR_ALERT if a reason of the error is availabine in err
2785 * ERR_WARN if a warning is available into err
2786 * The value 0 means there is no error nor warning and
2787 * the operation succeed.
2788 */
William Lallemandfa892222019-07-23 16:06:08 +02002789#ifndef OPENSSL_NO_DH
Emeric Brun7a883362019-10-17 13:27:40 +02002790static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct cert_key_and_chain *ckch,
2791 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02002792{
Emeric Brun7a883362019-10-17 13:27:40 +02002793 int ret = 0;
William Lallemandfa892222019-07-23 16:06:08 +02002794 DH *dh = NULL;
2795
William Lallemanda8c73742019-07-31 18:31:34 +02002796 if (ckch && ckch->dh) {
William Lallemandfa892222019-07-23 16:06:08 +02002797 dh = ckch->dh;
Emeric Bruna9363eb2019-10-17 14:53:03 +02002798 if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
2799 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
2800 err && *err ? *err : "", path);
2801#if defined(SSL_CTX_set_dh_auto)
2802 SSL_CTX_set_dh_auto(ctx, 1);
2803 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2804 err && *err ? *err : "");
2805#else
2806 memprintf(err, "%s, DH ciphers won't be available.\n",
2807 err && *err ? *err : "");
2808#endif
2809 ret |= ERR_WARN;
2810 goto end;
2811 }
William Lallemandfa892222019-07-23 16:06:08 +02002812
2813 if (ssl_dh_ptr_index >= 0) {
2814 /* store a pointer to the DH params to avoid complaining about
2815 ssl-default-dh-param not being set for this SSL_CTX */
2816 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
2817 }
2818 }
2819 else if (global_dh) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02002820 if (!SSL_CTX_set_tmp_dh(ctx, global_dh)) {
2821 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
2822 err && *err ? *err : "", path);
2823#if defined(SSL_CTX_set_dh_auto)
2824 SSL_CTX_set_dh_auto(ctx, 1);
2825 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2826 err && *err ? *err : "");
2827#else
2828 memprintf(err, "%s, DH ciphers won't be available.\n",
2829 err && *err ? *err : "");
2830#endif
2831 ret |= ERR_WARN;
2832 goto end;
2833 }
William Lallemandfa892222019-07-23 16:06:08 +02002834 }
2835 else {
2836 /* Clear openssl global errors stack */
2837 ERR_clear_error();
2838
2839 if (global_ssl.default_dh_param <= 1024) {
2840 /* we are limited to DH parameter of 1024 bits anyway */
2841 if (local_dh_1024 == NULL)
2842 local_dh_1024 = ssl_get_dh_1024();
2843
Emeric Brun7a883362019-10-17 13:27:40 +02002844 if (local_dh_1024 == NULL) {
2845 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
2846 err && *err ? *err : "", path);
2847 ret |= ERR_ALERT | ERR_FATAL;
William Lallemandfa892222019-07-23 16:06:08 +02002848 goto end;
Emeric Brun7a883362019-10-17 13:27:40 +02002849 }
William Lallemandfa892222019-07-23 16:06:08 +02002850
Emeric Bruna9363eb2019-10-17 14:53:03 +02002851 if (!SSL_CTX_set_tmp_dh(ctx, local_dh_1024)) {
2852 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
2853 err && *err ? *err : "", path);
2854#if defined(SSL_CTX_set_dh_auto)
2855 SSL_CTX_set_dh_auto(ctx, 1);
2856 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
2857 err && *err ? *err : "");
2858#else
2859 memprintf(err, "%s, DH ciphers won't be available.\n",
2860 err && *err ? *err : "");
2861#endif
2862 ret |= ERR_WARN;
2863 goto end;
2864 }
William Lallemandfa892222019-07-23 16:06:08 +02002865 }
2866 else {
2867 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh);
2868 }
William Lallemand8d0f8932019-10-17 18:03:58 +02002869 }
2870
William Lallemandf9568fc2019-10-16 18:27:58 +02002871end:
William Lallemandf9568fc2019-10-16 18:27:58 +02002872 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02002873 return ret;
2874}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02002875#endif
William Lallemandfa892222019-07-23 16:06:08 +02002876
yanbzhu488a4d22015-12-01 15:16:07 -05002877/* Loads the info in ckch into ctx
Emeric Bruna96b5822019-10-17 13:25:14 +02002878 * Returns a bitfield containing the flags:
2879 * ERR_FATAL in any fatal error case
2880 * ERR_ALERT if the reason of the error is available in err
2881 * ERR_WARN if a warning is available into err
2882 * The value 0 means there is no error nor warning and
2883 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05002884 */
2885static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
2886{
Emeric Bruna96b5822019-10-17 13:25:14 +02002887 int errcode = 0;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01002888 STACK_OF(X509) *find_chain = NULL;
Emeric Bruna96b5822019-10-17 13:25:14 +02002889
yanbzhu488a4d22015-12-01 15:16:07 -05002890 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
2891 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
2892 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02002893 errcode |= ERR_ALERT | ERR_FATAL;
2894 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05002895 }
2896
2897 if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
2898 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
2899 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02002900 errcode |= ERR_ALERT | ERR_FATAL;
2901 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05002902 }
2903
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01002904 if (ckch->chain) {
2905 find_chain = ckch->chain;
2906 } else {
2907 /* Find Certificate Chain in global */
2908 struct issuer_chain *issuer;
Emmanuel Hocdetef87e0a2020-03-23 11:29:11 +01002909 issuer = ssl_get0_issuer_chain(ckch->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01002910 if (issuer)
2911 find_chain = issuer->chain;
2912 }
William Lallemand85888572020-02-27 14:48:35 +01002913
William Lallemandf187ce62020-06-02 18:27:20 +02002914 /* Load all certs in the ckch into the ctx_chain for the ssl_ctx */
2915 if (find_chain)
2916#ifdef SSL_CTX_set1_chain
2917 if (!SSL_CTX_set1_chain(ctx, find_chain)) {
2918 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'. Make sure you are linking against Openssl >= 1.0.2.\n",
2919 err && *err ? *err : "", path);
2920 errcode |= ERR_ALERT | ERR_FATAL;
2921 goto end;
2922 }
2923#else
2924 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002925 X509 *ca;
William Lallemandf187ce62020-06-02 18:27:20 +02002926 STACK_OF(X509) *chain;
2927 chain = X509_chain_up_ref(find_chain);
2928 while ((ca = sk_X509_shift(chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002929 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002930 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
2931 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02002932 X509_free(ca);
2933 sk_X509_pop_free(chain, X509_free);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002934 errcode |= ERR_ALERT | ERR_FATAL;
2935 goto end;
2936 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01002937 }
William Lallemandf187ce62020-06-02 18:27:20 +02002938#endif
yanbzhu488a4d22015-12-01 15:16:07 -05002939
William Lallemandfa892222019-07-23 16:06:08 +02002940#ifndef OPENSSL_NO_DH
2941 /* store a NULL pointer to indicate we have not yet loaded
2942 a custom DH param file */
2943 if (ssl_dh_ptr_index >= 0) {
2944 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
2945 }
2946
Emeric Brun7a883362019-10-17 13:27:40 +02002947 errcode |= ssl_sock_load_dh_params(ctx, ckch, path, err);
2948 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02002949 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
2950 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02002951 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02002952 }
2953#endif
2954
William Lallemanda17f4112019-10-10 15:16:44 +02002955#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
2956 if (sctl_ex_index >= 0 && ckch->sctl) {
2957 if (ssl_sock_load_sctl(ctx, ckch->sctl) < 0) {
2958 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01002959 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02002960 errcode |= ERR_ALERT | ERR_FATAL;
2961 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02002962 }
2963 }
2964#endif
2965
William Lallemand4a660132019-10-14 14:51:41 +02002966#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
William Lallemand246c0242019-10-11 08:59:13 +02002967 /* Load OCSP Info into context */
2968 if (ckch->ocsp_response) {
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01002969 if (ssl_sock_load_ocsp(ctx, ckch, find_chain) < 0) {
Tim Duesterhus93128532019-11-23 23:45:10 +01002970 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",
2971 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02002972 errcode |= ERR_ALERT | ERR_FATAL;
2973 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02002974 }
2975 }
William Lallemand246c0242019-10-11 08:59:13 +02002976#endif
2977
Emeric Bruna96b5822019-10-17 13:25:14 +02002978 end:
2979 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05002980}
2981
William Lallemandc4ecddf2019-07-31 16:50:08 +02002982#if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL
yanbzhu08ce6ab2015-12-02 13:01:29 -05002983
William Lallemand28a8fce2019-10-04 17:36:55 +02002984static int ssl_sock_populate_sni_keytypes_hplr(const char *str, struct eb_root *sni_keytypes, int key_index)
yanbzhu08ce6ab2015-12-02 13:01:29 -05002985{
2986 struct sni_keytype *s_kt = NULL;
2987 struct ebmb_node *node;
2988 int i;
2989
2990 for (i = 0; i < trash.size; i++) {
2991 if (!str[i])
2992 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002993 trash.area[i] = tolower(str[i]);
yanbzhu08ce6ab2015-12-02 13:01:29 -05002994 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002995 trash.area[i] = 0;
2996 node = ebst_lookup(sni_keytypes, trash.area);
yanbzhu08ce6ab2015-12-02 13:01:29 -05002997 if (!node) {
2998 /* CN not found in tree */
2999 s_kt = malloc(sizeof(struct sni_keytype) + i + 1);
3000 /* Using memcpy here instead of strncpy.
3001 * strncpy will cause sig_abrt errors under certain versions of gcc with -O2
3002 * See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=60792
3003 */
William Lallemand28a8fce2019-10-04 17:36:55 +02003004 if (!s_kt)
3005 return -1;
3006
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003007 memcpy(s_kt->name.key, trash.area, i+1);
yanbzhu08ce6ab2015-12-02 13:01:29 -05003008 s_kt->keytypes = 0;
3009 ebst_insert(sni_keytypes, &s_kt->name);
3010 } else {
3011 /* CN found in tree */
3012 s_kt = container_of(node, struct sni_keytype, name);
3013 }
3014
3015 /* Mark that this CN has the keytype of key_index via keytypes mask */
3016 s_kt->keytypes |= 1<<key_index;
3017
William Lallemand28a8fce2019-10-04 17:36:55 +02003018 return 0;
3019
William Lallemand6af03992019-07-23 15:00:54 +02003020}
3021
William Lallemandc4ecddf2019-07-31 16:50:08 +02003022#endif
William Lallemand36b84632019-07-18 19:28:17 +02003023
William Lallemandc4ecddf2019-07-31 16:50:08 +02003024#if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL
3025
William Lallemand36b84632019-07-18 19:28:17 +02003026/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003027 * Take a ckch_store which contains a multi-certificate bundle.
William Lallemand36b84632019-07-18 19:28:17 +02003028 * Group these certificates into a set of SSL_CTX*
yanbzhu08ce6ab2015-12-02 13:01:29 -05003029 * based on shared and unique CN and SAN entries. Add these SSL_CTX* to the SNI tree.
3030 *
Joseph Herlant017b3da2018-11-15 09:07:59 -08003031 * This will allow the user to explicitly group multiple cert/keys for a single purpose
yanbzhu08ce6ab2015-12-02 13:01:29 -05003032 *
Emeric Brun054563d2019-10-17 13:16:58 +02003033 * Returns a bitfield containing the flags:
3034 * ERR_FATAL in any fatal error case
3035 * ERR_ALERT if the reason of the error is available in err
3036 * ERR_WARN if a warning is available into err
William Lallemand36b84632019-07-18 19:28:17 +02003037 *
yanbzhu08ce6ab2015-12-02 13:01:29 -05003038 */
William Lallemandda8584c2020-05-14 10:14:37 +02003039int ckch_inst_new_load_multi_store(const char *path, struct ckch_store *ckchs,
3040 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
3041 char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
yanbzhu08ce6ab2015-12-02 13:01:29 -05003042{
William Lallemand36b84632019-07-18 19:28:17 +02003043 int i = 0, n = 0;
3044 struct cert_key_and_chain *certs_and_keys;
William Lallemand4b989f22019-10-04 18:36:55 +02003045 struct eb_root sni_keytypes_map = EB_ROOT;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003046 struct ebmb_node *node;
3047 struct ebmb_node *next;
3048 /* Array of SSL_CTX pointers corresponding to each possible combo
3049 * of keytypes
3050 */
3051 struct key_combo_ctx key_combos[SSL_SOCK_POSSIBLE_KT_COMBOS] = { {0} };
Emeric Brun054563d2019-10-17 13:16:58 +02003052 int errcode = 0;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003053 X509_NAME *xname = NULL;
3054 char *str = NULL;
3055#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3056 STACK_OF(GENERAL_NAME) *names = NULL;
3057#endif
William Lallemand614ca0d2019-10-07 13:52:11 +02003058 struct ckch_inst *ckch_inst;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003059
Emeric Brun054563d2019-10-17 13:16:58 +02003060 *ckchi = NULL;
3061
William Lallemande3af8fb2019-10-08 11:36:53 +02003062 if (!ckchs || !ckchs->ckch || !ckchs->multi) {
William Lallemand36b84632019-07-18 19:28:17 +02003063 memprintf(err, "%sunable to load SSL certificate file '%s' file does not exist.\n",
3064 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003065 return ERR_ALERT | ERR_FATAL;
William Lallemand614ca0d2019-10-07 13:52:11 +02003066 }
3067
3068 ckch_inst = ckch_inst_new();
3069 if (!ckch_inst) {
3070 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3071 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003072 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemand614ca0d2019-10-07 13:52:11 +02003073 goto end;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003074 }
3075
William Lallemande3af8fb2019-10-08 11:36:53 +02003076 certs_and_keys = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003077
yanbzhu08ce6ab2015-12-02 13:01:29 -05003078 /* Process each ckch and update keytypes for each CN/SAN
3079 * for example, if CN/SAN www.a.com is associated with
3080 * certs with keytype 0 and 2, then at the end of the loop,
3081 * www.a.com will have:
3082 * keyindex = 0 | 1 | 4 = 5
3083 */
3084 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
William Lallemand28a8fce2019-10-04 17:36:55 +02003085 int ret;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003086
3087 if (!ssl_sock_is_ckch_valid(&certs_and_keys[n]))
3088 continue;
3089
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003090 if (fcount) {
William Lallemand28a8fce2019-10-04 17:36:55 +02003091 for (i = 0; i < fcount; i++) {
3092 ret = ssl_sock_populate_sni_keytypes_hplr(sni_filter[i], &sni_keytypes_map, n);
3093 if (ret < 0) {
3094 memprintf(err, "%sunable to allocate SSL context.\n",
3095 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003096 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemand28a8fce2019-10-04 17:36:55 +02003097 goto end;
3098 }
3099 }
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003100 } else {
3101 /* A lot of the following code is OpenSSL boilerplate for processing CN's and SAN's,
3102 * so the line that contains logic is marked via comments
3103 */
3104 xname = X509_get_subject_name(certs_and_keys[n].cert);
3105 i = -1;
3106 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3107 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003108 ASN1_STRING *value;
3109 value = X509_NAME_ENTRY_get_data(entry);
3110 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003111 /* Important line is here */
William Lallemand28a8fce2019-10-04 17:36:55 +02003112 ret = ssl_sock_populate_sni_keytypes_hplr(str, &sni_keytypes_map, n);
yanbzhu08ce6ab2015-12-02 13:01:29 -05003113
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003114 OPENSSL_free(str);
3115 str = NULL;
William Lallemand28a8fce2019-10-04 17:36:55 +02003116 if (ret < 0) {
3117 memprintf(err, "%sunable to allocate SSL context.\n",
3118 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003119 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemand28a8fce2019-10-04 17:36:55 +02003120 goto end;
3121 }
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003122 }
yanbzhu08ce6ab2015-12-02 13:01:29 -05003123 }
yanbzhu08ce6ab2015-12-02 13:01:29 -05003124
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003125 /* Do the above logic for each SAN */
yanbzhu08ce6ab2015-12-02 13:01:29 -05003126#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003127 names = X509_get_ext_d2i(certs_and_keys[n].cert, NID_subject_alt_name, NULL, NULL);
3128 if (names) {
3129 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3130 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
yanbzhu08ce6ab2015-12-02 13:01:29 -05003131
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003132 if (name->type == GEN_DNS) {
3133 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
3134 /* Important line is here */
William Lallemand28a8fce2019-10-04 17:36:55 +02003135 ret = ssl_sock_populate_sni_keytypes_hplr(str, &sni_keytypes_map, n);
yanbzhu08ce6ab2015-12-02 13:01:29 -05003136
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003137 OPENSSL_free(str);
3138 str = NULL;
William Lallemand28a8fce2019-10-04 17:36:55 +02003139 if (ret < 0) {
3140 memprintf(err, "%sunable to allocate SSL context.\n",
3141 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003142 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemand28a8fce2019-10-04 17:36:55 +02003143 goto end;
3144 }
Emmanuel Hocdetd294aea2016-05-13 11:14:06 +02003145 }
yanbzhu08ce6ab2015-12-02 13:01:29 -05003146 }
3147 }
3148 }
3149 }
3150#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
3151 }
3152
3153 /* If no files found, return error */
3154 if (eb_is_empty(&sni_keytypes_map)) {
3155 memprintf(err, "%sunable to load SSL certificate file '%s' file does not exist.\n",
3156 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003157 errcode |= ERR_ALERT | ERR_FATAL;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003158 goto end;
3159 }
3160
3161 /* We now have a map of CN/SAN to keytypes that are loaded in
3162 * Iterate through the map to create the SSL_CTX's (if needed)
3163 * and add each CTX to the SNI tree
3164 *
3165 * Some math here:
Joseph Herlant017b3da2018-11-15 09:07:59 -08003166 * There are 2^n - 1 possible combinations, each unique
yanbzhu08ce6ab2015-12-02 13:01:29 -05003167 * combination is denoted by the key in the map. Each key
3168 * has a value between 1 and 2^n - 1. Conveniently, the array
3169 * of SSL_CTX* is sized 2^n. So, we can simply use the i'th
3170 * entry in the array to correspond to the unique combo (key)
3171 * associated with i. This unique key combo (i) will be associated
3172 * with combos[i-1]
3173 */
3174
3175 node = ebmb_first(&sni_keytypes_map);
3176 while (node) {
3177 SSL_CTX *cur_ctx;
Bertrand Jacquin33423092016-11-13 16:37:13 +00003178 char cur_file[MAXPATHLEN+1];
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003179 const struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
yanbzhu08ce6ab2015-12-02 13:01:29 -05003180
3181 str = (char *)container_of(node, struct sni_keytype, name)->name.key;
3182 i = container_of(node, struct sni_keytype, name)->keytypes;
3183 cur_ctx = key_combos[i-1].ctx;
3184
3185 if (cur_ctx == NULL) {
3186 /* need to create SSL_CTX */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003187 cur_ctx = SSL_CTX_new(SSLv23_server_method());
yanbzhu08ce6ab2015-12-02 13:01:29 -05003188 if (cur_ctx == NULL) {
3189 memprintf(err, "%sunable to allocate SSL context.\n",
3190 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003191 errcode |= ERR_ALERT | ERR_FATAL;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003192 goto end;
3193 }
3194
yanbzhube2774d2015-12-10 15:07:30 -05003195 /* Load all required certs/keys/chains/OCSPs info into SSL_CTX */
yanbzhu08ce6ab2015-12-02 13:01:29 -05003196 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3197 if (i & (1<<n)) {
3198 /* Key combo contains ckch[n] */
Bertrand Jacquin33423092016-11-13 16:37:13 +00003199 snprintf(cur_file, MAXPATHLEN+1, "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
Emeric Bruna96b5822019-10-17 13:25:14 +02003200 errcode |= ssl_sock_put_ckch_into_ctx(cur_file, &certs_and_keys[n], cur_ctx, err);
3201 if (errcode & ERR_CODE)
yanbzhu08ce6ab2015-12-02 13:01:29 -05003202 goto end;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003203 }
3204 }
3205
yanbzhu08ce6ab2015-12-02 13:01:29 -05003206 /* Update key_combos */
3207 key_combos[i-1].ctx = cur_ctx;
3208 }
3209
3210 /* Update SNI Tree */
William Lallemand9117de92019-10-04 00:29:42 +02003211
William Lallemand1d29c742019-10-04 00:53:29 +02003212 key_combos[i-1].order = ckch_inst_add_cert_sni(cur_ctx, ckch_inst, bind_conf, ssl_conf,
William Lallemandfe49bb32019-10-03 23:46:33 +02003213 kinfo, str, key_combos[i-1].order);
3214 if (key_combos[i-1].order < 0) {
3215 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003216 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandfe49bb32019-10-03 23:46:33 +02003217 goto end;
3218 }
yanbzhu08ce6ab2015-12-02 13:01:29 -05003219 node = ebmb_next(node);
3220 }
3221
3222
3223 /* Mark a default context if none exists, using the ctx that has the most shared keys */
3224 if (!bind_conf->default_ctx) {
3225 for (i = SSL_SOCK_POSSIBLE_KT_COMBOS - 1; i >= 0; i--) {
3226 if (key_combos[i].ctx) {
3227 bind_conf->default_ctx = key_combos[i].ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003228 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003229 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003230 SSL_CTX_up_ref(bind_conf->default_ctx);
yanbzhu08ce6ab2015-12-02 13:01:29 -05003231 break;
3232 }
3233 }
3234 }
3235
William Lallemand614ca0d2019-10-07 13:52:11 +02003236 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003237 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003238 ckch_inst->ckch_store = ckchs;
William Lallemand02e19a52020-04-08 16:11:26 +02003239
yanbzhu08ce6ab2015-12-02 13:01:29 -05003240end:
3241
3242 if (names)
3243 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
3244
yanbzhu08ce6ab2015-12-02 13:01:29 -05003245 node = ebmb_first(&sni_keytypes_map);
3246 while (node) {
3247 next = ebmb_next(node);
3248 ebmb_delete(node);
William Lallemand8ed5b962019-10-04 17:24:39 +02003249 free(ebmb_entry(node, struct sni_keytype, name));
yanbzhu08ce6ab2015-12-02 13:01:29 -05003250 node = next;
3251 }
3252
William Lallemand02e19a52020-04-08 16:11:26 +02003253 /* we need to free the ctx since we incremented the refcount where it's used */
3254 for (i = 0; i < SSL_SOCK_POSSIBLE_KT_COMBOS; i++) {
3255 if (key_combos[i].ctx)
3256 SSL_CTX_free(key_combos[i].ctx);
3257 }
3258
Emeric Brun054563d2019-10-17 13:16:58 +02003259 if (errcode & ERR_CODE && ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003260 if (ckch_inst->is_default) {
3261 SSL_CTX_free(bind_conf->default_ctx);
3262 bind_conf->default_ctx = NULL;
3263 }
3264
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003265 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003266 ckch_inst = NULL;
William Lallemand0c6d12f2019-10-04 18:38:51 +02003267 }
3268
Emeric Brun054563d2019-10-17 13:16:58 +02003269 *ckchi = ckch_inst;
3270 return errcode;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003271}
3272#else
3273/* This is a dummy, that just logs an error and returns error */
William Lallemandda8584c2020-05-14 10:14:37 +02003274int ckch_inst_new_load_multi_store(const char *path, struct ckch_store *ckchs,
3275 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
3276 char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
yanbzhu08ce6ab2015-12-02 13:01:29 -05003277{
3278 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3279 err && *err ? *err : "", path, strerror(errno));
Emeric Brun054563d2019-10-17 13:16:58 +02003280 return ERR_ALERT | ERR_FATAL;
yanbzhu08ce6ab2015-12-02 13:01:29 -05003281}
3282
Willy Tarreau9a1ab082019-05-09 13:26:41 +02003283#endif /* #if HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL: Support for loading multiple certs into a single SSL_CTX */
yanbzhu488a4d22015-12-01 15:16:07 -05003284
William Lallemand614ca0d2019-10-07 13:52:11 +02003285/*
3286 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003287 *
3288 * Returns a bitfield containing the flags:
3289 * ERR_FATAL in any fatal error case
3290 * ERR_ALERT if the reason of the error is available in err
3291 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003292 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003293int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003294 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003295{
William Lallemandc9402072019-05-15 15:33:54 +02003296 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003297 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003298 int order = 0;
3299 X509_NAME *xname;
3300 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003301 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003302 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003303#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3304 STACK_OF(GENERAL_NAME) *names;
3305#endif
William Lallemand36b84632019-07-18 19:28:17 +02003306 struct cert_key_and_chain *ckch;
William Lallemand614ca0d2019-10-07 13:52:11 +02003307 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003308 int errcode = 0;
3309
3310 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003311
William Lallemande3af8fb2019-10-08 11:36:53 +02003312 if (!ckchs || !ckchs->ckch)
Emeric Brun054563d2019-10-17 13:16:58 +02003313 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003314
William Lallemande3af8fb2019-10-08 11:36:53 +02003315 ckch = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003316
William Lallemandc9402072019-05-15 15:33:54 +02003317 ctx = SSL_CTX_new(SSLv23_server_method());
3318 if (!ctx) {
3319 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3320 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003321 errcode |= ERR_ALERT | ERR_FATAL;
3322 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003323 }
3324
Emeric Bruna96b5822019-10-17 13:25:14 +02003325 errcode |= ssl_sock_put_ckch_into_ctx(path, ckch, ctx, err);
3326 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003327 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003328
3329 ckch_inst = ckch_inst_new();
3330 if (!ckch_inst) {
3331 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3332 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003333 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003334 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003335 }
3336
William Lallemand36b84632019-07-18 19:28:17 +02003337 pkey = X509_get_pubkey(ckch->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003338 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003339 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003340 switch(EVP_PKEY_base_id(pkey)) {
3341 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003342 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003343 break;
3344 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003345 kinfo.sig = TLSEXT_signature_ecdsa;
3346 break;
3347 case EVP_PKEY_DSA:
3348 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003349 break;
3350 }
3351 EVP_PKEY_free(pkey);
3352 }
3353
Emeric Brun50bcecc2013-04-22 13:05:23 +02003354 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003355 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003356 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, sni_filter[fcount], order);
William Lallemandfe49bb32019-10-03 23:46:33 +02003357 if (order < 0) {
3358 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003359 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003360 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003361 }
3362 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003363 }
3364 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003365#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand36b84632019-07-18 19:28:17 +02003366 names = X509_get_ext_d2i(ckch->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003367 if (names) {
3368 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3369 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3370 if (name->type == GEN_DNS) {
3371 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003372 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003373 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003374 if (order < 0) {
3375 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003376 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003377 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003378 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003379 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003380 }
3381 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003382 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003383 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003384#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand36b84632019-07-18 19:28:17 +02003385 xname = X509_get_subject_name(ckch->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003386 i = -1;
3387 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3388 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003389 ASN1_STRING *value;
3390
3391 value = X509_NAME_ENTRY_get_data(entry);
3392 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003393 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003394 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003395 if (order < 0) {
3396 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003397 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003398 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003399 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003400 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003401 }
3402 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003403 /* we must not free the SSL_CTX anymore below, since it's already in
3404 * the tree, so it will be discovered and cleaned in time.
3405 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003406
Emeric Brunfc0421f2012-09-07 17:30:07 +02003407#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003408 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003409 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3410 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003411 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003412 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003413 }
3414#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003415 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003416 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003417 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003418 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003419 SSL_CTX_up_ref(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003420 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003421
William Lallemand9117de92019-10-04 00:29:42 +02003422 /* everything succeed, the ckch instance can be used */
3423 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003424 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003425 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003426
William Lallemand02e19a52020-04-08 16:11:26 +02003427 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3428
Emeric Brun054563d2019-10-17 13:16:58 +02003429 *ckchi = ckch_inst;
3430 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003431
3432error:
3433 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003434 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003435 if (ckch_inst->is_default)
3436 SSL_CTX_free(ctx);
3437
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003438 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003439 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003440 }
William Lallemandd9199372019-10-04 15:37:05 +02003441 SSL_CTX_free(ctx);
3442
Emeric Brun054563d2019-10-17 13:16:58 +02003443 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003444}
3445
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003446/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003447static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3448 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003449 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003450{
Emeric Brun054563d2019-10-17 13:16:58 +02003451 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003452
3453 /* we found the ckchs in the tree, we can use it directly */
3454 if (ckchs->multi)
William Lallemand24bde432020-03-09 16:48:43 +01003455 errcode |= ckch_inst_new_load_multi_store(path, ckchs, bind_conf, ssl_conf, sni_filter, fcount, ckch_inst, err);
William Lallemand614ca0d2019-10-07 13:52:11 +02003456 else
William Lallemand24bde432020-03-09 16:48:43 +01003457 errcode |= ckch_inst_new_load_store(path, ckchs, bind_conf, ssl_conf, sni_filter, fcount, ckch_inst, err);
William Lallemand614ca0d2019-10-07 13:52:11 +02003458
Emeric Brun054563d2019-10-17 13:16:58 +02003459 if (errcode & ERR_CODE)
3460 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003461
William Lallemand24bde432020-03-09 16:48:43 +01003462 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003463
3464 /* succeed, add the instance to the ckch_store's list of instance */
William Lallemand24bde432020-03-09 16:48:43 +01003465 LIST_ADDQ(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003466 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003467}
3468
William Lallemand6be66ec2020-03-06 22:26:32 +01003469
William Lallemand4c68bba2020-03-30 18:45:10 +02003470
3471
3472/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3473 * done once. Zero is returned if the operation fails. No error is returned
3474 * if the random is said as not implemented, because we expect that openssl
3475 * will use another method once needed.
3476 */
3477static int ssl_initialize_random()
3478{
3479 unsigned char random;
3480 static int random_initialized = 0;
3481
3482 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3483 random_initialized = 1;
3484
3485 return random_initialized;
3486}
3487
William Lallemand2954c472020-03-06 21:54:13 +01003488/* Load a crt-list file, this is done in 2 parts:
3489 * - store the content of the file in a crtlist structure with crtlist_entry structures
3490 * - generate the instances by iterating on entries in the crtlist struct
3491 *
3492 * Nothing is locked there, this function is used in the configuration parser.
3493 *
3494 * Returns a set of ERR_* flags possibly with an error in <err>.
3495 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003496int ssl_sock_load_cert_list_file(char *file, int dir, struct bind_conf *bind_conf, struct proxy *curproxy, char **err)
William Lallemand2954c472020-03-06 21:54:13 +01003497{
3498 struct crtlist *crtlist = NULL;
3499 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003500 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003501 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003502 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003503 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003504
William Lallemand79d31ec2020-03-25 15:10:49 +01003505 bind_conf_node = malloc(sizeof(*bind_conf_node));
3506 if (!bind_conf_node) {
3507 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3508 cfgerr |= ERR_FATAL | ERR_ALERT;
3509 goto error;
3510 }
3511 bind_conf_node->next = NULL;
3512 bind_conf_node->bind_conf = bind_conf;
3513
William Lallemand41ca9302020-04-08 13:15:18 +02003514 /* strip trailing slashes, including first one */
3515 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3516 *end = 0;
3517
William Lallemand2954c472020-03-06 21:54:13 +01003518 /* look for an existing crtlist or create one */
3519 eb = ebst_lookup(&crtlists_tree, file);
3520 if (eb) {
3521 crtlist = ebmb_entry(eb, struct crtlist, node);
3522 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003523 /* load a crt-list OR a directory */
3524 if (dir)
3525 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3526 else
3527 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3528
William Lallemand2954c472020-03-06 21:54:13 +01003529 if (!(cfgerr & ERR_CODE))
3530 ebst_insert(&crtlists_tree, &crtlist->node);
3531 }
3532
3533 if (cfgerr & ERR_CODE) {
3534 cfgerr |= ERR_FATAL | ERR_ALERT;
3535 goto error;
3536 }
3537
3538 /* generates ckch instance from the crtlist_entry */
3539 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3540 struct ckch_store *store;
3541 struct ckch_inst *ckch_inst = NULL;
3542
3543 store = entry->node.key;
3544 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3545 if (cfgerr & ERR_CODE) {
3546 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3547 goto error;
3548 }
William Lallemand49398312020-03-30 17:01:33 +02003549 LIST_ADDQ(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003550 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003551 }
William Lallemand2954c472020-03-06 21:54:13 +01003552
William Lallemand79d31ec2020-03-25 15:10:49 +01003553 /* add the bind_conf to the list */
3554 bind_conf_node->next = crtlist->bind_conf;
3555 crtlist->bind_conf = bind_conf_node;
3556
William Lallemand2954c472020-03-06 21:54:13 +01003557 return cfgerr;
3558error:
3559 {
William Lallemand49398312020-03-30 17:01:33 +02003560 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003561 struct ckch_inst *inst, *s_inst;
3562
William Lallemand49398312020-03-30 17:01:33 +02003563 lastentry = entry; /* which entry we tried to generate last */
3564 if (lastentry) {
3565 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3566 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3567 break;
3568
3569 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003570
William Lallemand49398312020-03-30 17:01:33 +02003571 /* this was not generated for this bind_conf, skip */
3572 if (inst->bind_conf != bind_conf)
3573 continue;
3574
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003575 /* free the sni_ctx and instance */
3576 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003577 }
William Lallemand2954c472020-03-06 21:54:13 +01003578 }
William Lallemand2954c472020-03-06 21:54:13 +01003579 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003580 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003581 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003582 return cfgerr;
3583}
3584
William Lallemand06b22a82020-03-16 14:45:55 +01003585/* Returns a set of ERR_* flags possibly with an error in <err>. */
3586int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3587{
3588 struct stat buf;
3589 char fp[MAXPATHLEN+1];
3590 int cfgerr = 0;
3591 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003592 struct ckch_inst *ckch_inst = NULL;
William Lallemand06b22a82020-03-16 14:45:55 +01003593
3594 if ((ckchs = ckchs_lookup(path))) {
3595 /* we found the ckchs in the tree, we can use it directly */
William Lallemand24bde432020-03-09 16:48:43 +01003596 return ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003597 }
3598 if (stat(path, &buf) == 0) {
3599 if (S_ISDIR(buf.st_mode) == 0) {
3600 ckchs = ckchs_load_cert_file(path, 0, err);
3601 if (!ckchs)
3602 return ERR_ALERT | ERR_FATAL;
3603
William Lallemand24bde432020-03-09 16:48:43 +01003604 return ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003605 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003606 return ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003607 }
3608 } else {
3609 /* stat failed, could be a bundle */
3610 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
3611 /* try to load a bundle if it is permitted */
3612 ckchs = ckchs_load_cert_file(path, 1, err);
3613 if (!ckchs)
3614 return ERR_ALERT | ERR_FATAL;
William Lallemand24bde432020-03-09 16:48:43 +01003615 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003616 } else {
3617 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3618 err && *err ? *err : "", fp, strerror(errno));
3619 cfgerr |= ERR_ALERT | ERR_FATAL;
3620 }
3621 }
3622
3623 return cfgerr;
3624}
3625
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003626/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003627static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003628ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003629{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003630 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003631 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003632 SSL_OP_ALL | /* all known workarounds for bugs */
3633 SSL_OP_NO_SSLv2 |
3634 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003635 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02003636 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003637 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02003638 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003639 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003640 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003641 SSL_MODE_ENABLE_PARTIAL_WRITE |
3642 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01003643 SSL_MODE_RELEASE_BUFFERS |
3644 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02003645 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003646 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003647 int flags = MC_SSL_O_ALL;
3648 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02003649 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003650
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003651 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003652 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003653
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003654 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01003655 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
3656 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3657 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003658 else
3659 flags = conf_ssl_methods->flags;
3660
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003661 min = conf_ssl_methods->min;
3662 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02003663
3664 /* default minimum is TLSV12, */
3665 if (!min) {
3666 if (!max || (max >= default_min_ver)) {
3667 min = default_min_ver;
3668 } else {
3669 ha_warning("Proxy '%s': Ambiguous configuration for bind '%s' at [%s:%d]: the ssl-min-ver value is not configured and the ssl-max-ver value is lower than the default ssl-min-ver value (%s). "
3670 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
3671 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
3672 min = max;
3673 }
3674 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003675 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003676 if (min)
3677 flags |= (methodVersions[min].flag - 1);
3678 if (max)
3679 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003680 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003681 min = max = CONF_TLSV_NONE;
3682 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003683 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003684 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003685 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003686 if (min) {
3687 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003688 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
3689 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3690 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
3691 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003692 hole = 0;
3693 }
3694 max = i;
3695 }
3696 else {
3697 min = max = i;
3698 }
3699 }
3700 else {
3701 if (min)
3702 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003703 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003704 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003705 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
3706 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003707 cfgerr += 1;
3708 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02003709 /* save real min/max in bind_conf */
3710 conf_ssl_methods->min = min;
3711 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003712
Willy Tarreau9a1ab082019-05-09 13:26:41 +02003713#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003714 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08003715 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003716 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003717 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003718 else
3719 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
3720 if (flags & methodVersions[i].flag)
3721 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003722#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003723 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003724 methodVersions[min].ctx_set_version(ctx, SET_MIN);
3725 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02003726#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003727
3728 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
3729 options |= SSL_OP_NO_TICKET;
3730 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
3731 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08003732
3733#ifdef SSL_OP_NO_RENEGOTIATION
3734 options |= SSL_OP_NO_RENEGOTIATION;
3735#endif
3736
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003737 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003738
Willy Tarreau5db847a2019-05-09 14:13:35 +02003739#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003740 if (global_ssl.async)
3741 mode |= SSL_MODE_ASYNC;
3742#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003743 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003744 if (global_ssl.life_time)
3745 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003746
3747#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3748#ifdef OPENSSL_IS_BORINGSSL
3749 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
3750 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Ilya Shipitsine9ff8992020-01-19 12:20:14 +05003751#elif defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01003752 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01003753 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003754 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
3755 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003756#else
3757 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003758#endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003759 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003760#endif
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003761 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003762}
3763
William Lallemand4f45bb92017-10-30 20:08:51 +01003764
3765static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
3766{
3767 if (first == block) {
3768 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3769 if (first->len > 0)
3770 sh_ssl_sess_tree_delete(sh_ssl_sess);
3771 }
3772}
3773
3774/* return first block from sh_ssl_sess */
3775static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
3776{
3777 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
3778
3779}
3780
3781/* store a session into the cache
3782 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
3783 * data: asn1 encoded session
3784 * data_len: asn1 encoded session length
3785 * Returns 1 id session was stored (else 0)
3786 */
3787static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
3788{
3789 struct shared_block *first;
3790 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
3791
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003792 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01003793 if (!first) {
3794 /* Could not retrieve enough free blocks to store that session */
3795 return 0;
3796 }
3797
3798 /* STORE the key in the first elem */
3799 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3800 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
3801 first->len = sizeof(struct sh_ssl_sess_hdr);
3802
3803 /* it returns the already existing node
3804 or current node if none, never returns null */
3805 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
3806 if (oldsh_ssl_sess != sh_ssl_sess) {
3807 /* NOTE: Row couldn't be in use because we lock read & write function */
3808 /* release the reserved row */
3809 shctx_row_dec_hot(ssl_shctx, first);
3810 /* replace the previous session already in the tree */
3811 sh_ssl_sess = oldsh_ssl_sess;
3812 /* ignore the previous session data, only use the header */
3813 first = sh_ssl_sess_first_block(sh_ssl_sess);
3814 shctx_row_inc_hot(ssl_shctx, first);
3815 first->len = sizeof(struct sh_ssl_sess_hdr);
3816 }
3817
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003818 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01003819 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003820 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01003821 }
3822
3823 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01003824
3825 return 1;
3826}
William Lallemanded0b5ad2017-10-30 19:36:36 +01003827
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003828/* SSL callback used when a new session is created while connecting to a server */
3829static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
3830{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02003831 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01003832 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003833
Willy Tarreau07d94e42018-09-20 10:57:52 +02003834 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003835
Olivier Houcharde6060c52017-11-16 17:42:52 +01003836 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
3837 int len;
3838 unsigned char *ptr;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003839
Olivier Houcharde6060c52017-11-16 17:42:52 +01003840 len = i2d_SSL_SESSION(sess, NULL);
3841 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
3842 ptr = s->ssl_ctx.reused_sess[tid].ptr;
3843 } else {
3844 free(s->ssl_ctx.reused_sess[tid].ptr);
3845 ptr = s->ssl_ctx.reused_sess[tid].ptr = malloc(len);
3846 s->ssl_ctx.reused_sess[tid].allocated_size = len;
3847 }
3848 if (s->ssl_ctx.reused_sess[tid].ptr) {
3849 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
3850 &ptr);
3851 }
3852 } else {
3853 free(s->ssl_ctx.reused_sess[tid].ptr);
3854 s->ssl_ctx.reused_sess[tid].ptr = NULL;
3855 }
3856
3857 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01003858}
3859
Olivier Houcharde6060c52017-11-16 17:42:52 +01003860
William Lallemanded0b5ad2017-10-30 19:36:36 +01003861/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01003862int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003863{
3864 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
3865 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
3866 unsigned char *p;
3867 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02003868 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003869 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003870
3871 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003872 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02003873 * note: SSL_SESSION_set1_id is using
3874 * a memcpy so we need to use a different pointer
3875 * than sid_data or sid_ctx_data to avoid valgrind
3876 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01003877 */
3878
3879 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02003880
3881 /* copy value in an other buffer */
3882 memcpy(encid, sid_data, sid_length);
3883
3884 /* pad with 0 */
3885 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
3886 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
3887
3888 /* force length to zero to avoid ASN1 encoding */
3889 SSL_SESSION_set1_id(sess, encid, 0);
3890
3891 /* force length to zero to avoid ASN1 encoding */
3892 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003893
3894 /* check if buffer is large enough for the ASN1 encoded session */
3895 data_len = i2d_SSL_SESSION(sess, NULL);
3896 if (data_len > SHSESS_MAX_DATA_LEN)
3897 goto err;
3898
3899 p = encsess;
3900
3901 /* process ASN1 session encoding before the lock */
3902 i2d_SSL_SESSION(sess, &p);
3903
William Lallemanded0b5ad2017-10-30 19:36:36 +01003904
William Lallemanda3c77cf2017-10-30 23:44:40 +01003905 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003906 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003907 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01003908 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003909err:
3910 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02003911 SSL_SESSION_set1_id(sess, encid, sid_length);
3912 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01003913
3914 return 0; /* do not increment session reference count */
3915}
3916
3917/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003918SSL_SESSION *sh_ssl_sess_get_cb(SSL *ssl, __OPENSSL_110_CONST__ unsigned char *key, int key_len, int *do_copy)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003919{
William Lallemand4f45bb92017-10-30 20:08:51 +01003920 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003921 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
3922 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01003923 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01003924 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003925
3926 global.shctx_lookups++;
3927
3928 /* allow the session to be freed automatically by openssl */
3929 *do_copy = 0;
3930
3931 /* tree key is zeros padded sessionid */
3932 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
3933 memcpy(tmpkey, key, key_len);
3934 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
3935 key = tmpkey;
3936 }
3937
3938 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003939 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003940
3941 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003942 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
3943 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01003944 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003945 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003946 global.shctx_misses++;
3947 return NULL;
3948 }
3949
William Lallemand4f45bb92017-10-30 20:08:51 +01003950 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
3951 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003952
William Lallemand4f45bb92017-10-30 20:08:51 +01003953 shctx_row_data_get(ssl_shctx, first, data, sizeof(struct sh_ssl_sess_hdr), first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01003954
William Lallemanda3c77cf2017-10-30 23:44:40 +01003955 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003956
3957 /* decode ASN1 session */
3958 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01003959 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01003960 /* Reset session id and session id contenxt */
3961 if (sess) {
3962 SSL_SESSION_set1_id(sess, key, key_len);
3963 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
3964 }
3965
3966 return sess;
3967}
3968
William Lallemand4f45bb92017-10-30 20:08:51 +01003969
William Lallemanded0b5ad2017-10-30 19:36:36 +01003970/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01003971void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01003972{
William Lallemand4f45bb92017-10-30 20:08:51 +01003973 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01003974 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
3975 unsigned int sid_length;
3976 const unsigned char *sid_data;
3977 (void)ctx;
3978
3979 sid_data = SSL_SESSION_get_id(sess, &sid_length);
3980 /* tree key is zeros padded sessionid */
3981 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
3982 memcpy(tmpkey, sid_data, sid_length);
3983 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
3984 sid_data = tmpkey;
3985 }
3986
William Lallemanda3c77cf2017-10-30 23:44:40 +01003987 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003988
3989 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003990 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
3991 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01003992 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01003993 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003994 }
3995
3996 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01003997 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01003998}
3999
4000/* Set session cache mode to server and disable openssl internal cache.
4001 * Set shared cache callbacks on an ssl context.
4002 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004003void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004004{
4005 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4006
4007 if (!ssl_shctx) {
4008 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4009 return;
4010 }
4011
4012 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4013 SSL_SESS_CACHE_NO_INTERNAL |
4014 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4015
4016 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004017 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4018 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4019 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004020}
4021
William Lallemand8b453912019-11-21 15:48:10 +01004022/*
4023 * This function applies the SSL configuration on a SSL_CTX
4024 * It returns an error code and fills the <err> buffer
4025 */
4026int ssl_sock_prepare_ctx(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf, SSL_CTX *ctx, char **err)
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004027{
4028 struct proxy *curproxy = bind_conf->frontend;
4029 int cfgerr = 0;
4030 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004031 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004032 const char *conf_ciphers;
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004033#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004034 const char *conf_ciphersuites;
4035#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004036 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004037
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004038 if (ssl_conf) {
4039 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4040 int i, min, max;
4041 int flags = MC_SSL_O_ALL;
4042
4043 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004044 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4045 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004046 if (min)
4047 flags |= (methodVersions[min].flag - 1);
4048 if (max)
4049 flags |= ~((methodVersions[max].flag << 1) - 1);
4050 min = max = CONF_TLSV_NONE;
4051 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4052 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4053 if (min)
4054 max = i;
4055 else
4056 min = max = i;
4057 }
4058 /* save real min/max */
4059 conf_ssl_methods->min = min;
4060 conf_ssl_methods->max = max;
4061 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004062 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4063 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004064 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004065 }
4066 }
4067
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004068 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004069 case SSL_SOCK_VERIFY_NONE:
4070 verify = SSL_VERIFY_NONE;
4071 break;
4072 case SSL_SOCK_VERIFY_OPTIONAL:
4073 verify = SSL_VERIFY_PEER;
4074 break;
4075 case SSL_SOCK_VERIFY_REQUIRED:
4076 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4077 break;
4078 }
4079 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4080 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004081 char *ca_file = (ssl_conf && ssl_conf->ca_file) ? ssl_conf->ca_file : bind_conf->ssl_conf.ca_file;
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004082 char *ca_verify_file = (ssl_conf && ssl_conf->ca_verify_file) ? ssl_conf->ca_verify_file : bind_conf->ssl_conf.ca_verify_file;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004083 char *crl_file = (ssl_conf && ssl_conf->crl_file) ? ssl_conf->crl_file : bind_conf->ssl_conf.crl_file;
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004084 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004085 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004086 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004087 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004088 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004089 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004090 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004091 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4092 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4093 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4094 cfgerr |= ERR_ALERT | ERR_FATAL;
4095 }
4096 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004097 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004098 SSL_CTX_set_client_CA_list(ctx, SSL_dup_CA_list(ssl_get_client_ca_file(ca_file)));
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004099 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004100 }
Emeric Brun850efd52014-01-29 12:24:34 +01004101 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004102 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4103 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004104 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004105 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004106#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004107 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004108 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4109
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004110 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004111 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4112 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004113 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004114 }
Emeric Brun561e5742012-10-02 15:20:55 +02004115 else {
4116 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4117 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004118 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004119#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004120 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004121 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004122#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004123 if(bind_conf->keys_ref) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004124 if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004125 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4126 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004127 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004128 }
4129 }
4130#endif
4131
William Lallemand4f45bb92017-10-30 20:08:51 +01004132 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004133 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4134 if (conf_ciphers &&
4135 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004136 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4137 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004138 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004139 }
4140
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004141#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004142 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4143 if (conf_ciphersuites &&
4144 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004145 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4146 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004147 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004148 }
4149#endif
4150
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004151#ifndef OPENSSL_NO_DH
Remi Gacogne47783ef2015-05-29 15:53:22 +02004152 /* If tune.ssl.default-dh-param has not been set,
4153 neither has ssl-default-dh-file and no static DH
4154 params were in the certificate file. */
Willy Tarreauef934602016-12-22 23:12:01 +01004155 if (global_ssl.default_dh_param == 0 &&
Remi Gacogne47783ef2015-05-29 15:53:22 +02004156 global_dh == NULL &&
Remi Gacogne4f902b82015-05-28 16:23:00 +02004157 (ssl_dh_ptr_index == -1 ||
4158 SSL_CTX_get_ex_data(ctx, ssl_dh_ptr_index) == NULL)) {
Willy Tarreau3ba77d22020-05-08 09:31:18 +02004159 /* default to dh-param 2048 */
4160 global_ssl.default_dh_param = 2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004161 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004162
Willy Tarreauef934602016-12-22 23:12:01 +01004163 if (global_ssl.default_dh_param >= 1024) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004164 if (local_dh_1024 == NULL) {
4165 local_dh_1024 = ssl_get_dh_1024();
4166 }
Willy Tarreauef934602016-12-22 23:12:01 +01004167 if (global_ssl.default_dh_param >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004168 if (local_dh_2048 == NULL) {
4169 local_dh_2048 = ssl_get_dh_2048();
4170 }
Willy Tarreauef934602016-12-22 23:12:01 +01004171 if (global_ssl.default_dh_param >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004172 if (local_dh_4096 == NULL) {
4173 local_dh_4096 = ssl_get_dh_4096();
4174 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004175 }
4176 }
4177 }
4178#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004179
Emeric Brunfc0421f2012-09-07 17:30:07 +02004180 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004181#if HA_OPENSSL_VERSION_NUMBER >= 0x00907000L
Emeric Brun29f037d2014-04-25 19:05:36 +02004182 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004183#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004184
Bernard Spil13c53f82018-02-15 13:34:58 +01004185#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004186 ssl_conf_cur = NULL;
4187 if (ssl_conf && ssl_conf->npn_str)
4188 ssl_conf_cur = ssl_conf;
4189 else if (bind_conf->ssl_conf.npn_str)
4190 ssl_conf_cur = &bind_conf->ssl_conf;
4191 if (ssl_conf_cur)
4192 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004193#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004194#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004195 ssl_conf_cur = NULL;
4196 if (ssl_conf && ssl_conf->alpn_str)
4197 ssl_conf_cur = ssl_conf;
4198 else if (bind_conf->ssl_conf.alpn_str)
4199 ssl_conf_cur = &bind_conf->ssl_conf;
4200 if (ssl_conf_cur)
4201 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004202#endif
Lukas Tribusd14b49c2019-11-24 18:20:40 +01004203#if ((HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL) || defined(LIBRESSL_VERSION_NUMBER))
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004204 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4205 if (conf_curves) {
4206 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004207 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4208 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004209 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004210 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004211 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004212 }
4213#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004214#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004215 if (!conf_curves) {
Emeric Brun2b58d042012-09-20 17:10:03 +02004216 int i;
4217 EC_KEY *ecdh;
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004218#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004219 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004220 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4221 NULL);
4222
4223 if (ecdhe == NULL) {
Eric Salama3c8bde82019-11-20 11:33:40 +01004224 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Olivier Houchardc2aae742017-09-22 18:26:28 +02004225 return cfgerr;
4226 }
4227#else
4228 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4229 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4230 ECDHE_DEFAULT_CURVE);
4231#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004232
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004233 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004234 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004235 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4236 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004237 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004238 }
4239 else {
4240 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4241 EC_KEY_free(ecdh);
4242 }
4243 }
4244#endif
4245
Emeric Brunfc0421f2012-09-07 17:30:07 +02004246 return cfgerr;
4247}
4248
Evan Broderbe554312013-06-27 00:05:25 -07004249static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4250{
4251 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4252 size_t prefixlen, suffixlen;
4253
4254 /* Trivial case */
4255 if (strcmp(pattern, hostname) == 0)
4256 return 1;
4257
Evan Broderbe554312013-06-27 00:05:25 -07004258 /* The rest of this logic is based on RFC 6125, section 6.4.3
4259 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4260
Emeric Bruna848dae2013-10-08 11:27:28 +02004261 pattern_wildcard = NULL;
4262 pattern_left_label_end = pattern;
4263 while (*pattern_left_label_end != '.') {
4264 switch (*pattern_left_label_end) {
4265 case 0:
4266 /* End of label not found */
4267 return 0;
4268 case '*':
4269 /* If there is more than one wildcards */
4270 if (pattern_wildcard)
4271 return 0;
4272 pattern_wildcard = pattern_left_label_end;
4273 break;
4274 }
4275 pattern_left_label_end++;
4276 }
4277
4278 /* If it's not trivial and there is no wildcard, it can't
4279 * match */
4280 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004281 return 0;
4282
4283 /* Make sure all labels match except the leftmost */
4284 hostname_left_label_end = strchr(hostname, '.');
4285 if (!hostname_left_label_end
4286 || strcmp(pattern_left_label_end, hostname_left_label_end) != 0)
4287 return 0;
4288
4289 /* Make sure the leftmost label of the hostname is long enough
4290 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004291 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004292 return 0;
4293
4294 /* Finally compare the string on either side of the
4295 * wildcard */
4296 prefixlen = pattern_wildcard - pattern;
4297 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
Emeric Bruna848dae2013-10-08 11:27:28 +02004298 if ((prefixlen && (memcmp(pattern, hostname, prefixlen) != 0))
4299 || (suffixlen && (memcmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004300 return 0;
4301
4302 return 1;
4303}
4304
4305static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4306{
4307 SSL *ssl;
4308 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004309 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004310 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004311 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004312
4313 int depth;
4314 X509 *cert;
4315 STACK_OF(GENERAL_NAME) *alt_names;
4316 int i;
4317 X509_NAME *cert_subject;
4318 char *str;
4319
4320 if (ok == 0)
4321 return ok;
4322
4323 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004324 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard66ab4982019-02-26 18:37:15 +01004325 ssl_ctx = conn->xprt_ctx;
Evan Broderbe554312013-06-27 00:05:25 -07004326
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004327 /* We're checking if the provided hostnames match the desired one. The
4328 * desired hostname comes from the SNI we presented if any, or if not
4329 * provided then it may have been explicitly stated using a "verifyhost"
4330 * directive. If neither is set, we don't care about the name so the
4331 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004332 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004333 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004334 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004335 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004336 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004337 if (!servername)
4338 return ok;
4339 }
Evan Broderbe554312013-06-27 00:05:25 -07004340
4341 /* We only need to verify the CN on the actual server cert,
4342 * not the indirect CAs */
4343 depth = X509_STORE_CTX_get_error_depth(ctx);
4344 if (depth != 0)
4345 return ok;
4346
4347 /* At this point, the cert is *not* OK unless we can find a
4348 * hostname match */
4349 ok = 0;
4350
4351 cert = X509_STORE_CTX_get_current_cert(ctx);
4352 /* It seems like this might happen if verify peer isn't set */
4353 if (!cert)
4354 return ok;
4355
4356 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4357 if (alt_names) {
4358 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4359 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4360 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004361#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004362 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4363#else
Evan Broderbe554312013-06-27 00:05:25 -07004364 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004365#endif
Evan Broderbe554312013-06-27 00:05:25 -07004366 ok = ssl_sock_srv_hostcheck(str, servername);
4367 OPENSSL_free(str);
4368 }
4369 }
4370 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004371 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004372 }
4373
4374 cert_subject = X509_get_subject_name(cert);
4375 i = -1;
4376 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4377 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004378 ASN1_STRING *value;
4379 value = X509_NAME_ENTRY_get_data(entry);
4380 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004381 ok = ssl_sock_srv_hostcheck(str, servername);
4382 OPENSSL_free(str);
4383 }
4384 }
4385
Willy Tarreau71d058c2017-07-26 20:09:56 +02004386 /* report the mismatch and indicate if SNI was used or not */
4387 if (!ok && !conn->err_code)
4388 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004389 return ok;
4390}
4391
Emeric Brun94324a42012-10-11 14:00:19 +02004392/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004393int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004394{
Willy Tarreau03209342016-12-22 17:08:28 +01004395 struct proxy *curproxy = srv->proxy;
Emeric Brun94324a42012-10-11 14:00:19 +02004396 int cfgerr = 0;
Remi Gacogneaf5c3da2014-05-19 10:29:58 +02004397 long options =
Emeric Brun94324a42012-10-11 14:00:19 +02004398 SSL_OP_ALL | /* all known workarounds for bugs */
4399 SSL_OP_NO_SSLv2 |
4400 SSL_OP_NO_COMPRESSION;
Remi Gacogneaf5c3da2014-05-19 10:29:58 +02004401 long mode =
Emeric Brun94324a42012-10-11 14:00:19 +02004402 SSL_MODE_ENABLE_PARTIAL_WRITE |
4403 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004404 SSL_MODE_RELEASE_BUFFERS |
4405 SSL_MODE_SMALL_BUFFERS;
Emeric Brun850efd52014-01-29 12:24:34 +01004406 int verify = SSL_VERIFY_NONE;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004407 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004408 struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004409 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004410 int flags = MC_SSL_O_ALL;
Emeric Brun94324a42012-10-11 14:00:19 +02004411
Thierry Fournier383085f2013-01-24 14:15:43 +01004412 /* Make sure openssl opens /dev/urandom before the chroot */
4413 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004414 ha_alert("OpenSSL random data generator initialization failed.\n");
Thierry Fournier383085f2013-01-24 14:15:43 +01004415 cfgerr++;
4416 }
4417
Willy Tarreaufce03112015-01-15 21:32:40 +01004418 /* Automatic memory computations need to know we use SSL there */
4419 global.ssl_used_backend = 1;
4420
4421 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004422 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004423 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004424 ha_alert("Proxy '%s', server '%s' [%s:%d] out of memory.\n",
4425 curproxy->id, srv->id,
4426 srv->conf.file, srv->conf.line);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004427 cfgerr++;
4428 return cfgerr;
4429 }
4430 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004431 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004432 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004433
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004434 ctx = SSL_CTX_new(SSLv23_client_method());
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004435 if (!ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004436 ha_alert("config : %s '%s', server '%s': unable to allocate ssl context.\n",
4437 proxy_type_str(curproxy), curproxy->id,
4438 srv->id);
Emeric Brun94324a42012-10-11 14:00:19 +02004439 cfgerr++;
4440 return cfgerr;
4441 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004442
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004443 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004444 ha_warning("config : %s '%s': no-sslv3/no-tlsv1x are ignored for server '%s'. "
4445 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4446 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004447 else
4448 flags = conf_ssl_methods->flags;
4449
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004450 /* Real min and max should be determinate with configuration and openssl's capabilities */
4451 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004452 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004453 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004454 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004455
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004456 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004457 min = max = CONF_TLSV_NONE;
4458 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004459 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004460 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004461 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004462 if (min) {
4463 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004464 ha_warning("config : %s '%s': SSL/TLS versions range not contiguous for server '%s'. "
4465 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4466 proxy_type_str(curproxy), curproxy->id, srv->id,
4467 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004468 hole = 0;
4469 }
4470 max = i;
4471 }
4472 else {
4473 min = max = i;
4474 }
4475 }
4476 else {
4477 if (min)
4478 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004479 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004480 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004481 ha_alert("config : %s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
4482 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004483 cfgerr += 1;
4484 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004485
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004486#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004487 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004488 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004489 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004490 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004491 else
4492 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4493 if (flags & methodVersions[i].flag)
4494 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004495#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004496 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004497 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4498 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004499#endif
4500
4501 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
4502 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004503 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004504
Willy Tarreau5db847a2019-05-09 14:13:35 +02004505#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004506 if (global_ssl.async)
4507 mode |= SSL_MODE_ASYNC;
4508#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004509 SSL_CTX_set_mode(ctx, mode);
4510 srv->ssl_ctx.ctx = ctx;
4511
Emeric Bruna7aa3092012-10-26 12:58:00 +02004512 if (srv->ssl_ctx.client_crt) {
4513 if (SSL_CTX_use_PrivateKey_file(srv->ssl_ctx.ctx, srv->ssl_ctx.client_crt, SSL_FILETYPE_PEM) <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004514 ha_alert("config : %s '%s', server '%s': unable to load SSL private key from PEM file '%s'.\n",
4515 proxy_type_str(curproxy), curproxy->id,
4516 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004517 cfgerr++;
4518 }
4519 else if (SSL_CTX_use_certificate_chain_file(srv->ssl_ctx.ctx, srv->ssl_ctx.client_crt) <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004520 ha_alert("config : %s '%s', server '%s': unable to load ssl certificate from PEM file '%s'.\n",
4521 proxy_type_str(curproxy), curproxy->id,
4522 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004523 cfgerr++;
4524 }
4525 else if (SSL_CTX_check_private_key(srv->ssl_ctx.ctx) <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004526 ha_alert("config : %s '%s', server '%s': inconsistencies between private key and certificate loaded from PEM file '%s'.\n",
4527 proxy_type_str(curproxy), curproxy->id,
4528 srv->id, srv->ssl_ctx.client_crt);
Emeric Bruna7aa3092012-10-26 12:58:00 +02004529 cfgerr++;
4530 }
4531 }
Emeric Brun94324a42012-10-11 14:00:19 +02004532
Emeric Brun850efd52014-01-29 12:24:34 +01004533 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
4534 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01004535 switch (srv->ssl_ctx.verify) {
4536 case SSL_SOCK_VERIFY_NONE:
4537 verify = SSL_VERIFY_NONE;
4538 break;
4539 case SSL_SOCK_VERIFY_REQUIRED:
4540 verify = SSL_VERIFY_PEER;
4541 break;
4542 }
Evan Broderbe554312013-06-27 00:05:25 -07004543 SSL_CTX_set_verify(srv->ssl_ctx.ctx,
Emeric Brun850efd52014-01-29 12:24:34 +01004544 verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02004545 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01004546 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02004547 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004548 /* set CAfile to verify */
4549 if (!ssl_set_verify_locations_file(srv->ssl_ctx.ctx, srv->ssl_ctx.ca_file)) {
4550 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to set CA file '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01004551 curproxy->id, srv->id,
4552 srv->conf.file, srv->conf.line, srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004553 cfgerr++;
4554 }
4555 }
Emeric Brun850efd52014-01-29 12:24:34 +01004556 else {
4557 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Christopher Faulet767a84b2017-11-24 16:50:31 +01004558 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",
4559 curproxy->id, srv->id,
4560 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004561 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01004562 ha_alert("Proxy '%s', server '%s' [%s:%d] verify is enabled but no CA file specified.\n",
4563 curproxy->id, srv->id,
4564 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004565 cfgerr++;
4566 }
Emeric Brunef42d922012-10-11 16:11:36 +02004567#ifdef X509_V_FLAG_CRL_CHECK
4568 if (srv->ssl_ctx.crl_file) {
4569 X509_STORE *store = SSL_CTX_get_cert_store(srv->ssl_ctx.ctx);
4570
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004571 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004572 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to configure CRL file '%s'.\n",
4573 curproxy->id, srv->id,
4574 srv->conf.file, srv->conf.line, srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004575 cfgerr++;
4576 }
4577 else {
4578 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4579 }
4580 }
4581#endif
4582 }
4583
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004584 SSL_CTX_set_session_cache_mode(srv->ssl_ctx.ctx, SSL_SESS_CACHE_CLIENT |
4585 SSL_SESS_CACHE_NO_INTERNAL_STORE);
4586 SSL_CTX_sess_set_new_cb(srv->ssl_ctx.ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02004587 if (srv->ssl_ctx.ciphers &&
4588 !SSL_CTX_set_cipher_list(srv->ssl_ctx.ctx, srv->ssl_ctx.ciphers)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004589 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set SSL cipher list to '%s'.\n",
4590 curproxy->id, srv->id,
4591 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02004592 cfgerr++;
4593 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004594
Emmanuel Hocdet839af572019-05-14 16:27:35 +02004595#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004596 if (srv->ssl_ctx.ciphersuites &&
Pierre Cheynierbc34cd12019-03-21 16:15:47 +00004597 !SSL_CTX_set_ciphersuites(srv->ssl_ctx.ctx, srv->ssl_ctx.ciphersuites)) {
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004598 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set TLS 1.3 cipher suites to '%s'.\n",
4599 curproxy->id, srv->id,
4600 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphersuites);
4601 cfgerr++;
4602 }
4603#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01004604#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
4605 if (srv->ssl_ctx.npn_str)
4606 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, srv);
4607#endif
4608#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4609 if (srv->ssl_ctx.alpn_str)
4610 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
4611#endif
4612
Emeric Brun94324a42012-10-11 14:00:19 +02004613
4614 return cfgerr;
4615}
4616
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004617/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004618 * be NULL, in which case nothing is done. Returns the number of errors
4619 * encountered.
4620 */
Willy Tarreau03209342016-12-22 17:08:28 +01004621int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004622{
4623 struct ebmb_node *node;
4624 struct sni_ctx *sni;
4625 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01004626 int errcode = 0;
4627 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004628
Willy Tarreaufce03112015-01-15 21:32:40 +01004629 /* Automatic memory computations need to know we use SSL there */
4630 global.ssl_used_frontend = 1;
4631
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004632 /* Make sure openssl opens /dev/urandom before the chroot */
4633 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004634 ha_alert("OpenSSL random data generator initialization failed.\n");
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004635 err++;
4636 }
4637 /* Create initial_ctx used to start the ssl connection before do switchctx */
4638 if (!bind_conf->initial_ctx) {
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004639 err += ssl_sock_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004640 /* It should not be necessary to call this function, but it's
4641 necessary first to check and move all initialisation related
4642 to initial_ctx in ssl_sock_initial_ctx. */
William Lallemand8b453912019-11-21 15:48:10 +01004643 errcode |= ssl_sock_prepare_ctx(bind_conf, NULL, bind_conf->initial_ctx, &errmsg);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004644 }
Emeric Brun0bed9942014-10-30 19:25:24 +01004645 if (bind_conf->default_ctx)
William Lallemand8b453912019-11-21 15:48:10 +01004646 errcode |= ssl_sock_prepare_ctx(bind_conf, bind_conf->default_ssl_conf, bind_conf->default_ctx, &errmsg);
Emeric Brun0bed9942014-10-30 19:25:24 +01004647
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004648 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004649 while (node) {
4650 sni = ebmb_entry(node, struct sni_ctx, name);
Emeric Brun0bed9942014-10-30 19:25:24 +01004651 if (!sni->order && sni->ctx != bind_conf->default_ctx)
4652 /* only initialize the CTX on its first occurrence and
4653 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004654 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004655 node = ebmb_next(node);
4656 }
4657
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004658 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004659 while (node) {
4660 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01004661 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01004662 /* only initialize the CTX on its first occurrence and
4663 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004664 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
4665 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004666 node = ebmb_next(node);
4667 }
William Lallemand8b453912019-11-21 15:48:10 +01004668
4669 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004670 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004671 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01004672 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01004673 err++;
4674 }
4675
4676 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004677 return err;
4678}
4679
Willy Tarreau55d37912016-12-21 23:38:39 +01004680/* Prepares all the contexts for a bind_conf and allocates the shared SSL
4681 * context if needed. Returns < 0 on error, 0 on success. The warnings and
4682 * alerts are directly emitted since the rest of the stack does it below.
4683 */
4684int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
4685{
4686 struct proxy *px = bind_conf->frontend;
4687 int alloc_ctx;
4688 int err;
4689
4690 if (!bind_conf->is_ssl) {
4691 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004692 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
4693 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01004694 }
4695 return 0;
4696 }
4697 if (!bind_conf->default_ctx) {
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004698 if (bind_conf->strict_sni && !bind_conf->generate_certs) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004699 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
4700 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004701 }
4702 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004703 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
4704 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02004705 return -1;
4706 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004707 }
William Lallemandc61c0b32017-12-04 18:46:39 +01004708 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004709 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02004710 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
William Lallemandc3cd35f2017-11-28 11:04:43 +01004711 sizeof(*sh_ssl_sess_tree),
4712 ((global.nbthread > 1) || (!global_ssl.private_cache && (global.nbproc > 1))) ? 1 : 0);
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02004713 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01004714 if (alloc_ctx == SHCTX_E_INIT_LOCK)
4715 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");
4716 else
4717 ha_alert("Unable to allocate SSL session cache.\n");
4718 return -1;
4719 }
4720 /* free block callback */
4721 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
4722 /* init the root tree within the extra space */
4723 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
4724 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01004725 }
Willy Tarreau55d37912016-12-21 23:38:39 +01004726 err = 0;
4727 /* initialize all certificate contexts */
4728 err += ssl_sock_prepare_all_ctx(bind_conf);
4729
4730 /* initialize CA variables if the certificates generation is enabled */
4731 err += ssl_sock_load_ca(bind_conf);
4732
4733 return -err;
4734}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004735
4736/* release ssl context allocated for servers. */
4737void ssl_sock_free_srv_ctx(struct server *srv)
4738{
Olivier Houchardc7566002018-11-20 23:33:50 +01004739#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4740 if (srv->ssl_ctx.alpn_str)
4741 free(srv->ssl_ctx.alpn_str);
4742#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01004743#ifdef OPENSSL_NPN_NEGOTIATED
Olivier Houchardc7566002018-11-20 23:33:50 +01004744 if (srv->ssl_ctx.npn_str)
4745 free(srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01004746#endif
Christopher Faulet77fe80c2015-07-29 13:02:40 +02004747 if (srv->ssl_ctx.ctx)
4748 SSL_CTX_free(srv->ssl_ctx.ctx);
4749}
4750
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004751/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004752 * be NULL, in which case nothing is done. The default_ctx is nullified too.
4753 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004754void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004755{
4756 struct ebmb_node *node, *back;
4757 struct sni_ctx *sni;
4758
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004759 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004760 while (node) {
4761 sni = ebmb_entry(node, struct sni_ctx, name);
4762 back = ebmb_next(node);
4763 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02004764 SSL_CTX_free(sni->ctx);
4765 if (!sni->order) { /* only free the CTX conf on its first occurrence */
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004766 ssl_sock_free_ssl_conf(sni->conf);
4767 free(sni->conf);
4768 sni->conf = NULL;
4769 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004770 free(sni);
4771 node = back;
4772 }
4773
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004774 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004775 while (node) {
4776 sni = ebmb_entry(node, struct sni_ctx, name);
4777 back = ebmb_next(node);
4778 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02004779 SSL_CTX_free(sni->ctx);
4780 if (!sni->order) { /* only free the SSL conf its first occurrence */
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004781 ssl_sock_free_ssl_conf(sni->conf);
4782 free(sni->conf);
4783 sni->conf = NULL;
4784 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004785 free(sni);
4786 node = back;
4787 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004788 SSL_CTX_free(bind_conf->initial_ctx);
4789 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02004790 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004791 bind_conf->default_ctx = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004792 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02004793}
4794
Willy Tarreau795cdab2016-12-22 17:30:54 +01004795/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
4796void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
4797{
4798 ssl_sock_free_ca(bind_conf);
4799 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004800 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01004801 free(bind_conf->ca_sign_file);
4802 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02004803 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01004804 free(bind_conf->keys_ref->filename);
4805 free(bind_conf->keys_ref->tlskeys);
4806 LIST_DEL(&bind_conf->keys_ref->list);
4807 free(bind_conf->keys_ref);
4808 }
4809 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01004810 bind_conf->ca_sign_pass = NULL;
4811 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01004812}
4813
Christopher Faulet31af49d2015-06-09 17:29:50 +02004814/* Load CA cert file and private key used to generate certificates */
4815int
Willy Tarreau03209342016-12-22 17:08:28 +01004816ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02004817{
Willy Tarreau03209342016-12-22 17:08:28 +01004818 struct proxy *px = bind_conf->frontend;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004819 FILE *fp;
4820 X509 *cacert = NULL;
4821 EVP_PKEY *capkey = NULL;
4822 int err = 0;
4823
Christopher Fauletf8bb0ce2017-09-15 09:52:49 +02004824 if (!bind_conf->generate_certs)
Christopher Faulet31af49d2015-06-09 17:29:50 +02004825 return err;
4826
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01004827#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02004828 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01004829 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004830 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02004831 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004832 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02004833#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02004834
Christopher Faulet31af49d2015-06-09 17:29:50 +02004835 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004836 ha_alert("Proxy '%s': cannot enable certificate generation, "
4837 "no CA certificate File configured at [%s:%d].\n",
4838 px->id, bind_conf->file, bind_conf->line);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004839 goto load_error;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004840 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02004841
4842 /* read in the CA certificate */
4843 if (!(fp = fopen(bind_conf->ca_sign_file, "r"))) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004844 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d].\n",
4845 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004846 goto load_error;
4847 }
4848 if (!(cacert = PEM_read_X509(fp, NULL, NULL, NULL))) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004849 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d].\n",
4850 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004851 goto read_error;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004852 }
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004853 rewind(fp);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004854 if (!(capkey = PEM_read_PrivateKey(fp, NULL, NULL, bind_conf->ca_sign_pass))) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004855 ha_alert("Proxy '%s': Failed to read CA private key file '%s' at [%s:%d].\n",
4856 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004857 goto read_error;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004858 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02004859
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004860 fclose (fp);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004861 bind_conf->ca_sign_cert = cacert;
4862 bind_conf->ca_sign_pkey = capkey;
4863 return err;
4864
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004865 read_error:
4866 fclose (fp);
Christopher Faulet31af49d2015-06-09 17:29:50 +02004867 if (capkey) EVP_PKEY_free(capkey);
4868 if (cacert) X509_free(cacert);
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02004869 load_error:
4870 bind_conf->generate_certs = 0;
4871 err++;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004872 return err;
4873}
4874
4875/* Release CA cert and private key used to generate certificated */
4876void
4877ssl_sock_free_ca(struct bind_conf *bind_conf)
4878{
Christopher Faulet31af49d2015-06-09 17:29:50 +02004879 if (bind_conf->ca_sign_pkey)
4880 EVP_PKEY_free(bind_conf->ca_sign_pkey);
4881 if (bind_conf->ca_sign_cert)
4882 X509_free(bind_conf->ca_sign_cert);
Willy Tarreau94ff03a2016-12-22 17:57:46 +01004883 bind_conf->ca_sign_pkey = NULL;
4884 bind_conf->ca_sign_cert = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02004885}
4886
Emeric Brun46591952012-05-18 15:47:34 +02004887/*
4888 * This function is called if SSL * context is not yet allocated. The function
4889 * is designed to be called before any other data-layer operation and sets the
4890 * handshake flag on the connection. It is safe to call it multiple times.
4891 * It returns 0 on success and -1 in error case.
4892 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01004893static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02004894{
Olivier Houchard66ab4982019-02-26 18:37:15 +01004895 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02004896 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01004897 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02004898 return 0;
4899
Willy Tarreau3c728722014-01-23 13:50:42 +01004900 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02004901 return 0;
4902
Olivier Houchard66ab4982019-02-26 18:37:15 +01004903 ctx = pool_alloc(ssl_sock_ctx_pool);
4904 if (!ctx) {
4905 conn->err_code = CO_ER_SSL_NO_MEM;
4906 return -1;
4907 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02004908 ctx->wait_event.tasklet = tasklet_new();
4909 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02004910 conn->err_code = CO_ER_SSL_NO_MEM;
4911 pool_free(ssl_sock_ctx_pool, ctx);
4912 return -1;
4913 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02004914 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
4915 ctx->wait_event.tasklet->context = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02004916 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01004917 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01004918 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02004919 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01004920 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02004921 ctx->xprt_st = 0;
4922 ctx->xprt_ctx = NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02004923
4924 /* Only work with sockets for now, this should be adapted when we'll
4925 * add QUIC support.
4926 */
4927 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02004928 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02004929 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
4930 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02004931 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01004932
Willy Tarreau20879a02012-12-03 16:32:10 +01004933 if (global.maxsslconn && sslconns >= global.maxsslconn) {
4934 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02004935 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01004936 }
Willy Tarreau403edff2012-09-06 11:58:37 +02004937
Emeric Brun46591952012-05-18 15:47:34 +02004938 /* If it is in client mode initiate SSL session
4939 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01004940 if (objt_server(conn->target)) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004941 int may_retry = 1;
4942
4943 retry_connect:
Emeric Brun46591952012-05-18 15:47:34 +02004944 /* Alloc a new SSL session ctx */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004945 ctx->ssl = SSL_new(__objt_server(conn->target)->ssl_ctx.ctx);
4946 if (!ctx->ssl) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004947 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004948 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004949 goto retry_connect;
4950 }
Willy Tarreau20879a02012-12-03 16:32:10 +01004951 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004952 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01004953 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02004954 ctx->bio = BIO_new(ha_meth);
4955 if (!ctx->bio) {
Olivier Houchardefe5e8e2020-01-24 15:17:38 +01004956 SSL_free(ctx->ssl);
4957 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004958 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004959 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004960 goto retry_connect;
4961 }
Emeric Brun55476152014-11-12 17:35:37 +01004962 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004963 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01004964 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02004965 BIO_set_data(ctx->bio, ctx);
Olivier Houcharda8955d52019-04-07 22:00:38 +02004966 SSL_set_bio(ctx->ssl, ctx->bio, ctx->bio);
Emeric Brun46591952012-05-18 15:47:34 +02004967
Evan Broderbe554312013-06-27 00:05:25 -07004968 /* set connection pointer */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004969 if (!SSL_set_ex_data(ctx->ssl, ssl_app_data_index, conn)) {
4970 SSL_free(ctx->ssl);
4971 ctx->ssl = NULL;
Emeric Brun55476152014-11-12 17:35:37 +01004972 conn->xprt_ctx = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004973 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01004974 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01004975 goto retry_connect;
4976 }
Emeric Brun55476152014-11-12 17:35:37 +01004977 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004978 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01004979 }
4980
Olivier Houchard66ab4982019-02-26 18:37:15 +01004981 SSL_set_connect_state(ctx->ssl);
Willy Tarreau07d94e42018-09-20 10:57:52 +02004982 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
4983 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
4984 SSL_SESSION *sess = d2i_SSL_SESSION(NULL, &ptr, __objt_server(conn->target)->ssl_ctx.reused_sess[tid].size);
Olivier Houchard66ab4982019-02-26 18:37:15 +01004985 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004986 SSL_SESSION_free(sess);
Willy Tarreau07d94e42018-09-20 10:57:52 +02004987 free(__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
4988 __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr = NULL;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004989 } else if (sess) {
4990 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01004991 }
4992 }
Evan Broderbe554312013-06-27 00:05:25 -07004993
Emeric Brun46591952012-05-18 15:47:34 +02004994 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02004995 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02004996
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01004997 _HA_ATOMIC_ADD(&sslconns, 1);
4998 _HA_ATOMIC_ADD(&totalsslconns, 1);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01004999 *xprt_ctx = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005000 /* Start the handshake */
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005001 tasklet_wakeup(ctx->wait_event.tasklet);
Emeric Brun46591952012-05-18 15:47:34 +02005002 return 0;
5003 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005004 else if (objt_listener(conn->target)) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005005 int may_retry = 1;
5006
5007 retry_accept:
Emeric Brun46591952012-05-18 15:47:34 +02005008 /* Alloc a new SSL session ctx */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005009 ctx->ssl = SSL_new(__objt_listener(conn->target)->bind_conf->initial_ctx);
5010 if (!ctx->ssl) {
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005011 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005012 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005013 goto retry_accept;
5014 }
Willy Tarreau20879a02012-12-03 16:32:10 +01005015 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005016 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005017 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02005018 ctx->bio = BIO_new(ha_meth);
5019 if (!ctx->bio) {
Olivier Houchardefe5e8e2020-01-24 15:17:38 +01005020 SSL_free(ctx->ssl);
5021 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005022 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005023 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005024 goto retry_accept;
5025 }
Emeric Brun55476152014-11-12 17:35:37 +01005026 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005027 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005028 }
Olivier Houcharda8955d52019-04-07 22:00:38 +02005029 BIO_set_data(ctx->bio, ctx);
Olivier Houcharda8955d52019-04-07 22:00:38 +02005030 SSL_set_bio(ctx->ssl, ctx->bio, ctx->bio);
Emeric Brun46591952012-05-18 15:47:34 +02005031
Emeric Brune1f38db2012-09-03 20:36:47 +02005032 /* set connection pointer */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005033 if (!SSL_set_ex_data(ctx->ssl, ssl_app_data_index, conn)) {
5034 SSL_free(ctx->ssl);
5035 ctx->ssl = NULL;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005036 if (may_retry--) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005037 pool_gc(NULL);
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005038 goto retry_accept;
5039 }
Emeric Brun55476152014-11-12 17:35:37 +01005040 conn->err_code = CO_ER_SSL_NO_MEM;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005041 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005042 }
5043
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005044#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5045 if (__objt_listener(conn->target)->bind_conf->ssl_conf.early_data) {
5046 b_alloc(&ctx->early_buf);
5047 SSL_set_max_early_data(ctx->ssl,
5048 /* Only allow early data if we managed to allocate
5049 * a buffer.
5050 */
5051 (!b_is_null(&ctx->early_buf)) ?
5052 global.tune.bufsize - global.tune.maxrewrite : 0);
5053 }
5054#endif
5055
Olivier Houchard66ab4982019-02-26 18:37:15 +01005056 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005057
Emeric Brun46591952012-05-18 15:47:34 +02005058 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005059 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02005060#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Olivier Houchardc2aae742017-09-22 18:26:28 +02005061 conn->flags |= CO_FL_EARLY_SSL_HS;
5062#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005063
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005064 _HA_ATOMIC_ADD(&sslconns, 1);
5065 _HA_ATOMIC_ADD(&totalsslconns, 1);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005066 *xprt_ctx = ctx;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005067 /* Start the handshake */
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005068 tasklet_wakeup(ctx->wait_event.tasklet);
Emeric Brun46591952012-05-18 15:47:34 +02005069 return 0;
5070 }
5071 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005072 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005073err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005074 if (ctx && ctx->wait_event.tasklet)
5075 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005076 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005077 return -1;
5078}
5079
5080
5081/* This is the callback which is used when an SSL handshake is pending. It
5082 * updates the FD status if it wants some polling before being called again.
5083 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5084 * otherwise it returns non-zero and removes itself from the connection's
5085 * flags (the bit is provided in <flag> by the caller).
5086 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005087static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005088{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005089 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005090 int ret;
5091
Willy Tarreau3c728722014-01-23 13:50:42 +01005092 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005093 return 0;
5094
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02005095 if (!conn->xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005096 goto out_error;
5097
Willy Tarreau5db847a2019-05-09 14:13:35 +02005098#if HA_OPENSSL_VERSION_NUMBER >= 0x10101000L
Olivier Houchardc2aae742017-09-22 18:26:28 +02005099 /*
5100 * Check if we have early data. If we do, we have to read them
5101 * before SSL_do_handshake() is called, And there's no way to
5102 * detect early data, except to try to read them
5103 */
5104 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005105 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005106
Olivier Houchard54907bb2019-12-19 15:02:39 +01005107 while (1) {
5108 ret = SSL_read_early_data(ctx->ssl,
5109 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5110 &read_data);
5111 if (ret == SSL_READ_EARLY_DATA_ERROR)
5112 goto check_error;
5113 if (read_data > 0) {
5114 conn->flags |= CO_FL_EARLY_DATA;
5115 b_add(&ctx->early_buf, read_data);
5116 }
5117 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5118 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5119 if (!b_data(&ctx->early_buf))
5120 b_free(&ctx->early_buf);
5121 break;
5122 }
5123 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005124 }
5125#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005126 /* If we use SSL_do_handshake to process a reneg initiated by
5127 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5128 * Usually SSL_write and SSL_read are used and process implicitly
5129 * the reneg handshake.
5130 * Here we use SSL_peek as a workaround for reneg.
5131 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005132 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005133 char c;
5134
Olivier Houchard66ab4982019-02-26 18:37:15 +01005135 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005136 if (ret <= 0) {
5137 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005138 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005139
Emeric Brun674b7432012-11-08 19:21:55 +01005140 if (ret == SSL_ERROR_WANT_WRITE) {
5141 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005142 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005143 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005144 return 0;
5145 }
5146 else if (ret == SSL_ERROR_WANT_READ) {
5147 /* handshake may have been completed but we have
5148 * no more data to read.
5149 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005150 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005151 ret = 1;
5152 goto reneg_ok;
5153 }
5154 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005155 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005156 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005157 return 0;
5158 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005159#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005160 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005161 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005162 return 0;
5163 }
5164#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005165 else if (ret == SSL_ERROR_SYSCALL) {
5166 /* if errno is null, then connection was successfully established */
5167 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5168 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005169 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005170#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5171 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005172 conn->err_code = CO_ER_SSL_HANDSHAKE;
5173#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005174 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005175#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005176 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005177 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005178 empty_handshake = state == TLS_ST_BEFORE;
5179#else
Lukas Tribus49799162019-07-08 14:29:15 +02005180 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5181 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005182#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005183 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005184 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005185 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005186 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5187 else
5188 conn->err_code = CO_ER_SSL_EMPTY;
5189 }
5190 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005191 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005192 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5193 else
5194 conn->err_code = CO_ER_SSL_ABORT;
5195 }
5196 }
5197 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005198 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005199 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005200 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005201 conn->err_code = CO_ER_SSL_HANDSHAKE;
5202 }
Lukas Tribus49799162019-07-08 14:29:15 +02005203#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005204 }
Emeric Brun674b7432012-11-08 19:21:55 +01005205 goto out_error;
5206 }
5207 else {
5208 /* Fail on all other handshake errors */
5209 /* Note: OpenSSL may leave unread bytes in the socket's
5210 * buffer, causing an RST to be emitted upon close() on
5211 * TCP sockets. We first try to drain possibly pending
5212 * data to avoid this as much as possible.
5213 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01005214 conn_sock_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005215 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005216 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005217 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005218 goto out_error;
5219 }
5220 }
5221 /* read some data: consider handshake completed */
5222 goto reneg_ok;
5223 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005224 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005225check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005226 if (ret != 1) {
5227 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005228 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005229
5230 if (ret == SSL_ERROR_WANT_WRITE) {
5231 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005232 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005233 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005234 return 0;
5235 }
5236 else if (ret == SSL_ERROR_WANT_READ) {
5237 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005238 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005239 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5240 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005241 return 0;
5242 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005243#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005244 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005245 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005246 return 0;
5247 }
5248#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005249 else if (ret == SSL_ERROR_SYSCALL) {
5250 /* if errno is null, then connection was successfully established */
5251 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5252 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005253 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005254#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5255 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005256 conn->err_code = CO_ER_SSL_HANDSHAKE;
5257#else
5258 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005259#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005260 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005261 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005262 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005263#else
Lukas Tribus49799162019-07-08 14:29:15 +02005264 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5265 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005266#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005267 if (empty_handshake) {
5268 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005269 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005270 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5271 else
5272 conn->err_code = CO_ER_SSL_EMPTY;
5273 }
5274 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005275 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005276 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5277 else
5278 conn->err_code = CO_ER_SSL_ABORT;
5279 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005280 }
5281 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005282 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005283 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5284 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005285 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005286 }
Lukas Tribus49799162019-07-08 14:29:15 +02005287#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005288 }
Willy Tarreau89230192012-09-28 20:22:13 +02005289 goto out_error;
5290 }
Emeric Brun46591952012-05-18 15:47:34 +02005291 else {
5292 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005293 /* Note: OpenSSL may leave unread bytes in the socket's
5294 * buffer, causing an RST to be emitted upon close() on
5295 * TCP sockets. We first try to drain possibly pending
5296 * data to avoid this as much as possible.
5297 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01005298 conn_sock_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005299 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005300 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005301 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005302 goto out_error;
5303 }
5304 }
Willy Tarreau5db847a2019-05-09 14:13:35 +02005305#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Olivier Houchard522eea72017-11-03 16:27:47 +01005306 else {
5307 /*
5308 * If the server refused the early data, we have to send a
5309 * 425 to the client, as we no longer have the data to sent
5310 * them again.
5311 */
5312 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005313 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005314 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5315 goto out_error;
5316 }
5317 }
5318 }
5319#endif
5320
Emeric Brun46591952012-05-18 15:47:34 +02005321
Emeric Brun674b7432012-11-08 19:21:55 +01005322reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005323
Willy Tarreau5db847a2019-05-09 14:13:35 +02005324#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005325 /* ASYNC engine API doesn't support moving read/write
5326 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005327 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005328 */
5329 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005330 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005331#endif
Emeric Brun46591952012-05-18 15:47:34 +02005332 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005333 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005334 if (objt_server(conn->target)) {
5335 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5336 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5337 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005338 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005339 else {
5340 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5341 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5342 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5343 }
Emeric Brun46591952012-05-18 15:47:34 +02005344 }
5345
5346 /* The connection is now established at both layers, it's time to leave */
5347 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5348 return 1;
5349
5350 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005351 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005352 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005353 ERR_clear_error();
5354
Emeric Brun9fa89732012-10-04 17:09:56 +02005355 /* free resumed session if exists */
Willy Tarreau07d94e42018-09-20 10:57:52 +02005356 if (objt_server(conn->target) && __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5357 free(__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
5358 __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr = NULL;
Emeric Brun9fa89732012-10-04 17:09:56 +02005359 }
5360
Emeric Brun46591952012-05-18 15:47:34 +02005361 /* Fail on all other handshake errors */
5362 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01005363 if (!conn->err_code)
5364 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005365 return 0;
5366}
5367
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005368/* Called from the upper layer, to subscribe <es> to events <event_type>. The
5369 * event subscriber <es> is not allowed to change from a previous call as long
5370 * as at least one event is still subscribed. The <event_type> must only be a
5371 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
5372 * unless the transport layer was already released.
5373 */
5374static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005375{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005376 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005377
Olivier Houchard0ff28652019-06-24 18:57:39 +02005378 if (!ctx)
5379 return -1;
5380
Willy Tarreau113d52b2020-01-10 09:20:26 +01005381 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005382 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005383
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005384 ctx->subs = es;
5385 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005386
5387 /* we may have to subscribe to lower layers for new events */
5388 event_type &= ~ctx->wait_event.events;
5389 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
5390 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005391 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005392}
5393
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005394/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
5395 * The <es> pointer is not allowed to differ from the one passed to the
5396 * subscribe() call. It always returns zero.
5397 */
5398static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005399{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005400 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005401
Willy Tarreau113d52b2020-01-10 09:20:26 +01005402 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005403 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005404
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005405 es->events &= ~event_type;
5406 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01005407 ctx->subs = NULL;
5408
5409 /* If we subscribed, and we're not doing the handshake,
5410 * then we subscribed because the upper layer asked for it,
5411 * as the upper layer is no longer interested, we can
5412 * unsubscribe too.
5413 */
5414 event_type &= ctx->wait_event.events;
5415 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
5416 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005417
5418 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005419}
5420
Olivier Houchard2e055482019-05-27 19:50:12 +02005421/* Use the provided XPRT as an underlying XPRT, and provide the old one.
5422 * Returns 0 on success, and non-zero on failure.
5423 */
5424static int ssl_add_xprt(struct connection *conn, void *xprt_ctx, void *toadd_ctx, const struct xprt_ops *toadd_ops, void **oldxprt_ctx, const struct xprt_ops **oldxprt_ops)
5425{
5426 struct ssl_sock_ctx *ctx = xprt_ctx;
5427
5428 if (oldxprt_ops != NULL)
5429 *oldxprt_ops = ctx->xprt;
5430 if (oldxprt_ctx != NULL)
5431 *oldxprt_ctx = ctx->xprt_ctx;
5432 ctx->xprt = toadd_ops;
5433 ctx->xprt_ctx = toadd_ctx;
5434 return 0;
5435}
5436
Olivier Houchard5149b592019-05-23 17:47:36 +02005437/* Remove the specified xprt. If if it our underlying XPRT, remove it and
5438 * return 0, otherwise just call the remove_xprt method from the underlying
5439 * XPRT.
5440 */
5441static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
5442{
5443 struct ssl_sock_ctx *ctx = xprt_ctx;
5444
5445 if (ctx->xprt_ctx == toremove_ctx) {
5446 ctx->xprt_ctx = newctx;
5447 ctx->xprt = newops;
5448 return 0;
5449 }
5450 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
5451}
5452
Olivier Houchardea8dd942019-05-20 14:02:16 +02005453static struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned short state)
5454{
5455 struct ssl_sock_ctx *ctx = context;
5456
5457 /* First if we're doing an handshake, try that */
5458 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS)
5459 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
5460 /* If we had an error, or the handshake is done and I/O is available,
5461 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01005462 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02005463 * we can't be sure conn_fd_handler() will be called again.
5464 */
5465 if ((ctx->conn->flags & CO_FL_ERROR) ||
5466 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
5467 int ret = 0;
5468 int woke = 0;
5469
5470 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005471 if (ctx->subs) {
5472 tasklet_wakeup(ctx->subs->tasklet);
5473 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005474 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005475 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005476 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005477
Olivier Houchardea8dd942019-05-20 14:02:16 +02005478 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01005479 * upper layers know. If we have no mux, create it,
5480 * and once we have a mux, call its wake method if we didn't
5481 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02005482 */
5483 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01005484 if (!ctx->conn->mux)
5485 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005486 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
5487 ctx->conn->mux->wake(ctx->conn);
5488 return NULL;
5489 }
5490 }
Olivier Houchard54907bb2019-12-19 15:02:39 +01005491#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5492 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005493 else if (b_data(&ctx->early_buf) && ctx->subs &&
5494 ctx->subs->events & SUB_RETRY_RECV) {
5495 tasklet_wakeup(ctx->subs->tasklet);
5496 ctx->subs->events &= ~SUB_RETRY_RECV;
5497 if (!ctx->subs->events)
5498 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005499 }
5500#endif
Olivier Houchardea8dd942019-05-20 14:02:16 +02005501 return NULL;
5502}
5503
Emeric Brun46591952012-05-18 15:47:34 +02005504/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01005505 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02005506 * buffer wraps, in which case a second call may be performed. The connection's
5507 * flags are updated with whatever special event is detected (error, read0,
5508 * empty). The caller is responsible for taking care of those events and
5509 * avoiding the call if inappropriate. The function does not call the
5510 * connection's polling update function, so the caller is responsible for this.
5511 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005512static size_t ssl_sock_to_buf(struct connection *conn, void *xprt_ctx, struct buffer *buf, size_t count, int flags)
Emeric Brun46591952012-05-18 15:47:34 +02005513{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005514 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02005515 ssize_t ret;
5516 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02005517
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005518 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005519 goto out_error;
5520
Olivier Houchard54907bb2019-12-19 15:02:39 +01005521#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5522 if (b_data(&ctx->early_buf)) {
5523 try = b_contig_space(buf);
5524 if (try > b_data(&ctx->early_buf))
5525 try = b_data(&ctx->early_buf);
5526 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
5527 b_add(buf, try);
5528 b_del(&ctx->early_buf, try);
5529 if (b_data(&ctx->early_buf) == 0)
5530 b_free(&ctx->early_buf);
5531 return try;
5532 }
5533#endif
5534
Willy Tarreau911db9b2020-01-23 16:27:54 +01005535 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005536 /* a handshake was requested */
5537 return 0;
5538
Emeric Brun46591952012-05-18 15:47:34 +02005539 /* read the largest possible block. For this, we perform only one call
5540 * to recv() unless the buffer wraps and we exactly fill the first hunk,
5541 * in which case we accept to do it once again. A new attempt is made on
5542 * EINTR too.
5543 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01005544 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02005545
Willy Tarreau591d4452018-06-15 17:21:00 +02005546 try = b_contig_space(buf);
5547 if (!try)
5548 break;
5549
Willy Tarreauabf08d92014-01-14 11:31:27 +01005550 if (try > count)
5551 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02005552
Olivier Houchard66ab4982019-02-26 18:37:15 +01005553 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02005554
Emeric Brune1f38db2012-09-03 20:36:47 +02005555 if (conn->flags & CO_FL_ERROR) {
5556 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01005557 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02005558 }
Emeric Brun46591952012-05-18 15:47:34 +02005559 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02005560 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005561 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02005562 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02005563 }
Emeric Brun46591952012-05-18 15:47:34 +02005564 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005565 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005566 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01005567 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02005568 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005569 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005570#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005571 /* Async mode can be re-enabled, because we're leaving data state.*/
5572 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005573 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005574#endif
Emeric Brun46591952012-05-18 15:47:34 +02005575 break;
5576 }
5577 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005578 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005579 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5580 SUB_RETRY_RECV,
5581 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01005582 /* handshake is running, and it may need to re-enable read */
5583 conn->flags |= CO_FL_SSL_WAIT_HS;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005584#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005585 /* Async mode can be re-enabled, because we're leaving data state.*/
5586 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005587 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005588#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01005589 break;
5590 }
Emeric Brun46591952012-05-18 15:47:34 +02005591 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005592 } else if (ret == SSL_ERROR_ZERO_RETURN)
5593 goto read0;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005594 /* For SSL_ERROR_SYSCALL, make sure to clear the error
5595 * stack before shutting down the connection for
5596 * reading. */
Olivier Houchard7e2e5052018-02-13 15:17:23 +01005597 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN))
5598 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02005599 /* otherwise it's a real error */
5600 goto out_error;
5601 }
5602 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005603 leave:
Emeric Brun46591952012-05-18 15:47:34 +02005604 return done;
5605
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005606 clear_ssl_error:
5607 /* Clear openssl global errors stack */
5608 ssl_sock_dump_errors(conn);
5609 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02005610 read0:
5611 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005612 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01005613
Emeric Brun46591952012-05-18 15:47:34 +02005614 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01005615 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01005616 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005617 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005618 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005619 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02005620}
5621
5622
Willy Tarreau787db9a2018-06-14 18:31:46 +02005623/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
5624 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
5625 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02005626 * Only one call to send() is performed, unless the buffer wraps, in which case
5627 * a second call may be performed. The connection's flags are updated with
5628 * whatever special event is detected (error, empty). The caller is responsible
5629 * for taking care of those events and avoiding the call if inappropriate. The
5630 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02005631 * is responsible for this. The buffer's output is not adjusted, it's up to the
5632 * caller to take care of this. It's up to the caller to update the buffer's
5633 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02005634 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005635static size_t ssl_sock_from_buf(struct connection *conn, void *xprt_ctx, const struct buffer *buf, size_t count, int flags)
Emeric Brun46591952012-05-18 15:47:34 +02005636{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005637 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02005638 ssize_t ret;
5639 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02005640
5641 done = 0;
5642
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005643 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005644 goto out_error;
5645
Willy Tarreau911db9b2020-01-23 16:27:54 +01005646 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005647 /* a handshake was requested */
5648 return 0;
5649
5650 /* send the largest possible block. For this we perform only one call
5651 * to send() unless the buffer wraps and we exactly fill the first hunk,
5652 * in which case we accept to do it once again.
5653 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02005654 while (count) {
Willy Tarreau5db847a2019-05-09 14:13:35 +02005655#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Olivier Houchardc2aae742017-09-22 18:26:28 +02005656 size_t written_data;
5657#endif
5658
Willy Tarreau787db9a2018-06-14 18:31:46 +02005659 try = b_contig_data(buf, done);
5660 if (try > count)
5661 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01005662
Willy Tarreau7bed9452014-02-02 02:00:24 +01005663 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005664 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01005665 global_ssl.max_record && try > global_ssl.max_record) {
5666 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01005667 }
5668 else {
5669 /* we need to keep the information about the fact that
5670 * we're not limiting the upcoming send(), because if it
5671 * fails, we'll have to retry with at least as many data.
5672 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005673 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01005674 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01005675
Willy Tarreau5db847a2019-05-09 14:13:35 +02005676#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Olivier Houchard010941f2019-05-03 20:56:19 +02005677 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02005678 unsigned int max_early;
5679
Olivier Houchard522eea72017-11-03 16:27:47 +01005680 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01005681 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01005682 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005683 if (SSL_get0_session(ctx->ssl))
5684 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01005685 else
5686 max_early = 0;
5687 }
5688
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005689 if (try + ctx->sent_early_data > max_early) {
5690 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01005691 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02005692 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005693 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005694 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01005695 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005696 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005697 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005698 if (ret == 1) {
5699 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005700 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005701 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005702 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02005703 /* Initiate the handshake, now */
5704 tasklet_wakeup(ctx->wait_event.tasklet);
5705 }
Olivier Houchard522eea72017-11-03 16:27:47 +01005706
Olivier Houchardc2aae742017-09-22 18:26:28 +02005707 }
5708
5709 } else
5710#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01005711 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01005712
Emeric Brune1f38db2012-09-03 20:36:47 +02005713 if (conn->flags & CO_FL_ERROR) {
5714 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01005715 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02005716 }
Emeric Brun46591952012-05-18 15:47:34 +02005717 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005718 /* A send succeeded, so we can consider ourself connected */
5719 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005720 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02005721 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02005722 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02005723 }
5724 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005725 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005726
Emeric Brun46591952012-05-18 15:47:34 +02005727 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005728 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01005729 /* handshake is running, and it may need to re-enable write */
5730 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005731 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005732#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005733 /* Async mode can be re-enabled, because we're leaving data state.*/
5734 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005735 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005736#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01005737 break;
5738 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005739
Emeric Brun46591952012-05-18 15:47:34 +02005740 break;
5741 }
5742 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01005743 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02005744 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005745 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5746 SUB_RETRY_RECV,
5747 &ctx->wait_event);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005748#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brunb5e42a82017-06-06 12:35:14 +00005749 /* Async mode can be re-enabled, because we're leaving data state.*/
5750 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005751 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005752#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005753 break;
5754 }
Emeric Brun46591952012-05-18 15:47:34 +02005755 goto out_error;
5756 }
5757 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005758 leave:
Emeric Brun46591952012-05-18 15:47:34 +02005759 return done;
5760
5761 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005762 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005763 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005764 ERR_clear_error();
5765
Emeric Brun46591952012-05-18 15:47:34 +02005766 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02005767 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02005768}
5769
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005770static void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02005771
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005772 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005773
Olivier Houchardea8dd942019-05-20 14:02:16 +02005774
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005775 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005776 if (ctx->wait_event.events != 0)
5777 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
5778 ctx->wait_event.events,
5779 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01005780 if (ctx->subs) {
5781 ctx->subs->events = 0;
5782 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005783 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005784
Olivier Houchard692c1d02019-05-23 18:41:47 +02005785 if (ctx->xprt->close)
5786 ctx->xprt->close(conn, ctx->xprt_ctx);
Willy Tarreau5db847a2019-05-09 14:13:35 +02005787#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
Emeric Brun3854e012017-05-17 20:42:48 +02005788 if (global_ssl.async) {
5789 OSSL_ASYNC_FD all_fd[32], afd;
5790 size_t num_all_fds = 0;
5791 int i;
5792
Olivier Houchard66ab4982019-02-26 18:37:15 +01005793 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02005794 if (num_all_fds > 32) {
5795 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
5796 return;
5797 }
5798
Olivier Houchard66ab4982019-02-26 18:37:15 +01005799 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02005800
5801 /* If an async job is pending, we must try to
5802 to catch the end using polling before calling
5803 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005804 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02005805 for (i=0 ; i < num_all_fds ; i++) {
5806 /* switch on an handler designed to
5807 * handle the SSL_free
5808 */
5809 afd = all_fd[i];
5810 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005811 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02005812 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00005813 /* To ensure that the fd cache won't be used
5814 * and we'll catch a real RD event.
5815 */
5816 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02005817 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005818 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005819 pool_free(ssl_sock_ctx_pool, ctx);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005820 _HA_ATOMIC_ADD(&jobs, 1);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005821 return;
5822 }
Emeric Brun3854e012017-05-17 20:42:48 +02005823 /* Else we can remove the fds from the fdtab
5824 * and call SSL_free.
5825 * note: we do a fd_remove and not a delete
5826 * because the fd is owned by the engine.
5827 * the engine is responsible to close
5828 */
5829 for (i=0 ; i < num_all_fds ; i++)
5830 fd_remove(all_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005831 }
5832#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01005833 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01005834 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005835 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005836 pool_free(ssl_sock_ctx_pool, ctx);
Olivier Houchard2be5a4c2019-03-08 18:54:43 +01005837 _HA_ATOMIC_SUB(&sslconns, 1);
Emeric Brun46591952012-05-18 15:47:34 +02005838 }
Emeric Brun46591952012-05-18 15:47:34 +02005839}
5840
5841/* This function tries to perform a clean shutdown on an SSL connection, and in
5842 * any case, flags the connection as reusable if no handshake was in progress.
5843 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005844static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02005845{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005846 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005847
Willy Tarreau911db9b2020-01-23 16:27:54 +01005848 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02005849 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01005850 if (!clean)
5851 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005852 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02005853 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005854 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01005855 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005856 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005857 ERR_clear_error();
5858 }
Emeric Brun46591952012-05-18 15:47:34 +02005859}
5860
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01005861
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005862/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01005863int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
5864{
5865 struct ssl_sock_ctx *ctx;
5866 X509 *crt;
5867
5868 if (!ssl_sock_is_ssl(conn))
5869 return 0;
5870
5871 ctx = conn->xprt_ctx;
5872
5873 crt = SSL_get_certificate(ctx->ssl);
5874 if (!crt)
5875 return 0;
5876
5877 return cert_get_pkey_algo(crt, out);
5878}
5879
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01005880/* used for ppv2 cert signature (can be used for logging) */
5881const char *ssl_sock_get_cert_sig(struct connection *conn)
5882{
Christopher Faulet82004142019-09-10 10:12:03 +02005883 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005884
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01005885 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
5886 X509 *crt;
5887
5888 if (!ssl_sock_is_ssl(conn))
5889 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005890 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005891 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01005892 if (!crt)
5893 return NULL;
5894 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
5895 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
5896}
5897
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005898/* used for ppv2 authority */
5899const char *ssl_sock_get_sni(struct connection *conn)
5900{
5901#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02005902 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005903
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005904 if (!ssl_sock_is_ssl(conn))
5905 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005906 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005907 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005908#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01005909 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01005910#endif
5911}
5912
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005913/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005914const char *ssl_sock_get_cipher_name(struct connection *conn)
5915{
Christopher Faulet82004142019-09-10 10:12:03 +02005916 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005917
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005918 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005919 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005920 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005921 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005922}
5923
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005924/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005925const char *ssl_sock_get_proto_version(struct connection *conn)
5926{
Christopher Faulet82004142019-09-10 10:12:03 +02005927 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005928
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02005929 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005930 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02005931 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005932 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02005933}
5934
Olivier Houchardab28a322018-12-21 19:45:40 +01005935void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
5936{
5937#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christopher Faulet82004142019-09-10 10:12:03 +02005938 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005939
Olivier Houcharde488ea82019-06-28 14:10:33 +02005940 if (!ssl_sock_is_ssl(conn))
5941 return;
Christopher Faulet82004142019-09-10 10:12:03 +02005942 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005943 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01005944#endif
5945}
5946
Willy Tarreau119a4082016-12-22 21:58:38 +01005947/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
5948 * to disable SNI.
5949 */
Willy Tarreau63076412015-07-10 11:33:32 +02005950void ssl_sock_set_servername(struct connection *conn, const char *hostname)
5951{
5952#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02005953 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005954
Willy Tarreau119a4082016-12-22 21:58:38 +01005955 char *prev_name;
5956
Willy Tarreau63076412015-07-10 11:33:32 +02005957 if (!ssl_sock_is_ssl(conn))
5958 return;
Christopher Faulet82004142019-09-10 10:12:03 +02005959 ctx = conn->xprt_ctx;
Willy Tarreau63076412015-07-10 11:33:32 +02005960
Willy Tarreau119a4082016-12-22 21:58:38 +01005961 /* if the SNI changes, we must destroy the reusable context so that a
5962 * new connection will present a new SNI. As an optimization we could
5963 * later imagine having a small cache of ssl_ctx to hold a few SNI per
5964 * server.
5965 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005966 prev_name = (char *)SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau119a4082016-12-22 21:58:38 +01005967 if ((!prev_name && hostname) ||
5968 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01005969 SSL_set_session(ctx->ssl, NULL);
Willy Tarreau119a4082016-12-22 21:58:38 +01005970
Olivier Houchard66ab4982019-02-26 18:37:15 +01005971 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02005972#endif
5973}
5974
Emeric Brun0abf8362014-06-24 18:26:41 +02005975/* Extract peer certificate's common name into the chunk dest
5976 * Returns
5977 * the len of the extracted common name
5978 * or 0 if no CN found in DN
5979 * or -1 on error case (i.e. no peer certificate)
5980 */
Willy Tarreau83061a82018-07-13 11:56:34 +02005981int ssl_sock_get_remote_common_name(struct connection *conn,
5982 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04005983{
Christopher Faulet82004142019-09-10 10:12:03 +02005984 struct ssl_sock_ctx *ctx;
David Safb76832014-05-08 23:42:08 -04005985 X509 *crt = NULL;
5986 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04005987 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02005988 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005989 .area = (char *)&find_cn,
5990 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04005991 };
Emeric Brun0abf8362014-06-24 18:26:41 +02005992 int result = -1;
David Safb76832014-05-08 23:42:08 -04005993
5994 if (!ssl_sock_is_ssl(conn))
Emeric Brun0abf8362014-06-24 18:26:41 +02005995 goto out;
Christopher Faulet82004142019-09-10 10:12:03 +02005996 ctx = conn->xprt_ctx;
David Safb76832014-05-08 23:42:08 -04005997
5998 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005999 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006000 if (!crt)
6001 goto out;
6002
6003 name = X509_get_subject_name(crt);
6004 if (!name)
6005 goto out;
David Safb76832014-05-08 23:42:08 -04006006
Emeric Brun0abf8362014-06-24 18:26:41 +02006007 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6008out:
David Safb76832014-05-08 23:42:08 -04006009 if (crt)
6010 X509_free(crt);
6011
6012 return result;
6013}
6014
Dave McCowan328fb582014-07-30 10:39:13 -04006015/* returns 1 if client passed a certificate for this session, 0 if not */
6016int ssl_sock_get_cert_used_sess(struct connection *conn)
6017{
Christopher Faulet82004142019-09-10 10:12:03 +02006018 struct ssl_sock_ctx *ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006019 X509 *crt = NULL;
6020
6021 if (!ssl_sock_is_ssl(conn))
6022 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006023 ctx = conn->xprt_ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006024
6025 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006026 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006027 if (!crt)
6028 return 0;
6029
6030 X509_free(crt);
6031 return 1;
6032}
6033
6034/* returns 1 if client passed a certificate for this connection, 0 if not */
6035int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006036{
Christopher Faulet82004142019-09-10 10:12:03 +02006037 struct ssl_sock_ctx *ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006038
David Safb76832014-05-08 23:42:08 -04006039 if (!ssl_sock_is_ssl(conn))
6040 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006041 ctx = conn->xprt_ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006042 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006043}
6044
6045/* returns result from SSL verify */
6046unsigned int ssl_sock_get_verify_result(struct connection *conn)
6047{
Christopher Faulet82004142019-09-10 10:12:03 +02006048 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006049
David Safb76832014-05-08 23:42:08 -04006050 if (!ssl_sock_is_ssl(conn))
6051 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Christopher Faulet82004142019-09-10 10:12:03 +02006052 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006053 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006054}
6055
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006056/* Returns the application layer protocol name in <str> and <len> when known.
6057 * Zero is returned if the protocol name was not found, otherwise non-zero is
6058 * returned. The string is allocated in the SSL context and doesn't have to be
6059 * freed by the caller. NPN is also checked if available since older versions
6060 * of openssl (1.0.1) which are more common in field only support this one.
6061 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006062static int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006063{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006064#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6065 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006066 struct ssl_sock_ctx *ctx = xprt_ctx;
6067 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006068 return 0;
6069
6070 *str = NULL;
6071
6072#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006073 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006074 if (*str)
6075 return 1;
6076#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006077#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006078 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006079 if (*str)
6080 return 1;
6081#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006082#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006083 return 0;
6084}
6085
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006086/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006087int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006088{
6089 X509 *ca;
6090 X509_NAME *name = NULL;
6091 ASN1_OCTET_STRING *skid = NULL;
6092 STACK_OF(X509) *chain = NULL;
6093 struct issuer_chain *issuer;
6094 struct eb64_node *node;
6095 char *path;
6096 u64 key;
6097 int ret = 0;
6098
6099 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6100 if (chain == NULL) {
6101 chain = sk_X509_new_null();
6102 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6103 name = X509_get_subject_name(ca);
6104 }
6105 if (!sk_X509_push(chain, ca)) {
6106 X509_free(ca);
6107 goto end;
6108 }
6109 }
6110 if (!chain) {
6111 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6112 goto end;
6113 }
6114 if (!skid) {
6115 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6116 goto end;
6117 }
6118 if (!name) {
6119 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6120 goto end;
6121 }
6122 key = XXH64(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006123 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006124 issuer = container_of(node, typeof(*issuer), node);
6125 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6126 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6127 goto end;
6128 }
6129 }
6130 issuer = calloc(1, sizeof *issuer);
6131 path = strdup(fp);
6132 if (!issuer || !path) {
6133 free(issuer);
6134 free(path);
6135 goto end;
6136 }
6137 issuer->node.key = key;
6138 issuer->path = path;
6139 issuer->chain = chain;
6140 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006141 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006142 ret = 1;
6143 end:
6144 if (skid)
6145 ASN1_OCTET_STRING_free(skid);
6146 if (chain)
6147 sk_X509_pop_free(chain, X509_free);
6148 return ret;
6149}
6150
William Lallemandda8584c2020-05-14 10:14:37 +02006151 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006152{
6153 AUTHORITY_KEYID *akid;
6154 struct issuer_chain *issuer = NULL;
6155
6156 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
6157 if (akid) {
6158 struct eb64_node *node;
6159 u64 hk;
6160 hk = XXH64(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
6161 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6162 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6163 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6164 issuer = ti;
6165 break;
6166 }
6167 }
6168 AUTHORITY_KEYID_free(akid);
6169 }
6170 return issuer;
6171}
6172
William Lallemanddad31052020-05-14 17:47:32 +02006173void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006174{
6175 struct eb64_node *node, *back;
6176 struct issuer_chain *issuer;
6177
William Lallemande0f3fd52020-02-25 14:53:06 +01006178 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006179 while (node) {
6180 issuer = container_of(node, typeof(*issuer), node);
6181 back = eb64_next(node);
6182 eb64_delete(node);
6183 free(issuer->path);
6184 sk_X509_pop_free(issuer->chain, X509_free);
6185 free(issuer);
6186 node = back;
6187 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006188}
6189
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006190#ifndef OPENSSL_NO_ENGINE
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006191static int ssl_check_async_engine_count(void) {
6192 int err_code = 0;
6193
Emeric Brun3854e012017-05-17 20:42:48 +02006194 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006195 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006196 err_code = ERR_ABORT;
6197 }
6198 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006199}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006200#endif
6201
William Lallemand32af2032016-10-29 18:09:35 +02006202/* This function is used with TLS ticket keys management. It permits to browse
6203 * each reference. The variable <getnext> must contain the current node,
6204 * <end> point to the root node.
6205 */
6206#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6207static inline
6208struct tls_keys_ref *tlskeys_list_get_next(struct tls_keys_ref *getnext, struct list *end)
6209{
6210 struct tls_keys_ref *ref = getnext;
6211
6212 while (1) {
6213
6214 /* Get next list entry. */
6215 ref = LIST_NEXT(&ref->list, struct tls_keys_ref *, list);
6216
6217 /* If the entry is the last of the list, return NULL. */
6218 if (&ref->list == end)
6219 return NULL;
6220
6221 return ref;
6222 }
6223}
6224
6225static inline
6226struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
6227{
6228 int id;
6229 char *error;
6230
6231 /* If the reference starts by a '#', this is numeric id. */
6232 if (reference[0] == '#') {
6233 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
6234 id = strtol(reference + 1, &error, 10);
6235 if (*error != '\0')
6236 return NULL;
6237
6238 /* Perform the unique id lookup. */
6239 return tlskeys_ref_lookupid(id);
6240 }
6241
6242 /* Perform the string lookup. */
6243 return tlskeys_ref_lookup(reference);
6244}
6245#endif
6246
6247
6248#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6249
6250static int cli_io_handler_tlskeys_files(struct appctx *appctx);
6251
6252static inline int cli_io_handler_tlskeys_entries(struct appctx *appctx) {
6253 return cli_io_handler_tlskeys_files(appctx);
6254}
6255
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006256/* dumps all tls keys. Relies on cli.i0 (non-null = only list file names), cli.i1
6257 * (next index to be dumped), and cli.p0 (next key reference).
6258 */
William Lallemand32af2032016-10-29 18:09:35 +02006259static int cli_io_handler_tlskeys_files(struct appctx *appctx) {
6260
6261 struct stream_interface *si = appctx->owner;
6262
6263 switch (appctx->st2) {
6264 case STAT_ST_INIT:
6265 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08006266 * quit the function with returning 0. The function is called
William Lallemand32af2032016-10-29 18:09:35 +02006267 * later and restart at the state "STAT_ST_INIT".
6268 */
6269 chunk_reset(&trash);
6270
6271 if (appctx->io_handler == cli_io_handler_tlskeys_entries)
6272 chunk_appendf(&trash, "# id secret\n");
6273 else
6274 chunk_appendf(&trash, "# id (file)\n");
6275
Willy Tarreau06d80a92017-10-19 14:32:15 +02006276 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01006277 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006278 return 0;
6279 }
6280
William Lallemand32af2032016-10-29 18:09:35 +02006281 /* Now, we start the browsing of the references lists.
6282 * Note that the following call to LIST_ELEM return bad pointer. The only
6283 * available field of this pointer is <list>. It is used with the function
6284 * tlskeys_list_get_next() for retruning the first available entry
6285 */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006286 if (appctx->ctx.cli.p0 == NULL) {
6287 appctx->ctx.cli.p0 = LIST_ELEM(&tlskeys_reference, struct tls_keys_ref *, list);
6288 appctx->ctx.cli.p0 = tlskeys_list_get_next(appctx->ctx.cli.p0, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006289 }
6290
6291 appctx->st2 = STAT_ST_LIST;
6292 /* fall through */
6293
6294 case STAT_ST_LIST:
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006295 while (appctx->ctx.cli.p0) {
6296 struct tls_keys_ref *ref = appctx->ctx.cli.p0;
William Lallemand32af2032016-10-29 18:09:35 +02006297
6298 chunk_reset(&trash);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006299 if (appctx->io_handler == cli_io_handler_tlskeys_entries && appctx->ctx.cli.i1 == 0)
William Lallemand32af2032016-10-29 18:09:35 +02006300 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006301
6302 if (appctx->ctx.cli.i1 == 0)
6303 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
6304
William Lallemand32af2032016-10-29 18:09:35 +02006305 if (appctx->io_handler == cli_io_handler_tlskeys_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01006306 int head;
6307
6308 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
6309 head = ref->tls_ticket_enc_index;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006310 while (appctx->ctx.cli.i1 < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02006311 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02006312
6313 chunk_reset(t2);
6314 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01006315 if (ref->key_size_bits == 128) {
6316 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6317 sizeof(struct tls_sess_key_128),
6318 t2->area, t2->size);
6319 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6320 t2->area);
6321 }
6322 else if (ref->key_size_bits == 256) {
6323 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6324 sizeof(struct tls_sess_key_256),
6325 t2->area, t2->size);
6326 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6327 t2->area);
6328 }
6329 else {
6330 /* This case should never happen */
6331 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, appctx->ctx.cli.i1);
6332 }
William Lallemand32af2032016-10-29 18:09:35 +02006333
Willy Tarreau06d80a92017-10-19 14:32:15 +02006334 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006335 /* let's try again later from this stream. We add ourselves into
6336 * this stream's users so that it can remove us upon termination.
6337 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01006338 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaudb398432018-11-15 11:08:52 +01006339 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006340 return 0;
6341 }
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006342 appctx->ctx.cli.i1++;
William Lallemand32af2032016-10-29 18:09:35 +02006343 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01006344 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006345 appctx->ctx.cli.i1 = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006346 }
Willy Tarreau06d80a92017-10-19 14:32:15 +02006347 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006348 /* let's try again later from this stream. We add ourselves into
6349 * this stream's users so that it can remove us upon termination.
6350 */
Willy Tarreaudb398432018-11-15 11:08:52 +01006351 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006352 return 0;
6353 }
6354
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006355 if (appctx->ctx.cli.i0 == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02006356 break;
6357
6358 /* get next list entry and check the end of the list */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006359 appctx->ctx.cli.p0 = tlskeys_list_get_next(appctx->ctx.cli.p0, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006360 }
6361
6362 appctx->st2 = STAT_ST_FIN;
6363 /* fall through */
6364
6365 default:
6366 appctx->st2 = STAT_ST_FIN;
6367 return 1;
6368 }
6369 return 0;
6370}
6371
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006372/* sets cli.i0 to non-zero if only file lists should be dumped */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006373static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006374{
William Lallemand32af2032016-10-29 18:09:35 +02006375 /* no parameter, shows only file list */
6376 if (!*args[2]) {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006377 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006378 appctx->io_handler = cli_io_handler_tlskeys_files;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006379 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006380 }
6381
6382 if (args[2][0] == '*') {
6383 /* list every TLS ticket keys */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006384 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006385 } else {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006386 appctx->ctx.cli.p0 = tlskeys_ref_lookup_ref(args[2]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006387 if (!appctx->ctx.cli.p0)
6388 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006389 }
William Lallemand32af2032016-10-29 18:09:35 +02006390 appctx->io_handler = cli_io_handler_tlskeys_entries;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006391 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006392}
6393
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006394static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006395{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006396 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006397 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006398
William Lallemand32af2032016-10-29 18:09:35 +02006399 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006400 if (!*args[3] || !*args[4])
6401 return cli_err(appctx, "'set ssl tls-key' expects a filename and the new TLS key in base64 encoding.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006402
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006403 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006404 if (!ref)
6405 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006406
Willy Tarreau1c913e42018-08-22 05:26:57 +02006407 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006408 if (ret < 0)
6409 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01006410
Willy Tarreau1c913e42018-08-22 05:26:57 +02006411 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02006412 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
6413 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006414
Willy Tarreau9d008692019-08-09 11:21:01 +02006415 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006416}
William Lallemandd4f946c2019-12-05 10:26:40 +01006417#endif
William Lallemand419e6342020-04-08 12:05:39 +02006418
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006419static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006420{
6421#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
6422 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006423 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006424
6425 if (!payload)
6426 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02006427
6428 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006429 if (!*payload)
6430 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006431
6432 /* remove \r and \n from the payload */
6433 for (i = 0, j = 0; payload[i]; i++) {
6434 if (payload[i] == '\r' || payload[i] == '\n')
6435 continue;
6436 payload[j++] = payload[i];
6437 }
6438 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006439
Willy Tarreau1c913e42018-08-22 05:26:57 +02006440 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006441 if (ret < 0)
6442 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006443
Willy Tarreau1c913e42018-08-22 05:26:57 +02006444 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02006445 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02006446 if (err)
6447 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
6448 else
6449 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006450 }
Willy Tarreau9d008692019-08-09 11:21:01 +02006451
6452 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006453#else
Willy Tarreau9d008692019-08-09 11:21:01 +02006454 return cli_err(appctx, "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006455#endif
6456
Elliot Otchet71f82972020-01-15 08:12:14 -05006457}
6458
William Lallemand32af2032016-10-29 18:09:35 +02006459/* register cli keywords */
6460static struct cli_kw_list cli_kws = {{ },{
6461#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6462 { { "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 },
Lukas Tribusf4bbc432017-10-24 12:26:31 +02006463 { { "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 },
William Lallemand32af2032016-10-29 18:09:35 +02006464#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006465 { { "set", "ssl", "ocsp-response", NULL }, NULL, cli_parse_set_ocspresponse, NULL },
William Lallemand32af2032016-10-29 18:09:35 +02006466 { { NULL }, NULL, NULL, NULL }
6467}};
6468
Willy Tarreau0108d902018-11-25 19:14:37 +01006469INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02006470
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02006471/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02006472struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02006473 .snd_buf = ssl_sock_from_buf,
6474 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01006475 .subscribe = ssl_subscribe,
6476 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02006477 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02006478 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02006479 .rcv_pipe = NULL,
6480 .snd_pipe = NULL,
6481 .shutr = NULL,
6482 .shutw = ssl_sock_shutw,
6483 .close = ssl_sock_close,
6484 .init = ssl_sock_init,
Willy Tarreau55d37912016-12-21 23:38:39 +01006485 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01006486 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01006487 .prepare_srv = ssl_sock_prepare_srv_ctx,
6488 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006489 .get_alpn = ssl_sock_get_alpn,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01006490 .name = "SSL",
Emeric Brun46591952012-05-18 15:47:34 +02006491};
6492
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006493enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
6494 struct session *sess, struct stream *s, int flags)
6495{
6496 struct connection *conn;
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006497 struct conn_stream *cs;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006498
6499 conn = objt_conn(sess->origin);
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006500 cs = objt_cs(s->si[0].end);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006501
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006502 if (conn && cs) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006503 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Olivier Houchard6fa63d92017-11-27 18:41:32 +01006504 cs->flags |= CS_FL_WAIT_FOR_HS;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02006505 s->req.flags |= CF_READ_NULL;
6506 return ACT_RET_YIELD;
6507 }
6508 }
6509 return (ACT_RET_CONT);
6510}
6511
6512static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
6513{
6514 rule->action_ptr = ssl_action_wait_for_hs;
6515
6516 return ACT_RET_PRS_OK;
6517}
6518
6519static struct action_kw_list http_req_actions = {ILH, {
6520 { "wait-for-handshake", ssl_parse_wait_for_hs },
6521 { /* END */ }
6522}};
6523
Willy Tarreau0108d902018-11-25 19:14:37 +01006524INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
6525
Willy Tarreau5db847a2019-05-09 14:13:35 +02006526#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006527
6528static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6529{
6530 if (ptr) {
6531 chunk_destroy(ptr);
6532 free(ptr);
6533 }
6534}
6535
6536#endif
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01006537static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6538{
Willy Tarreaubafbe012017-11-24 17:34:44 +01006539 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01006540}
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006541
Emeric Brun46591952012-05-18 15:47:34 +02006542__attribute__((constructor))
Willy Tarreau92faadf2012-10-10 23:04:25 +02006543static void __ssl_sock_init(void)
6544{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006545#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02006546 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006547 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006548#endif
Emeric Brun46591952012-05-18 15:47:34 +02006549
Willy Tarreauef934602016-12-22 23:12:01 +01006550 if (global_ssl.listen_default_ciphers)
6551 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
6552 if (global_ssl.connect_default_ciphers)
6553 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Emmanuel Hocdet839af572019-05-14 16:27:35 +02006554#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Dirkjan Bussink415150f2018-09-14 11:14:21 +02006555 if (global_ssl.listen_default_ciphersuites)
6556 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
6557 if (global_ssl.connect_default_ciphersuites)
6558 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
6559#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01006560
Willy Tarreau13e14102016-12-22 20:25:26 +01006561 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02006562#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02006563 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08006564#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006565#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02006566 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006567 n = sk_SSL_COMP_num(cm);
6568 while (n--) {
6569 (void) sk_SSL_COMP_pop(cm);
6570 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05006571#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05006572
Willy Tarreau5db847a2019-05-09 14:13:35 +02006573#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02006574 ssl_locking_init();
6575#endif
Willy Tarreau5db847a2019-05-09 14:13:35 +02006576#if (HA_OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01006577 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
6578#endif
Thierry FOURNIER28962c92018-06-17 21:37:05 +02006579 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02006580 ssl_capture_ptr_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_capture_free_func);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006581#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00006582 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006583 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006584#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01006585#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6586 hap_register_post_check(tlskeys_finalize_config);
6587#endif
Willy Tarreau80713382018-11-26 10:19:54 +01006588
6589 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
6590 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
6591
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006592 hap_register_post_deinit(ssl_free_global_issuers);
6593
Willy Tarreau80713382018-11-26 10:19:54 +01006594#ifndef OPENSSL_NO_DH
6595 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
6596 hap_register_post_deinit(ssl_free_dh);
6597#endif
6598#ifndef OPENSSL_NO_ENGINE
6599 hap_register_post_deinit(ssl_free_engines);
6600#endif
6601 /* Load SSL string for the verbose & debug mode. */
6602 ERR_load_SSL_strings();
Olivier Houcharda8955d52019-04-07 22:00:38 +02006603 ha_meth = BIO_meth_new(0x666, "ha methods");
6604 BIO_meth_set_write(ha_meth, ha_ssl_write);
6605 BIO_meth_set_read(ha_meth, ha_ssl_read);
6606 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
6607 BIO_meth_set_create(ha_meth, ha_ssl_new);
6608 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
6609 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
6610 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02006611
6612 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02006613
Dragan Dosen9ac98092020-05-11 15:51:45 +02006614 /* Try to register dedicated SSL/TLS protocol message callbacks for
6615 * heartbleed attack (CVE-2014-0160) and clienthello.
6616 */
6617 hap_register_post_check(ssl_sock_register_msg_callbacks);
6618
Dragan Dosen1e7ed042020-05-08 18:30:00 +02006619 /* Try to free all callbacks that were registered by using
6620 * ssl_sock_register_msg_callback().
6621 */
6622 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01006623}
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01006624
Willy Tarreau80713382018-11-26 10:19:54 +01006625/* Compute and register the version string */
6626static void ssl_register_build_options()
6627{
6628 char *ptr = NULL;
6629 int i;
6630
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006631 memprintf(&ptr, "Built with OpenSSL version : "
6632#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01006633 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006634#else /* OPENSSL_IS_BORINGSSL */
6635 OPENSSL_VERSION_TEXT
6636 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08006637 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02006638 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006639#endif
6640 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02006641#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006642 "no (library version too old)"
6643#elif defined(OPENSSL_NO_TLSEXT)
6644 "no (disabled via OPENSSL_NO_TLSEXT)"
6645#else
6646 "yes"
6647#endif
6648 "", ptr);
6649
6650 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
6651#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
6652 "yes"
6653#else
6654#ifdef OPENSSL_NO_TLSEXT
6655 "no (because of OPENSSL_NO_TLSEXT)"
6656#else
6657 "no (version might be too old, 0.9.8f min needed)"
6658#endif
6659#endif
6660 "", ptr);
6661
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02006662 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
6663 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
6664 if (methodVersions[i].option)
6665 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01006666
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006667 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01006668}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01006669
Willy Tarreau80713382018-11-26 10:19:54 +01006670INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02006671
Emeric Brun46591952012-05-18 15:47:34 +02006672
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006673#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00006674void ssl_free_engines(void) {
6675 struct ssl_engine_list *wl, *wlb;
6676 /* free up engine list */
6677 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
6678 ENGINE_finish(wl->e);
6679 ENGINE_free(wl->e);
6680 LIST_DEL(&wl->list);
6681 free(wl);
6682 }
6683}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006684#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02006685
Remi Gacogned3a23c32015-05-28 16:39:47 +02006686#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00006687void ssl_free_dh(void) {
6688 if (local_dh_1024) {
6689 DH_free(local_dh_1024);
6690 local_dh_1024 = NULL;
6691 }
6692 if (local_dh_2048) {
6693 DH_free(local_dh_2048);
6694 local_dh_2048 = NULL;
6695 }
6696 if (local_dh_4096) {
6697 DH_free(local_dh_4096);
6698 local_dh_4096 = NULL;
6699 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02006700 if (global_dh) {
6701 DH_free(global_dh);
6702 global_dh = NULL;
6703 }
Grant Zhang872f9c22017-01-21 01:10:18 +00006704}
6705#endif
6706
6707__attribute__((destructor))
6708static void __ssl_sock_deinit(void)
6709{
6710#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02006711 if (ssl_ctx_lru_tree) {
6712 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01006713 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02006714 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02006715#endif
6716
Willy Tarreau5db847a2019-05-09 14:13:35 +02006717#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02006718 ERR_remove_state(0);
6719 ERR_free_strings();
6720
6721 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08006722#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02006723
Willy Tarreau5db847a2019-05-09 14:13:35 +02006724#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02006725 CRYPTO_cleanup_all_ex_data();
6726#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02006727 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02006728}
6729
Emeric Brun46591952012-05-18 15:47:34 +02006730/*
6731 * Local variables:
6732 * c-indent-level: 8
6733 * c-basic-offset: 8
6734 * End:
6735 */