blob: bf7bb0135a7f4b2d5ae7ebde0fddd2391c066cc2 [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>
Emeric Brun46591952012-05-18 15:47:34 +020031#include <stdio.h>
32#include <stdlib.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020033#include <string.h>
34#include <unistd.h>
Emeric Brun46591952012-05-18 15:47:34 +020035
36#include <sys/socket.h>
37#include <sys/stat.h>
38#include <sys/types.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020039#include <netdb.h>
Emeric Brun46591952012-05-18 15:47:34 +020040#include <netinet/tcp.h>
41
Willy Tarreaub2551052020-06-09 09:07:15 +020042#include <import/ebpttree.h>
43#include <import/ebsttree.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020044#include <import/lru.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020045
Willy Tarreaub2551052020-06-09 09:07:15 +020046#include <haproxy/api.h>
Willy Tarreaua9380522022-05-05 08:50:17 +020047#include <haproxy/applet.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020048#include <haproxy/arg.h>
49#include <haproxy/base64.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020050#include <haproxy/channel.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020051#include <haproxy/chunk.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020052#include <haproxy/cli.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020053#include <haproxy/connection.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020054#include <haproxy/dynbuf.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020055#include <haproxy/errors.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020056#include <haproxy/fd.h>
57#include <haproxy/freq_ctr.h>
Willy Tarreau762d7a52020-06-04 11:23:07 +020058#include <haproxy/frontend.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020059#include <haproxy/global.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020060#include <haproxy/http_rules.h>
Willy Tarreauaeed4a82020-06-04 22:01:04 +020061#include <haproxy/log.h>
Willy Tarreau6019fab2020-05-27 16:26:00 +020062#include <haproxy/openssl-compat.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020063#include <haproxy/pattern-t.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020064#include <haproxy/proto_tcp.h>
Willy Tarreaua264d962020-06-04 22:29:18 +020065#include <haproxy/proxy.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020066#include <haproxy/sample.h>
67#include <haproxy/sc_strm.h>
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020068#include <haproxy/quic_conn.h>
Frédéric Lécaille748ece62022-05-21 23:58:40 +020069#include <haproxy/quic_tp.h>
Willy Tarreau1e56f922020-06-04 23:20:13 +020070#include <haproxy/server.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020071#include <haproxy/shctx.h>
Willy Tarreau47d7f902020-06-04 14:25:47 +020072#include <haproxy/ssl_ckch.h>
Willy Tarreau52d88722020-06-04 14:29:23 +020073#include <haproxy/ssl_crtlist.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020074#include <haproxy/ssl_sock.h>
Willy Tarreaub2bd8652020-06-04 14:21:22 +020075#include <haproxy/ssl_utils.h>
Amaury Denoyelle9963fa72020-11-03 17:10:00 +010076#include <haproxy/stats.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020077#include <haproxy/stconn.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020078#include <haproxy/stream-t.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020079#include <haproxy/task.h>
Willy Tarreauc2f7c582020-06-02 18:15:32 +020080#include <haproxy/ticks.h>
Willy Tarreau92b4f132020-06-01 11:05:15 +020081#include <haproxy/time.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020082#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020083#include <haproxy/vars.h>
Tim Duesterhusd5fc8fc2021-09-11 17:51:13 +020084#include <haproxy/xxhash.h>
Remi Tricot-Le Breton2e7d1eb2022-01-11 10:11:10 +010085#include <haproxy/istbuf.h>
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +010086#include <haproxy/ssl_ocsp.h>
Emeric Brun46591952012-05-18 15:47:34 +020087
Emeric Brun46591952012-05-18 15:47:34 +020088
Willy Tarreau9356dac2019-05-10 09:22:53 +020089/* ***** READ THIS before adding code here! *****
90 *
91 * Due to API incompatibilities between multiple OpenSSL versions and their
92 * derivatives, it's often tempting to add macros to (re-)define certain
93 * symbols. Please do not do this here, and do it in common/openssl-compat.h
94 * exclusively so that the whole code consistently uses the same macros.
95 *
96 * Whenever possible if a macro is missing in certain versions, it's better
97 * to conditionally define it in openssl-compat.h than using lots of ifdefs.
98 */
99
Emeric Brunece0c332017-12-06 13:51:49 +0100100int nb_engines = 0;
Emeric Brune1f38db2012-09-03 20:36:47 +0200101
William Lallemande0f3fd52020-02-25 14:53:06 +0100102static struct eb_root cert_issuer_tree = EB_ROOT; /* issuers tree from "issuers-chain-path" */
103
William Lallemand7fd8b452020-05-07 15:20:43 +0200104struct global_ssl global_ssl = {
Willy Tarreauef934602016-12-22 23:12:01 +0100105#ifdef LISTEN_DEFAULT_CIPHERS
106 .listen_default_ciphers = LISTEN_DEFAULT_CIPHERS,
107#endif
108#ifdef CONNECT_DEFAULT_CIPHERS
109 .connect_default_ciphers = CONNECT_DEFAULT_CIPHERS,
110#endif
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +0500111#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200112 .listen_default_ciphersuites = LISTEN_DEFAULT_CIPHERSUITES,
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200113 .connect_default_ciphersuites = CONNECT_DEFAULT_CIPHERSUITES,
114#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100115 .listen_default_ssloptions = BC_SSL_O_NONE,
116 .connect_default_ssloptions = SRV_SSL_O_NONE,
117
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +0200118 .listen_default_sslmethods.flags = MC_SSL_O_ALL,
119 .listen_default_sslmethods.min = CONF_TLSV_NONE,
120 .listen_default_sslmethods.max = CONF_TLSV_NONE,
121 .connect_default_sslmethods.flags = MC_SSL_O_ALL,
122 .connect_default_sslmethods.min = CONF_TLSV_NONE,
123 .connect_default_sslmethods.max = CONF_TLSV_NONE,
124
Willy Tarreauef934602016-12-22 23:12:01 +0100125#ifdef DEFAULT_SSL_MAX_RECORD
126 .max_record = DEFAULT_SSL_MAX_RECORD,
127#endif
Thomas Prückl10243932022-04-27 13:04:54 +0200128 .hard_max_record = 0,
Willy Tarreauef934602016-12-22 23:12:01 +0100129 .default_dh_param = SSL_DEFAULT_DH_PARAM,
130 .ctx_cache = DEFAULT_SSL_CTX_CACHE,
Marcin Deranek310a2602021-07-13 19:04:24 +0200131 .capture_buffer_size = 0,
William Lallemand3af48e72020-02-03 17:15:52 +0100132 .extra_files = SSL_GF_ALL,
William Lallemand8e8581e2020-10-20 17:36:46 +0200133 .extra_files_noext = 0,
William Lallemand722180a2021-06-09 16:46:12 +0200134#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200135 .keylog = 0
136#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100137};
138
Olivier Houcharda8955d52019-04-07 22:00:38 +0200139static BIO_METHOD *ha_meth;
140
Willy Tarreaub8dec4a2022-06-23 11:02:08 +0200141DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx", sizeof(struct ssl_sock_ctx));
Olivier Houchard66ab4982019-02-26 18:37:15 +0100142
Willy Tarreaub8dec4a2022-06-23 11:02:08 +0200143DECLARE_STATIC_POOL(ssl_sock_client_sni_pool, "ssl_sock_client_sni", TLSEXT_MAXLEN_host_name + 1);
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100144
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100145/* ssl stats module */
146enum {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100147 SSL_ST_SESS,
148 SSL_ST_REUSED_SESS,
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100149 SSL_ST_FAILED_HANDSHAKE,
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100150
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100151 SSL_ST_STATS_COUNT /* must be the last member of the enum */
152};
153
154static struct name_desc ssl_stats[] = {
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100155 [SSL_ST_SESS] = { .name = "ssl_sess",
156 .desc = "Total number of ssl sessions established" },
157 [SSL_ST_REUSED_SESS] = { .name = "ssl_reused_sess",
158 .desc = "Total number of ssl sessions reused" },
159 [SSL_ST_FAILED_HANDSHAKE] = { .name = "ssl_failed_handshake",
160 .desc = "Total number of failed handshake" },
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100161};
162
163static struct ssl_counters {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100164 long long sess;
165 long long reused_sess;
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100166 long long failed_handshake;
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100167} ssl_counters;
168
169static void ssl_fill_stats(void *data, struct field *stats)
170{
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100171 struct ssl_counters *counters = data;
172
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100173 stats[SSL_ST_SESS] = mkf_u64(FN_COUNTER, counters->sess);
174 stats[SSL_ST_REUSED_SESS] = mkf_u64(FN_COUNTER, counters->reused_sess);
175 stats[SSL_ST_FAILED_HANDSHAKE] = mkf_u64(FN_COUNTER, counters->failed_handshake);
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100176}
177
178static struct stats_module ssl_stats_module = {
179 .name = "ssl",
180 .fill_stats = ssl_fill_stats,
181 .stats = ssl_stats,
182 .stats_count = SSL_ST_STATS_COUNT,
183 .counters = &ssl_counters,
184 .counters_size = sizeof(ssl_counters),
185 .domain_flags = MK_STATS_PROXY_DOMAIN(STATS_PX_CAP_FE|STATS_PX_CAP_LI|STATS_PX_CAP_BE|STATS_PX_CAP_SRV),
186 .clearable = 1,
187};
188
189INITCALL1(STG_REGISTER, stats_register_module, &ssl_stats_module);
190
Willy Tarreaua9380522022-05-05 08:50:17 +0200191/* CLI context for "show tls-keys" */
192struct show_keys_ctx {
193 struct tls_keys_ref *next_ref; /* next reference to be dumped */
194 int names_only; /* non-zero = only show file names */
195 int next_index; /* next index to be dumped */
Willy Tarreaubd338642022-05-05 08:59:17 +0200196 int dump_entries; /* dump entries also */
Willy Tarreau9c5a38c2022-05-05 09:03:44 +0200197 enum {
198 SHOW_KEYS_INIT = 0,
199 SHOW_KEYS_LIST,
200 SHOW_KEYS_DONE,
201 } state; /* phase of the current dump */
Willy Tarreaua9380522022-05-05 08:50:17 +0200202};
203
Willy Tarreau691d5032021-01-20 14:55:01 +0100204/* ssl_sock_io_cb is exported to see it resolved in "show fd" */
Willy Tarreau144f84a2021-03-02 16:09:26 +0100205struct task *ssl_sock_io_cb(struct task *, void *, unsigned int);
Olivier Houchard000694c2019-05-23 14:45:12 +0200206static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
Olivier Houchardea8dd942019-05-20 14:02:16 +0200207
Olivier Houcharda8955d52019-04-07 22:00:38 +0200208/* Methods to implement OpenSSL BIO */
209static int ha_ssl_write(BIO *h, const char *buf, int num)
210{
211 struct buffer tmpbuf;
212 struct ssl_sock_ctx *ctx;
213 int ret;
214
215 ctx = BIO_get_data(h);
216 tmpbuf.size = num;
217 tmpbuf.area = (void *)(uintptr_t)buf;
218 tmpbuf.data = num;
219 tmpbuf.head = 0;
220 ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200221 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200222 BIO_set_retry_write(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200223 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200224 } else if (ret == 0)
225 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200226 return ret;
227}
228
229static int ha_ssl_gets(BIO *h, char *buf, int size)
230{
231
232 return 0;
233}
234
235static int ha_ssl_puts(BIO *h, const char *str)
236{
237
238 return ha_ssl_write(h, str, strlen(str));
239}
240
241static int ha_ssl_read(BIO *h, char *buf, int size)
242{
243 struct buffer tmpbuf;
244 struct ssl_sock_ctx *ctx;
245 int ret;
246
247 ctx = BIO_get_data(h);
248 tmpbuf.size = size;
249 tmpbuf.area = buf;
250 tmpbuf.data = 0;
251 tmpbuf.head = 0;
252 ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200253 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200254 BIO_set_retry_read(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200255 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200256 } else if (ret == 0)
257 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200258
259 return ret;
260}
261
262static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
263{
264 int ret = 0;
265 switch (cmd) {
266 case BIO_CTRL_DUP:
267 case BIO_CTRL_FLUSH:
268 ret = 1;
269 break;
270 }
271 return ret;
272}
273
274static int ha_ssl_new(BIO *h)
275{
276 BIO_set_init(h, 1);
277 BIO_set_data(h, NULL);
278 BIO_clear_flags(h, ~0);
279 return 1;
280}
281
282static int ha_ssl_free(BIO *data)
283{
284
285 return 1;
286}
287
288
Willy Tarreau5db847a2019-05-09 14:13:35 +0200289#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100290
Emeric Brun821bb9b2017-06-15 16:37:39 +0200291static HA_RWLOCK_T *ssl_rwlocks;
292
293
294unsigned long ssl_id_function(void)
295{
296 return (unsigned long)tid;
297}
298
299void ssl_locking_function(int mode, int n, const char * file, int line)
300{
301 if (mode & CRYPTO_LOCK) {
302 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100303 HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200304 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100305 HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200306 }
307 else {
308 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100309 HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200310 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100311 HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200312 }
313}
314
315static int ssl_locking_init(void)
316{
317 int i;
318
319 ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
320 if (!ssl_rwlocks)
321 return -1;
322
323 for (i = 0 ; i < CRYPTO_num_locks() ; i++)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100324 HA_RWLOCK_INIT(&ssl_rwlocks[i]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200325
326 CRYPTO_set_id_callback(ssl_id_function);
327 CRYPTO_set_locking_callback(ssl_locking_function);
328
329 return 0;
330}
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100331
Emeric Brun821bb9b2017-06-15 16:37:39 +0200332#endif
333
Willy Tarreauaf613e82020-06-05 08:40:51 +0200334__decl_thread(HA_SPINLOCK_T ckch_lock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200335
William Lallemandbc6ca7c2019-10-29 23:48:19 +0100336
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200337
338/* mimic what X509_STORE_load_locations do with store_ctx */
339static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
340{
Remi Tricot-Le Bretond75b99e2021-05-17 11:45:55 +0200341 X509_STORE *store = NULL;
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +0100342 struct cafile_entry *ca_e = ssl_store_get_cafile_entry(path, 0);
343 if (ca_e)
344 store = ca_e->ca_store;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200345 if (store_ctx && store) {
346 int i;
347 X509_OBJECT *obj;
348 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
349 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
350 obj = sk_X509_OBJECT_value(objs, i);
351 switch (X509_OBJECT_get_type(obj)) {
352 case X509_LU_X509:
353 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
354 break;
355 case X509_LU_CRL:
356 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
357 break;
358 default:
359 break;
360 }
361 }
362 return 1;
363 }
364 return 0;
365}
366
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500367/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200368static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
369{
370 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
371 return ssl_set_cert_crl_file(store_ctx, path);
372}
373
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200374/*
375 Extract CA_list from CA_file already in tree.
376 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
377 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
378*/
379static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
380{
381 struct ebmb_node *eb;
382 struct cafile_entry *ca_e;
383
384 eb = ebst_lookup(&cafile_tree, path);
385 if (!eb)
386 return NULL;
387 ca_e = ebmb_entry(eb, struct cafile_entry, node);
388
389 if (ca_e->ca_list == NULL) {
390 int i;
391 unsigned long key;
392 struct eb_root ca_name_tree = EB_ROOT;
393 struct eb64_node *node, *back;
394 struct {
395 struct eb64_node node;
396 X509_NAME *xname;
397 } *ca_name;
398 STACK_OF(X509_OBJECT) *objs;
399 STACK_OF(X509_NAME) *skn;
400 X509 *x;
401 X509_NAME *xn;
402
403 skn = sk_X509_NAME_new_null();
404 /* take x509 from cafile_tree */
405 objs = X509_STORE_get0_objects(ca_e->ca_store);
406 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
407 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
408 if (!x)
409 continue;
410 xn = X509_get_subject_name(x);
411 if (!xn)
412 continue;
413 /* Check for duplicates. */
414 key = X509_NAME_hash(xn);
415 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
416 node && ca_name == NULL;
417 node = eb64_next(node)) {
418 ca_name = container_of(node, typeof(*ca_name), node);
419 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
420 ca_name = NULL;
421 }
422 /* find a duplicate */
423 if (ca_name)
424 continue;
425 ca_name = calloc(1, sizeof *ca_name);
426 xn = X509_NAME_dup(xn);
427 if (!ca_name ||
428 !xn ||
429 !sk_X509_NAME_push(skn, xn)) {
430 free(ca_name);
431 X509_NAME_free(xn);
432 sk_X509_NAME_pop_free(skn, X509_NAME_free);
433 sk_X509_NAME_free(skn);
434 skn = NULL;
435 break;
436 }
437 ca_name->node.key = key;
438 ca_name->xname = xn;
439 eb64_insert(&ca_name_tree, &ca_name->node);
440 }
441 ca_e->ca_list = skn;
442 /* remove temporary ca_name tree */
443 node = eb64_first(&ca_name_tree);
444 while (node) {
445 ca_name = container_of(node, typeof(*ca_name), node);
446 back = eb64_next(node);
447 eb64_delete(node);
448 free(ca_name);
449 node = back;
450 }
451 }
452 return ca_e->ca_list;
453}
454
Willy Tarreauff882702021-04-10 17:23:00 +0200455struct pool_head *pool_head_ssl_capture __read_mostly = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200456int ssl_capture_ptr_index = -1;
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +0100457int ssl_app_data_index = -1;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +0100458#ifdef USE_QUIC
459int ssl_qc_app_data_index = -1;
460#endif /* USE_QUIC */
Willy Tarreauef934602016-12-22 23:12:01 +0100461
William Lallemand722180a2021-06-09 16:46:12 +0200462#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200463int ssl_keylog_index = -1;
Willy Tarreauff882702021-04-10 17:23:00 +0200464struct pool_head *pool_head_ssl_keylog __read_mostly = NULL;
465struct pool_head *pool_head_ssl_keylog_str __read_mostly = NULL;
William Lallemand7d42ef52020-07-06 11:41:30 +0200466#endif
467
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +0200468int ssl_client_crt_ref_index = -1;
469
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100470/* Used to store the client's SNI in case of ClientHello callback error */
471int ssl_client_sni_index = -1;
472
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200473#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
474struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
475#endif
476
William Lallemandd7bfbe22022-04-11 18:41:24 +0200477#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200478unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000479struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
480struct ssl_engine_list {
481 struct list list;
482 ENGINE *e;
483};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200484#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000485
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +0200486#ifdef HAVE_SSL_PROVIDERS
487struct list openssl_providers = LIST_HEAD_INIT(openssl_providers);
488struct ssl_provider_list {
489 struct list list;
490 OSSL_PROVIDER *provider;
491};
492#endif
493
Remi Gacogne8de54152014-07-15 11:36:40 +0200494#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200495static int ssl_dh_ptr_index = -1;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +0100496static HASSL_DH *global_dh = NULL;
497static HASSL_DH *local_dh_1024 = NULL;
498static HASSL_DH *local_dh_2048 = NULL;
499static HASSL_DH *local_dh_4096 = NULL;
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100500#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +0100501static DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100502#else
503static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey);
504#endif
Remi Gacogne8de54152014-07-15 11:36:40 +0200505#endif /* OPENSSL_NO_DH */
506
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100507#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200508/* X509V3 Extensions that will be added on generated certificates */
509#define X509V3_EXT_SIZE 5
510static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
511 "basicConstraints",
512 "nsComment",
513 "subjectKeyIdentifier",
514 "authorityKeyIdentifier",
515 "keyUsage",
516};
517static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
518 "CA:FALSE",
519 "\"OpenSSL Generated Certificate\"",
520 "hash",
521 "keyid,issuer:always",
522 "nonRepudiation,digitalSignature,keyEncipherment"
523};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200524/* LRU cache to store generated certificate */
525static struct lru64_head *ssl_ctx_lru_tree = NULL;
526static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200527static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100528__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200529
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200530#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
531
yanbzhube2774d2015-12-10 15:07:30 -0500532/* The order here matters for picking a default context,
533 * keep the most common keytype at the bottom of the list
534 */
535const char *SSL_SOCK_KEYTYPE_NAMES[] = {
536 "dsa",
537 "ecdsa",
538 "rsa"
539};
yanbzhube2774d2015-12-10 15:07:30 -0500540
William Lallemandc3cd35f2017-11-28 11:04:43 +0100541static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100542static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
543
Dragan Dosen9ac98092020-05-11 15:51:45 +0200544/* Dedicated callback functions for heartbeat and clienthello.
545 */
546#ifdef TLS1_RT_HEARTBEAT
547static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
548 int content_type, const void *buf, size_t len,
549 SSL *ssl);
550#endif
551static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
552 int content_type, const void *buf, size_t len,
553 SSL *ssl);
554
William Lallemand722180a2021-06-09 16:46:12 +0200555#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200556static void ssl_init_keylog(struct connection *conn, int write_p, int version,
557 int content_type, const void *buf, size_t len,
558 SSL *ssl);
559#endif
560
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200561/* List head of all registered SSL/TLS protocol message callbacks. */
562struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
563
564/* Registers the function <func> in order to be called on SSL/TLS protocol
565 * message processing. It will return 0 if the function <func> is not set
566 * or if it fails to allocate memory.
567 */
568int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
569{
570 struct ssl_sock_msg_callback *cbk;
571
572 if (!func)
573 return 0;
574
575 cbk = calloc(1, sizeof(*cbk));
576 if (!cbk) {
577 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
578 return 0;
579 }
580
581 cbk->func = func;
582
Willy Tarreau2b718102021-04-21 07:32:39 +0200583 LIST_APPEND(&ssl_sock_msg_callbacks, &cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200584
585 return 1;
586}
587
Dragan Dosen9ac98092020-05-11 15:51:45 +0200588/* Used to register dedicated SSL/TLS protocol message callbacks.
589 */
590static int ssl_sock_register_msg_callbacks(void)
591{
592#ifdef TLS1_RT_HEARTBEAT
593 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
594 return ERR_ABORT;
595#endif
Marcin Deranek310a2602021-07-13 19:04:24 +0200596 if (global_ssl.capture_buffer_size > 0) {
Dragan Dosen9ac98092020-05-11 15:51:45 +0200597 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
598 return ERR_ABORT;
599 }
William Lallemand722180a2021-06-09 16:46:12 +0200600#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200601 if (global_ssl.keylog > 0) {
602 if (!ssl_sock_register_msg_callback(ssl_init_keylog))
603 return ERR_ABORT;
604 }
605#endif
606
Christopher Fauletfc633b62020-11-06 15:24:23 +0100607 return ERR_NONE;
Dragan Dosen9ac98092020-05-11 15:51:45 +0200608}
609
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200610/* Used to free all SSL/TLS protocol message callbacks that were
611 * registered by using ssl_sock_register_msg_callback().
612 */
613static void ssl_sock_unregister_msg_callbacks(void)
614{
615 struct ssl_sock_msg_callback *cbk, *cbkback;
616
617 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +0200618 LIST_DELETE(&cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200619 free(cbk);
620 }
621}
622
Willy Tarreaude827952022-04-11 10:43:28 +0200623static struct ssl_sock_ctx *ssl_sock_get_ctx(struct connection *conn)
624{
625 if (!conn || conn->xprt != xprt_get(XPRT_SSL) || !conn->xprt_ctx)
626 return NULL;
627
628 return (struct ssl_sock_ctx *)conn->xprt_ctx;
629}
630
Dragan Doseneb607fe2020-05-11 17:17:06 +0200631SSL *ssl_sock_get_ssl_object(struct connection *conn)
632{
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200633 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dragan Doseneb607fe2020-05-11 17:17:06 +0200634
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200635 return ctx ? ctx->ssl : NULL;
Dragan Doseneb607fe2020-05-11 17:17:06 +0200636}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100637/*
638 * This function gives the detail of the SSL error. It is used only
639 * if the debug mode and the verbose mode are activated. It dump all
640 * the SSL error until the stack was empty.
641 */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +0200642static forceinline void ssl_sock_dump_errors(struct connection *conn,
643 struct quic_conn *qc)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100644{
645 unsigned long ret;
646
647 if (unlikely(global.mode & MODE_DEBUG)) {
648 while(1) {
Remi Tricot-Le Breton1effd9a2022-02-11 12:04:44 +0100649 const char *func = NULL;
650 ERR_peek_error_func(&func);
651
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100652 ret = ERR_get_error();
653 if (ret == 0)
654 return;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +0200655 if (conn) {
656 fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
657 conn_fd(conn), ret,
658 func, ERR_reason_error_string(ret));
659 }
660#ifdef USE_QUIC
661 else {
662 /* TODO: we are not sure <conn> is always initialized for QUIC connections */
663 fprintf(stderr, "qc @%p OpenSSL error[0x%lx] %s: %s\n", qc, ret,
664 func, ERR_reason_error_string(ret));
665 }
666#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100667 }
668 }
669}
670
yanbzhube2774d2015-12-10 15:07:30 -0500671
William Lallemandd7bfbe22022-04-11 18:41:24 +0200672#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200673int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000674{
675 int err_code = ERR_ABORT;
676 ENGINE *engine;
677 struct ssl_engine_list *el;
678
679 /* grab the structural reference to the engine */
680 engine = ENGINE_by_id(engine_id);
681 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100682 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000683 goto fail_get;
684 }
685
686 if (!ENGINE_init(engine)) {
687 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100688 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000689 goto fail_init;
690 }
691
692 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100693 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000694 goto fail_set_method;
695 }
696
697 el = calloc(1, sizeof(*el));
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200698 if (!el)
699 goto fail_alloc;
Grant Zhang872f9c22017-01-21 01:10:18 +0000700 el->e = engine;
Willy Tarreau2b718102021-04-21 07:32:39 +0200701 LIST_INSERT(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100702 nb_engines++;
703 if (global_ssl.async)
704 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000705 return 0;
706
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200707fail_alloc:
Grant Zhang872f9c22017-01-21 01:10:18 +0000708fail_set_method:
709 /* release the functional reference from ENGINE_init() */
710 ENGINE_finish(engine);
711
712fail_init:
713 /* release the structural reference from ENGINE_by_id() */
714 ENGINE_free(engine);
715
716fail_get:
717 return err_code;
718}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200719#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000720
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +0200721#ifdef HAVE_SSL_PROVIDERS
722int ssl_init_provider(const char *provider_name)
723{
724 int err_code = ERR_ABORT;
725 struct ssl_provider_list *prov = NULL;
726
727 prov = calloc(1, sizeof(*prov));
728 if (!prov) {
729 ha_alert("ssl-provider %s: memory allocation failure\n", provider_name);
730 goto error;
731 }
732
733 if ((prov->provider = OSSL_PROVIDER_load(NULL, provider_name)) == NULL) {
734 ha_alert("ssl-provider %s: unknown provider\n", provider_name);
735 goto error;
736 }
737
738 LIST_INSERT(&openssl_providers, &prov->list);
739
740 return 0;
741
742error:
743 ha_free(&prov);
744 return err_code;
745}
746#endif /* HAVE_SSL_PROVIDERS */
747
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +0500748#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +0200749/*
750 * openssl async fd handler
751 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200752void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000753{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200754 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000755
Emeric Brun3854e012017-05-17 20:42:48 +0200756 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000757 * to poll this fd until it is requested
758 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000759 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000760 fd_cant_recv(fd);
761
762 /* crypto engine is available, let's notify the associated
763 * connection that it can pursue its processing.
764 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200765 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000766}
767
Emeric Brun3854e012017-05-17 20:42:48 +0200768/*
769 * openssl async delayed SSL_free handler
770 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200771void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000772{
773 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200774 OSSL_ASYNC_FD all_fd[32];
775 size_t num_all_fds = 0;
776 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000777
Emeric Brun3854e012017-05-17 20:42:48 +0200778 /* We suppose that the async job for a same SSL *
779 * are serialized. So if we are awake it is
780 * because the running job has just finished
781 * and we can remove all async fds safely
782 */
783 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
784 if (num_all_fds > 32) {
785 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
786 return;
787 }
788
789 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
Emeric Brun7d392a52022-07-01 17:36:50 +0200790 for (i=0 ; i < num_all_fds ; i++) {
791 /* We want to remove the fd from the fdtab
792 * but we flag it to disown because the
793 * close is performed by the engine itself
794 */
795 fdtab[all_fd[i]].state |= FD_DISOWN;
796 fd_delete(all_fd[i]);
797 }
Emeric Brun3854e012017-05-17 20:42:48 +0200798
799 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000800 SSL_free(ssl);
Willy Tarreau82531f62021-10-06 12:15:18 +0200801 _HA_ATOMIC_DEC(&global.sslconns);
Willy Tarreau4781b152021-04-06 13:53:36 +0200802 _HA_ATOMIC_DEC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000803}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000804/*
Emeric Brun3854e012017-05-17 20:42:48 +0200805 * function used to manage a returned SSL_ERROR_WANT_ASYNC
806 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000807 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200808static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000809{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100810 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200811 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200812 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000813 size_t num_add_fds = 0;
814 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200815 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000816
817 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
818 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200819 if (num_add_fds > 32 || num_del_fds > 32) {
820 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 +0000821 return;
822 }
823
Emeric Brun3854e012017-05-17 20:42:48 +0200824 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000825
Emeric Brun3854e012017-05-17 20:42:48 +0200826 /* We remove unused fds from the fdtab */
Emeric Brun7d392a52022-07-01 17:36:50 +0200827 for (i=0 ; i < num_del_fds ; i++) {
828 /* We want to remove the fd from the fdtab
829 * but we flag it to disown because the
830 * close is performed by the engine itself
831 */
832 fdtab[del_fd[i]].state |= FD_DISOWN;
833 fd_delete(del_fd[i]);
834 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000835
Emeric Brun3854e012017-05-17 20:42:48 +0200836 /* We add new fds to the fdtab */
837 for (i=0 ; i < num_add_fds ; i++) {
Willy Tarreau27a32452022-07-07 08:29:00 +0200838 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tgid, ti->ltid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000839 }
840
Emeric Brun3854e012017-05-17 20:42:48 +0200841 num_add_fds = 0;
842 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
843 if (num_add_fds > 32) {
844 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
845 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000846 }
Emeric Brun3854e012017-05-17 20:42:48 +0200847
848 /* We activate the polling for all known async fds */
849 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000850 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200851 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000852 /* To ensure that the fd cache won't be used
853 * We'll prefer to catch a real RD event
854 * because handling an EAGAIN on this fd will
855 * result in a context switch and also
856 * some engines uses a fd in blocking mode.
857 */
858 fd_cant_recv(add_fd[i]);
859 }
Emeric Brun3854e012017-05-17 20:42:48 +0200860
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000861}
862#endif
863
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100864
865/*
866 * Initialize an HMAC context <hctx> using the <key> and <md> parameters.
867 * Returns -1 in case of error, 1 otherwise.
868 */
869static int ssl_hmac_init(MAC_CTX *hctx, unsigned char *key, int key_len, const EVP_MD *md)
870{
871#ifdef HAVE_OSSL_PARAM
872 OSSL_PARAM params[3];
873
874 params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, key, key_len);
875 params[1] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, (char*)EVP_MD_name(md), 0);
876 params[2] = OSSL_PARAM_construct_end();
877 if (EVP_MAC_CTX_set_params(hctx, params) == 0)
878 return -1; /* error in mac initialisation */
879
880#else
881 HMAC_Init_ex(hctx, key, key_len, md, NULL);
882#endif
883 return 1;
884}
885
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100886#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +0100887
888static int ssl_tlsext_ticket_key_cb(SSL *s, unsigned char key_name[16], unsigned char *iv, EVP_CIPHER_CTX *ectx, MAC_CTX *hctx, int enc)
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100889{
Frédéric Lécaille6aec1f32022-09-06 17:04:55 +0200890 struct tls_keys_ref *ref = NULL;
Emeric Brun9e754772019-01-10 17:51:55 +0100891 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100892 int head;
893 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +0100894 int ret = -1; /* error by default */
Frédéric Lécaille6aec1f32022-09-06 17:04:55 +0200895 struct connection *conn = SSL_get_ex_data(s, ssl_app_data_index);
896#ifdef USE_QUIC
897 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
898#endif
899
900 if (conn)
901 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
902#ifdef USE_QUIC
903 else if (qc)
904 ref = qc->li->bind_conf->keys_ref;
905#endif
906
907 if (!ref) {
908 /* must never happen */
909 ABORT_NOW();
910 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100911
Christopher Faulet16f45c82018-02-16 11:23:49 +0100912 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
913
914 keys = ref->tlskeys;
915 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100916
917 if (enc) {
918 memcpy(key_name, keys[head].name, 16);
919
920 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +0100921 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100922
Emeric Brun9e754772019-01-10 17:51:55 +0100923 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100924
Emeric Brun9e754772019-01-10 17:51:55 +0100925 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
926 goto end;
927
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100928 if (ssl_hmac_init(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
929 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100930 ret = 1;
931 }
932 else if (ref->key_size_bits == 256 ) {
933
934 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
935 goto end;
936
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100937 if (ssl_hmac_init(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
938 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100939 ret = 1;
940 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100941 } else {
942 for (i = 0; i < TLS_TICKETS_NO; i++) {
943 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
944 goto found;
945 }
Christopher Faulet16f45c82018-02-16 11:23:49 +0100946 ret = 0;
947 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100948
Christopher Faulet16f45c82018-02-16 11:23:49 +0100949 found:
Emeric Brun9e754772019-01-10 17:51:55 +0100950 if (ref->key_size_bits == 128) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100951 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
952 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100953 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
954 goto end;
955 /* 2 for key renewal, 1 if current key is still valid */
956 ret = i ? 2 : 1;
957 }
958 else if (ref->key_size_bits == 256) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100959 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
960 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100961 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
962 goto end;
963 /* 2 for key renewal, 1 if current key is still valid */
964 ret = i ? 2 : 1;
965 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100966 }
Emeric Brun9e754772019-01-10 17:51:55 +0100967
Christopher Faulet16f45c82018-02-16 11:23:49 +0100968 end:
969 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
970 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200971}
972
973struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
974{
975 struct tls_keys_ref *ref;
976
977 list_for_each_entry(ref, &tlskeys_reference, list)
978 if (ref->filename && strcmp(filename, ref->filename) == 0)
979 return ref;
980 return NULL;
981}
982
983struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
984{
985 struct tls_keys_ref *ref;
986
987 list_for_each_entry(ref, &tlskeys_reference, list)
988 if (ref->unique_id == unique_id)
989 return ref;
990 return NULL;
991}
992
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500993/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +0100994 * match existing ones, this function returns -1
995 * else it returns 0 on success.
996 */
997int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +0200998 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +0100999{
Emeric Brun9e754772019-01-10 17:51:55 +01001000 if (ref->key_size_bits == 128) {
1001 if (tlskey->data != sizeof(struct tls_sess_key_128))
1002 return -1;
1003 }
1004 else if (ref->key_size_bits == 256) {
1005 if (tlskey->data != sizeof(struct tls_sess_key_256))
1006 return -1;
1007 }
1008 else
1009 return -1;
1010
Christopher Faulet16f45c82018-02-16 11:23:49 +01001011 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001012 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1013 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001014 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1015 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001016
1017 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001018}
1019
Willy Tarreau83061a82018-07-13 11:56:34 +02001020int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001021{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001022 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1023
1024 if(!ref) {
1025 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1026 return 1;
1027 }
Emeric Brun9e754772019-01-10 17:51:55 +01001028 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1029 memprintf(err, "Invalid key size");
1030 return 1;
1031 }
1032
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001033 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001034}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001035
1036/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001037 * automatic ids. It's called just after the basic checks. It returns
1038 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001039 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001040static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001041{
1042 int i = 0;
1043 struct tls_keys_ref *ref, *ref2, *ref3;
1044 struct list tkr = LIST_HEAD_INIT(tkr);
1045
1046 list_for_each_entry(ref, &tlskeys_reference, list) {
1047 if (ref->unique_id == -1) {
1048 /* Look for the first free id. */
1049 while (1) {
1050 list_for_each_entry(ref2, &tlskeys_reference, list) {
1051 if (ref2->unique_id == i) {
1052 i++;
1053 break;
1054 }
1055 }
1056 if (&ref2->list == &tlskeys_reference)
1057 break;
1058 }
1059
1060 /* Uses the unique id and increment it for the next entry. */
1061 ref->unique_id = i;
1062 i++;
1063 }
1064 }
1065
1066 /* This sort the reference list by id. */
1067 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001068 LIST_DELETE(&ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001069 list_for_each_entry(ref3, &tkr, list) {
1070 if (ref->unique_id < ref3->unique_id) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001071 LIST_APPEND(&ref3->list, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001072 break;
1073 }
1074 }
1075 if (&ref3->list == &tkr)
Willy Tarreau2b718102021-04-21 07:32:39 +02001076 LIST_APPEND(&tkr, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001077 }
1078
1079 /* swap root */
Willy Tarreau2b718102021-04-21 07:32:39 +02001080 LIST_INSERT(&tkr, &tlskeys_reference);
1081 LIST_DELETE(&tkr);
Christopher Fauletfc633b62020-11-06 15:24:23 +01001082 return ERR_NONE;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001083}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001084#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1085
William Lallemand4a660132019-10-14 14:51:41 +02001086
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001087#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001088/*
1089 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001090 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1091 * status extension, the issuer's certificate is mandatory. It should be
1092 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001093 *
William Lallemand246c0242019-10-11 08:59:13 +02001094 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1095 * OCSP response. If file is empty or content is not a valid OCSP response,
1096 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1097 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001098 *
1099 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001100 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001101 */
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001102static int ssl_sock_load_ocsp(SSL_CTX *ctx, struct ckch_data *data, STACK_OF(X509) *chain)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001103{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001104 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001105 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001106 struct certificate_ocsp *ocsp = NULL, *iocsp;
1107 char *warn = NULL;
1108 unsigned char *p;
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01001109#ifndef USE_OPENSSL_WOLFSSL
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001110 void (*callback) (void);
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01001111#else
1112 tlsextStatusCb callback;
1113#endif
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001114 struct buffer *ocsp_uri = get_trash_chunk();
Emeric Brun4147b2e2014-06-16 18:36:30 +02001115
Emeric Brun4147b2e2014-06-16 18:36:30 +02001116
William Lallemand52ddd992022-11-22 11:51:53 +01001117 x = data->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001118 if (!x)
1119 goto out;
1120
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001121 if (data->ocsp_update_mode == SSL_SOCK_OCSP_UPDATE_ON) {
1122 ssl_ocsp_get_uri_from_cert(x, ocsp_uri, NULL);
1123 /* We should have an "OCSP URI" field in order for auto update to work. */
1124 if (b_data(ocsp_uri) == 0)
1125 goto out;
1126 }
1127
1128 /* In case of ocsp update mode set to 'on', this function might be
1129 * called with no known ocsp response. If no ocsp uri can be found in
1130 * the certificate, nothing needs to be done here. */
1131 if (!data->ocsp_response) {
1132 if (data->ocsp_update_mode != SSL_SOCK_OCSP_UPDATE_ON || b_data(ocsp_uri) == 0) {
1133 ret = 0;
1134 goto out;
1135 }
1136 }
1137
William Lallemand52ddd992022-11-22 11:51:53 +01001138 issuer = data->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001139 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1140 if (chain) {
1141 /* check if one of the certificate of the chain is the issuer */
1142 for (i = 0; i < sk_X509_num(chain); i++) {
1143 X509 *ti = sk_X509_value(chain, i);
1144 if (X509_check_issued(ti, x) == X509_V_OK) {
1145 issuer = ti;
1146 break;
1147 }
1148 }
1149 }
William Lallemand246c0242019-10-11 08:59:13 +02001150 if (!issuer)
1151 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001152
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001153 data->ocsp_cid = OCSP_cert_to_id(0, x, issuer);
1154 if (!data->ocsp_cid)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001155 goto out;
1156
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001157 i = i2d_OCSP_CERTID(data->ocsp_cid, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001158 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1159 goto out;
1160
Vincent Bernat02779b62016-04-03 13:48:43 +02001161 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001162 if (!ocsp)
1163 goto out;
1164
1165 p = ocsp->key_data;
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001166 ocsp->key_length = i2d_OCSP_CERTID(data->ocsp_cid, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001167
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001168 HA_SPIN_LOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001169 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1170 if (iocsp == ocsp)
1171 ocsp = NULL;
1172
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001173#ifndef SSL_CTX_get_tlsext_status_cb
1174# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1175 *cb = (void (*) (void))ctx->tlsext_status_cb;
1176#endif
1177 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1178
1179 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001180 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001181 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001182
William Lallemanda560c062020-07-31 11:43:20 +02001183 cb_arg = calloc(1, sizeof(*cb_arg));
1184 if (!cb_arg)
1185 goto out;
1186
yanbzhube2774d2015-12-10 15:07:30 -05001187 cb_arg->is_single = 1;
1188 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001189 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001190
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001191 pkey = X509_get_pubkey(x);
1192 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1193 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001194
1195 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001196 SSL_CTX_set_ex_data(ctx, ocsp_ex_index, cb_arg); /* we use the ex_data instead of the cb_arg function here, so we can use the cleanup callback to free */
1197
yanbzhube2774d2015-12-10 15:07:30 -05001198 } else {
1199 /*
1200 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1201 * Update that cb_arg with the new cert's staple
1202 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001203 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001204 struct certificate_ocsp *tmp_ocsp;
1205 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001206 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001207 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001208
William Lallemand76b4a122020-08-04 17:41:39 +02001209 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001210
1211 /*
1212 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1213 * the order of operations below matter, take care when changing it
1214 */
1215 tmp_ocsp = cb_arg->s_ocsp;
1216 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1217 cb_arg->s_ocsp = NULL;
1218 cb_arg->m_ocsp[index] = tmp_ocsp;
1219 cb_arg->is_single = 0;
1220 cb_arg->single_kt = 0;
1221
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001222 pkey = X509_get_pubkey(x);
1223 key_type = EVP_PKEY_base_id(pkey);
1224 EVP_PKEY_free(pkey);
1225
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001226 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001227 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001228 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001229 iocsp->refcount++;
1230 }
yanbzhube2774d2015-12-10 15:07:30 -05001231 }
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001232 HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001233
1234 ret = 0;
1235
1236 warn = NULL;
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001237 if (data->ocsp_response && ssl_sock_load_ocsp_response(data->ocsp_response, iocsp, data->ocsp_cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001238 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001239 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001240 }
1241
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001242 if (data->ocsp_update_mode == SSL_SOCK_OCSP_UPDATE_ON) {
1243
1244 /* Do not insert the same certificate_ocsp structure in the
1245 * update tree more than once. */
1246 if (!ocsp) {
1247 iocsp->issuer = issuer;
1248 X509_up_ref(issuer);
1249 if (data->chain)
1250 iocsp->chain = X509_chain_up_ref(data->chain);
1251
1252 iocsp->uri = alloc_trash_chunk();
1253 if (!iocsp->uri)
1254 goto out;
1255 if (!chunk_cpy(iocsp->uri, ocsp_uri))
1256 goto out;
1257
1258 ssl_ocsp_update_insert(iocsp);
1259 }
1260 }
1261
Emeric Brun4147b2e2014-06-16 18:36:30 +02001262out:
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001263 if (ret && data->ocsp_cid)
1264 OCSP_CERTID_free(data->ocsp_cid);
1265
1266 if (!ret && data->ocsp_response) {
1267 ha_free(&data->ocsp_response->area);
1268 ha_free(&data->ocsp_response);
1269 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001270
1271 if (ocsp)
Remi Tricot-Le Bretonaa529f72022-11-03 15:16:49 +01001272 ssl_sock_free_ocsp(ocsp);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001273
1274 if (warn)
1275 free(warn);
1276
Emeric Brun4147b2e2014-06-16 18:36:30 +02001277 return ret;
1278}
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01001279
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001280#endif
1281
1282#ifdef OPENSSL_IS_BORINGSSL
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001283static int ssl_sock_load_ocsp(SSL_CTX *ctx, struct ckch_data *data, STACK_OF(X509) *chain)
Emmanuel Hocdet2c32d8f2017-05-22 14:58:00 +02001284{
William Lallemand4a660132019-10-14 14:51:41 +02001285 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 +02001286}
1287#endif
1288
William Lallemand4a660132019-10-14 14:51:41 +02001289
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001290#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001291
1292#define CT_EXTENSION_TYPE 18
1293
William Lallemand03c331c2020-05-13 10:10:01 +02001294int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001295
1296int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1297{
Willy Tarreau83061a82018-07-13 11:56:34 +02001298 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001299
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001300 *out = (unsigned char *) sctl->area;
1301 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001302
1303 return 1;
1304}
1305
1306int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1307{
1308 return 1;
1309}
1310
William Lallemanda17f4112019-10-10 15:16:44 +02001311static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001312{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001313 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001314
William Lallemanda17f4112019-10-10 15:16:44 +02001315 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 +01001316 goto out;
1317
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001318 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1319
1320 ret = 0;
1321
1322out:
1323 return ret;
1324}
1325
1326#endif
1327
Emeric Brune1f38db2012-09-03 20:36:47 +02001328void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1329{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001330 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001331#ifdef USE_QUIC
1332 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1333#endif /* USE_QUIC */
1334 struct ssl_sock_ctx *ctx = NULL;
1335
Emeric Brund8b2bb52014-01-28 15:43:53 +01001336 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001337 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001338
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001339 if (conn)
Willy Tarreau939b0bf2022-04-11 11:29:11 +02001340 ctx = conn_get_ssl_sock_ctx(conn);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001341#ifdef USE_QUIC
1342 else if (qc)
1343 ctx = qc->xprt_ctx;
1344#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01001345
1346 if (!ctx) {
1347 /* must never happen */
1348 ABORT_NOW();
1349 return;
1350 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001351
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001352#ifndef SSL_OP_NO_RENEGOTIATION
1353 /* Please note that BoringSSL defines this macro to zero so don't
1354 * change this to #if and do not assign a default value to this macro!
1355 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001356 if (where & SSL_CB_HANDSHAKE_START) {
1357 /* Disable renegotiation (CVE-2009-3555) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001358 if (conn && (conn->flags & (CO_FL_WAIT_L6_CONN | CO_FL_EARLY_SSL_HS | CO_FL_EARLY_DATA)) == 0) {
Emeric Brune1f38db2012-09-03 20:36:47 +02001359 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001360 conn->err_code = CO_ER_SSL_RENEG;
1361 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001362 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001363#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001364
1365 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001366 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001367 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001368 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001369 consider that the buffering was activated,
1370 so we rise the output buffer size from 4k
1371 to 16k */
1372 write_bio = SSL_get_wbio(ssl);
1373 if (write_bio != SSL_get_rbio(ssl)) {
1374 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001375 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001376 }
1377 }
1378 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001379}
1380
Emeric Brune64aef12012-09-21 13:15:06 +02001381/* Callback is called for each certificate of the chain during a verify
1382 ok is set to 1 if preverify detect no error on current certificate.
1383 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001384int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001385{
1386 SSL *ssl;
1387 struct connection *conn;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001388 struct ssl_sock_ctx *ctx = NULL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001389 int err, depth;
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001390 X509 *client_crt;
1391 STACK_OF(X509) *certs;
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001392 struct bind_conf *bind_conf = NULL;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001393 struct quic_conn *qc = NULL;
Emeric Brune64aef12012-09-21 13:15:06 +02001394
1395 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001396 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001397 client_crt = SSL_get_ex_data(ssl, ssl_client_crt_ref_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001398
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001399 if (conn) {
1400 bind_conf = __objt_listener(conn->target)->bind_conf;
1401 ctx = __conn_get_ssl_sock_ctx(conn);
1402 }
1403#ifdef USE_QUIC
1404 else {
1405 qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
Amaury Denoyelleba303de2022-10-17 18:46:49 +02001406 BUG_ON(!qc); /* Must never happen */
1407 bind_conf = qc->li->bind_conf;
1408 ctx = qc->xprt_ctx;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001409 }
1410#endif
1411
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001412 BUG_ON(!ctx || !bind_conf);
Christopher Faulet881cce92022-11-23 09:27:13 +01001413 ALREADY_CHECKED(ctx);
1414 ALREADY_CHECKED(bind_conf);
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001415
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001416 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001417
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001418 depth = X509_STORE_CTX_get_error_depth(x_store);
1419 err = X509_STORE_CTX_get_error(x_store);
1420
Emeric Brun81c00f02012-09-21 14:31:21 +02001421 if (ok) /* no errors */
1422 return ok;
1423
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001424 /* Keep a reference to the client's certificate in order to be able to
1425 * dump some fetches values in a log even when the verification process
1426 * fails. */
1427 if (depth == 0) {
1428 X509_free(client_crt);
1429 client_crt = X509_STORE_CTX_get0_cert(x_store);
1430 if (client_crt) {
1431 X509_up_ref(client_crt);
1432 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
1433 }
1434 }
1435 else {
1436 /* An error occurred on a CA certificate of the certificate
1437 * chain, we might never call this verify callback on the client
1438 * certificate's depth (which is 0) so we try to store the
1439 * reference right now. */
Remi Tricot-Le Bretonf95c2952021-08-20 09:51:23 +02001440 certs = X509_STORE_CTX_get1_chain(x_store);
1441 if (certs) {
1442 client_crt = sk_X509_value(certs, 0);
1443 if (client_crt) {
1444 X509_up_ref(client_crt);
1445 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001446 }
1447 sk_X509_pop_free(certs, X509_free);
1448 }
1449 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001450
1451 /* check if CA error needs to be ignored */
1452 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001453 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1454 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1455 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001456 }
1457
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01001458 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01001459 cert_ignerr_bitfield_get(bind_conf->ca_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001460 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02001461
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001462 /* TODO: for QUIC connection, this error code is lost */
1463 if (conn)
1464 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001465 return 0;
1466 }
1467
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001468 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1469 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001470
Emeric Brun81c00f02012-09-21 14:31:21 +02001471 /* check if certificate error needs to be ignored */
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01001472 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01001473 cert_ignerr_bitfield_get(bind_conf->crt_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001474 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02001475
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001476 /* TODO: for QUIC connection, this error code is lost */
1477 if (conn)
1478 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001479 return 0;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001480
1481 err_ignored:
1482 ssl_sock_dump_errors(conn, qc);
1483 ERR_clear_error();
1484 return 1;
Emeric Brune64aef12012-09-21 13:15:06 +02001485}
1486
Dragan Dosen9ac98092020-05-11 15:51:45 +02001487#ifdef TLS1_RT_HEARTBEAT
1488static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1489 int content_type, const void *buf, size_t len,
1490 SSL *ssl)
1491{
1492 /* test heartbeat received (write_p is set to 0
1493 for a received record) */
1494 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02001495 struct ssl_sock_ctx *ctx = __conn_get_ssl_sock_ctx(conn);
Dragan Dosen9ac98092020-05-11 15:51:45 +02001496 const unsigned char *p = buf;
1497 unsigned int payload;
1498
1499 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1500
1501 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1502 if (*p != TLS1_HB_REQUEST)
1503 return;
1504
1505 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1506 goto kill_it;
1507
1508 payload = (p[1] * 256) + p[2];
1509 if (3 + payload + 16 <= len)
1510 return; /* OK no problem */
1511 kill_it:
1512 /* We have a clear heartbleed attack (CVE-2014-0160), the
1513 * advertised payload is larger than the advertised packet
1514 * length, so we have garbage in the buffer between the
1515 * payload and the end of the buffer (p+len). We can't know
1516 * if the SSL stack is patched, and we don't know if we can
1517 * safely wipe out the area between p+3+len and payload.
1518 * So instead, we prevent the response from being sent by
1519 * setting the max_send_fragment to 0 and we report an SSL
1520 * error, which will kill this connection. It will be reported
1521 * above as SSL_ERROR_SSL while an other handshake failure with
1522 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1523 */
1524 ssl->max_send_fragment = 0;
1525 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1526 }
1527}
1528#endif
1529
1530static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1531 int content_type, const void *buf, size_t len,
1532 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001533{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001534 struct ssl_capture *capture;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001535 uchar *msg;
1536 uchar *end;
1537 uchar *extensions_end;
1538 uchar *ec_start = NULL;
1539 uchar *ec_formats_start = NULL;
1540 uchar *list_end;
1541 ushort protocol_version;
1542 ushort extension_id;
1543 ushort ec_len = 0;
1544 uchar ec_formats_len = 0;
1545 int offset = 0;
1546 int rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001547
1548 /* This function is called for "from client" and "to server"
1549 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001550 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001551 */
1552
1553 /* "write_p" is set to 0 is the bytes are received messages,
1554 * otherwise it is set to 1.
1555 */
1556 if (write_p != 0)
1557 return;
1558
1559 /* content_type contains the type of message received or sent
1560 * according with the SSL/TLS protocol spec. This message is
1561 * encoded with one byte. The value 256 (two bytes) is used
1562 * for designing the SSL/TLS record layer. According with the
1563 * rfc6101, the expected message (other than 256) are:
1564 * - change_cipher_spec(20)
1565 * - alert(21)
1566 * - handshake(22)
1567 * - application_data(23)
1568 * - (255)
1569 * We are interessed by the handshake and specially the client
1570 * hello.
1571 */
1572 if (content_type != 22)
1573 return;
1574
1575 /* The message length is at least 4 bytes, containing the
1576 * message type and the message length.
1577 */
1578 if (len < 4)
1579 return;
1580
1581 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001582 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001583 * - hello_request(0)
1584 * - client_hello(1)
1585 * - server_hello(2)
1586 * - certificate(11)
1587 * - server_key_exchange (12)
1588 * - certificate_request(13)
1589 * - server_hello_done(14)
1590 * We are interested by the client hello.
1591 */
1592 msg = (unsigned char *)buf;
1593 if (msg[0] != 1)
1594 return;
1595
1596 /* Next three bytes are the length of the message. The total length
1597 * must be this decoded length + 4. If the length given as argument
1598 * is not the same, we abort the protocol dissector.
1599 */
1600 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1601 if (len < rec_len + 4)
1602 return;
1603 msg += 4;
1604 end = msg + rec_len;
1605 if (end < msg)
1606 return;
1607
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001608 /* Expect 2 bytes for protocol version
1609 * (1 byte for major and 1 byte for minor)
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001610 */
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001611 if (msg + 2 > end)
1612 return;
1613 protocol_version = (msg[0] << 8) + msg[1];
1614 msg += 2;
1615
1616 /* Expect the random, composed by 4 bytes for the unix time and
1617 * 28 bytes for unix payload. So we jump 4 + 28.
1618 */
1619 msg += 4 + 28;
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001620 if (msg > end)
1621 return;
1622
1623 /* Next, is session id:
1624 * if present, we have to jump by length + 1 for the size information
1625 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001626 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001627 if (msg[0] > 0)
1628 msg += msg[0];
1629 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001630 if (msg > end)
1631 return;
1632
1633 /* Next two bytes are the ciphersuite length. */
1634 if (msg + 2 > end)
1635 return;
1636 rec_len = (msg[0] << 8) + msg[1];
1637 msg += 2;
1638 if (msg + rec_len > end || msg + rec_len < msg)
1639 return;
1640
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001641 capture = pool_zalloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001642 if (!capture)
1643 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001644 /* Compute the xxh64 of the ciphersuite. */
1645 capture->xxh64 = XXH64(msg, rec_len, 0);
1646
1647 /* Capture the ciphersuite. */
Marcin Deranek310a2602021-07-13 19:04:24 +02001648 capture->ciphersuite_len = MIN(global_ssl.capture_buffer_size, rec_len);
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001649 capture->ciphersuite_offset = 0;
1650 memcpy(capture->data, msg, capture->ciphersuite_len);
1651 msg += rec_len;
1652 offset += capture->ciphersuite_len;
1653
1654 /* Initialize other data */
1655 capture->protocol_version = protocol_version;
1656
1657 /* Next, compression methods:
1658 * if present, we have to jump by length + 1 for the size information
1659 * if not present, we have to jump by 1 only
1660 */
1661 if (msg[0] > 0)
1662 msg += msg[0];
1663 msg += 1;
1664 if (msg > end)
1665 goto store_capture;
1666
1667 /* We reached extensions */
1668 if (msg + 2 > end)
1669 goto store_capture;
1670 rec_len = (msg[0] << 8) + msg[1];
1671 msg += 2;
1672 if (msg + rec_len > end || msg + rec_len < msg)
1673 goto store_capture;
1674 extensions_end = msg + rec_len;
1675 capture->extensions_offset = offset;
1676
1677 /* Parse each extension */
1678 while (msg + 4 < extensions_end) {
1679 /* Add 2 bytes of extension_id */
Marcin Deranek310a2602021-07-13 19:04:24 +02001680 if (global_ssl.capture_buffer_size >= offset + 2) {
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001681 capture->data[offset++] = msg[0];
1682 capture->data[offset++] = msg[1];
1683 capture->extensions_len += 2;
1684 }
1685 else
1686 break;
1687 extension_id = (msg[0] << 8) + msg[1];
1688 /* Length of the extension */
1689 rec_len = (msg[2] << 8) + msg[3];
1690
1691 /* Expect 2 bytes extension id + 2 bytes extension size */
1692 msg += 2 + 2;
1693 if (msg + rec_len > extensions_end || msg + rec_len < msg)
1694 goto store_capture;
1695 /* TLS Extensions
1696 * https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml */
1697 if (extension_id == 0x000a) {
1698 /* Elliptic Curves:
1699 * https://www.rfc-editor.org/rfc/rfc8422.html
1700 * https://www.rfc-editor.org/rfc/rfc7919.html */
1701 list_end = msg + rec_len;
1702 if (msg + 2 > list_end)
1703 goto store_capture;
1704 rec_len = (msg[0] << 8) + msg[1];
1705 msg += 2;
1706
1707 if (msg + rec_len > list_end || msg + rec_len < msg)
1708 goto store_capture;
1709 /* Store location/size of the list */
1710 ec_start = msg;
1711 ec_len = rec_len;
1712 }
1713 else if (extension_id == 0x000b) {
1714 /* Elliptic Curves Point Formats:
1715 * https://www.rfc-editor.org/rfc/rfc8422.html */
1716 list_end = msg + rec_len;
1717 if (msg + 1 > list_end)
1718 goto store_capture;
1719 rec_len = msg[0];
1720 msg += 1;
1721
1722 if (msg + rec_len > list_end || msg + rec_len < msg)
1723 goto store_capture;
1724 /* Store location/size of the list */
1725 ec_formats_start = msg;
1726 ec_formats_len = rec_len;
1727 }
1728 msg += rec_len;
1729 }
1730
1731 if (ec_start) {
1732 rec_len = ec_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001733 if (offset + rec_len > global_ssl.capture_buffer_size)
1734 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001735 memcpy(capture->data + offset, ec_start, rec_len);
1736 capture->ec_offset = offset;
1737 capture->ec_len = rec_len;
1738 offset += rec_len;
1739 }
1740 if (ec_formats_start) {
1741 rec_len = ec_formats_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001742 if (offset + rec_len > global_ssl.capture_buffer_size)
1743 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001744 memcpy(capture->data + offset, ec_formats_start, rec_len);
1745 capture->ec_formats_offset = offset;
1746 capture->ec_formats_len = rec_len;
1747 offset += rec_len;
1748 }
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001749
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001750 store_capture:
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001751 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001752}
William Lallemand7d42ef52020-07-06 11:41:30 +02001753
1754
William Lallemand722180a2021-06-09 16:46:12 +02001755#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001756static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1757 int content_type, const void *buf, size_t len,
1758 SSL *ssl)
1759{
1760 struct ssl_keylog *keylog;
1761
1762 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1763 return;
1764
Willy Tarreauf208ac02021-03-22 21:10:12 +01001765 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02001766 if (!keylog)
1767 return;
1768
William Lallemand7d42ef52020-07-06 11:41:30 +02001769 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
1770 pool_free(pool_head_ssl_keylog, keylog);
1771 return;
1772 }
1773}
1774#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001775
Emeric Brun29f037d2014-04-25 19:05:36 +02001776/* Callback is called for ssl protocol analyse */
1777void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1778{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001779 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1780 struct ssl_sock_msg_callback *cbk;
1781
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001782 /* Try to call all callback functions that were registered by using
1783 * ssl_sock_register_msg_callback().
1784 */
1785 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1786 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1787 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001788}
1789
Bernard Spil13c53f82018-02-15 13:34:58 +01001790#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001791static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1792 const unsigned char *in, unsigned int inlen,
1793 void *arg)
1794{
1795 struct server *srv = arg;
1796
1797 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1798 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1799 return SSL_TLSEXT_ERR_OK;
1800 return SSL_TLSEXT_ERR_NOACK;
1801}
1802#endif
1803
1804#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001805/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001806 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001807 */
1808static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1809 unsigned int *len, void *arg)
1810{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001811 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001812
1813 *data = (const unsigned char *)conf->npn_str;
1814 *len = conf->npn_len;
1815 return SSL_TLSEXT_ERR_OK;
1816}
1817#endif
1818
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001819#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001820/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001821 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001822 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001823static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1824 unsigned char *outlen,
1825 const unsigned char *server,
1826 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001827{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001828 struct ssl_bind_conf *conf = arg;
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001829#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001830 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001831#endif
Willy Tarreauab861d32013-04-02 02:30:41 +02001832
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001833 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1834 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01001835#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001836 if (qc)
1837 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01001838#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001839 return SSL_TLSEXT_ERR_NOACK;
1840 }
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001841
1842#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001843 if (qc && !quic_set_app_ops(qc, *out, *outlen)) {
1844 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001845 return SSL_TLSEXT_ERR_NOACK;
1846 }
1847#endif
1848
Willy Tarreauab861d32013-04-02 02:30:41 +02001849 return SSL_TLSEXT_ERR_OK;
1850}
1851#endif
1852
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001853#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001854#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001855
cui flitera94bedc2022-08-29 14:42:57 +08001856/* Configure a DNS SAN extension on a certificate. */
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001857int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
1858 int failure = 0;
1859 X509_EXTENSION *san_ext = NULL;
1860 CONF *conf = NULL;
1861 struct buffer *san_name = get_trash_chunk();
1862
1863 conf = NCONF_new(NULL);
1864 if (!conf) {
1865 failure = 1;
1866 goto cleanup;
1867 }
1868
1869 /* Build an extension based on the DNS entry above */
1870 chunk_appendf(san_name, "DNS:%s", servername);
1871 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
1872 if (!san_ext) {
1873 failure = 1;
1874 goto cleanup;
1875 }
1876
1877 /* Add the extension */
1878 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
1879 failure = 1;
1880 goto cleanup;
1881 }
1882
1883 /* Success */
1884 failure = 0;
1885
1886cleanup:
1887 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
1888 if (NULL != conf) NCONF_free(conf);
1889
1890 return failure;
1891}
1892
Christopher Faulet30548802015-06-11 13:39:32 +02001893/* Create a X509 certificate with the specified servername and serial. This
1894 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001895static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001896ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001897{
Shimi Gersner5846c492020-08-23 13:58:12 +03001898 X509 *cacert = bind_conf->ca_sign_ckch->cert;
1899 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001900 SSL_CTX *ssl_ctx = NULL;
1901 X509 *newcrt = NULL;
1902 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001903 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001904 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001905 X509_NAME *name;
1906 const EVP_MD *digest;
1907 X509V3_CTX ctx;
1908 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001909 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001910
Christopher Faulet48a83322017-07-28 16:56:09 +02001911 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05001912#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001913 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1914#else
1915 tmp_ssl = SSL_new(bind_conf->default_ctx);
1916 if (tmp_ssl)
1917 pkey = SSL_get_privatekey(tmp_ssl);
1918#endif
1919 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001920 goto mkcert_error;
1921
1922 /* Create the certificate */
1923 if (!(newcrt = X509_new()))
1924 goto mkcert_error;
1925
1926 /* Set version number for the certificate (X509v3) and the serial
1927 * number */
1928 if (X509_set_version(newcrt, 2L) != 1)
1929 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02001930 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001931
1932 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001933 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1934 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001935 goto mkcert_error;
1936
1937 /* set public key in the certificate */
1938 if (X509_set_pubkey(newcrt, pkey) != 1)
1939 goto mkcert_error;
1940
1941 /* Set issuer name from the CA */
1942 if (!(name = X509_get_subject_name(cacert)))
1943 goto mkcert_error;
1944 if (X509_set_issuer_name(newcrt, name) != 1)
1945 goto mkcert_error;
1946
1947 /* Set the subject name using the same, but the CN */
1948 name = X509_NAME_dup(name);
1949 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1950 (const unsigned char *)servername,
1951 -1, -1, 0) != 1) {
1952 X509_NAME_free(name);
1953 goto mkcert_error;
1954 }
1955 if (X509_set_subject_name(newcrt, name) != 1) {
1956 X509_NAME_free(name);
1957 goto mkcert_error;
1958 }
1959 X509_NAME_free(name);
1960
1961 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001962 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001963 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1964 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1965 X509_EXTENSION *ext;
1966
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001967 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001968 goto mkcert_error;
1969 if (!X509_add_ext(newcrt, ext, -1)) {
1970 X509_EXTENSION_free(ext);
1971 goto mkcert_error;
1972 }
1973 X509_EXTENSION_free(ext);
1974 }
1975
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001976 /* Add SAN extension */
1977 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
1978 goto mkcert_error;
1979 }
1980
Christopher Faulet31af49d2015-06-09 17:29:50 +02001981 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001982
1983 key_type = EVP_PKEY_base_id(capkey);
1984
1985 if (key_type == EVP_PKEY_DSA)
1986 digest = EVP_sha1();
1987 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001988 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001989 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02001990 digest = EVP_sha256();
1991 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05001992#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02001993 int nid;
1994
1995 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
1996 goto mkcert_error;
1997 if (!(digest = EVP_get_digestbynid(nid)))
1998 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02001999#else
2000 goto mkcert_error;
2001#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02002002 }
2003
Christopher Faulet31af49d2015-06-09 17:29:50 +02002004 if (!(X509_sign(newcrt, capkey, digest)))
2005 goto mkcert_error;
2006
2007 /* Create and set the new SSL_CTX */
2008 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
2009 goto mkcert_error;
2010 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
2011 goto mkcert_error;
2012 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
2013 goto mkcert_error;
2014 if (!SSL_CTX_check_private_key(ssl_ctx))
2015 goto mkcert_error;
2016
Shimi Gersner5846c492020-08-23 13:58:12 +03002017 /* Build chaining the CA cert and the rest of the chain, keep these order */
2018#if defined(SSL_CTX_add1_chain_cert)
2019 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
2020 goto mkcert_error;
2021 }
2022
2023 if (bind_conf->ca_sign_ckch->chain) {
2024 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2025 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2026 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2027 goto mkcert_error;
2028 }
2029 }
2030 }
2031#endif
2032
Christopher Faulet31af49d2015-06-09 17:29:50 +02002033 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002034
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002035#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002036#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002037 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002038#else
2039 ssl_sock_set_tmp_dh_from_pkey(ssl_ctx, pkey);
2040#endif
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002041#endif
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002042
2043#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
2044#if defined(SSL_CTX_set1_curves_list)
2045 {
2046 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
2047 if (!SSL_CTX_set1_curves_list(ssl_ctx, ecdhe))
2048 goto end;
2049 }
2050#endif
2051#else
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002052#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2053 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002054 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002055 EC_KEY *ecc;
2056 int nid;
2057
2058 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2059 goto end;
2060 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2061 goto end;
2062 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2063 EC_KEY_free(ecc);
2064 }
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002065#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
2066#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002067 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002068 return ssl_ctx;
2069
2070 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002071 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002072 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002073 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2074 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002075 return NULL;
2076}
2077
Christopher Faulet7969a332015-10-09 11:15:03 +02002078
Christopher Faulet30548802015-06-11 13:39:32 +02002079/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002080 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002081SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002082ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002083{
2084 struct lru64 *lru = NULL;
2085
2086 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002087 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002088 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002089 if (lru && lru->domain) {
2090 if (ssl)
2091 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002092 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002093 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002094 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002095 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002096 }
2097 return NULL;
2098}
2099
Emeric Brun821bb9b2017-06-15 16:37:39 +02002100/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2101 * function is not thread-safe, it should only be used to check if a certificate
2102 * exists in the lru cache (with no warranty it will not be removed by another
2103 * thread). It is kept for backward compatibility. */
2104SSL_CTX *
2105ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2106{
2107 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2108}
2109
Christopher Fauletd2cab922015-07-28 16:03:47 +02002110/* Set a certificate int the LRU cache used to store generated
2111 * certificate. Return 0 on success, otherwise -1 */
2112int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002113ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002114{
2115 struct lru64 *lru = NULL;
2116
2117 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002118 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002119 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002120 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002121 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002122 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002123 }
Christopher Faulet30548802015-06-11 13:39:32 +02002124 if (lru->domain && lru->data)
2125 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002126 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002127 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002128 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002129 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002130 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002131}
2132
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002133/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002134unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002135ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002136{
2137 return XXH32(data, len, ssl_ctx_lru_seed);
2138}
2139
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002140/* Generate a cert and immediately assign it to the SSL session so that the cert's
2141 * refcount is maintained regardless of the cert's presence in the LRU cache.
2142 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002143static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002144ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002145{
Shimi Gersner5846c492020-08-23 13:58:12 +03002146 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002147 SSL_CTX *ssl_ctx = NULL;
2148 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002149 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002150
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002151 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002152 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002153 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002154 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002155 if (lru && lru->domain)
2156 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002157 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002158 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002159 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002160 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002161 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002162 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002163 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002164 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002165 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002166 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002167 SSL_set_SSL_CTX(ssl, ssl_ctx);
2168 /* No LRU cache, this CTX will be released as soon as the session dies */
2169 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002170 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002171 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002172 return 0;
2173}
2174static int
2175ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2176{
2177 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002178 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002179
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002180 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002181 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002182 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002183 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002184 }
2185 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002186}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002187#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002188
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002189#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002190
2191static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002192{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002193#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002194 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002195 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2196#endif
2197}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002198static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2199 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002200 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2201}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002202static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002203#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002204 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002205 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2206#endif
2207}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002208static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002209#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002210 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002211 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2212#endif
2213}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002214/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002215static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2216/* Unusable in this context. */
2217static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2218static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2219static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2220static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2221static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002222#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002223
2224static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2225 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002226 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2227}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002228static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2229 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2230 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2231}
2232static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2233 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002234 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2235}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002236static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2237 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2238 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2239}
2240static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2241 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002242 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2243}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002244static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2245 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2246 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2247}
2248static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2249 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002250 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2251}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002252static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2253 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2254 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2255}
2256static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002257#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002258 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002259 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2260#endif
2261}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002262static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002263#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002264 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2265 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002266#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002267}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002268#endif
2269static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2270static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002271
William Lallemand7fd8b452020-05-07 15:20:43 +02002272struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002273 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2274 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2275 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2276 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2277 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2278 {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 +02002279};
2280
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002281static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2282{
2283 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2284 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2285 SSL_set_SSL_CTX(ssl, ctx);
2286}
2287
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002288#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002289
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002290int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002291{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002292 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002293 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002294
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002295 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || (s->options & BC_O_GENERATE_CERTS))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002296 return SSL_TLSEXT_ERR_OK;
2297 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002298}
2299
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002300#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002301int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002302{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002303 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002304#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002305int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002306{
2307#endif
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002308 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2309#ifdef USE_QUIC
2310 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2311#endif /* USE_QUIC */
2312 struct bind_conf *s = NULL;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002313 const uint8_t *extension_data;
2314 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002315 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002316
2317 char *wildp = NULL;
2318 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002319 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002320 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002321 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002322 int i;
2323
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002324 if (conn)
2325 s = __objt_listener(conn->target)->bind_conf;
2326#ifdef USE_QUIC
2327 else if (qc)
2328 s = qc->li->bind_conf;
2329#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01002330
2331 if (!s) {
2332 /* must never happen */
2333 ABORT_NOW();
2334 return 0;
2335 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002336
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002337#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002338 if (qc) {
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002339 /* Look for the QUIC transport parameters. */
2340#ifdef OPENSSL_IS_BORINGSSL
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002341 if (!SSL_early_callback_ctx_extension_get(ctx, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002342 &extension_data, &extension_len))
2343#else
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002344 if (!SSL_client_hello_get0_ext(ssl, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002345 &extension_data, &extension_len))
2346#endif
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002347 {
2348 /* This is not redundant. It we only return 0 without setting
2349 * <*al>, this has as side effect to generate another TLS alert
2350 * which would be set after calling quic_set_tls_alert().
2351 */
2352 *al = SSL_AD_MISSING_EXTENSION;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002353 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002354 return 0;
2355 }
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002356
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002357 if (!quic_transport_params_store(qc, 0, extension_data,
Frédéric Lécaille301425b2022-06-14 17:40:39 +02002358 extension_data + extension_len) ||
2359 !qc_conn_finalize(qc, 0))
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002360 goto abort;
2361 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002362#endif /* USE_QUIC */
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002363
Olivier Houchard9679ac92017-10-27 14:58:08 +02002364 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002365 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002366#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002367 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2368 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002369#else
2370 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2371#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002372 /*
2373 * The server_name extension was given too much extensibility when it
2374 * was written, so parsing the normal case is a bit complex.
2375 */
2376 size_t len;
2377 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002378 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002379 /* Extract the length of the supplied list of names. */
2380 len = (*extension_data++) << 8;
2381 len |= *extension_data++;
2382 if (len + 2 != extension_len)
2383 goto abort;
2384 /*
2385 * The list in practice only has a single element, so we only consider
2386 * the first one.
2387 */
2388 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2389 goto abort;
2390 extension_len = len - 1;
2391 /* Now we can finally pull out the byte array with the actual hostname. */
2392 if (extension_len <= 2)
2393 goto abort;
2394 len = (*extension_data++) << 8;
2395 len |= *extension_data++;
2396 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2397 || memchr(extension_data, 0, len) != NULL)
2398 goto abort;
2399 servername = extension_data;
2400 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002401 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002402#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002403 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002404 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002405 }
2406#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002407 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002408 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002409 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002410 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002411 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002412 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002413 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002414 goto abort;
2415 }
2416
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002417 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002418#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002419 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002420#else
2421 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2422#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002423 uint8_t sign;
2424 size_t len;
2425 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002426 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002427 len = (*extension_data++) << 8;
2428 len |= *extension_data++;
2429 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002430 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002431 if (len % 2 != 0)
2432 goto abort;
2433 for (; len > 0; len -= 2) {
2434 extension_data++; /* hash */
2435 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002436 switch (sign) {
2437 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002438 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002439 break;
2440 case TLSEXT_signature_ecdsa:
2441 has_ecdsa_sig = 1;
2442 break;
2443 default:
2444 continue;
2445 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002446 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002447 break;
2448 }
2449 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002450 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002451 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002452 }
2453 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002454 const SSL_CIPHER *cipher;
2455 size_t len;
2456 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002457 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002458#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002459 len = ctx->cipher_suites_len;
2460 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002461#else
2462 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2463#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002464 if (len % 2 != 0)
2465 goto abort;
2466 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002467#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002468 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002469 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002470#else
2471 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2472#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002473 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002474 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002475 break;
2476 }
2477 }
2478 }
2479
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002480 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002481 trash.area[i] = tolower(servername[i]);
2482 if (!wildp && (trash.area[i] == '.'))
2483 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002484 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002485 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002486
William Lallemand150bfa82019-09-19 17:12:49 +02002487 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002488
William Lallemand94bd3192020-08-14 14:43:35 +02002489 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2490 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002491 for (i = 0; i < 2; i++) {
2492 if (i == 0) /* lookup in full qualified names */
2493 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002494 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002495 node = ebst_lookup(&s->sni_w_ctx, wildp);
2496 else
2497 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002498
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002499 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002500
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002501 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002502 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002503 struct sni_ctx *sni, *sni_tmp;
2504 int skip = 0;
2505
2506 if (i == 1 && wildp) { /* wildcard */
2507 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2508 sni = container_of(n, struct sni_ctx, name);
2509 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002510 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002511 skip = 1;
2512 break;
2513 }
2514 }
2515 if (skip)
2516 continue;
2517 }
2518
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002519 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002520 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002521 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002522 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002523 break;
2524 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002525 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002526 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002527 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002528 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002529 if (!node_anonymous)
2530 node_anonymous = n;
2531 break;
2532 }
2533 }
2534 }
William Lallemand94bd3192020-08-14 14:43:35 +02002535 }
2536 /* Once the certificates are found, select them depending on what is
2537 * supported in the client and by key_signature priority order: EDSA >
2538 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002539 if (has_ecdsa_sig && node_ecdsa)
2540 node = node_ecdsa;
2541 else if (has_rsa_sig && node_rsa)
2542 node = node_rsa;
2543 else if (node_anonymous)
2544 node = node_anonymous;
2545 else if (node_ecdsa)
2546 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2547 else
2548 node = node_rsa; /* no rsa signature case (far far away) */
2549
William Lallemand94bd3192020-08-14 14:43:35 +02002550 if (node) {
2551 /* switch ctx */
2552 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2553 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2554 if (conf) {
2555 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2556 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2557 if (conf->early_data)
2558 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002559 }
William Lallemand94bd3192020-08-14 14:43:35 +02002560 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2561 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002562 }
William Lallemand150bfa82019-09-19 17:12:49 +02002563
William Lallemand02010472019-10-18 11:02:19 +02002564 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002565#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002566 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002567 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002568 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002569 }
2570#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002571 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002572 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002573 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002574 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002575 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
William Lallemand7980dff2021-11-18 17:46:26 +01002576 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002577 }
William Lallemand7980dff2021-11-18 17:46:26 +01002578
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01002579 /* We are about to raise an handshake error so the servername extension
2580 * callback will never be called and the SNI will never be stored in the
2581 * SSL context. In order for the ssl_fc_sni sample fetch to still work
2582 * in such a case, we store the SNI ourselves as an ex_data information
2583 * in the SSL context.
2584 */
2585 {
2586 char *client_sni = pool_alloc(ssl_sock_client_sni_pool);
2587 if (client_sni) {
2588 strncpy(client_sni, trash.area, TLSEXT_MAXLEN_host_name);
2589 client_sni[TLSEXT_MAXLEN_host_name] = '\0';
2590 SSL_set_ex_data(ssl, ssl_client_sni_index, client_sni);
2591 }
2592 }
2593
William Lallemand7980dff2021-11-18 17:46:26 +01002594 /* other cases fallback on abort, if strict-sni is set but no node was found */
2595
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002596 abort:
2597 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002598 if (conn)
2599 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002600#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002601 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002602#else
2603 *al = SSL_AD_UNRECOGNIZED_NAME;
2604 return 0;
2605#endif
William Lallemand7980dff2021-11-18 17:46:26 +01002606
2607allow_early:
2608#ifdef OPENSSL_IS_BORINGSSL
2609 if (allow_early)
2610 SSL_set_early_data_enabled(ssl, 1);
2611#else
2612 if (!allow_early)
2613 SSL_set_max_early_data(ssl, 0);
2614#endif
2615 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002616}
2617
William Lallemand002e2062021-11-18 15:25:16 +01002618#else /* ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002619
Emeric Brunfc0421f2012-09-07 17:30:07 +02002620/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2621 * warning when no match is found, which implies the default (first) cert
2622 * will keep being used.
2623 */
William Lallemand844009d2022-09-02 15:27:32 +02002624int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002625{
2626 const char *servername;
2627 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002628 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002629 struct bind_conf *s = priv;
William Lallemand70a6e632022-09-07 11:21:34 +02002630#ifdef USE_QUIC
2631 const uint8_t *extension_data;
2632 size_t extension_len;
2633 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2634#endif /* USE_QUIC */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002635 int i;
2636 (void)al; /* shut gcc stupid warning */
2637
William Lallemand70a6e632022-09-07 11:21:34 +02002638#ifdef USE_QUIC
2639 if (qc) {
2640
2641 /* Look for the QUIC transport parameters. */
2642 SSL_get_peer_quic_transport_params(ssl, &extension_data, &extension_len);
2643 if (extension_len == 0) {
2644 /* This is not redundant. It we only return 0 without setting
2645 * <*al>, this has as side effect to generate another TLS alert
2646 * which would be set after calling quic_set_tls_alert().
2647 */
2648 *al = SSL_AD_MISSING_EXTENSION;
2649 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
2650 return SSL_TLSEXT_ERR_NOACK;
2651 }
2652
2653 if (!quic_transport_params_store(qc, 0, extension_data,
2654 extension_data + extension_len) ||
2655 !qc_conn_finalize(qc, 0)) {
2656 return SSL_TLSEXT_ERR_NOACK;
2657 }
2658 }
2659#endif /* USE_QUIC */
2660
Emeric Brunfc0421f2012-09-07 17:30:07 +02002661 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002662 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002663#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002664 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002665 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002666#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002667 if (s->strict_sni)
2668 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002669 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002670 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002671 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002672 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002673 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002674
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002675 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002676 if (!servername[i])
2677 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002678 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002679 if (!wildp && (trash.area[i] == '.'))
2680 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002681 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002682 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002683
William Lallemand150bfa82019-09-19 17:12:49 +02002684 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002685 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002686 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002687 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2688 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002689 if (!container_of(n, struct sni_ctx, name)->neg) {
2690 node = n;
2691 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002692 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002693 }
2694 if (!node && wildp) {
2695 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002696 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2697 /* lookup a not neg filter */
2698 if (!container_of(n, struct sni_ctx, name)->neg) {
2699 node = n;
2700 break;
2701 }
2702 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002703 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002704 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002705#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002706 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(servername, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002707 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002708 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002709 return SSL_TLSEXT_ERR_OK;
2710 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002711#endif
William Lallemand21724f02019-11-04 17:56:13 +01002712 if (s->strict_sni) {
2713 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002714 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002715 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002716 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002717 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002718 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002719 }
2720
2721 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002722 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002723 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002724 return SSL_TLSEXT_ERR_OK;
2725}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002726#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002727#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2728
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002729#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002730
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002731static inline HASSL_DH *ssl_new_dh_fromdata(BIGNUM *p, BIGNUM *g)
2732{
2733#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2734 OSSL_PARAM_BLD *tmpl = NULL;
2735 OSSL_PARAM *params = NULL;
2736 EVP_PKEY_CTX *ctx = NULL;
2737 EVP_PKEY *pkey = NULL;
2738
2739 if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
2740 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
2741 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)
2742 || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
2743 goto end;
2744 }
2745 ctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2746 if (ctx == NULL
2747 || !EVP_PKEY_fromdata_init(ctx)
2748 || !EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params)) {
2749 goto end;
2750 }
2751
2752end:
2753 EVP_PKEY_CTX_free(ctx);
2754 OSSL_PARAM_free(params);
2755 OSSL_PARAM_BLD_free(tmpl);
Remi Tricot-Le Bretona2c21db2022-11-03 15:16:47 +01002756 BN_free(p);
2757 BN_free(g);
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002758 return pkey;
2759#else
2760
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002761 HASSL_DH *dh = DH_new();
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002762
2763 if (!dh)
2764 return NULL;
2765
2766 DH_set0_pqg(dh, p, NULL, g);
2767
2768 return dh;
2769#endif
2770}
2771
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02002772#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002773static inline HASSL_DH *ssl_get_dh_by_nid(int nid)
2774{
2775#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2776 OSSL_PARAM params[2];
2777 EVP_PKEY *pkey = NULL;
2778 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2779 const char *named_group = NULL;
2780
2781 if (!pctx)
2782 goto end;
2783
2784 named_group = OBJ_nid2ln(nid);
2785
2786 if (!named_group)
2787 goto end;
2788
2789 params[0] = OSSL_PARAM_construct_utf8_string("group", (char*)named_group, 0);
2790 params[1] = OSSL_PARAM_construct_end();
2791
2792 if (EVP_PKEY_keygen_init(pctx) && EVP_PKEY_CTX_set_params(pctx, params))
2793 EVP_PKEY_generate(pctx, &pkey);
2794
2795end:
2796 EVP_PKEY_CTX_free(pctx);
2797 return pkey;
2798#else
2799
2800 HASSL_DH *dh = NULL;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002801 dh = DH_new_by_nid(nid);
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002802 return dh;
2803#endif
2804}
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02002805#endif
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002806
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002807
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002808static HASSL_DH * ssl_get_dh_1024(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002809{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002810 static unsigned char dh1024_p[]={
2811 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2812 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2813 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2814 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2815 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2816 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2817 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2818 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2819 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2820 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2821 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2822 };
2823 static unsigned char dh1024_g[]={
2824 0x02,
2825 };
2826
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002827 BIGNUM *p;
2828 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002829
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002830 HASSL_DH *dh = NULL;
2831
2832 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2833 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
2834
2835 if (p && g)
2836 dh = ssl_new_dh_fromdata(p, g);
2837
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002838 return dh;
2839}
2840
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002841static HASSL_DH *ssl_get_dh_2048(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002842{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002843#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02002844 static unsigned char dh2048_p[]={
2845 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2846 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2847 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2848 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2849 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2850 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2851 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2852 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2853 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2854 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2855 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2856 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2857 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2858 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2859 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2860 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2861 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2862 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2863 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2864 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2865 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2866 0xB7,0x1F,0x77,0xF3,
2867 };
2868 static unsigned char dh2048_g[]={
2869 0x02,
2870 };
2871
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002872 BIGNUM *p;
2873 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002874
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002875 HASSL_DH *dh = NULL;
2876
2877 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2878 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
2879
2880 if (p && g)
2881 dh = ssl_new_dh_fromdata(p, g);
2882
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002883 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002884#else
2885 return ssl_get_dh_by_nid(NID_ffdhe2048);
2886#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002887}
2888
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002889static HASSL_DH *ssl_get_dh_4096(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002890{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002891#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02002892 static unsigned char dh4096_p[]={
2893 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2894 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2895 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2896 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2897 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2898 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2899 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2900 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2901 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2902 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2903 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2904 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2905 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2906 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2907 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2908 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2909 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2910 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2911 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2912 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2913 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2914 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2915 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2916 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2917 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2918 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2919 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2920 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2921 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2922 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2923 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2924 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2925 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2926 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2927 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2928 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2929 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2930 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2931 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2932 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2933 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2934 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2935 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002936 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002937 static unsigned char dh4096_g[]={
2938 0x02,
2939 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002940
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002941 BIGNUM *p;
2942 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002943
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002944 HASSL_DH *dh = NULL;
2945
2946 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2947 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
2948
2949 if (p && g)
2950 dh = ssl_new_dh_fromdata(p, g);
2951
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002952 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002953#else
2954 return ssl_get_dh_by_nid(NID_ffdhe4096);
2955#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002956}
2957
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002958static HASSL_DH *ssl_get_tmp_dh(EVP_PKEY *pkey)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002959{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002960 HASSL_DH *dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002961 int type;
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002962 int keylen = 0;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002963
2964 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002965
Ilya Shipitsin52f2ff52022-07-23 23:55:19 +05002966 if (type == EVP_PKEY_EC) {
2967 keylen = global_ssl.default_dh_param;
2968 }
2969
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002970 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2971 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2972 */
2973 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2974 keylen = EVP_PKEY_bits(pkey);
2975 }
2976
Willy Tarreauef934602016-12-22 23:12:01 +01002977 if (keylen > global_ssl.default_dh_param) {
2978 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002979 }
2980
Remi Gacogned3a341a2015-05-29 16:26:17 +02002981 if (keylen >= 4096) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01002982 if (!local_dh_4096)
2983 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02002984 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002985 }
2986 else if (keylen >= 2048) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01002987 if (!local_dh_2048)
2988 local_dh_2048 = ssl_get_dh_2048();
Remi Gacogne8de54152014-07-15 11:36:40 +02002989 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002990 }
2991 else {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01002992 if (!local_dh_1024)
2993 local_dh_1024 = ssl_get_dh_1024();
Remi Gacogne8de54152014-07-15 11:36:40 +02002994 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002995 }
2996
2997 return dh;
2998}
2999
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003000#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003001/* Returns Diffie-Hellman parameters matching the private key length
3002 but not exceeding global_ssl.default_dh_param */
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003003static HASSL_DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003004{
3005 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
3006
3007 return ssl_get_tmp_dh(pkey);
3008}
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003009#endif
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003010
Remi Tricot-Le Breton846eda92022-02-11 12:04:50 +01003011static int ssl_sock_set_tmp_dh(SSL_CTX *ctx, HASSL_DH *dh)
3012{
3013#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
3014 return SSL_CTX_set_tmp_dh(ctx, dh);
3015#else
3016 int retval = 0;
3017 HASSL_DH_up_ref(dh);
3018
3019 retval = SSL_CTX_set0_tmp_dh_pkey(ctx, dh);
3020
3021 if (!retval)
3022 HASSL_DH_free(dh);
3023
3024 return retval;
3025#endif
3026}
3027
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003028#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3029static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey)
3030{
3031 HASSL_DH *dh = NULL;
3032 if (pkey && (dh = ssl_get_tmp_dh(pkey))) {
3033 HASSL_DH_up_ref(dh);
3034 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dh))
3035 HASSL_DH_free(dh);
3036 }
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003037}
3038#endif
3039
Remi Tricot-Le Breton09ebb332022-02-11 12:04:48 +01003040HASSL_DH *ssl_sock_get_dh_from_bio(BIO *bio)
3041{
3042#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3043 HASSL_DH *dh = NULL;
3044 OSSL_DECODER_CTX *dctx = NULL;
3045 const char *format = "PEM";
3046 const char *keytype = "DH";
3047
3048 dctx = OSSL_DECODER_CTX_new_for_pkey(&dh, format, NULL, keytype,
3049 OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
3050 NULL, NULL);
3051
3052 if (dctx == NULL || OSSL_DECODER_CTX_get_num_decoders(dctx) == 0)
3053 goto end;
3054
3055 /* The DH parameters might not be the first section found in the PEM
3056 * file so we need to iterate over all of them until we find the right
3057 * one.
3058 */
3059 while (!BIO_eof(bio) && !dh)
3060 OSSL_DECODER_from_bio(dctx, bio);
3061
3062end:
3063 OSSL_DECODER_CTX_free(dctx);
3064 return dh;
3065#else
3066 HASSL_DH *dh = NULL;
3067
3068 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3069
3070 return dh;
3071#endif
3072}
3073
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003074static HASSL_DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003075{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003076 HASSL_DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02003077 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003078
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003079 if (in == NULL)
3080 goto end;
3081
Remi Gacogne47783ef2015-05-29 15:53:22 +02003082 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003083 goto end;
3084
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003085 dh = ssl_sock_get_dh_from_bio(in);
Remi Gacogne47783ef2015-05-29 15:53:22 +02003086
3087end:
3088 if (in)
3089 BIO_free(in);
3090
Emeric Brune1b4ed42018-08-16 15:14:12 +02003091 ERR_clear_error();
3092
Remi Gacogne47783ef2015-05-29 15:53:22 +02003093 return dh;
3094}
3095
3096int ssl_sock_load_global_dh_param_from_file(const char *filename)
3097{
3098 global_dh = ssl_sock_get_dh_from_file(filename);
3099
3100 if (global_dh) {
3101 return 0;
3102 }
3103
3104 return -1;
3105}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003106#endif
3107
William Lallemand9117de92019-10-04 00:29:42 +02003108/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02003109static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02003110 struct bind_conf *s, struct ssl_bind_conf *conf,
3111 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003112{
3113 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003114 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003115
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003116 if (*name == '!') {
3117 neg = 1;
3118 name++;
3119 }
3120 if (*name == '*') {
3121 wild = 1;
3122 name++;
3123 }
3124 /* !* filter is a nop */
3125 if (neg && wild)
3126 return order;
3127 if (*name) {
3128 int j, len;
3129 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003130 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02003131 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003132 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02003133 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003134 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003135
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003136 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02003137 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02003138 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003139 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02003140 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003141 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003142 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003143 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003144 sc->order = order++;
3145 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02003146 sc->wild = wild;
3147 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01003148 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02003149 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003150 }
3151 return order;
3152}
3153
William Lallemand6af03992019-07-23 15:00:54 +02003154/*
William Lallemand1d29c742019-10-04 00:53:29 +02003155 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
3156 * This function can't return an error.
3157 *
3158 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
3159 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003160void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02003161{
3162
3163 struct sni_ctx *sc0, *sc0b, *sc1;
3164 struct ebmb_node *node;
3165
3166 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
3167
3168 /* ignore if sc0 was already inserted in a tree */
3169 if (sc0->name.node.leaf_p)
3170 continue;
3171
3172 /* Check for duplicates. */
3173 if (sc0->wild)
3174 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
3175 else
3176 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
3177
3178 for (; node; node = ebmb_next_dup(node)) {
3179 sc1 = ebmb_entry(node, struct sni_ctx, name);
3180 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
3181 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
3182 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02003183 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02003184 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003185 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02003186 break;
William Lallemand1d29c742019-10-04 00:53:29 +02003187 }
3188 }
3189
3190 /* if duplicate, ignore the insertion */
3191 if (!sc0)
3192 continue;
3193
3194 if (sc0->wild)
3195 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
3196 else
3197 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003198 }
William Lallemand21724f02019-11-04 17:56:13 +01003199
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003200 /* replace the default_ctx if required with the instance's ctx. */
3201 if (ckch_inst->is_default) {
3202 SSL_CTX_free(bind_conf->default_ctx);
3203 SSL_CTX_up_ref(ckch_inst->ctx);
3204 bind_conf->default_ctx = ckch_inst->ctx;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003205 bind_conf->default_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02003206 }
3207}
3208
3209/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003210 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02003211 */
William Lallemande3af8fb2019-10-08 11:36:53 +02003212struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02003213
William Lallemand2954c472020-03-06 21:54:13 +01003214/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02003215struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02003216
Emeric Brun7a883362019-10-17 13:27:40 +02003217/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003218 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02003219 * DH parameter is loaded into the SSL_CTX and if there is no
3220 * DH parameter available in ckchs nor in global, the default
3221 * DH parameters are applied on the SSL_CTX.
3222 * Returns a bitfield containing the flags:
3223 * ERR_FATAL in any fatal error case
3224 * ERR_ALERT if a reason of the error is availabine in err
3225 * ERR_WARN if a warning is available into err
3226 * The value 0 means there is no error nor warning and
3227 * the operation succeed.
3228 */
William Lallemandfa892222019-07-23 16:06:08 +02003229#ifndef OPENSSL_NO_DH
William Lallemand52ddd992022-11-22 11:51:53 +01003230static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct ckch_data *data,
Emeric Brun7a883362019-10-17 13:27:40 +02003231 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02003232{
Emeric Brun7a883362019-10-17 13:27:40 +02003233 int ret = 0;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003234 HASSL_DH *dh = NULL;
William Lallemandfa892222019-07-23 16:06:08 +02003235
William Lallemand52ddd992022-11-22 11:51:53 +01003236 if (data && data->dh) {
3237 dh = data->dh;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003238 if (!ssl_sock_set_tmp_dh(ctx, dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003239 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
3240 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003241 memprintf(err, "%s, DH ciphers won't be available.\n",
3242 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003243 ret |= ERR_WARN;
3244 goto end;
3245 }
William Lallemandfa892222019-07-23 16:06:08 +02003246
3247 if (ssl_dh_ptr_index >= 0) {
3248 /* store a pointer to the DH params to avoid complaining about
3249 ssl-default-dh-param not being set for this SSL_CTX */
3250 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
3251 }
3252 }
3253 else if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003254 if (!ssl_sock_set_tmp_dh(ctx, global_dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003255 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
3256 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003257 memprintf(err, "%s, DH ciphers won't be available.\n",
3258 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003259 ret |= ERR_WARN;
3260 goto end;
3261 }
William Lallemandfa892222019-07-23 16:06:08 +02003262 }
3263 else {
3264 /* Clear openssl global errors stack */
3265 ERR_clear_error();
3266
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003267 /* We do not want DHE ciphers to be added to the cipher list
3268 * unless there is an explicit global dh option in the conf.
3269 */
3270 if (global_ssl.default_dh_param) {
3271 if (global_ssl.default_dh_param <= 1024) {
3272 /* we are limited to DH parameter of 1024 bits anyway */
3273 if (local_dh_1024 == NULL)
3274 local_dh_1024 = ssl_get_dh_1024();
William Lallemandfa892222019-07-23 16:06:08 +02003275
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003276 if (local_dh_1024 == NULL) {
3277 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3278 err && *err ? *err : "", path);
3279 ret |= ERR_ALERT | ERR_FATAL;
3280 goto end;
3281 }
William Lallemandfa892222019-07-23 16:06:08 +02003282
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003283 if (!ssl_sock_set_tmp_dh(ctx, local_dh_1024)) {
3284 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3285 err && *err ? *err : "", path);
3286 memprintf(err, "%s, DH ciphers won't be available.\n",
3287 err && *err ? *err : "");
3288 ret |= ERR_WARN;
3289 goto end;
3290 }
Emeric Bruna9363eb2019-10-17 14:53:03 +02003291 }
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003292 else {
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003293#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003294 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003295#else
William Lallemand52ddd992022-11-22 11:51:53 +01003296 ssl_sock_set_tmp_dh_from_pkey(ctx, data ? data->key : NULL);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003297#endif
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003298 }
William Lallemandfa892222019-07-23 16:06:08 +02003299 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003300 }
3301
William Lallemandf9568fc2019-10-16 18:27:58 +02003302end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003303 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003304 return ret;
3305}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003306#endif
William Lallemandfa892222019-07-23 16:06:08 +02003307
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003308
3309/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003310 * Returns a bitfield containing the flags:
3311 * ERR_FATAL in any fatal error case
3312 * ERR_ALERT if the reason of the error is available in err
3313 * ERR_WARN if a warning is available into err
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003314 * The caller is responsible of freeing the newly built or newly refcounted
3315 * find_chain element.
Emeric Bruna96b5822019-10-17 13:25:14 +02003316 * The value 0 means there is no error nor warning and
3317 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003318 */
William Lallemand52ddd992022-11-22 11:51:53 +01003319static int ssl_sock_load_cert_chain(const char *path, const struct ckch_data *data,
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003320 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003321{
Emeric Bruna96b5822019-10-17 13:25:14 +02003322 int errcode = 0;
William Lallemand45fed2c2022-11-15 16:56:03 +01003323 int ret;
3324
3325 ERR_clear_error();
Emeric Bruna96b5822019-10-17 13:25:14 +02003326
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003327 if (find_chain == NULL) {
3328 errcode |= ERR_FATAL;
3329 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003330 }
3331
William Lallemand52ddd992022-11-22 11:51:53 +01003332 if (!SSL_CTX_use_certificate(ctx, data->cert)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003333 ret = ERR_get_error();
3334 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s': %s.\n",
3335 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Emeric Bruna96b5822019-10-17 13:25:14 +02003336 errcode |= ERR_ALERT | ERR_FATAL;
3337 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003338 }
3339
William Lallemand52ddd992022-11-22 11:51:53 +01003340 if (data->chain) {
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003341 *find_chain = X509_chain_up_ref(data->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003342 } else {
3343 /* Find Certificate Chain in global */
3344 struct issuer_chain *issuer;
William Lallemand52ddd992022-11-22 11:51:53 +01003345 issuer = ssl_get0_issuer_chain(data->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003346 if (issuer)
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003347 *find_chain = X509_chain_up_ref(issuer->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003348 }
William Lallemand85888572020-02-27 14:48:35 +01003349
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003350 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003351 /* always put a null chain stack in the SSL_CTX so it does not
3352 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003353 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003354 }
3355
William Lallemand52ddd992022-11-22 11:51:53 +01003356 /* Load all certs in the data into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003357#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003358 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003359 ret = ERR_get_error();
3360 memprintf(err, "%sunable to load chain certificate into SSL Context '%s': %s. Make sure you are linking against Openssl >= 1.0.2.\n",
3361 err && *err ? *err : "", path, ERR_reason_error_string(ret));
William Lallemand935d8292020-08-12 20:02:10 +02003362 errcode |= ERR_ALERT | ERR_FATAL;
3363 goto end;
3364 }
William Lallemandf187ce62020-06-02 18:27:20 +02003365#else
3366 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003367 X509 *ca;
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003368 while ((ca = sk_X509_shift(*find_chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003369 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003370 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3371 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003372 X509_free(ca);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003373 errcode |= ERR_ALERT | ERR_FATAL;
3374 goto end;
3375 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003376 }
William Lallemandf187ce62020-06-02 18:27:20 +02003377#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003378
William Lallemand9a1d8392020-08-10 17:28:23 +02003379#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003380 /* remove the Root CA from the SSL_CTX if the option is activated */
3381 if (global_ssl.skip_self_issued_ca) {
3382 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3383 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3384 err && *err ? *err : "", path);
3385 errcode |= ERR_ALERT | ERR_FATAL;
3386 goto end;
3387 }
3388 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003389#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003390
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003391end:
3392 return errcode;
3393}
3394
3395
3396/* Loads the info in ckch into ctx
3397 * Returns a bitfield containing the flags:
3398 * ERR_FATAL in any fatal error case
3399 * ERR_ALERT if the reason of the error is available in err
3400 * ERR_WARN if a warning is available into err
3401 * The value 0 means there is no error nor warning and
3402 * the operation succeed.
3403 */
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01003404static int ssl_sock_put_ckch_into_ctx(const char *path, struct ckch_data *data, SSL_CTX *ctx, char **err)
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003405{
3406 int errcode = 0;
3407 STACK_OF(X509) *find_chain = NULL;
3408
William Lallemand5de49512022-10-27 14:41:07 +02003409 ERR_clear_error();
3410
William Lallemand52ddd992022-11-22 11:51:53 +01003411 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
William Lallemand5de49512022-10-27 14:41:07 +02003412 int ret;
3413
3414 ret = ERR_get_error();
3415 memprintf(err, "%sunable to load SSL private key into SSL Context '%s': %s.\n",
3416 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003417 errcode |= ERR_ALERT | ERR_FATAL;
3418 return errcode;
3419 }
3420
3421 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01003422 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003423 if (errcode & ERR_CODE)
3424 goto end;
3425
William Lallemandfa892222019-07-23 16:06:08 +02003426#ifndef OPENSSL_NO_DH
3427 /* store a NULL pointer to indicate we have not yet loaded
3428 a custom DH param file */
3429 if (ssl_dh_ptr_index >= 0) {
3430 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3431 }
3432
William Lallemand52ddd992022-11-22 11:51:53 +01003433 errcode |= ssl_sock_load_dh_params(ctx, data, path, err);
Emeric Brun7a883362019-10-17 13:27:40 +02003434 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003435 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3436 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003437 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003438 }
3439#endif
3440
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003441#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemand52ddd992022-11-22 11:51:53 +01003442 if (sctl_ex_index >= 0 && data->sctl) {
3443 if (ssl_sock_load_sctl(ctx, data->sctl) < 0) {
William Lallemanda17f4112019-10-10 15:16:44 +02003444 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003445 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003446 errcode |= ERR_ALERT | ERR_FATAL;
3447 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003448 }
3449 }
3450#endif
3451
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003452#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01003453 /* Load OCSP Info into context
3454 * If OCSP update mode is set to 'on', an entry will be created in the
3455 * ocsp tree even if no ocsp_response was known during init, unless the
3456 * frontend's conf disables ocsp update explicitely.
3457 */
3458 if (ssl_sock_load_ocsp(ctx, data, find_chain) < 0) {
3459 if (data->ocsp_response)
Tim Duesterhus93128532019-11-23 23:45:10 +01003460 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",
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01003461 err && *err ? *err : "", path);
3462 else
3463 memprintf(err, "%s '%s' has an OCSP URI and OCSP auto-update is set to 'on' but an error occurred (maybe the issuer could not be found)'.\n",
3464 err && *err ? *err : "", path);
3465 errcode |= ERR_ALERT | ERR_FATAL;
3466 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003467 }
William Lallemand246c0242019-10-11 08:59:13 +02003468#endif
3469
Emeric Bruna96b5822019-10-17 13:25:14 +02003470 end:
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003471 sk_X509_pop_free(find_chain, X509_free);
Emeric Bruna96b5822019-10-17 13:25:14 +02003472 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003473}
3474
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003475
3476/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
3477 * Returns a bitfield containing the flags:
3478 * ERR_FATAL in any fatal error case
3479 * ERR_ALERT if the reason of the error is available in err
3480 * ERR_WARN if a warning is available into err
3481 * The value 0 means there is no error nor warning and
3482 * the operation succeed.
3483 */
William Lallemand52ddd992022-11-22 11:51:53 +01003484static int ssl_sock_put_srv_ckch_into_ctx(const char *path, const struct ckch_data *data,
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003485 SSL_CTX *ctx, char **err)
3486{
3487 int errcode = 0;
3488 STACK_OF(X509) *find_chain = NULL;
3489
3490 /* Load the private key */
William Lallemand52ddd992022-11-22 11:51:53 +01003491 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003492 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3493 err && *err ? *err : "", path);
3494 errcode |= ERR_ALERT | ERR_FATAL;
3495 }
3496
3497 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01003498 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003499 if (errcode & ERR_CODE)
3500 goto end;
3501
3502 if (SSL_CTX_check_private_key(ctx) <= 0) {
3503 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3504 err && *err ? *err : "", path);
3505 errcode |= ERR_ALERT | ERR_FATAL;
3506 }
3507
3508end:
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003509 sk_X509_pop_free(find_chain, X509_free);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003510 return errcode;
3511}
3512
3513
William Lallemand614ca0d2019-10-07 13:52:11 +02003514/*
3515 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003516 *
3517 * Returns a bitfield containing the flags:
3518 * ERR_FATAL in any fatal error case
3519 * ERR_ALERT if the reason of the error is available in err
3520 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003521 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003522int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003523 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003524{
William Lallemandc9402072019-05-15 15:33:54 +02003525 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003526 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003527 int order = 0;
3528 X509_NAME *xname;
3529 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003530 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003531 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003532#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3533 STACK_OF(GENERAL_NAME) *names;
3534#endif
William Lallemand52ddd992022-11-22 11:51:53 +01003535 struct ckch_data *data;
William Lallemand614ca0d2019-10-07 13:52:11 +02003536 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003537 int errcode = 0;
3538
3539 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003540
William Lallemand52ddd992022-11-22 11:51:53 +01003541 if (!ckchs || !ckchs->data)
Emeric Brun054563d2019-10-17 13:16:58 +02003542 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003543
William Lallemand52ddd992022-11-22 11:51:53 +01003544 data = ckchs->data;
William Lallemand36b84632019-07-18 19:28:17 +02003545
William Lallemandc9402072019-05-15 15:33:54 +02003546 ctx = SSL_CTX_new(SSLv23_server_method());
3547 if (!ctx) {
3548 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3549 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003550 errcode |= ERR_ALERT | ERR_FATAL;
3551 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003552 }
3553
William Lallemand52ddd992022-11-22 11:51:53 +01003554 errcode |= ssl_sock_put_ckch_into_ctx(path, data, ctx, err);
Emeric Bruna96b5822019-10-17 13:25:14 +02003555 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003556 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003557
3558 ckch_inst = ckch_inst_new();
3559 if (!ckch_inst) {
3560 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3561 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003562 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003563 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003564 }
3565
William Lallemand52ddd992022-11-22 11:51:53 +01003566 pkey = X509_get_pubkey(data->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003567 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003568 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003569 switch(EVP_PKEY_base_id(pkey)) {
3570 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003571 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003572 break;
3573 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003574 kinfo.sig = TLSEXT_signature_ecdsa;
3575 break;
3576 case EVP_PKEY_DSA:
3577 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003578 break;
3579 }
3580 EVP_PKEY_free(pkey);
3581 }
3582
Emeric Brun50bcecc2013-04-22 13:05:23 +02003583 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003584 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003585 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 +02003586 if (order < 0) {
3587 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003588 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003589 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003590 }
3591 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003592 }
3593 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003594#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand52ddd992022-11-22 11:51:53 +01003595 names = X509_get_ext_d2i(data->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003596 if (names) {
3597 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3598 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3599 if (name->type == GEN_DNS) {
3600 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003601 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003602 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003603 if (order < 0) {
3604 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003605 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003606 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003607 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003608 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003609 }
3610 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003611 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003612 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003613#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand52ddd992022-11-22 11:51:53 +01003614 xname = X509_get_subject_name(data->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003615 i = -1;
3616 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3617 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003618 ASN1_STRING *value;
3619
3620 value = X509_NAME_ENTRY_get_data(entry);
3621 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003622 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003623 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003624 if (order < 0) {
3625 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003626 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003627 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003628 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003629 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003630 }
3631 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003632 /* we must not free the SSL_CTX anymore below, since it's already in
3633 * the tree, so it will be discovered and cleaned in time.
3634 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003635
Emeric Brunfc0421f2012-09-07 17:30:07 +02003636#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003637 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003638 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3639 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003640 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003641 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003642 }
3643#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003644 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003645 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003646 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003647 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003648 SSL_CTX_up_ref(ctx);
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003649 bind_conf->default_inst = ckch_inst;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003650 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003651
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003652 /* Always keep a reference to the newly constructed SSL_CTX in the
3653 * instance. This way if the instance has no SNIs, the SSL_CTX will
3654 * still be linked. */
3655 SSL_CTX_up_ref(ctx);
3656 ckch_inst->ctx = ctx;
3657
William Lallemand9117de92019-10-04 00:29:42 +02003658 /* everything succeed, the ckch instance can be used */
3659 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003660 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003661 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003662
William Lallemand02e19a52020-04-08 16:11:26 +02003663 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3664
Emeric Brun054563d2019-10-17 13:16:58 +02003665 *ckchi = ckch_inst;
3666 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003667
3668error:
3669 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003670 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003671 if (ckch_inst->is_default)
3672 SSL_CTX_free(ctx);
3673
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003674 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003675 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003676 }
William Lallemandd9199372019-10-04 15:37:05 +02003677 SSL_CTX_free(ctx);
3678
Emeric Brun054563d2019-10-17 13:16:58 +02003679 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003680}
3681
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003682
3683/*
3684 * This function allocate a ckch_inst that will be used on the backend side
3685 * (server line)
3686 *
3687 * Returns a bitfield containing the flags:
3688 * ERR_FATAL in any fatal error case
3689 * ERR_ALERT if the reason of the error is available in err
3690 * ERR_WARN if a warning is available into err
3691 */
3692int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01003693 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003694{
3695 SSL_CTX *ctx;
William Lallemand52ddd992022-11-22 11:51:53 +01003696 struct ckch_data *data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003697 struct ckch_inst *ckch_inst = NULL;
3698 int errcode = 0;
3699
3700 *ckchi = NULL;
3701
William Lallemand52ddd992022-11-22 11:51:53 +01003702 if (!ckchs || !ckchs->data)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003703 return ERR_FATAL;
3704
William Lallemand52ddd992022-11-22 11:51:53 +01003705 data = ckchs->data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003706
3707 ctx = SSL_CTX_new(SSLv23_client_method());
3708 if (!ctx) {
3709 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3710 err && *err ? *err : "", path);
3711 errcode |= ERR_ALERT | ERR_FATAL;
3712 goto error;
3713 }
3714
William Lallemand52ddd992022-11-22 11:51:53 +01003715 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, data, ctx, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003716 if (errcode & ERR_CODE)
3717 goto error;
3718
3719 ckch_inst = ckch_inst_new();
3720 if (!ckch_inst) {
3721 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3722 err && *err ? *err : "", path);
3723 errcode |= ERR_ALERT | ERR_FATAL;
3724 goto error;
3725 }
3726
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003727 /* everything succeed, the ckch instance can be used */
3728 ckch_inst->bind_conf = NULL;
3729 ckch_inst->ssl_conf = NULL;
3730 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01003731 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003732 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003733
3734 *ckchi = ckch_inst;
3735 return errcode;
3736
3737error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003738 SSL_CTX_free(ctx);
3739
3740 return errcode;
3741}
3742
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003743/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003744static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3745 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003746 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003747{
Emeric Brun054563d2019-10-17 13:16:58 +02003748 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003749
3750 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003751 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 +02003752
Emeric Brun054563d2019-10-17 13:16:58 +02003753 if (errcode & ERR_CODE)
3754 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003755
William Lallemand24bde432020-03-09 16:48:43 +01003756 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003757
3758 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003759 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003760 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003761}
3762
William Lallemanddb26e2b2021-01-26 12:01:46 +01003763/* This function generates a <struct ckch_inst *> for a <struct server *>, and
3764 * fill the SSL_CTX of the server.
3765 *
3766 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003767static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01003768 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003769{
3770 int errcode = 0;
3771
3772 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01003773 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003774
3775 if (errcode & ERR_CODE)
3776 return errcode;
3777
William Lallemanddb26e2b2021-01-26 12:01:46 +01003778 (*ckch_inst)->server = server;
3779 /* Keep the reference to the SSL_CTX in the server. */
3780 SSL_CTX_up_ref((*ckch_inst)->ctx);
3781 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003782 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003783 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003784 return errcode;
3785}
3786
William Lallemand6be66ec2020-03-06 22:26:32 +01003787
William Lallemand4c68bba2020-03-30 18:45:10 +02003788
3789
3790/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3791 * done once. Zero is returned if the operation fails. No error is returned
3792 * if the random is said as not implemented, because we expect that openssl
3793 * will use another method once needed.
3794 */
Amaury Denoyellec593bcd2021-05-19 15:35:29 +02003795int ssl_initialize_random(void)
William Lallemand4c68bba2020-03-30 18:45:10 +02003796{
3797 unsigned char random;
3798 static int random_initialized = 0;
3799
3800 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3801 random_initialized = 1;
3802
3803 return random_initialized;
3804}
3805
William Lallemand2954c472020-03-06 21:54:13 +01003806/* Load a crt-list file, this is done in 2 parts:
3807 * - store the content of the file in a crtlist structure with crtlist_entry structures
3808 * - generate the instances by iterating on entries in the crtlist struct
3809 *
3810 * Nothing is locked there, this function is used in the configuration parser.
3811 *
3812 * Returns a set of ERR_* flags possibly with an error in <err>.
3813 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003814int 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 +01003815{
3816 struct crtlist *crtlist = NULL;
3817 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003818 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003819 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003820 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003821 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003822
William Lallemand79d31ec2020-03-25 15:10:49 +01003823 bind_conf_node = malloc(sizeof(*bind_conf_node));
3824 if (!bind_conf_node) {
3825 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3826 cfgerr |= ERR_FATAL | ERR_ALERT;
3827 goto error;
3828 }
3829 bind_conf_node->next = NULL;
3830 bind_conf_node->bind_conf = bind_conf;
3831
William Lallemand41ca9302020-04-08 13:15:18 +02003832 /* strip trailing slashes, including first one */
3833 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3834 *end = 0;
3835
William Lallemand2954c472020-03-06 21:54:13 +01003836 /* look for an existing crtlist or create one */
3837 eb = ebst_lookup(&crtlists_tree, file);
3838 if (eb) {
3839 crtlist = ebmb_entry(eb, struct crtlist, node);
3840 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003841 /* load a crt-list OR a directory */
3842 if (dir)
3843 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3844 else
3845 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3846
William Lallemand2954c472020-03-06 21:54:13 +01003847 if (!(cfgerr & ERR_CODE))
3848 ebst_insert(&crtlists_tree, &crtlist->node);
3849 }
3850
3851 if (cfgerr & ERR_CODE) {
3852 cfgerr |= ERR_FATAL | ERR_ALERT;
3853 goto error;
3854 }
3855
3856 /* generates ckch instance from the crtlist_entry */
3857 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3858 struct ckch_store *store;
3859 struct ckch_inst *ckch_inst = NULL;
3860
3861 store = entry->node.key;
3862 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3863 if (cfgerr & ERR_CODE) {
3864 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3865 goto error;
3866 }
Willy Tarreau2b718102021-04-21 07:32:39 +02003867 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003868 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003869 }
William Lallemand2954c472020-03-06 21:54:13 +01003870
William Lallemand79d31ec2020-03-25 15:10:49 +01003871 /* add the bind_conf to the list */
3872 bind_conf_node->next = crtlist->bind_conf;
3873 crtlist->bind_conf = bind_conf_node;
3874
William Lallemand2954c472020-03-06 21:54:13 +01003875 return cfgerr;
3876error:
3877 {
William Lallemand49398312020-03-30 17:01:33 +02003878 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003879 struct ckch_inst *inst, *s_inst;
3880
William Lallemand49398312020-03-30 17:01:33 +02003881 lastentry = entry; /* which entry we tried to generate last */
3882 if (lastentry) {
3883 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3884 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3885 break;
3886
3887 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003888
William Lallemand49398312020-03-30 17:01:33 +02003889 /* this was not generated for this bind_conf, skip */
3890 if (inst->bind_conf != bind_conf)
3891 continue;
3892
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003893 /* free the sni_ctx and instance */
3894 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003895 }
William Lallemand2954c472020-03-06 21:54:13 +01003896 }
William Lallemand2954c472020-03-06 21:54:13 +01003897 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003898 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003899 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003900 return cfgerr;
3901}
3902
William Lallemand06b22a82020-03-16 14:45:55 +01003903/* Returns a set of ERR_* flags possibly with an error in <err>. */
3904int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3905{
3906 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01003907 int cfgerr = 0;
3908 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003909 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01003910 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01003911
3912 if ((ckchs = ckchs_lookup(path))) {
3913 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01003914 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3915 found++;
3916 } else if (stat(path, &buf) == 0) {
3917 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01003918 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003919 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003920 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003921 cfgerr |= ERR_ALERT | ERR_FATAL;
3922 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003923 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01003924 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003925 }
3926 } else {
3927 /* stat failed, could be a bundle */
3928 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02003929 char fp[MAXPATHLEN+1] = {0};
3930 int n = 0;
3931
3932 /* Load all possible certs and keys in separate ckch_store */
3933 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3934 struct stat buf;
3935 int ret;
3936
3937 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3938 if (ret > sizeof(fp))
3939 continue;
3940
3941 if ((ckchs = ckchs_lookup(fp))) {
3942 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01003943 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02003944 } else {
3945 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01003946 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003947 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02003948 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003949 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02003950 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3951 }
3952 }
3953 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01003954#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
3955 if (found) {
3956 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
3957 err && *err ? *err : "", path);
3958 cfgerr |= ERR_ALERT | ERR_FATAL;
3959 }
3960#endif
William Lallemand06b22a82020-03-16 14:45:55 +01003961 }
3962 }
William Lallemand06ce84a2020-11-20 15:36:13 +01003963 if (!found) {
3964 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3965 err && *err ? *err : "", path, strerror(errno));
3966 cfgerr |= ERR_ALERT | ERR_FATAL;
3967 }
William Lallemand06b22a82020-03-16 14:45:55 +01003968
3969 return cfgerr;
3970}
3971
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003972
3973/* Create a full ssl context and ckch instance that will be used for a specific
3974 * backend server (server configuration line).
3975 * Returns a set of ERR_* flags possibly with an error in <err>.
3976 */
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02003977int ssl_sock_load_srv_cert(char *path, struct server *server, int create_if_none, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003978{
3979 struct stat buf;
3980 int cfgerr = 0;
3981 struct ckch_store *ckchs;
3982 int found = 0; /* did we found a file to load ? */
3983
3984 if ((ckchs = ckchs_lookup(path))) {
3985 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01003986 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003987 found++;
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02003988 } else {
3989 if (!create_if_none) {
3990 memprintf(err, "%sunable to stat SSL certificate '%s'.\n",
3991 err && *err ? *err : "", path);
3992 cfgerr |= ERR_ALERT | ERR_FATAL;
3993 goto out;
3994 }
3995
3996 if (stat(path, &buf) == 0) {
3997 /* We do not manage directories on backend side. */
3998 if (S_ISDIR(buf.st_mode) == 0) {
3999 ++found;
4000 ckchs = ckchs_load_cert_file(path, err);
4001 if (!ckchs)
4002 cfgerr |= ERR_ALERT | ERR_FATAL;
4003 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
4004 }
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004005 }
4006 }
4007 if (!found) {
4008 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
4009 err && *err ? *err : "", path, strerror(errno));
4010 cfgerr |= ERR_ALERT | ERR_FATAL;
4011 }
4012
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004013out:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004014 return cfgerr;
4015}
4016
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004017/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004018static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004019ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004020{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004021 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004022 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004023 SSL_OP_ALL | /* all known workarounds for bugs */
4024 SSL_OP_NO_SSLv2 |
4025 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02004026 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02004027 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004028 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02004029 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004030 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004031 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004032 SSL_MODE_ENABLE_PARTIAL_WRITE |
4033 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004034 SSL_MODE_RELEASE_BUFFERS |
4035 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004036 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004037 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004038 int flags = MC_SSL_O_ALL;
4039 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02004040 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004041
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004042 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004043 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004044
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004045 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004046 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
4047 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4048 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004049 else
4050 flags = conf_ssl_methods->flags;
4051
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004052 min = conf_ssl_methods->min;
4053 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02004054
4055 /* default minimum is TLSV12, */
4056 if (!min) {
4057 if (!max || (max >= default_min_ver)) {
4058 min = default_min_ver;
4059 } else {
4060 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). "
4061 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
4062 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
4063 min = max;
4064 }
4065 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004066 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004067 if (min)
4068 flags |= (methodVersions[min].flag - 1);
4069 if (max)
4070 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004071 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004072 min = max = CONF_TLSV_NONE;
4073 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004074 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004075 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004076 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004077 if (min) {
4078 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004079 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
4080 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4081 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
4082 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004083 hole = 0;
4084 }
4085 max = i;
4086 }
4087 else {
4088 min = max = i;
4089 }
4090 }
4091 else {
4092 if (min)
4093 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004094 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004095 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004096 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4097 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004098 cfgerr += 1;
4099 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004100 /* save real min/max in bind_conf */
4101 conf_ssl_methods->min = min;
4102 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004103
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004104#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004105 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004106 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004107 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004108 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004109 else
William Lallemandd0712f32020-06-11 17:34:00 +02004110 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
4111 /* clear every version flags in case SSL_CTX_new()
4112 * returns an SSL_CTX with disabled versions */
4113 SSL_CTX_clear_options(ctx, methodVersions[i].option);
4114
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004115 if (flags & methodVersions[i].flag)
4116 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02004117
4118 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004119#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004120 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004121 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4122 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02004123#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004124
4125 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
4126 options |= SSL_OP_NO_TICKET;
4127 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
4128 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08004129
4130#ifdef SSL_OP_NO_RENEGOTIATION
4131 options |= SSL_OP_NO_RENEGOTIATION;
4132#endif
4133
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004134 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004135
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004136#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004137 if (global_ssl.async)
4138 mode |= SSL_MODE_ASYNC;
4139#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004140 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004141 if (global_ssl.life_time)
4142 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004143
4144#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand4b7938d2022-09-07 10:54:17 +02004145# ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004146 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
4147 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004148# elif defined(HAVE_SSL_CLIENT_HELLO_CB)
4149# if defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01004150 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01004151 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
William Lallemand4b7938d2022-09-07 10:54:17 +02004152# endif /* ! SSL_OP_NO_ANTI_REPLAY */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02004153 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
4154 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004155# else /* ! OPENSSL_IS_BORINGSSL && ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004156 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004157# endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02004158 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
William Lallemand4b7938d2022-09-07 10:54:17 +02004159#endif /* ! SSL_CTRL_SET_TLSEXT_HOSTNAME */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004160 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004161}
4162
William Lallemand4f45bb92017-10-30 20:08:51 +01004163
4164static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
4165{
4166 if (first == block) {
4167 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4168 if (first->len > 0)
4169 sh_ssl_sess_tree_delete(sh_ssl_sess);
4170 }
4171}
4172
4173/* return first block from sh_ssl_sess */
4174static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
4175{
4176 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
4177
4178}
4179
4180/* store a session into the cache
4181 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
4182 * data: asn1 encoded session
4183 * data_len: asn1 encoded session length
4184 * Returns 1 id session was stored (else 0)
4185 */
4186static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
4187{
4188 struct shared_block *first;
4189 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
4190
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004191 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01004192 if (!first) {
4193 /* Could not retrieve enough free blocks to store that session */
4194 return 0;
4195 }
4196
4197 /* STORE the key in the first elem */
4198 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4199 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
4200 first->len = sizeof(struct sh_ssl_sess_hdr);
4201
4202 /* it returns the already existing node
4203 or current node if none, never returns null */
4204 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
4205 if (oldsh_ssl_sess != sh_ssl_sess) {
4206 /* NOTE: Row couldn't be in use because we lock read & write function */
4207 /* release the reserved row */
4208 shctx_row_dec_hot(ssl_shctx, first);
4209 /* replace the previous session already in the tree */
4210 sh_ssl_sess = oldsh_ssl_sess;
4211 /* ignore the previous session data, only use the header */
4212 first = sh_ssl_sess_first_block(sh_ssl_sess);
4213 shctx_row_inc_hot(ssl_shctx, first);
4214 first->len = sizeof(struct sh_ssl_sess_hdr);
4215 }
4216
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004217 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01004218 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004219 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01004220 }
4221
4222 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004223
4224 return 1;
4225}
William Lallemanded0b5ad2017-10-30 19:36:36 +01004226
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004227/* SSL callback used when a new session is created while connecting to a server */
4228static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4229{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004230 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004231 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004232
Willy Tarreau07d94e42018-09-20 10:57:52 +02004233 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004234
William Lallemand3ce6eed2021-02-08 10:43:44 +01004235 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4236 * one cache per thread, it only prevents to flush it from the CLI in
4237 * another thread */
4238
Olivier Houcharde6060c52017-11-16 17:42:52 +01004239 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4240 int len;
4241 unsigned char *ptr;
William Lallemande18d4e82021-11-17 02:59:21 +01004242 const char *sni;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004243
Olivier Houcharde6060c52017-11-16 17:42:52 +01004244 len = i2d_SSL_SESSION(sess, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01004245 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004246 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004247 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4248 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4249 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004250 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
4251 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004252 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4253 }
4254 if (s->ssl_ctx.reused_sess[tid].ptr) {
4255 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4256 &ptr);
4257 }
William Lallemande18d4e82021-11-17 02:59:21 +01004258
4259 if (s->ssl_ctx.reused_sess[tid].sni) {
4260 /* if the new sni is empty or isn' t the same as the old one */
4261 if ((!sni) || strcmp(s->ssl_ctx.reused_sess[tid].sni, sni) != 0) {
4262 ha_free(&s->ssl_ctx.reused_sess[tid].sni);
4263 if (sni)
4264 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4265 }
4266 } else if (sni) {
4267 /* if there wasn't an old sni but there is a new one */
4268 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4269 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004270 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004271 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004272 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004273 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004274 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004275 }
4276
4277 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004278}
4279
Olivier Houcharde6060c52017-11-16 17:42:52 +01004280
William Lallemanded0b5ad2017-10-30 19:36:36 +01004281/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004282int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004283{
4284 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4285 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4286 unsigned char *p;
4287 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004288 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004289 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004290
4291 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004292 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004293 * note: SSL_SESSION_set1_id is using
4294 * a memcpy so we need to use a different pointer
4295 * than sid_data or sid_ctx_data to avoid valgrind
4296 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004297 */
4298
4299 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004300
4301 /* copy value in an other buffer */
4302 memcpy(encid, sid_data, sid_length);
4303
4304 /* pad with 0 */
4305 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4306 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4307
4308 /* force length to zero to avoid ASN1 encoding */
4309 SSL_SESSION_set1_id(sess, encid, 0);
4310
4311 /* force length to zero to avoid ASN1 encoding */
4312 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004313
4314 /* check if buffer is large enough for the ASN1 encoded session */
4315 data_len = i2d_SSL_SESSION(sess, NULL);
4316 if (data_len > SHSESS_MAX_DATA_LEN)
4317 goto err;
4318
4319 p = encsess;
4320
4321 /* process ASN1 session encoding before the lock */
4322 i2d_SSL_SESSION(sess, &p);
4323
William Lallemanded0b5ad2017-10-30 19:36:36 +01004324
William Lallemanda3c77cf2017-10-30 23:44:40 +01004325 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004326 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004327 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004328 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004329err:
4330 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004331 SSL_SESSION_set1_id(sess, encid, sid_length);
4332 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004333
4334 return 0; /* do not increment session reference count */
4335}
4336
4337/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004338SSL_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 +01004339{
William Lallemand4f45bb92017-10-30 20:08:51 +01004340 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004341 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4342 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004343 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004344 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004345
Willy Tarreau4c19e992021-06-15 16:39:22 +02004346 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004347
4348 /* allow the session to be freed automatically by openssl */
4349 *do_copy = 0;
4350
4351 /* tree key is zeros padded sessionid */
4352 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4353 memcpy(tmpkey, key, key_len);
4354 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4355 key = tmpkey;
4356 }
4357
4358 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004359 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004360
4361 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004362 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4363 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004364 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004365 shctx_unlock(ssl_shctx);
Willy Tarreau4c19e992021-06-15 16:39:22 +02004366 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004367 return NULL;
4368 }
4369
William Lallemand4f45bb92017-10-30 20:08:51 +01004370 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4371 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004372
William Lallemand4f45bb92017-10-30 20:08:51 +01004373 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 +01004374
William Lallemanda3c77cf2017-10-30 23:44:40 +01004375 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004376
4377 /* decode ASN1 session */
4378 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004379 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004380 /* Reset session id and session id contenxt */
4381 if (sess) {
4382 SSL_SESSION_set1_id(sess, key, key_len);
4383 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4384 }
4385
4386 return sess;
4387}
4388
William Lallemand4f45bb92017-10-30 20:08:51 +01004389
William Lallemanded0b5ad2017-10-30 19:36:36 +01004390/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004391void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004392{
William Lallemand4f45bb92017-10-30 20:08:51 +01004393 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004394 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4395 unsigned int sid_length;
4396 const unsigned char *sid_data;
4397 (void)ctx;
4398
4399 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4400 /* tree key is zeros padded sessionid */
4401 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4402 memcpy(tmpkey, sid_data, sid_length);
4403 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4404 sid_data = tmpkey;
4405 }
4406
William Lallemanda3c77cf2017-10-30 23:44:40 +01004407 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004408
4409 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004410 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4411 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004412 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004413 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004414 }
4415
4416 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004417 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004418}
4419
4420/* Set session cache mode to server and disable openssl internal cache.
4421 * Set shared cache callbacks on an ssl context.
4422 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004423void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004424{
4425 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4426
4427 if (!ssl_shctx) {
4428 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4429 return;
4430 }
4431
4432 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4433 SSL_SESS_CACHE_NO_INTERNAL |
4434 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4435
4436 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004437 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4438 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4439 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004440}
William Lallemand7d42ef52020-07-06 11:41:30 +02004441
4442/*
4443 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4444 *
4445 * The format is:
4446 * * <Label> <space> <ClientRandom> <space> <Secret>
4447 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4448 */
4449
William Lallemand722180a2021-06-09 16:46:12 +02004450#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004451void SSL_CTX_keylog(const SSL *ssl, const char *line)
4452{
4453 struct ssl_keylog *keylog;
4454 char *lastarg = NULL;
4455 char *dst = NULL;
4456
4457 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4458 if (!keylog)
4459 return;
4460
4461 lastarg = strrchr(line, ' ');
4462 if (lastarg == NULL || ++lastarg == NULL)
4463 return;
4464
4465 dst = pool_alloc(pool_head_ssl_keylog_str);
4466 if (!dst)
4467 return;
4468
4469 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4470 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4471
4472 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4473 if (keylog->client_random)
4474 goto error;
4475 keylog->client_random = dst;
4476
4477 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4478 if (keylog->client_early_traffic_secret)
4479 goto error;
4480 keylog->client_early_traffic_secret = dst;
4481
4482 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4483 if(keylog->client_handshake_traffic_secret)
4484 goto error;
4485 keylog->client_handshake_traffic_secret = dst;
4486
4487 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4488 if (keylog->server_handshake_traffic_secret)
4489 goto error;
4490 keylog->server_handshake_traffic_secret = dst;
4491
4492 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4493 if (keylog->client_traffic_secret_0)
4494 goto error;
4495 keylog->client_traffic_secret_0 = dst;
4496
4497 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4498 if (keylog->server_traffic_secret_0)
4499 goto error;
4500 keylog->server_traffic_secret_0 = dst;
4501
4502 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4503 if (keylog->early_exporter_secret)
4504 goto error;
4505 keylog->early_exporter_secret = dst;
4506
4507 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4508 if (keylog->exporter_secret)
4509 goto error;
4510 keylog->exporter_secret = dst;
4511 } else {
4512 goto error;
4513 }
4514
4515 return;
4516
4517error:
4518 pool_free(pool_head_ssl_keylog_str, dst);
4519
4520 return;
4521}
4522#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004523
William Lallemand8b453912019-11-21 15:48:10 +01004524/*
4525 * This function applies the SSL configuration on a SSL_CTX
4526 * It returns an error code and fills the <err> buffer
4527 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004528static int 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 +01004529{
4530 struct proxy *curproxy = bind_conf->frontend;
4531 int cfgerr = 0;
4532 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004533 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004534 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004535#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004536 const char *conf_ciphersuites;
4537#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004538 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004539
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004540 if (ssl_conf) {
4541 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4542 int i, min, max;
4543 int flags = MC_SSL_O_ALL;
4544
4545 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004546 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4547 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004548 if (min)
4549 flags |= (methodVersions[min].flag - 1);
4550 if (max)
4551 flags |= ~((methodVersions[max].flag << 1) - 1);
4552 min = max = CONF_TLSV_NONE;
4553 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4554 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4555 if (min)
4556 max = i;
4557 else
4558 min = max = i;
4559 }
4560 /* save real min/max */
4561 conf_ssl_methods->min = min;
4562 conf_ssl_methods->max = max;
4563 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004564 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4565 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004566 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004567 }
4568 }
4569
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004570 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004571 case SSL_SOCK_VERIFY_NONE:
4572 verify = SSL_VERIFY_NONE;
4573 break;
4574 case SSL_SOCK_VERIFY_OPTIONAL:
4575 verify = SSL_VERIFY_PEER;
4576 break;
4577 case SSL_SOCK_VERIFY_REQUIRED:
4578 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4579 break;
4580 }
4581 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4582 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004583 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 +01004584 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 +01004585 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 +01004586 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004587 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004588 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004589 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004590 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004591 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004592 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004593 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4594 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4595 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4596 cfgerr |= ERR_ALERT | ERR_FATAL;
4597 }
4598 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004599 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004600 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 +02004601 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004602 }
Emeric Brun850efd52014-01-29 12:24:34 +01004603 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004604 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4605 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004606 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004607 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004608#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004609 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004610 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4611
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004612 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004613 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4614 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004615 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004616 }
Emeric Brun561e5742012-10-02 15:20:55 +02004617 else {
4618 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4619 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004620 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004621#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004622 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004623 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004624#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004625 if(bind_conf->keys_ref) {
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +01004626 if (!SSL_CTX_set_tlsext_ticket_key_evp_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004627 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4628 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004629 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004630 }
4631 }
4632#endif
4633
William Lallemand4f45bb92017-10-30 20:08:51 +01004634 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004635 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4636 if (conf_ciphers &&
4637 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004638 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4639 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004640 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004641 }
4642
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004643#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004644 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4645 if (conf_ciphersuites &&
4646 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004647 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4648 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004649 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004650 }
4651#endif
4652
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004653#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02004654 if (!local_dh_1024)
4655 local_dh_1024 = ssl_get_dh_1024();
4656 if (!local_dh_2048)
4657 local_dh_2048 = ssl_get_dh_2048();
4658 if (!local_dh_4096)
4659 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02004660#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004661
Emeric Brunfc0421f2012-09-07 17:30:07 +02004662 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004663#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004664 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004665#endif
William Lallemand722180a2021-06-09 16:46:12 +02004666#ifdef HAVE_SSL_KEYLOG
William Lallemandb60a77b2022-11-18 15:00:15 +01004667 /* only activate the keylog callback if it was required to prevent performance loss */
4668 if (global_ssl.keylog > 0)
4669 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02004670#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004671
Bernard Spil13c53f82018-02-15 13:34:58 +01004672#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004673 ssl_conf_cur = NULL;
4674 if (ssl_conf && ssl_conf->npn_str)
4675 ssl_conf_cur = ssl_conf;
4676 else if (bind_conf->ssl_conf.npn_str)
4677 ssl_conf_cur = &bind_conf->ssl_conf;
4678 if (ssl_conf_cur)
4679 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004680#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004681#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004682 ssl_conf_cur = NULL;
4683 if (ssl_conf && ssl_conf->alpn_str)
4684 ssl_conf_cur = ssl_conf;
4685 else if (bind_conf->ssl_conf.alpn_str)
4686 ssl_conf_cur = &bind_conf->ssl_conf;
4687 if (ssl_conf_cur)
4688 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004689#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004690#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004691 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4692 if (conf_curves) {
4693 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004694 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4695 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004696 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004697 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004698 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004699 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004700#endif /* defined(SSL_CTX_set1_curves_list) */
4701
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004702 if (!conf_curves) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004703#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004704#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004705 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004706 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4707 NULL);
4708
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004709 if (ecdhe && SSL_CTX_set1_curves_list(ctx, ecdhe) == 0) {
4710 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4711 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
4712 cfgerr |= ERR_ALERT | ERR_FATAL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02004713 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004714#endif /* defined(SSL_CTX_set1_curves_list) */
Olivier Houchardc2aae742017-09-22 18:26:28 +02004715#else
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004716#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
4717 int i;
4718 EC_KEY *ecdh;
4719
Olivier Houchardc2aae742017-09-22 18:26:28 +02004720 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4721 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4722 ECDHE_DEFAULT_CURVE);
Emeric Brun2b58d042012-09-20 17:10:03 +02004723
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004724 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004725 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004726 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004727 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004728 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004729 }
4730 else {
4731 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4732 EC_KEY_free(ecdh);
4733 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004734#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
4735#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Emeric Brun2b58d042012-09-20 17:10:03 +02004736 }
Emeric Brun2b58d042012-09-20 17:10:03 +02004737
Emeric Brunfc0421f2012-09-07 17:30:07 +02004738 return cfgerr;
4739}
4740
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004741
4742/*
4743 * Prepare the SSL_CTX based on the bind line configuration.
4744 * Since the CA file loading is made depending on the verify option of the bind
4745 * line, the link between the SSL_CTX and the CA file tree entry is made here.
4746 * If we want to create a link between the CA file entry and the corresponding
4747 * ckch instance (for CA file hot update), it needs to be done after
4748 * ssl_sock_prepare_ctx.
4749 * Returns 0 in case of success.
4750 */
4751int ssl_sock_prep_ctx_and_inst(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
4752 SSL_CTX *ctx, struct ckch_inst *ckch_inst, char **err)
4753{
4754 int errcode = 0;
4755
4756 errcode |= ssl_sock_prepare_ctx(bind_conf, ssl_conf, ctx, err);
4757 if (!errcode && ckch_inst)
4758 ckch_inst_add_cafile_link(ckch_inst, bind_conf, ssl_conf, NULL);
4759
4760 return errcode;
4761}
4762
Evan Broderbe554312013-06-27 00:05:25 -07004763static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4764{
4765 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4766 size_t prefixlen, suffixlen;
4767
4768 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004769 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004770 return 1;
4771
Evan Broderbe554312013-06-27 00:05:25 -07004772 /* The rest of this logic is based on RFC 6125, section 6.4.3
4773 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4774
Emeric Bruna848dae2013-10-08 11:27:28 +02004775 pattern_wildcard = NULL;
4776 pattern_left_label_end = pattern;
4777 while (*pattern_left_label_end != '.') {
4778 switch (*pattern_left_label_end) {
4779 case 0:
4780 /* End of label not found */
4781 return 0;
4782 case '*':
4783 /* If there is more than one wildcards */
4784 if (pattern_wildcard)
4785 return 0;
4786 pattern_wildcard = pattern_left_label_end;
4787 break;
4788 }
4789 pattern_left_label_end++;
4790 }
4791
4792 /* If it's not trivial and there is no wildcard, it can't
4793 * match */
4794 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004795 return 0;
4796
4797 /* Make sure all labels match except the leftmost */
4798 hostname_left_label_end = strchr(hostname, '.');
4799 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004800 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004801 return 0;
4802
4803 /* Make sure the leftmost label of the hostname is long enough
4804 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004805 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004806 return 0;
4807
4808 /* Finally compare the string on either side of the
4809 * wildcard */
4810 prefixlen = pattern_wildcard - pattern;
4811 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004812 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4813 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004814 return 0;
4815
4816 return 1;
4817}
4818
4819static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4820{
4821 SSL *ssl;
4822 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004823 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004824 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004825 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004826
4827 int depth;
4828 X509 *cert;
4829 STACK_OF(GENERAL_NAME) *alt_names;
4830 int i;
4831 X509_NAME *cert_subject;
4832 char *str;
4833
4834 if (ok == 0)
4835 return ok;
4836
4837 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004838 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02004839 ssl_ctx = __conn_get_ssl_sock_ctx(conn);
Evan Broderbe554312013-06-27 00:05:25 -07004840
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004841 /* We're checking if the provided hostnames match the desired one. The
4842 * desired hostname comes from the SNI we presented if any, or if not
4843 * provided then it may have been explicitly stated using a "verifyhost"
4844 * directive. If neither is set, we don't care about the name so the
4845 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004846 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004847 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004848 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004849 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004850 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004851 if (!servername)
4852 return ok;
4853 }
Evan Broderbe554312013-06-27 00:05:25 -07004854
4855 /* We only need to verify the CN on the actual server cert,
4856 * not the indirect CAs */
4857 depth = X509_STORE_CTX_get_error_depth(ctx);
4858 if (depth != 0)
4859 return ok;
4860
4861 /* At this point, the cert is *not* OK unless we can find a
4862 * hostname match */
4863 ok = 0;
4864
4865 cert = X509_STORE_CTX_get_current_cert(ctx);
4866 /* It seems like this might happen if verify peer isn't set */
4867 if (!cert)
4868 return ok;
4869
4870 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4871 if (alt_names) {
4872 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4873 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4874 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004875#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004876 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4877#else
Evan Broderbe554312013-06-27 00:05:25 -07004878 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004879#endif
Evan Broderbe554312013-06-27 00:05:25 -07004880 ok = ssl_sock_srv_hostcheck(str, servername);
4881 OPENSSL_free(str);
4882 }
4883 }
4884 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004885 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004886 }
4887
4888 cert_subject = X509_get_subject_name(cert);
4889 i = -1;
4890 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4891 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004892 ASN1_STRING *value;
4893 value = X509_NAME_ENTRY_get_data(entry);
4894 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004895 ok = ssl_sock_srv_hostcheck(str, servername);
4896 OPENSSL_free(str);
4897 }
4898 }
4899
Willy Tarreau71d058c2017-07-26 20:09:56 +02004900 /* report the mismatch and indicate if SNI was used or not */
4901 if (!ok && !conn->err_code)
4902 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004903 return ok;
4904}
4905
Emeric Brun94324a42012-10-11 14:00:19 +02004906/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004907int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004908{
4909 int cfgerr = 0;
William Lallemand2c776f12021-12-28 18:47:17 +01004910 SSL_CTX *ctx;
William Lallemand0adafb32022-12-13 18:17:44 +01004911 /* Automatic memory computations need to know we use SSL there
4912 * If this is an internal proxy, don't use it for the computation */
William Lallemand04007cb2022-12-14 10:34:36 +01004913 if (!(srv->proxy->cap & PR_CAP_INT))
William Lallemand0adafb32022-12-13 18:17:44 +01004914 global.ssl_used_backend = 1;
Willy Tarreaufce03112015-01-15 21:32:40 +01004915
4916 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004917 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004918 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004919 ha_alert("out of memory.\n");
Emeric Brun821bb9b2017-06-15 16:37:39 +02004920 cfgerr++;
4921 return cfgerr;
4922 }
4923 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004924 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004925 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004926
William Lallemand2c776f12021-12-28 18:47:17 +01004927 if (srv->ssl_ctx.client_crt) {
4928 const int create_if_none = srv->flags & SRV_F_DYNAMIC ? 0 : 1;
4929 char *err = NULL;
4930 int err_code = 0;
4931
4932 /* If there is a crt keyword there, the SSL_CTX will be created here. */
4933 err_code = ssl_sock_load_srv_cert(srv->ssl_ctx.client_crt, srv, create_if_none, &err);
4934 if (err_code != ERR_NONE) {
4935 if ((err_code & ERR_WARN) && !(err_code & ERR_ALERT))
4936 ha_warning("%s", err);
4937 else
4938 ha_alert("%s", err);
4939
4940 if (err_code & (ERR_FATAL|ERR_ABORT))
4941 cfgerr++;
4942 }
4943 ha_free(&err);
4944 }
4945
4946 ctx = srv->ssl_ctx.ctx;
4947
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004948 /* The context will be uninitialized if there wasn't any "cert" option
4949 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004950 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004951 ctx = SSL_CTX_new(SSLv23_client_method());
4952 if (!ctx) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004953 ha_alert("unable to allocate ssl context.\n");
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004954 cfgerr++;
4955 return cfgerr;
4956 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004957
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004958 srv->ssl_ctx.ctx = ctx;
4959 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004960
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004961 cfgerr += ssl_sock_prep_srv_ctx_and_inst(srv, srv->ssl_ctx.ctx, srv->ssl_ctx.inst);
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004962
4963 return cfgerr;
4964}
4965
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004966/* Initialize an SSL context that will be used on the backend side.
4967 * Returns an error count.
4968 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004969static int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004970{
4971 struct proxy *curproxy = srv->proxy;
4972 int cfgerr = 0;
4973 long options =
4974 SSL_OP_ALL | /* all known workarounds for bugs */
4975 SSL_OP_NO_SSLv2 |
4976 SSL_OP_NO_COMPRESSION;
4977 long mode =
4978 SSL_MODE_ENABLE_PARTIAL_WRITE |
4979 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
4980 SSL_MODE_RELEASE_BUFFERS |
4981 SSL_MODE_SMALL_BUFFERS;
4982 int verify = SSL_VERIFY_NONE;
4983 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
4984 int i, min, max, hole;
4985 int flags = MC_SSL_O_ALL;
4986
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004987 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004988 ha_warning("no-sslv3/no-tlsv1x are ignored for this server. "
4989 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n");
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004990 else
4991 flags = conf_ssl_methods->flags;
4992
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004993 /* Real min and max should be determinate with configuration and openssl's capabilities */
4994 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004995 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004996 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004997 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004998
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004999 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005000 min = max = CONF_TLSV_NONE;
5001 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005002 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005003 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005004 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005005 if (min) {
5006 if (hole) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005007 ha_warning("%s '%s': SSL/TLS versions range not contiguous for server '%s'. "
Christopher Faulet767a84b2017-11-24 16:50:31 +01005008 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
5009 proxy_type_str(curproxy), curproxy->id, srv->id,
5010 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005011 hole = 0;
5012 }
5013 max = i;
5014 }
5015 else {
5016 min = max = i;
5017 }
5018 }
5019 else {
5020 if (min)
5021 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005022 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005023 if (!min) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005024 ha_alert("%s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01005025 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005026 cfgerr += 1;
5027 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005028
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005029#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005030 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08005031 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005032 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005033 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005034 else
5035 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
5036 if (flags & methodVersions[i].flag)
5037 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005038#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005039 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005040 methodVersions[min].ctx_set_version(ctx, SET_MIN);
5041 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005042#endif
5043
5044 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
5045 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005046 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005047
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005048#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005049 if (global_ssl.async)
5050 mode |= SSL_MODE_ASYNC;
5051#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005052 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005053
Emeric Brun850efd52014-01-29 12:24:34 +01005054 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
5055 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01005056 switch (srv->ssl_ctx.verify) {
5057 case SSL_SOCK_VERIFY_NONE:
5058 verify = SSL_VERIFY_NONE;
5059 break;
5060 case SSL_SOCK_VERIFY_REQUIRED:
5061 verify = SSL_VERIFY_PEER;
5062 break;
5063 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005064 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02005065 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01005066 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02005067 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02005068 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005069 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005070 ha_alert("unable to set CA file '%s'.\n",
5071 srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005072 cfgerr++;
5073 }
5074 }
Emeric Brun850efd52014-01-29 12:24:34 +01005075 else {
5076 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005077 ha_alert("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");
Emeric Brun850efd52014-01-29 12:24:34 +01005078 else
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005079 ha_alert("verify is enabled but no CA file specified.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01005080 cfgerr++;
5081 }
Emeric Brunef42d922012-10-11 16:11:36 +02005082#ifdef X509_V_FLAG_CRL_CHECK
5083 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005084 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02005085
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01005086 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005087 ha_alert("unable to configure CRL file '%s'.\n",
5088 srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005089 cfgerr++;
5090 }
5091 else {
5092 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5093 }
5094 }
5095#endif
5096 }
5097
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005098 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5099 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02005100 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005101 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005102 ha_alert("unable to set SSL cipher list to '%s'.\n",
5103 srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02005104 cfgerr++;
5105 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005106
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05005107#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005108 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005109 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005110 ha_alert("unable to set TLS 1.3 cipher suites to '%s'.\n",
5111 srv->ssl_ctx.ciphersuites);
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005112 cfgerr++;
5113 }
5114#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01005115#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
5116 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005117 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01005118#endif
5119#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5120 if (srv->ssl_ctx.alpn_str)
5121 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
5122#endif
5123
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005124
5125 return cfgerr;
5126}
5127
5128/*
5129 * Prepare the frontend's SSL_CTX based on the server line configuration.
5130 * Since the CA file loading is made depending on the verify option of the
5131 * server line, the link between the SSL_CTX and the CA file tree entry is
5132 * made here.
5133 * If we want to create a link between the CA file entry and the corresponding
5134 * ckch instance (for CA file hot update), it needs to be done after
5135 * ssl_sock_prepare_srv_ssl_ctx.
5136 * Returns an error count.
5137 */
5138int ssl_sock_prep_srv_ctx_and_inst(const struct server *srv, SSL_CTX *ctx,
5139 struct ckch_inst *ckch_inst)
5140{
5141 int cfgerr = 0;
5142
5143 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, ctx);
5144 if (!cfgerr && ckch_inst)
5145 ckch_inst_add_cafile_link(ckch_inst, NULL, NULL, srv);
Emeric Brun94324a42012-10-11 14:00:19 +02005146
5147 return cfgerr;
5148}
5149
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005150
Frédéric Lécailleec216522020-11-23 14:33:30 +01005151/*
5152 * Create an initial CTX used to start the SSL connections.
5153 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
5154 * Returns 0 if succeeded, or something >0 if not.
5155 */
5156#ifdef USE_QUIC
5157static int ssl_initial_ctx(struct bind_conf *bind_conf)
5158{
5159 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
5160 return ssl_quic_initial_ctx(bind_conf);
5161 else
5162 return ssl_sock_initial_ctx(bind_conf);
5163}
5164#else
5165static int ssl_initial_ctx(struct bind_conf *bind_conf)
5166{
5167 return ssl_sock_initial_ctx(bind_conf);
5168}
5169#endif
5170
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005171/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005172 * be NULL, in which case nothing is done. Returns the number of errors
5173 * encountered.
5174 */
Willy Tarreau03209342016-12-22 17:08:28 +01005175int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005176{
5177 struct ebmb_node *node;
5178 struct sni_ctx *sni;
5179 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01005180 int errcode = 0;
5181 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02005182
Willy Tarreaufce03112015-01-15 21:32:40 +01005183 /* Automatic memory computations need to know we use SSL there */
5184 global.ssl_used_frontend = 1;
5185
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005186 /* Create initial_ctx used to start the ssl connection before do switchctx */
5187 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01005188 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005189 /* It should not be necessary to call this function, but it's
5190 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01005191 to initial_ctx in ssl_initial_ctx. */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005192 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, NULL, bind_conf->initial_ctx, NULL, &errmsg);
5193 }
5194 if (bind_conf->default_ctx) {
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005195 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, bind_conf->default_ssl_conf, bind_conf->default_ctx, bind_conf->default_inst, &errmsg);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005196 }
Emeric Brun0bed9942014-10-30 19:25:24 +01005197
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005198 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005199 while (node) {
5200 sni = ebmb_entry(node, struct sni_ctx, name);
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005201 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005202 /* only initialize the CTX on its first occurrence and
5203 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005204 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
5205 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005206 node = ebmb_next(node);
5207 }
5208
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005209 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005210 while (node) {
5211 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01005212 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005213 /* only initialize the CTX on its first occurrence and
5214 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005215 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005216 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005217 node = ebmb_next(node);
5218 }
William Lallemand8b453912019-11-21 15:48:10 +01005219
5220 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005221 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005222 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005223 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005224 err++;
5225 }
5226
5227 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005228 return err;
5229}
5230
Willy Tarreau55d37912016-12-21 23:38:39 +01005231/* Prepares all the contexts for a bind_conf and allocates the shared SSL
5232 * context if needed. Returns < 0 on error, 0 on success. The warnings and
5233 * alerts are directly emitted since the rest of the stack does it below.
5234 */
5235int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
5236{
5237 struct proxy *px = bind_conf->frontend;
5238 int alloc_ctx;
5239 int err;
5240
Willy Tarreau11ba4042022-05-20 15:56:32 +02005241 if (!(bind_conf->options & BC_O_USE_SSL)) {
Willy Tarreau55d37912016-12-21 23:38:39 +01005242 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005243 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
5244 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01005245 }
5246 return 0;
5247 }
5248 if (!bind_conf->default_ctx) {
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005249 if (bind_conf->strict_sni && !(bind_conf->options & BC_O_GENERATE_CERTS)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005250 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5251 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005252 }
5253 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005254 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5255 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005256 return -1;
5257 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005258 }
William Lallemandc61c0b32017-12-04 18:46:39 +01005259 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005260 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02005261 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
Willy Tarreau91358592021-06-15 08:08:04 +02005262 sizeof(*sh_ssl_sess_tree), (global.nbthread > 1));
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02005263 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005264 if (alloc_ctx == SHCTX_E_INIT_LOCK)
5265 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");
5266 else
5267 ha_alert("Unable to allocate SSL session cache.\n");
5268 return -1;
5269 }
5270 /* free block callback */
5271 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5272 /* init the root tree within the extra space */
5273 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5274 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01005275 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005276 err = 0;
5277 /* initialize all certificate contexts */
5278 err += ssl_sock_prepare_all_ctx(bind_conf);
5279
5280 /* initialize CA variables if the certificates generation is enabled */
5281 err += ssl_sock_load_ca(bind_conf);
5282
5283 return -err;
5284}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005285
William Lallemand231610a2021-12-30 11:25:43 +01005286/* release ssl context allocated for servers. Most of the field free here
5287 * must also be allocated in srv_ssl_settings_cpy() */
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005288void ssl_sock_free_srv_ctx(struct server *srv)
5289{
Olivier Houchardc7566002018-11-20 23:33:50 +01005290#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
William Lallemand231610a2021-12-30 11:25:43 +01005291 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005292#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005293#ifdef OPENSSL_NPN_NEGOTIATED
William Lallemand231610a2021-12-30 11:25:43 +01005294 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005295#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005296 if (srv->ssl_ctx.reused_sess) {
5297 int i;
5298
William Lallemande18d4e82021-11-17 02:59:21 +01005299 for (i = 0; i < global.nbthread; i++) {
Willy Tarreaue709e822021-02-26 21:06:32 +01005300 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
William Lallemande18d4e82021-11-17 02:59:21 +01005301 ha_free(&srv->ssl_ctx.reused_sess[i].sni);
5302 }
Willy Tarreaue709e822021-02-26 21:06:32 +01005303 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005304 }
5305
Willy Tarreaue709e822021-02-26 21:06:32 +01005306 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005307 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005308 srv->ssl_ctx.ctx = NULL;
5309 }
William Lallemand231610a2021-12-30 11:25:43 +01005310
5311 ha_free(&srv->ssl_ctx.ca_file);
5312 ha_free(&srv->ssl_ctx.crl_file);
5313 ha_free(&srv->ssl_ctx.client_crt);
5314 ha_free(&srv->ssl_ctx.verify_host);
5315#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5316 ha_free(&srv->sni_expr);
William Lallemand43c2ce42022-03-16 17:48:19 +01005317 release_sample_expr(srv->ssl_ctx.sni);
5318 srv->ssl_ctx.sni = NULL;
William Lallemand231610a2021-12-30 11:25:43 +01005319#endif
5320 ha_free(&srv->ssl_ctx.ciphers);
5321#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
5322 ha_free(&srv->ssl_ctx.ciphersuites);
5323#endif
William Lallemande69563f2021-12-30 14:45:19 +01005324 /* If there is a certificate we must unlink the ckch instance */
5325 ckch_inst_free(srv->ssl_ctx.inst);
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005326}
5327
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005328/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005329 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5330 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005331void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005332{
5333 struct ebmb_node *node, *back;
5334 struct sni_ctx *sni;
5335
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005336 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005337 while (node) {
5338 sni = ebmb_entry(node, struct sni_ctx, name);
5339 back = ebmb_next(node);
5340 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005341 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005342 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005343 free(sni);
5344 node = back;
5345 }
5346
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005347 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005348 while (node) {
5349 sni = ebmb_entry(node, struct sni_ctx, name);
5350 back = ebmb_next(node);
5351 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005352 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005353 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005354 free(sni);
5355 node = back;
5356 }
William Lallemandb2408692020-06-24 09:54:29 +02005357
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005358 SSL_CTX_free(bind_conf->initial_ctx);
5359 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005360 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005361 bind_conf->default_ctx = NULL;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005362 bind_conf->default_inst = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005363 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005364}
William Lallemandb2408692020-06-24 09:54:29 +02005365
5366
5367void ssl_sock_deinit()
5368{
5369 crtlist_deinit(); /* must be free'd before the ckchs */
5370 ckch_deinit();
5371}
5372REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005373
Willy Tarreau795cdab2016-12-22 17:30:54 +01005374/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5375void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5376{
5377 ssl_sock_free_ca(bind_conf);
5378 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005379 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005380 free(bind_conf->ca_sign_file);
5381 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005382 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005383 free(bind_conf->keys_ref->filename);
5384 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005385 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005386 free(bind_conf->keys_ref);
5387 }
5388 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005389 bind_conf->ca_sign_pass = NULL;
5390 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005391}
5392
Christopher Faulet31af49d2015-06-09 17:29:50 +02005393/* Load CA cert file and private key used to generate certificates */
5394int
Willy Tarreau03209342016-12-22 17:08:28 +01005395ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005396{
Willy Tarreau03209342016-12-22 17:08:28 +01005397 struct proxy *px = bind_conf->frontend;
William Lallemand52ddd992022-11-22 11:51:53 +01005398 struct ckch_data *data = NULL;
Shimi Gersner5846c492020-08-23 13:58:12 +03005399 int ret = 0;
5400 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005401
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005402 if (!(bind_conf->options & BC_O_GENERATE_CERTS))
Shimi Gersner5846c492020-08-23 13:58:12 +03005403 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005404
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005405#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005406 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005407 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005408 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005409 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005410 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005411#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005412
Christopher Faulet31af49d2015-06-09 17:29:50 +02005413 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005414 ha_alert("Proxy '%s': cannot enable certificate generation, "
5415 "no CA certificate File configured at [%s:%d].\n",
5416 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005417 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005418 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005419
Shimi Gersner5846c492020-08-23 13:58:12 +03005420 /* Allocate cert structure */
William Lallemand52ddd992022-11-22 11:51:53 +01005421 data = calloc(1, sizeof(*data));
5422 if (!data) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005423 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5424 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5425 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005426 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005427
5428 /* Try to parse file */
William Lallemand52ddd992022-11-22 11:51:53 +01005429 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, data, &err)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005430 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5431 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005432 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005433 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005434 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005435
5436 /* Fail if missing cert or pkey */
William Lallemand52ddd992022-11-22 11:51:53 +01005437 if ((!data->cert) || (!data->key)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005438 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5439 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5440 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005441 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005442
Shimi Gersner5846c492020-08-23 13:58:12 +03005443 /* Final assignment to bind */
William Lallemand52ddd992022-11-22 11:51:53 +01005444 bind_conf->ca_sign_ckch = data;
Shimi Gersner5846c492020-08-23 13:58:12 +03005445 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005446
Shimi Gersner5846c492020-08-23 13:58:12 +03005447 failed:
William Lallemand52ddd992022-11-22 11:51:53 +01005448 if (data) {
5449 ssl_sock_free_cert_key_and_chain_contents(data);
5450 free(data);
Shimi Gersner5846c492020-08-23 13:58:12 +03005451 }
5452
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005453 bind_conf->options &= ~BC_O_GENERATE_CERTS;
Shimi Gersner5846c492020-08-23 13:58:12 +03005454 ret++;
5455 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005456}
5457
5458/* Release CA cert and private key used to generate certificated */
5459void
5460ssl_sock_free_ca(struct bind_conf *bind_conf)
5461{
Shimi Gersner5846c492020-08-23 13:58:12 +03005462 if (bind_conf->ca_sign_ckch) {
5463 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005464 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005465 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005466}
5467
Emeric Brun46591952012-05-18 15:47:34 +02005468/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005469 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5470 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5471 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5472 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005473 * This is the responsibility of the caller to check the validity of all the pointers passed
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005474 * as parameters to this function.
5475 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5476 * CO_ER_SSL_NO_MEM.
5477 */
5478int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5479 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5480{
5481 int retry = 1;
5482
5483 retry:
5484 /* Alloc a new SSL session. */
5485 *ssl = SSL_new(ssl_ctx);
5486 if (!*ssl) {
5487 if (!retry--)
5488 goto err;
5489
5490 pool_gc(NULL);
5491 goto retry;
5492 }
5493
5494 *bio = BIO_new(bio_meth);
5495 if (!*bio) {
5496 SSL_free(*ssl);
5497 *ssl = NULL;
5498 if (!retry--)
5499 goto err;
5500
5501 pool_gc(NULL);
5502 goto retry;
5503 }
5504
5505 BIO_set_data(*bio, ctx);
5506 SSL_set_bio(*ssl, *bio, *bio);
5507
5508 /* set connection pointer. */
5509 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5510 SSL_free(*ssl);
5511 *ssl = NULL;
5512 if (!retry--)
5513 goto err;
5514
5515 pool_gc(NULL);
5516 goto retry;
5517 }
5518
5519 return 0;
5520
5521 err:
5522 conn->err_code = CO_ER_SSL_NO_MEM;
5523 return -1;
5524}
5525
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005526/* This function is called when all the XPRT have been initialized. We can
5527 * now attempt to start the SSL handshake.
5528 */
5529static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5530{
5531 struct ssl_sock_ctx *ctx = xprt_ctx;
5532
5533 if (ctx->xprt->start) {
5534 int ret;
5535
5536 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5537 if (ret < 0)
5538 return ret;
5539 }
5540 tasklet_wakeup(ctx->wait_event.tasklet);
5541
5542 return 0;
5543}
5544
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005545/*
Emeric Brun46591952012-05-18 15:47:34 +02005546 * This function is called if SSL * context is not yet allocated. The function
5547 * is designed to be called before any other data-layer operation and sets the
5548 * handshake flag on the connection. It is safe to call it multiple times.
5549 * It returns 0 on success and -1 in error case.
5550 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005551static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005552{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005553 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005554 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005555 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005556 return 0;
5557
Olivier Houchard66ab4982019-02-26 18:37:15 +01005558 ctx = pool_alloc(ssl_sock_ctx_pool);
5559 if (!ctx) {
5560 conn->err_code = CO_ER_SSL_NO_MEM;
5561 return -1;
5562 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005563 ctx->wait_event.tasklet = tasklet_new();
5564 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005565 conn->err_code = CO_ER_SSL_NO_MEM;
5566 pool_free(ssl_sock_ctx_pool, ctx);
5567 return -1;
5568 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005569 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5570 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005571 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005572 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005573 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005574 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005575 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005576 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005577 ctx->xprt_st = 0;
5578 ctx->xprt_ctx = NULL;
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005579 ctx->error_code = 0;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005580
5581 /* Only work with sockets for now, this should be adapted when we'll
5582 * add QUIC support.
5583 */
5584 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005585 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005586 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5587 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005588 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005589
Willy Tarreau82531f62021-10-06 12:15:18 +02005590 if (global.maxsslconn && global.sslconns >= global.maxsslconn) {
Willy Tarreau20879a02012-12-03 16:32:10 +01005591 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005592 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005593 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005594
Emeric Brun46591952012-05-18 15:47:34 +02005595 /* If it is in client mode initiate SSL session
5596 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005597 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005598 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5599 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005600 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005601
Olivier Houchard66ab4982019-02-26 18:37:15 +01005602 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005603 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005604 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5605 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5606 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 +01005607 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005608 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005609 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005610 } else if (sess) {
5611 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005612 }
5613 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005614 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005615
Emeric Brun46591952012-05-18 15:47:34 +02005616 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005617 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005618
Willy Tarreau82531f62021-10-06 12:15:18 +02005619 _HA_ATOMIC_INC(&global.sslconns);
5620 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005621 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005622 return 0;
5623 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005624 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005625 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005626
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005627 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5628 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005629 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005630
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005631#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005632 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005633 b_alloc(&ctx->early_buf);
5634 SSL_set_max_early_data(ctx->ssl,
5635 /* Only allow early data if we managed to allocate
5636 * a buffer.
5637 */
5638 (!b_is_null(&ctx->early_buf)) ?
5639 global.tune.bufsize - global.tune.maxrewrite : 0);
5640 }
5641#endif
5642
Olivier Houchard66ab4982019-02-26 18:37:15 +01005643 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005644
Emeric Brun46591952012-05-18 15:47:34 +02005645 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005646 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005647#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005648 if (bc->ssl_conf.early_data)
5649 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005650#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005651
Willy Tarreau82531f62021-10-06 12:15:18 +02005652 _HA_ATOMIC_INC(&global.sslconns);
5653 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005654 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005655 return 0;
5656 }
5657 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005658 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005659err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005660 if (ctx && ctx->wait_event.tasklet)
5661 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005662 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005663 return -1;
5664}
5665
5666
5667/* This is the callback which is used when an SSL handshake is pending. It
5668 * updates the FD status if it wants some polling before being called again.
5669 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5670 * otherwise it returns non-zero and removes itself from the connection's
5671 * flags (the bit is provided in <flag> by the caller).
5672 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005673static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005674{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005675 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Emeric Brun46591952012-05-18 15:47:34 +02005676 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005677 struct ssl_counters *counters = NULL;
5678 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005679 struct listener *li;
5680 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005681 socklen_t lskerr;
5682 int skerr;
5683
Emeric Brun46591952012-05-18 15:47:34 +02005684
Willy Tarreau3c728722014-01-23 13:50:42 +01005685 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005686 return 0;
5687
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005688 /* get counters */
5689 switch (obj_type(conn->target)) {
5690 case OBJ_TYPE_LISTENER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005691 li = __objt_listener(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005692 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5693 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5694 &ssl_stats_module);
5695 break;
5696
5697 case OBJ_TYPE_SERVER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005698 srv = __objt_server(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005699 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5700 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5701 &ssl_stats_module);
5702 break;
5703
5704 default:
5705 break;
5706 }
5707
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005708 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005709 goto out_error;
5710
Willy Tarreau06300382021-02-02 15:42:25 +01005711 /* don't start calculating a handshake on a dead connection */
5712 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5713 goto out_error;
5714
5715 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5716 * status from the lower layers, so let's check the FD directly. Ideally
5717 * the xprt layers should provide some status indicating their knowledge
5718 * of shutdowns or error.
5719 */
Willy Tarreau07ecfc52022-04-11 18:07:03 +02005720 BUG_ON(conn->flags & CO_FL_FDLESS);
5721
Willy Tarreau06300382021-02-02 15:42:25 +01005722 skerr = 0;
5723 lskerr = sizeof(skerr);
5724 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5725 skerr != 0)
5726 goto out_error;
5727
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005728#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005729 /*
5730 * Check if we have early data. If we do, we have to read them
5731 * before SSL_do_handshake() is called, And there's no way to
5732 * detect early data, except to try to read them
5733 */
5734 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005735 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005736
Olivier Houchard54907bb2019-12-19 15:02:39 +01005737 while (1) {
5738 ret = SSL_read_early_data(ctx->ssl,
5739 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5740 &read_data);
5741 if (ret == SSL_READ_EARLY_DATA_ERROR)
5742 goto check_error;
5743 if (read_data > 0) {
5744 conn->flags |= CO_FL_EARLY_DATA;
5745 b_add(&ctx->early_buf, read_data);
5746 }
5747 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5748 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5749 if (!b_data(&ctx->early_buf))
5750 b_free(&ctx->early_buf);
5751 break;
5752 }
5753 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005754 }
5755#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005756 /* If we use SSL_do_handshake to process a reneg initiated by
5757 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5758 * Usually SSL_write and SSL_read are used and process implicitly
5759 * the reneg handshake.
5760 * Here we use SSL_peek as a workaround for reneg.
5761 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005762 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005763 char c;
5764
Olivier Houchard66ab4982019-02-26 18:37:15 +01005765 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005766 if (ret <= 0) {
5767 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005768 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005769
Emeric Brun674b7432012-11-08 19:21:55 +01005770 if (ret == SSL_ERROR_WANT_WRITE) {
5771 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005772 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005773 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005774 return 0;
5775 }
5776 else if (ret == SSL_ERROR_WANT_READ) {
5777 /* handshake may have been completed but we have
5778 * no more data to read.
5779 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005780 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005781 ret = 1;
5782 goto reneg_ok;
5783 }
5784 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005785 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005786 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005787 return 0;
5788 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005789#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005790 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005791 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005792 return 0;
5793 }
5794#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005795 else if (ret == SSL_ERROR_SYSCALL) {
5796 /* if errno is null, then connection was successfully established */
5797 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5798 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005799 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005800#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5801 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005802 conn->err_code = CO_ER_SSL_HANDSHAKE;
5803#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005804 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005805#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005806 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005807 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005808 empty_handshake = state == TLS_ST_BEFORE;
5809#else
Lukas Tribus49799162019-07-08 14:29:15 +02005810 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5811 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005812#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005813 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005814 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005815 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005816 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5817 else
5818 conn->err_code = CO_ER_SSL_EMPTY;
5819 }
5820 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005821 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005822 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5823 else
5824 conn->err_code = CO_ER_SSL_ABORT;
5825 }
5826 }
5827 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005828 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005829 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005830 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005831 conn->err_code = CO_ER_SSL_HANDSHAKE;
5832 }
Lukas Tribus49799162019-07-08 14:29:15 +02005833#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005834 }
Emeric Brun674b7432012-11-08 19:21:55 +01005835 goto out_error;
5836 }
5837 else {
5838 /* Fail on all other handshake errors */
5839 /* Note: OpenSSL may leave unread bytes in the socket's
5840 * buffer, causing an RST to be emitted upon close() on
5841 * TCP sockets. We first try to drain possibly pending
5842 * data to avoid this as much as possible.
5843 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005844 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005845 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005846 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005847 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005848 goto out_error;
5849 }
5850 }
5851 /* read some data: consider handshake completed */
5852 goto reneg_ok;
5853 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005854 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005855check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005856 if (ret != 1) {
5857 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005858 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005859
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005860 if (!ctx->error_code)
5861 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton7c6898e2021-07-29 09:45:51 +02005862
Emeric Brun46591952012-05-18 15:47:34 +02005863 if (ret == SSL_ERROR_WANT_WRITE) {
5864 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005865 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005866 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005867 return 0;
5868 }
5869 else if (ret == SSL_ERROR_WANT_READ) {
5870 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005871 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005872 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5873 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005874 return 0;
5875 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005876#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005877 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005878 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005879 return 0;
5880 }
5881#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005882 else if (ret == SSL_ERROR_SYSCALL) {
5883 /* if errno is null, then connection was successfully established */
5884 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5885 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005886 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005887#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5888 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005889 conn->err_code = CO_ER_SSL_HANDSHAKE;
5890#else
5891 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005892#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005893 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005894 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005895 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005896#else
Lukas Tribus49799162019-07-08 14:29:15 +02005897 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5898 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005899#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005900 if (empty_handshake) {
5901 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005902 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005903 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5904 else
5905 conn->err_code = CO_ER_SSL_EMPTY;
5906 }
5907 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005908 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005909 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5910 else
5911 conn->err_code = CO_ER_SSL_ABORT;
5912 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005913 }
5914 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005915 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005916 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5917 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005918 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005919 }
Lukas Tribus49799162019-07-08 14:29:15 +02005920#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005921 }
Willy Tarreau89230192012-09-28 20:22:13 +02005922 goto out_error;
5923 }
Emeric Brun46591952012-05-18 15:47:34 +02005924 else {
5925 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005926 /* Note: OpenSSL may leave unread bytes in the socket's
5927 * buffer, causing an RST to be emitted upon close() on
5928 * TCP sockets. We first try to drain possibly pending
5929 * data to avoid this as much as possible.
5930 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005931 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005932 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005933 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005934 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005935 goto out_error;
5936 }
5937 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005938#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005939 else {
5940 /*
5941 * If the server refused the early data, we have to send a
5942 * 425 to the client, as we no longer have the data to sent
5943 * them again.
5944 */
5945 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005946 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005947 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5948 goto out_error;
5949 }
5950 }
5951 }
5952#endif
5953
Emeric Brun46591952012-05-18 15:47:34 +02005954
Emeric Brun674b7432012-11-08 19:21:55 +01005955reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005956
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005957#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00005958 /* ASYNC engine API doesn't support moving read/write
5959 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005960 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005961 */
5962 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005963 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005964#endif
Emeric Brun46591952012-05-18 15:47:34 +02005965 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005966 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005967 if (objt_server(conn->target)) {
5968 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5969 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5970 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005971 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005972 else {
5973 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5974 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5975 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5976 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005977
Willy Tarreau42995282020-11-06 13:19:18 +01005978 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01005979 HA_ATOMIC_INC(&counters->sess);
5980 HA_ATOMIC_INC(&counters_px->sess);
Willy Tarreau42995282020-11-06 13:19:18 +01005981 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005982 }
Willy Tarreau42995282020-11-06 13:19:18 +01005983 else if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01005984 HA_ATOMIC_INC(&counters->reused_sess);
5985 HA_ATOMIC_INC(&counters_px->reused_sess);
Emeric Brun46591952012-05-18 15:47:34 +02005986 }
5987
5988 /* The connection is now established at both layers, it's time to leave */
5989 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5990 return 1;
5991
5992 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005993 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02005994 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01005995 ERR_clear_error();
5996
Emeric Brun9fa89732012-10-04 17:09:56 +02005997 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01005998 if (objt_server(conn->target)) {
5999 struct server *s = __objt_server(conn->target);
6000 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
6001 * one cache per thread, it only prevents to flush it from the CLI in
6002 * another thread */
6003
6004 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01006005 if (s->ssl_ctx.reused_sess[tid].ptr)
6006 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01006007 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02006008 }
6009
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006010 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006011 HA_ATOMIC_INC(&counters->failed_handshake);
6012 HA_ATOMIC_INC(&counters_px->failed_handshake);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006013 }
6014
Emeric Brun46591952012-05-18 15:47:34 +02006015 /* Fail on all other handshake errors */
6016 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01006017 if (!conn->err_code)
6018 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006019 return 0;
6020}
6021
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006022/* Called from the upper layer, to subscribe <es> to events <event_type>. The
6023 * event subscriber <es> is not allowed to change from a previous call as long
6024 * as at least one event is still subscribed. The <event_type> must only be a
6025 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
6026 * unless the transport layer was already released.
6027 */
6028static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006029{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006030 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006031
Olivier Houchard0ff28652019-06-24 18:57:39 +02006032 if (!ctx)
6033 return -1;
6034
Willy Tarreau113d52b2020-01-10 09:20:26 +01006035 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006036 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006037
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006038 ctx->subs = es;
6039 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006040
6041 /* we may have to subscribe to lower layers for new events */
6042 event_type &= ~ctx->wait_event.events;
6043 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
6044 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006045 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006046}
6047
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006048/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
6049 * The <es> pointer is not allowed to differ from the one passed to the
6050 * subscribe() call. It always returns zero.
6051 */
6052static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006053{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006054 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006055
Willy Tarreau113d52b2020-01-10 09:20:26 +01006056 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006057 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006058
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006059 es->events &= ~event_type;
6060 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01006061 ctx->subs = NULL;
6062
6063 /* If we subscribed, and we're not doing the handshake,
6064 * then we subscribed because the upper layer asked for it,
6065 * as the upper layer is no longer interested, we can
6066 * unsubscribe too.
6067 */
6068 event_type &= ctx->wait_event.events;
6069 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
6070 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006071
6072 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006073}
6074
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006075/* The connection has been taken over, so destroy the old tasklet and create
6076 * a new one. The original thread ID must be passed into orig_tid
6077 * It should be called with the takeover lock for the old thread held.
6078 * Returns 0 on success, and -1 on failure
6079 */
6080static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
6081{
6082 struct ssl_sock_ctx *ctx = xprt_ctx;
6083 struct tasklet *tl = tasklet_new();
6084
6085 if (!tl)
6086 return -1;
6087
6088 ctx->wait_event.tasklet->context = NULL;
6089 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
6090 ctx->wait_event.tasklet = tl;
6091 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
6092 ctx->wait_event.tasklet->context = ctx;
6093 return 0;
6094}
6095
Willy Tarreau41491682021-03-02 17:29:56 +01006096/* notify the next xprt that the connection is about to become idle and that it
6097 * may be stolen at any time after the function returns and that any tasklet in
6098 * the chain must be careful before dereferencing its context.
6099 */
6100static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
6101{
6102 struct ssl_sock_ctx *ctx = xprt_ctx;
6103
6104 if (!ctx || !ctx->wait_event.tasklet)
6105 return;
6106
6107 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6108 if (ctx->xprt)
6109 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
6110}
6111
6112/* notify the next xprt that the connection is not idle anymore and that it may
6113 * not be stolen before the next xprt_set_idle().
6114 */
6115static void ssl_set_used(struct connection *conn, void *xprt_ctx)
6116{
6117 struct ssl_sock_ctx *ctx = xprt_ctx;
6118
6119 if (!ctx || !ctx->wait_event.tasklet)
6120 return;
6121
6122 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6123 if (ctx->xprt)
6124 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
6125}
6126
Olivier Houchard2e055482019-05-27 19:50:12 +02006127/* Use the provided XPRT as an underlying XPRT, and provide the old one.
6128 * Returns 0 on success, and non-zero on failure.
6129 */
6130static 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)
6131{
6132 struct ssl_sock_ctx *ctx = xprt_ctx;
6133
6134 if (oldxprt_ops != NULL)
6135 *oldxprt_ops = ctx->xprt;
6136 if (oldxprt_ctx != NULL)
6137 *oldxprt_ctx = ctx->xprt_ctx;
6138 ctx->xprt = toadd_ops;
6139 ctx->xprt_ctx = toadd_ctx;
6140 return 0;
6141}
6142
Olivier Houchard5149b592019-05-23 17:47:36 +02006143/* Remove the specified xprt. If if it our underlying XPRT, remove it and
6144 * return 0, otherwise just call the remove_xprt method from the underlying
6145 * XPRT.
6146 */
6147static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
6148{
6149 struct ssl_sock_ctx *ctx = xprt_ctx;
6150
6151 if (ctx->xprt_ctx == toremove_ctx) {
6152 ctx->xprt_ctx = newctx;
6153 ctx->xprt = newops;
6154 return 0;
6155 }
6156 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
6157}
6158
Willy Tarreau144f84a2021-03-02 16:09:26 +01006159struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02006160{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006161 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006162 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006163 struct connection *conn;
6164 int conn_in_list;
6165 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006166
Willy Tarreau41491682021-03-02 17:29:56 +01006167 if (state & TASK_F_USR1) {
6168 /* the tasklet was idling on an idle connection, it might have
6169 * been stolen, let's be careful!
6170 */
6171 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6172 if (tl->context == NULL) {
6173 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6174 tasklet_free(tl);
6175 return NULL;
6176 }
6177 conn = ctx->conn;
6178 conn_in_list = conn->flags & CO_FL_LIST_MASK;
6179 if (conn_in_list)
6180 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006181 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01006182 } else {
6183 conn = ctx->conn;
6184 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006185 }
Willy Tarreau41491682021-03-02 17:29:56 +01006186
Olivier Houchardea8dd942019-05-20 14:02:16 +02006187 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01006188 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006189 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006190 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
6191 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01006192 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006193 }
6194 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006195 /* If we had an error, or the handshake is done and I/O is available,
6196 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01006197 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02006198 * we can't be sure conn_fd_handler() will be called again.
6199 */
6200 if ((ctx->conn->flags & CO_FL_ERROR) ||
6201 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006202 int woke = 0;
6203
6204 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006205 if (ctx->subs) {
6206 tasklet_wakeup(ctx->subs->tasklet);
6207 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006208 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006209 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006210 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006211
Olivier Houchardea8dd942019-05-20 14:02:16 +02006212 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01006213 * upper layers know. If we have no mux, create it,
6214 * and once we have a mux, call its wake method if we didn't
6215 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02006216 */
6217 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01006218 if (!ctx->conn->mux)
6219 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006220 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006221 ret = ctx->conn->mux->wake(ctx->conn);
6222 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006223 }
6224 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006225#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006226 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006227 else if (b_data(&ctx->early_buf) && ctx->subs &&
6228 ctx->subs->events & SUB_RETRY_RECV) {
6229 tasklet_wakeup(ctx->subs->tasklet);
6230 ctx->subs->events &= ~SUB_RETRY_RECV;
6231 if (!ctx->subs->events)
6232 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01006233 }
6234#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006235leave:
6236 if (!ret && conn_in_list) {
6237 struct server *srv = objt_server(conn->target);
6238
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006239 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006240 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau85223482022-09-29 20:32:43 +02006241 eb64_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006242 else
Willy Tarreau85223482022-09-29 20:32:43 +02006243 eb64_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006244 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006245 }
Willy Tarreau74163142021-03-13 11:30:19 +01006246 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006247}
6248
Emeric Brun46591952012-05-18 15:47:34 +02006249/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01006250 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02006251 * buffer wraps, in which case a second call may be performed. The connection's
6252 * flags are updated with whatever special event is detected (error, read0,
6253 * empty). The caller is responsible for taking care of those events and
6254 * avoiding the call if inappropriate. The function does not call the
6255 * connection's polling update function, so the caller is responsible for this.
6256 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006257static 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 +02006258{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006259 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02006260 ssize_t ret;
6261 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02006262
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006263 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006264 goto out_error;
6265
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006266#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006267 if (b_data(&ctx->early_buf)) {
6268 try = b_contig_space(buf);
6269 if (try > b_data(&ctx->early_buf))
6270 try = b_data(&ctx->early_buf);
6271 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
6272 b_add(buf, try);
6273 b_del(&ctx->early_buf, try);
6274 if (b_data(&ctx->early_buf) == 0)
6275 b_free(&ctx->early_buf);
6276 return try;
6277 }
6278#endif
6279
Willy Tarreau911db9b2020-01-23 16:27:54 +01006280 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006281 /* a handshake was requested */
6282 return 0;
6283
Emeric Brun46591952012-05-18 15:47:34 +02006284 /* read the largest possible block. For this, we perform only one call
6285 * to recv() unless the buffer wraps and we exactly fill the first hunk,
6286 * in which case we accept to do it once again. A new attempt is made on
6287 * EINTR too.
6288 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01006289 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006290
Willy Tarreau591d4452018-06-15 17:21:00 +02006291 try = b_contig_space(buf);
6292 if (!try)
6293 break;
6294
Willy Tarreauabf08d92014-01-14 11:31:27 +01006295 if (try > count)
6296 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02006297
Olivier Houchard66ab4982019-02-26 18:37:15 +01006298 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02006299
Emeric Brune1f38db2012-09-03 20:36:47 +02006300 if (conn->flags & CO_FL_ERROR) {
6301 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006302 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006303 }
Emeric Brun46591952012-05-18 15:47:34 +02006304 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006305 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006306 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006307 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006308 }
Emeric Brun46591952012-05-18 15:47:34 +02006309 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006310 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006311 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006312 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006313 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006314 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006315#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006316 /* Async mode can be re-enabled, because we're leaving data state.*/
6317 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006318 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006319#endif
Emeric Brun46591952012-05-18 15:47:34 +02006320 break;
6321 }
6322 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006323 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006324 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6325 SUB_RETRY_RECV,
6326 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006327 /* handshake is running, and it may need to re-enable read */
6328 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006329#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006330 /* Async mode can be re-enabled, because we're leaving data state.*/
6331 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006332 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006333#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006334 break;
6335 }
Emeric Brun46591952012-05-18 15:47:34 +02006336 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006337 } else if (ret == SSL_ERROR_ZERO_RETURN)
6338 goto read0;
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006339 else if (ret == SSL_ERROR_SSL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006340 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6341 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006342 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006343 conn->err_code = CO_ERR_SSL_FATAL;
6344 }
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006345 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6346 * stack before shutting down the connection for
6347 * reading. */
Willy Tarreauacef5e22022-04-25 20:32:15 +02006348 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN || errno == EWOULDBLOCK))
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006349 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006350 /* otherwise it's a real error */
6351 goto out_error;
6352 }
6353 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006354 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006355 return done;
6356
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006357 clear_ssl_error:
6358 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006359 ssl_sock_dump_errors(conn, NULL);
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006360 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006361 read0:
6362 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006363 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006364
Emeric Brun46591952012-05-18 15:47:34 +02006365 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006366 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006367 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006368 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006369 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006370 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006371}
6372
6373
Willy Tarreau787db9a2018-06-14 18:31:46 +02006374/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6375 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6376 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006377 * Only one call to send() is performed, unless the buffer wraps, in which case
6378 * a second call may be performed. The connection's flags are updated with
6379 * whatever special event is detected (error, empty). The caller is responsible
6380 * for taking care of those events and avoiding the call if inappropriate. The
6381 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006382 * is responsible for this. The buffer's output is not adjusted, it's up to the
6383 * caller to take care of this. It's up to the caller to update the buffer's
6384 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006385 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006386static 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 +02006387{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006388 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006389 ssize_t ret;
6390 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006391
6392 done = 0;
6393
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006394 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006395 goto out_error;
6396
Willy Tarreau911db9b2020-01-23 16:27:54 +01006397 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006398 /* a handshake was requested */
6399 return 0;
6400
6401 /* send the largest possible block. For this we perform only one call
6402 * to send() unless the buffer wraps and we exactly fill the first hunk,
6403 * in which case we accept to do it once again.
6404 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006405 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006406#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006407 size_t written_data;
6408#endif
6409
Willy Tarreau787db9a2018-06-14 18:31:46 +02006410 try = b_contig_data(buf, done);
6411 if (try > count)
6412 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006413
Thomas Prückl10243932022-04-27 13:04:54 +02006414 if (global_ssl.hard_max_record && try > global_ssl.hard_max_record)
6415 try = global_ssl.hard_max_record;
6416
Willy Tarreau7bed9452014-02-02 02:00:24 +01006417 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006418 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006419 global_ssl.max_record && try > global_ssl.max_record) {
6420 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006421 }
6422 else {
6423 /* we need to keep the information about the fact that
6424 * we're not limiting the upcoming send(), because if it
6425 * fails, we'll have to retry with at least as many data.
6426 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006427 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006428 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006429
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006430#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006431 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006432 unsigned int max_early;
6433
Olivier Houchard522eea72017-11-03 16:27:47 +01006434 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006435 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006436 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006437 if (SSL_get0_session(ctx->ssl))
6438 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006439 else
6440 max_early = 0;
6441 }
6442
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006443 if (try + ctx->sent_early_data > max_early) {
6444 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006445 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006446 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006447 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006448 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006449 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006450 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006451 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006452 if (ret == 1) {
6453 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006454 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006455 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006456 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006457 /* Initiate the handshake, now */
6458 tasklet_wakeup(ctx->wait_event.tasklet);
6459 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006460
Olivier Houchardc2aae742017-09-22 18:26:28 +02006461 }
6462
6463 } else
6464#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006465 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006466
Emeric Brune1f38db2012-09-03 20:36:47 +02006467 if (conn->flags & CO_FL_ERROR) {
6468 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006469 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006470 }
Emeric Brun46591952012-05-18 15:47:34 +02006471 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006472 /* A send succeeded, so we can consider ourself connected */
6473 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006474 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006475 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006476 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006477 }
6478 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006479 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006480
Emeric Brun46591952012-05-18 15:47:34 +02006481 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006482 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006483 /* handshake is running, and it may need to re-enable write */
6484 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006485 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006486#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006487 /* Async mode can be re-enabled, because we're leaving data state.*/
6488 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006489 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006490#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006491 break;
6492 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006493
Emeric Brun46591952012-05-18 15:47:34 +02006494 break;
6495 }
6496 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006497 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006498 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006499 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6500 SUB_RETRY_RECV,
6501 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006502#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006503 /* Async mode can be re-enabled, because we're leaving data state.*/
6504 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006505 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006506#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006507 break;
6508 }
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006509 else if (ret == SSL_ERROR_SSL || ret == SSL_ERROR_SYSCALL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006510 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6511
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02006512 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006513 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006514 conn->err_code = CO_ERR_SSL_FATAL;
6515 }
Emeric Brun46591952012-05-18 15:47:34 +02006516 goto out_error;
6517 }
6518 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006519 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006520 return done;
6521
6522 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006523 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006524 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006525 ERR_clear_error();
6526
Emeric Brun46591952012-05-18 15:47:34 +02006527 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006528 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006529}
6530
Willy Tarreau832e2422021-05-13 10:11:03 +02006531void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006532
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006533 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006534
Olivier Houchardea8dd942019-05-20 14:02:16 +02006535
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006536 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006537 if (ctx->wait_event.events != 0)
6538 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6539 ctx->wait_event.events,
6540 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006541 if (ctx->subs) {
6542 ctx->subs->events = 0;
6543 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006544 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006545
Olivier Houchard692c1d02019-05-23 18:41:47 +02006546 if (ctx->xprt->close)
6547 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006548#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006549 if (global_ssl.async) {
6550 OSSL_ASYNC_FD all_fd[32], afd;
6551 size_t num_all_fds = 0;
6552 int i;
6553
Olivier Houchard66ab4982019-02-26 18:37:15 +01006554 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006555 if (num_all_fds > 32) {
6556 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6557 return;
6558 }
6559
Olivier Houchard66ab4982019-02-26 18:37:15 +01006560 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006561
6562 /* If an async job is pending, we must try to
6563 to catch the end using polling before calling
6564 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006565 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006566 for (i=0 ; i < num_all_fds ; i++) {
6567 /* switch on an handler designed to
6568 * handle the SSL_free
6569 */
6570 afd = all_fd[i];
6571 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006572 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006573 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006574 /* To ensure that the fd cache won't be used
6575 * and we'll catch a real RD event.
6576 */
6577 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006578 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006579 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006580 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006581 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006582 return;
6583 }
Emeric Brun3854e012017-05-17 20:42:48 +02006584 /* Else we can remove the fds from the fdtab
6585 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006586 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006587 * because the fd is owned by the engine.
6588 * the engine is responsible to close
6589 */
Emeric Brun7d392a52022-07-01 17:36:50 +02006590 for (i=0 ; i < num_all_fds ; i++) {
6591 /* We want to remove the fd from the fdtab
6592 * but we flag it to disown because the
6593 * close is performed by the engine itself
6594 */
6595 fdtab[all_fd[i]].state |= FD_DISOWN;
6596 fd_delete(all_fd[i]);
6597 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006598 }
6599#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006600 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006601 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006602 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006603 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau82531f62021-10-06 12:15:18 +02006604 _HA_ATOMIC_DEC(&global.sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006605 }
Emeric Brun46591952012-05-18 15:47:34 +02006606}
6607
6608/* This function tries to perform a clean shutdown on an SSL connection, and in
6609 * any case, flags the connection as reusable if no handshake was in progress.
6610 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006611static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006612{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006613 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006614
Willy Tarreau911db9b2020-01-23 16:27:54 +01006615 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006616 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006617 if (!clean)
6618 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006619 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006620 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006621 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006622 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006623 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006624 ERR_clear_error();
6625 }
Emeric Brun46591952012-05-18 15:47:34 +02006626}
6627
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006628
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006629/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006630int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6631{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006632 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemandd4f946c2019-12-05 10:26:40 +01006633 X509 *crt;
6634
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006635 if (!ctx)
William Lallemandd4f946c2019-12-05 10:26:40 +01006636 return 0;
William Lallemandd4f946c2019-12-05 10:26:40 +01006637 crt = SSL_get_certificate(ctx->ssl);
6638 if (!crt)
6639 return 0;
6640
6641 return cert_get_pkey_algo(crt, out);
6642}
6643
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006644/* used for ppv2 cert signature (can be used for logging) */
6645const char *ssl_sock_get_cert_sig(struct connection *conn)
6646{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006647 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006648
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006649 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6650 X509 *crt;
6651
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006652 if (!ctx)
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006653 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006654 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006655 if (!crt)
6656 return NULL;
6657 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6658 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6659}
6660
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006661/* used for ppv2 authority */
6662const char *ssl_sock_get_sni(struct connection *conn)
6663{
6664#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006665 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006666
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006667 if (!ctx)
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006668 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006669 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006670#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006671 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006672#endif
6673}
6674
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006675/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006676const char *ssl_sock_get_cipher_name(struct connection *conn)
6677{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006678 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006679
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006680 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006681 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006682 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006683}
6684
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006685/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006686const char *ssl_sock_get_proto_version(struct connection *conn)
6687{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006688 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006689
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006690 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006691 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006692 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006693}
6694
Olivier Houchardab28a322018-12-21 19:45:40 +01006695void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6696{
6697#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006698 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006699
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006700 if (!ctx)
Olivier Houcharde488ea82019-06-28 14:10:33 +02006701 return;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006702 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006703#endif
6704}
6705
Willy Tarreau119a4082016-12-22 21:58:38 +01006706/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6707 * to disable SNI.
6708 */
Willy Tarreau63076412015-07-10 11:33:32 +02006709void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6710{
6711#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006712 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemande18d4e82021-11-17 02:59:21 +01006713 struct server *s;
Willy Tarreau119a4082016-12-22 21:58:38 +01006714 char *prev_name;
6715
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006716 if (!ctx)
Willy Tarreau63076412015-07-10 11:33:32 +02006717 return;
Willy Tarreau77bfa662021-12-23 11:12:13 +01006718
6719 BUG_ON(!(conn->flags & CO_FL_WAIT_L6_CONN));
6720 BUG_ON(!(conn->flags & CO_FL_SSL_WAIT_HS));
6721
William Lallemande18d4e82021-11-17 02:59:21 +01006722 s = __objt_server(conn->target);
Willy Tarreau63076412015-07-10 11:33:32 +02006723
Willy Tarreau119a4082016-12-22 21:58:38 +01006724 /* if the SNI changes, we must destroy the reusable context so that a
William Lallemande18d4e82021-11-17 02:59:21 +01006725 * new connection will present a new SNI. compare with the SNI
6726 * previously stored in the reused_sess */
6727 /* the RWLOCK is used to ensure that we are not trying to flush the
6728 * cache from the CLI */
6729
6730 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
6731 prev_name = s->ssl_ctx.reused_sess[tid].sni;
Willy Tarreau119a4082016-12-22 21:58:38 +01006732 if ((!prev_name && hostname) ||
6733 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006734 SSL_set_session(ctx->ssl, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01006735 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau119a4082016-12-22 21:58:38 +01006736
Olivier Houchard66ab4982019-02-26 18:37:15 +01006737 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006738#endif
6739}
6740
Emeric Brun0abf8362014-06-24 18:26:41 +02006741/* Extract peer certificate's common name into the chunk dest
6742 * Returns
6743 * the len of the extracted common name
6744 * or 0 if no CN found in DN
6745 * or -1 on error case (i.e. no peer certificate)
6746 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006747int ssl_sock_get_remote_common_name(struct connection *conn,
6748 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006749{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006750 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
David Safb76832014-05-08 23:42:08 -04006751 X509 *crt = NULL;
6752 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006753 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006754 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006755 .area = (char *)&find_cn,
6756 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006757 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006758 int result = -1;
David Safb76832014-05-08 23:42:08 -04006759
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006760 if (!ctx)
Emeric Brun0abf8362014-06-24 18:26:41 +02006761 goto out;
David Safb76832014-05-08 23:42:08 -04006762
6763 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006764 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006765 if (!crt)
6766 goto out;
6767
6768 name = X509_get_subject_name(crt);
6769 if (!name)
6770 goto out;
David Safb76832014-05-08 23:42:08 -04006771
Emeric Brun0abf8362014-06-24 18:26:41 +02006772 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6773out:
David Safb76832014-05-08 23:42:08 -04006774 if (crt)
6775 X509_free(crt);
6776
6777 return result;
6778}
6779
Dave McCowan328fb582014-07-30 10:39:13 -04006780/* returns 1 if client passed a certificate for this session, 0 if not */
6781int ssl_sock_get_cert_used_sess(struct connection *conn)
6782{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006783 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dave McCowan328fb582014-07-30 10:39:13 -04006784 X509 *crt = NULL;
6785
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006786 if (!ctx)
Dave McCowan328fb582014-07-30 10:39:13 -04006787 return 0;
6788
6789 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006790 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006791 if (!crt)
6792 return 0;
6793
6794 X509_free(crt);
6795 return 1;
6796}
6797
6798/* returns 1 if client passed a certificate for this connection, 0 if not */
6799int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006800{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006801 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006802
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006803 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006804 return 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006805 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006806}
6807
6808/* returns result from SSL verify */
6809unsigned int ssl_sock_get_verify_result(struct connection *conn)
6810{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006811 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006812
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006813 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006814 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006815 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006816}
6817
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006818/* Returns the application layer protocol name in <str> and <len> when known.
6819 * Zero is returned if the protocol name was not found, otherwise non-zero is
6820 * returned. The string is allocated in the SSL context and doesn't have to be
6821 * freed by the caller. NPN is also checked if available since older versions
6822 * of openssl (1.0.1) which are more common in field only support this one.
6823 */
Amaury Denoyelle71e588c2021-11-12 11:23:29 +01006824int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006825{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006826#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6827 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006828 struct ssl_sock_ctx *ctx = xprt_ctx;
6829 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006830 return 0;
6831
6832 *str = NULL;
6833
6834#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006835 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006836 if (*str)
6837 return 1;
6838#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006839#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006840 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006841 if (*str)
6842 return 1;
6843#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006844#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006845 return 0;
6846}
6847
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006848/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006849int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006850{
6851 X509 *ca;
6852 X509_NAME *name = NULL;
6853 ASN1_OCTET_STRING *skid = NULL;
6854 STACK_OF(X509) *chain = NULL;
6855 struct issuer_chain *issuer;
6856 struct eb64_node *node;
6857 char *path;
6858 u64 key;
6859 int ret = 0;
6860
6861 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6862 if (chain == NULL) {
6863 chain = sk_X509_new_null();
6864 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6865 name = X509_get_subject_name(ca);
6866 }
6867 if (!sk_X509_push(chain, ca)) {
6868 X509_free(ca);
6869 goto end;
6870 }
6871 }
6872 if (!chain) {
6873 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6874 goto end;
6875 }
6876 if (!skid) {
6877 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6878 goto end;
6879 }
6880 if (!name) {
6881 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6882 goto end;
6883 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01006884 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006885 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006886 issuer = container_of(node, typeof(*issuer), node);
6887 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6888 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6889 goto end;
6890 }
6891 }
6892 issuer = calloc(1, sizeof *issuer);
6893 path = strdup(fp);
6894 if (!issuer || !path) {
6895 free(issuer);
6896 free(path);
6897 goto end;
6898 }
6899 issuer->node.key = key;
6900 issuer->path = path;
6901 issuer->chain = chain;
6902 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006903 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006904 ret = 1;
6905 end:
6906 if (skid)
6907 ASN1_OCTET_STRING_free(skid);
6908 if (chain)
6909 sk_X509_pop_free(chain, X509_free);
6910 return ret;
6911}
6912
William Lallemandda8584c2020-05-14 10:14:37 +02006913 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006914{
6915 AUTHORITY_KEYID *akid;
6916 struct issuer_chain *issuer = NULL;
6917
6918 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01006919 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006920 struct eb64_node *node;
6921 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01006922 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006923 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6924 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6925 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6926 issuer = ti;
6927 break;
6928 }
6929 }
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006930 }
Remi Tricot-Le Breton1621dc12022-11-03 15:16:48 +01006931 AUTHORITY_KEYID_free(akid);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006932 return issuer;
6933}
6934
William Lallemanddad31052020-05-14 17:47:32 +02006935void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006936{
6937 struct eb64_node *node, *back;
6938 struct issuer_chain *issuer;
6939
William Lallemande0f3fd52020-02-25 14:53:06 +01006940 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006941 while (node) {
6942 issuer = container_of(node, typeof(*issuer), node);
6943 back = eb64_next(node);
6944 eb64_delete(node);
6945 free(issuer->path);
6946 sk_X509_pop_free(issuer->chain, X509_free);
6947 free(issuer);
6948 node = back;
6949 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006950}
6951
William Lallemandd7bfbe22022-04-11 18:41:24 +02006952#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006953static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01006954 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006955
Emeric Brun3854e012017-05-17 20:42:48 +02006956 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006957 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006958 err_code = ERR_ABORT;
6959 }
6960 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006961}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006962#endif
6963
Willy Tarreaude5675a2021-01-20 14:41:29 +01006964/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006965 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01006966 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01006967static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01006968{
6969 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006970 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006971
6972 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006973 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006974
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006975 if (sctx->conn != conn) {
6976 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
6977 ret = 1;
6978 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01006979 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
6980
6981 if (sctx->xprt) {
6982 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
6983 if (sctx->xprt_ctx)
6984 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
6985 }
6986
6987 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006988
6989 /* as soon as a shutdown is reported the lower layer unregisters its
6990 * subscriber, so the situations below are transient and rare enough to
6991 * be reported as suspicious. In any case they shouldn't last.
6992 */
6993 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
6994 ret = 1;
6995 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
6996 ret = 1;
6997
Willy Tarreaude5675a2021-01-20 14:41:29 +01006998 chunk_appendf(&trash, " .subs=%p", sctx->subs);
6999 if (sctx->subs) {
7000 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007001 if (sctx->subs->tasklet->calls >= 1000000)
7002 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007003 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
7004 sctx->subs->tasklet->calls,
7005 sctx->subs->tasklet->context);
7006 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
7007 chunk_appendf(&trash, ")");
7008 }
7009 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
7010 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007011 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007012}
7013
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007014#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02007015/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007016 * each reference. The variable <ref> must point to the current node's list
7017 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02007018 */
William Lallemand32af2032016-10-29 18:09:35 +02007019static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007020struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02007021{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007022 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007023 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02007024
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007025 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007026 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007027 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02007028
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007029 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02007030}
7031
7032static inline
7033struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
7034{
7035 int id;
7036 char *error;
7037
7038 /* If the reference starts by a '#', this is numeric id. */
7039 if (reference[0] == '#') {
7040 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
7041 id = strtol(reference + 1, &error, 10);
7042 if (*error != '\0')
7043 return NULL;
7044
7045 /* Perform the unique id lookup. */
7046 return tlskeys_ref_lookupid(id);
7047 }
7048
7049 /* Perform the string lookup. */
7050 return tlskeys_ref_lookup(reference);
7051}
7052#endif
7053
7054
7055#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7056
Willy Tarreaua9380522022-05-05 08:50:17 +02007057/* dumps all tls keys. Relies on the show_keys_ctx context from the appctx. */
Willy Tarreaubd338642022-05-05 08:59:17 +02007058static int cli_io_handler_tlskeys_files(struct appctx *appctx)
7059{
Willy Tarreaua9380522022-05-05 08:50:17 +02007060 struct show_keys_ctx *ctx = appctx->svcctx;
William Lallemand32af2032016-10-29 18:09:35 +02007061
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007062 switch (ctx->state) {
7063 case SHOW_KEYS_INIT:
William Lallemand32af2032016-10-29 18:09:35 +02007064 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08007065 * quit the function with returning 0. The function is called
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007066 * later and restart at the state "SHOW_KEYS_INIT".
William Lallemand32af2032016-10-29 18:09:35 +02007067 */
7068 chunk_reset(&trash);
7069
Willy Tarreaubd338642022-05-05 08:59:17 +02007070 if (ctx->dump_entries)
William Lallemand32af2032016-10-29 18:09:35 +02007071 chunk_appendf(&trash, "# id secret\n");
7072 else
7073 chunk_appendf(&trash, "# id (file)\n");
7074
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007075 if (applet_putchk(appctx, &trash) == -1)
William Lallemand32af2032016-10-29 18:09:35 +02007076 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007077
William Lallemand32af2032016-10-29 18:09:35 +02007078 /* Now, we start the browsing of the references lists.
7079 * Note that the following call to LIST_ELEM return bad pointer. The only
7080 * available field of this pointer is <list>. It is used with the function
7081 * tlskeys_list_get_next() for retruning the first available entry
7082 */
Willy Tarreaua9380522022-05-05 08:50:17 +02007083 if (ctx->next_ref == NULL)
7084 ctx->next_ref = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007085
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007086 ctx->state = SHOW_KEYS_LIST;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007087 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007088
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007089 case SHOW_KEYS_LIST:
Willy Tarreaua9380522022-05-05 08:50:17 +02007090 while (ctx->next_ref) {
7091 struct tls_keys_ref *ref = ctx->next_ref;
William Lallemand32af2032016-10-29 18:09:35 +02007092
7093 chunk_reset(&trash);
Willy Tarreaubd338642022-05-05 08:59:17 +02007094 if (ctx->dump_entries && ctx->next_index == 0)
William Lallemand32af2032016-10-29 18:09:35 +02007095 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007096
Willy Tarreaua9380522022-05-05 08:50:17 +02007097 if (ctx->next_index == 0)
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007098 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
7099
Willy Tarreaubd338642022-05-05 08:59:17 +02007100 if (ctx->dump_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01007101 int head;
7102
7103 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
7104 head = ref->tls_ticket_enc_index;
Willy Tarreaua9380522022-05-05 08:50:17 +02007105 while (ctx->next_index < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02007106 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02007107
7108 chunk_reset(t2);
7109 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01007110 if (ref->key_size_bits == 128) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007111 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007112 sizeof(struct tls_sess_key_128),
7113 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007114 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007115 t2->area);
7116 }
7117 else if (ref->key_size_bits == 256) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007118 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007119 sizeof(struct tls_sess_key_256),
7120 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007121 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007122 t2->area);
7123 }
7124 else {
7125 /* This case should never happen */
Willy Tarreaua9380522022-05-05 08:50:17 +02007126 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, ctx->next_index);
Emeric Brun9e754772019-01-10 17:51:55 +01007127 }
William Lallemand32af2032016-10-29 18:09:35 +02007128
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007129 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007130 /* let's try again later from this stream. We add ourselves into
7131 * this stream's users so that it can remove us upon termination.
7132 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01007133 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
William Lallemand32af2032016-10-29 18:09:35 +02007134 return 0;
7135 }
Willy Tarreaua9380522022-05-05 08:50:17 +02007136 ctx->next_index++;
William Lallemand32af2032016-10-29 18:09:35 +02007137 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01007138 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaua9380522022-05-05 08:50:17 +02007139 ctx->next_index = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007140 }
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007141 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007142 /* let's try again later from this stream. We add ourselves into
7143 * this stream's users so that it can remove us upon termination.
7144 */
William Lallemand32af2032016-10-29 18:09:35 +02007145 return 0;
7146 }
7147
Willy Tarreaua9380522022-05-05 08:50:17 +02007148 if (ctx->names_only == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02007149 break;
7150
7151 /* get next list entry and check the end of the list */
Willy Tarreaua9380522022-05-05 08:50:17 +02007152 ctx->next_ref = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007153 }
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007154 ctx->state = SHOW_KEYS_DONE;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007155 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007156
7157 default:
William Lallemand32af2032016-10-29 18:09:35 +02007158 return 1;
7159 }
7160 return 0;
7161}
7162
Willy Tarreaua9380522022-05-05 08:50:17 +02007163/* Prepares a "show_keys_ctx" and sets the appropriate io_handler if needed */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007164static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007165{
Willy Tarreaua9380522022-05-05 08:50:17 +02007166 struct show_keys_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
7167
William Lallemand32af2032016-10-29 18:09:35 +02007168 /* no parameter, shows only file list */
7169 if (!*args[2]) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007170 ctx->names_only = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007171 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007172 }
7173
7174 if (args[2][0] == '*') {
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007175 /* list every TLS ticket keys */
7176 ctx->names_only = 1;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007177 } else {
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007178 ctx->next_ref = tlskeys_ref_lookup_ref(args[2]);
7179 if (!ctx->next_ref)
7180 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007181 }
7182
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007183 ctx->dump_entries = 1;
7184 return 0;
7185}
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007186
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007187static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
7188{
7189 struct tls_keys_ref *ref;
7190 int ret;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007191
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007192 /* Expect two parameters: the filename and the new new TLS key in encoding */
7193 if (!*args[3] || !*args[4])
7194 return cli_err(appctx, "'set ssl tls-key' expects a filename and the new TLS key in base64 encoding.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007195
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007196 ref = tlskeys_ref_lookup_ref(args[3]);
7197 if (!ref)
7198 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007199
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007200 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
7201 if (ret < 0)
7202 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007203
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007204 trash.data = ret;
7205 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
7206 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007207
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007208 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007209}
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007210#endif
7211
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007212
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007213#ifdef HAVE_SSL_PROVIDERS
7214struct provider_name {
7215 const char *name;
7216 struct list list;
7217};
7218
7219
7220static int ssl_provider_get_name_cb(OSSL_PROVIDER *provider, void *cbdata)
7221{
7222 struct list *provider_names = cbdata;
7223 struct provider_name *item = NULL;
7224 const char *name = OSSL_PROVIDER_get0_name(provider);
7225
7226 if (!provider_names)
7227 return 0;
7228
7229 item = calloc(1, sizeof(*item));
7230
7231 if (!item)
7232 return 0;
7233
7234 item->name = name;
7235 LIST_APPEND(provider_names, &item->list);
7236
7237 return 1;
7238}
7239
7240static void ssl_provider_get_name_list(struct list *provider_names)
7241{
7242 if (!provider_names)
7243 return;
7244
7245 OSSL_PROVIDER_do_all(NULL, ssl_provider_get_name_cb, provider_names);
7246}
7247
7248static void ssl_provider_clear_name_list(struct list *provider_names)
7249{
7250 struct provider_name *item = NULL, *item_s = NULL;
7251
7252 if (provider_names) {
7253 list_for_each_entry_safe(item, item_s, provider_names, list) {
7254 LIST_DELETE(&item->list);
7255 free(item);
7256 }
7257 }
7258}
7259
7260static int cli_io_handler_show_providers(struct appctx *appctx)
7261{
7262 struct buffer *trash = get_trash_chunk();
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007263 struct list provider_names;
7264 struct provider_name *name;
7265
7266 LIST_INIT(&provider_names);
7267
7268 chunk_appendf(trash, "Loaded providers : \n");
7269
7270 ssl_provider_get_name_list(&provider_names);
7271
7272 list_for_each_entry(name, &provider_names, list) {
7273 chunk_appendf(trash, "\t- %s\n", name->name);
7274 }
7275
7276 ssl_provider_clear_name_list(&provider_names);
7277
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007278 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007279 goto yield;
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007280
7281 return 1;
7282
7283yield:
7284 return 0;
7285}
7286#endif
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01007287
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007288
William Lallemand32af2032016-10-29 18:09:35 +02007289/* register cli keywords */
7290static struct cli_kw_list cli_kws = {{ },{
7291#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01007292 { { "show", "tls-keys", NULL }, "show tls-keys [id|*] : show tls keys references or dump tls ticket keys when id specified", cli_parse_show_tlskeys, cli_io_handler_tlskeys_files },
7293 { { "set", "ssl", "tls-key", NULL }, "set ssl tls-key [id|file] <key> : set the next TLS key for the <id> or <file> listener to <key>", cli_parse_set_tlskeys, NULL },
William Lallemand32af2032016-10-29 18:09:35 +02007294#endif
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007295#ifdef HAVE_SSL_PROVIDERS
7296 { { "show", "ssl", "providers", NULL }, "show ssl providers : show loaded SSL providers", NULL, cli_io_handler_show_providers },
7297#endif
William Lallemand32af2032016-10-29 18:09:35 +02007298 { { NULL }, NULL, NULL, NULL }
7299}};
7300
Willy Tarreau0108d902018-11-25 19:14:37 +01007301INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02007302
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02007303/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02007304struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02007305 .snd_buf = ssl_sock_from_buf,
7306 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01007307 .subscribe = ssl_subscribe,
7308 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02007309 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02007310 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02007311 .rcv_pipe = NULL,
7312 .snd_pipe = NULL,
7313 .shutr = NULL,
7314 .shutw = ssl_sock_shutw,
7315 .close = ssl_sock_close,
7316 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01007317 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01007318 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01007319 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01007320 .prepare_srv = ssl_sock_prepare_srv_ctx,
7321 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007322 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02007323 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01007324 .set_idle = ssl_set_idle,
7325 .set_used = ssl_set_used,
Willy Tarreaude827952022-04-11 10:43:28 +02007326 .get_ssl_sock_ctx = ssl_sock_get_ctx,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01007327 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01007328 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02007329};
7330
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007331enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
7332 struct session *sess, struct stream *s, int flags)
7333{
7334 struct connection *conn;
7335
7336 conn = objt_conn(sess->origin);
7337
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007338 if (conn) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007339 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007340 sc_ep_set(s->scf, SE_FL_WAIT_FOR_HS);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007341 s->req.flags |= CF_READ_NULL;
7342 return ACT_RET_YIELD;
7343 }
7344 }
7345 return (ACT_RET_CONT);
7346}
7347
7348static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
7349{
7350 rule->action_ptr = ssl_action_wait_for_hs;
7351
7352 return ACT_RET_PRS_OK;
7353}
7354
7355static struct action_kw_list http_req_actions = {ILH, {
7356 { "wait-for-handshake", ssl_parse_wait_for_hs },
7357 { /* END */ }
7358}};
7359
Willy Tarreau0108d902018-11-25 19:14:37 +01007360INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
7361
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007362#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007363
7364static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7365{
7366 if (ptr) {
7367 chunk_destroy(ptr);
7368 free(ptr);
7369 }
7370}
7371
7372#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007373
William Lallemand76b4a122020-08-04 17:41:39 +02007374
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007375static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7376{
Willy Tarreaubafbe012017-11-24 17:34:44 +01007377 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007378}
William Lallemand7d42ef52020-07-06 11:41:30 +02007379
William Lallemand722180a2021-06-09 16:46:12 +02007380#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007381static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7382{
7383 struct ssl_keylog *keylog;
7384
7385 if (!ptr)
7386 return;
7387
7388 keylog = ptr;
7389
7390 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7391 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7392 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7393 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7394 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7395 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7396 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7397 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7398
7399 pool_free(pool_head_ssl_keylog, ptr);
7400}
7401#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007402
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007403static void ssl_sock_clt_crt_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7404{
7405 if (!ptr)
7406 return;
7407
7408 X509_free((X509*)ptr);
7409}
7410
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01007411static void ssl_sock_clt_sni_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7412{
7413 pool_free(ssl_sock_client_sni_pool, ptr);
7414}
7415
Willy Tarreau92faadf2012-10-10 23:04:25 +02007416static void __ssl_sock_init(void)
7417{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007418#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007419 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007420 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007421#endif
Emeric Brun46591952012-05-18 15:47:34 +02007422
Willy Tarreauef934602016-12-22 23:12:01 +01007423 if (global_ssl.listen_default_ciphers)
7424 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7425 if (global_ssl.connect_default_ciphers)
7426 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007427#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007428 if (global_ssl.listen_default_ciphersuites)
7429 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7430 if (global_ssl.connect_default_ciphersuites)
7431 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7432#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007433
Willy Tarreau13e14102016-12-22 20:25:26 +01007434 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007435#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007436 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007437#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007438#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007439 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007440 n = sk_SSL_COMP_num(cm);
7441 while (n--) {
7442 (void) sk_SSL_COMP_pop(cm);
7443 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007444#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007445
Willy Tarreau5db847a2019-05-09 14:13:35 +02007446#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007447 ssl_locking_init();
7448#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007449#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007450 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
7451#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007452
7453#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7454 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
7455#endif
7456
Thierry FOURNIER28962c92018-06-17 21:37:05 +02007457 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02007458 ssl_capture_ptr_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_capture_free_func);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01007459#ifdef USE_QUIC
7460 ssl_qc_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7461#endif /* USE_QUIC */
William Lallemand722180a2021-06-09 16:46:12 +02007462#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007463 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
7464#endif
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007465 ssl_client_crt_ref_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_clt_crt_free_func);
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01007466 ssl_client_sni_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_clt_sni_free_func);
William Lallemandd7bfbe22022-04-11 18:41:24 +02007467#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00007468 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007469 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007470#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01007471#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7472 hap_register_post_check(tlskeys_finalize_config);
7473#endif
Willy Tarreau80713382018-11-26 10:19:54 +01007474
7475 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
7476 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
7477
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007478 hap_register_post_deinit(ssl_free_global_issuers);
7479
Willy Tarreau80713382018-11-26 10:19:54 +01007480#ifndef OPENSSL_NO_DH
7481 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7482 hap_register_post_deinit(ssl_free_dh);
7483#endif
William Lallemandd7bfbe22022-04-11 18:41:24 +02007484#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Willy Tarreau80713382018-11-26 10:19:54 +01007485 hap_register_post_deinit(ssl_free_engines);
7486#endif
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02007487#ifdef HAVE_SSL_PROVIDERS
7488 hap_register_post_deinit(ssl_unload_providers);
7489#endif
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01007490#if HA_OPENSSL_VERSION_NUMBER < 0x3000000fL
Willy Tarreau80713382018-11-26 10:19:54 +01007491 /* Load SSL string for the verbose & debug mode. */
7492 ERR_load_SSL_strings();
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01007493#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007494 ha_meth = BIO_meth_new(0x666, "ha methods");
7495 BIO_meth_set_write(ha_meth, ha_ssl_write);
7496 BIO_meth_set_read(ha_meth, ha_ssl_read);
7497 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
7498 BIO_meth_set_create(ha_meth, ha_ssl_new);
7499 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
7500 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
7501 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02007502
7503 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007504
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01007505 HA_SPIN_INIT(&ocsp_tree_lock);
7506
Dragan Dosen9ac98092020-05-11 15:51:45 +02007507 /* Try to register dedicated SSL/TLS protocol message callbacks for
7508 * heartbleed attack (CVE-2014-0160) and clienthello.
7509 */
7510 hap_register_post_check(ssl_sock_register_msg_callbacks);
7511
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007512 /* Try to free all callbacks that were registered by using
7513 * ssl_sock_register_msg_callback().
7514 */
7515 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01007516}
Willy Tarreau79367f92022-04-25 19:18:24 +02007517INITCALL0(STG_REGISTER, __ssl_sock_init);
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01007518
Willy Tarreau80713382018-11-26 10:19:54 +01007519/* Compute and register the version string */
7520static void ssl_register_build_options()
7521{
7522 char *ptr = NULL;
7523 int i;
7524
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007525 memprintf(&ptr, "Built with OpenSSL version : "
7526#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007527 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007528#else /* OPENSSL_IS_BORINGSSL */
7529 OPENSSL_VERSION_TEXT
7530 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08007531 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02007532 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007533#endif
7534 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007535#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007536 "no (library version too old)"
7537#elif defined(OPENSSL_NO_TLSEXT)
7538 "no (disabled via OPENSSL_NO_TLSEXT)"
7539#else
7540 "yes"
7541#endif
7542 "", ptr);
7543
7544 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
7545#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
7546 "yes"
7547#else
7548#ifdef OPENSSL_NO_TLSEXT
7549 "no (because of OPENSSL_NO_TLSEXT)"
7550#else
7551 "no (version might be too old, 0.9.8f min needed)"
7552#endif
7553#endif
7554 "", ptr);
7555
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02007556 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
7557 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
7558 if (methodVersions[i].option)
7559 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007560
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007561#ifdef HAVE_SSL_PROVIDERS
7562 {
7563 struct list provider_names;
7564 struct provider_name *name;
7565 LIST_INIT(&provider_names);
7566 ssl_provider_get_name_list(&provider_names);
7567
7568 memprintf(&ptr, "%s\nOpenSSL providers loaded :", ptr);
7569
7570 list_for_each_entry(name, &provider_names, list) {
7571 memprintf(&ptr, "%s %s", ptr, name->name);
7572 }
7573
7574 ssl_provider_clear_name_list(&provider_names);
7575 }
7576#endif
7577
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007578 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01007579}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007580
Willy Tarreau80713382018-11-26 10:19:54 +01007581INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02007582
William Lallemandd7bfbe22022-04-11 18:41:24 +02007583#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00007584void ssl_free_engines(void) {
7585 struct ssl_engine_list *wl, *wlb;
7586 /* free up engine list */
7587 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
7588 ENGINE_finish(wl->e);
7589 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02007590 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00007591 free(wl);
7592 }
7593}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007594#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02007595
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02007596#ifdef HAVE_SSL_PROVIDERS
7597void ssl_unload_providers(void) {
7598 struct ssl_provider_list *prov, *provb;
7599 list_for_each_entry_safe(prov, provb, &openssl_providers, list) {
7600 OSSL_PROVIDER_unload(prov->provider);
7601 LIST_DELETE(&prov->list);
7602 free(prov);
7603 }
7604}
7605#endif
7606
Remi Gacogned3a23c32015-05-28 16:39:47 +02007607#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00007608void ssl_free_dh(void) {
7609 if (local_dh_1024) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007610 HASSL_DH_free(local_dh_1024);
Grant Zhang872f9c22017-01-21 01:10:18 +00007611 local_dh_1024 = NULL;
7612 }
7613 if (local_dh_2048) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007614 HASSL_DH_free(local_dh_2048);
Grant Zhang872f9c22017-01-21 01:10:18 +00007615 local_dh_2048 = NULL;
7616 }
7617 if (local_dh_4096) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007618 HASSL_DH_free(local_dh_4096);
Grant Zhang872f9c22017-01-21 01:10:18 +00007619 local_dh_4096 = NULL;
7620 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02007621 if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007622 HASSL_DH_free(global_dh);
Remi Gacogne47783ef2015-05-29 15:53:22 +02007623 global_dh = NULL;
7624 }
Grant Zhang872f9c22017-01-21 01:10:18 +00007625}
7626#endif
7627
Grant Zhang872f9c22017-01-21 01:10:18 +00007628static void __ssl_sock_deinit(void)
7629{
7630#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007631 if (ssl_ctx_lru_tree) {
7632 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007633 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02007634 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02007635#endif
7636
Willy Tarreau5db847a2019-05-09 14:13:35 +02007637#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007638 ERR_remove_state(0);
7639 ERR_free_strings();
7640
7641 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08007642#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007643
Willy Tarreau5db847a2019-05-09 14:13:35 +02007644#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007645 CRYPTO_cleanup_all_ex_data();
7646#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007647 BIO_meth_free(ha_meth);
Remi Tricot-Le Breton6477bbd2022-12-20 11:11:13 +01007648
7649#if !defined OPENSSL_NO_OCSP
7650 ssl_destroy_ocsp_update_task();
7651#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007652}
Willy Tarreau79367f92022-04-25 19:18:24 +02007653REGISTER_POST_DEINIT(__ssl_sock_deinit);
Remi Gacogned3a23c32015-05-28 16:39:47 +02007654
William Dauchyf6370442020-11-14 19:25:33 +01007655
Emeric Brun46591952012-05-18 15:47:34 +02007656/*
7657 * Local variables:
7658 * c-indent-level: 8
7659 * c-basic-offset: 8
7660 * End:
7661 */