blob: 5993a72b0647fc46ca163bdc31f3a82ac8e36c5d [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
Remi Tricot-Le Breton58432372023-02-28 17:46:29 +0100135 .keylog = 0,
136#endif
137#ifndef OPENSSL_NO_OCSP
138 .ocsp_update.delay_max = SSL_OCSP_UPDATE_DELAY_MAX,
139 .ocsp_update.delay_min = SSL_OCSP_UPDATE_DELAY_MIN,
William Lallemand7d42ef52020-07-06 11:41:30 +0200140#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100141};
142
Olivier Houcharda8955d52019-04-07 22:00:38 +0200143static BIO_METHOD *ha_meth;
144
Willy Tarreaub8dec4a2022-06-23 11:02:08 +0200145DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx", sizeof(struct ssl_sock_ctx));
Olivier Houchard66ab4982019-02-26 18:37:15 +0100146
Willy Tarreaub8dec4a2022-06-23 11:02:08 +0200147DECLARE_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 +0100148
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100149/* ssl stats module */
150enum {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100151 SSL_ST_SESS,
152 SSL_ST_REUSED_SESS,
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100153 SSL_ST_FAILED_HANDSHAKE,
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100154
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100155 SSL_ST_STATS_COUNT /* must be the last member of the enum */
156};
157
158static struct name_desc ssl_stats[] = {
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100159 [SSL_ST_SESS] = { .name = "ssl_sess",
160 .desc = "Total number of ssl sessions established" },
161 [SSL_ST_REUSED_SESS] = { .name = "ssl_reused_sess",
162 .desc = "Total number of ssl sessions reused" },
163 [SSL_ST_FAILED_HANDSHAKE] = { .name = "ssl_failed_handshake",
164 .desc = "Total number of failed handshake" },
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100165};
166
167static struct ssl_counters {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100168 long long sess;
169 long long reused_sess;
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100170 long long failed_handshake;
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100171} ssl_counters;
172
173static void ssl_fill_stats(void *data, struct field *stats)
174{
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100175 struct ssl_counters *counters = data;
176
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100177 stats[SSL_ST_SESS] = mkf_u64(FN_COUNTER, counters->sess);
178 stats[SSL_ST_REUSED_SESS] = mkf_u64(FN_COUNTER, counters->reused_sess);
179 stats[SSL_ST_FAILED_HANDSHAKE] = mkf_u64(FN_COUNTER, counters->failed_handshake);
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100180}
181
182static struct stats_module ssl_stats_module = {
183 .name = "ssl",
184 .fill_stats = ssl_fill_stats,
185 .stats = ssl_stats,
186 .stats_count = SSL_ST_STATS_COUNT,
187 .counters = &ssl_counters,
188 .counters_size = sizeof(ssl_counters),
189 .domain_flags = MK_STATS_PROXY_DOMAIN(STATS_PX_CAP_FE|STATS_PX_CAP_LI|STATS_PX_CAP_BE|STATS_PX_CAP_SRV),
190 .clearable = 1,
191};
192
193INITCALL1(STG_REGISTER, stats_register_module, &ssl_stats_module);
194
Willy Tarreaua9380522022-05-05 08:50:17 +0200195/* CLI context for "show tls-keys" */
196struct show_keys_ctx {
197 struct tls_keys_ref *next_ref; /* next reference to be dumped */
198 int names_only; /* non-zero = only show file names */
199 int next_index; /* next index to be dumped */
Willy Tarreaubd338642022-05-05 08:59:17 +0200200 int dump_entries; /* dump entries also */
Willy Tarreau9c5a38c2022-05-05 09:03:44 +0200201 enum {
202 SHOW_KEYS_INIT = 0,
203 SHOW_KEYS_LIST,
204 SHOW_KEYS_DONE,
205 } state; /* phase of the current dump */
Willy Tarreaua9380522022-05-05 08:50:17 +0200206};
207
Willy Tarreau691d5032021-01-20 14:55:01 +0100208/* ssl_sock_io_cb is exported to see it resolved in "show fd" */
Willy Tarreau144f84a2021-03-02 16:09:26 +0100209struct task *ssl_sock_io_cb(struct task *, void *, unsigned int);
Olivier Houchard000694c2019-05-23 14:45:12 +0200210static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
Olivier Houchardea8dd942019-05-20 14:02:16 +0200211
Olivier Houcharda8955d52019-04-07 22:00:38 +0200212/* Methods to implement OpenSSL BIO */
213static int ha_ssl_write(BIO *h, const char *buf, int num)
214{
215 struct buffer tmpbuf;
216 struct ssl_sock_ctx *ctx;
Willy Tarreauac78c4f2023-03-17 16:13:05 +0100217 uint flags;
Olivier Houcharda8955d52019-04-07 22:00:38 +0200218 int ret;
219
220 ctx = BIO_get_data(h);
221 tmpbuf.size = num;
222 tmpbuf.area = (void *)(uintptr_t)buf;
223 tmpbuf.data = num;
224 tmpbuf.head = 0;
Willy Tarreauac78c4f2023-03-17 16:13:05 +0100225 flags = (ctx->xprt_st & SSL_SOCK_SEND_MORE) ? CO_SFL_MSG_MORE : 0;
226 ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, flags);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200227 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200228 BIO_set_retry_write(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200229 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200230 } else if (ret == 0)
231 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200232 return ret;
233}
234
235static int ha_ssl_gets(BIO *h, char *buf, int size)
236{
237
238 return 0;
239}
240
241static int ha_ssl_puts(BIO *h, const char *str)
242{
243
244 return ha_ssl_write(h, str, strlen(str));
245}
246
247static int ha_ssl_read(BIO *h, char *buf, int size)
248{
249 struct buffer tmpbuf;
250 struct ssl_sock_ctx *ctx;
251 int ret;
252
253 ctx = BIO_get_data(h);
254 tmpbuf.size = size;
255 tmpbuf.area = buf;
256 tmpbuf.data = 0;
257 tmpbuf.head = 0;
258 ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200259 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200260 BIO_set_retry_read(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200261 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200262 } else if (ret == 0)
263 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200264
265 return ret;
266}
267
268static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
269{
270 int ret = 0;
271 switch (cmd) {
272 case BIO_CTRL_DUP:
273 case BIO_CTRL_FLUSH:
274 ret = 1;
275 break;
276 }
277 return ret;
278}
279
280static int ha_ssl_new(BIO *h)
281{
282 BIO_set_init(h, 1);
283 BIO_set_data(h, NULL);
284 BIO_clear_flags(h, ~0);
285 return 1;
286}
287
288static int ha_ssl_free(BIO *data)
289{
290
291 return 1;
292}
293
294
Willy Tarreau5db847a2019-05-09 14:13:35 +0200295#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100296
Emeric Brun821bb9b2017-06-15 16:37:39 +0200297static HA_RWLOCK_T *ssl_rwlocks;
298
299
300unsigned long ssl_id_function(void)
301{
302 return (unsigned long)tid;
303}
304
305void ssl_locking_function(int mode, int n, const char * file, int line)
306{
307 if (mode & CRYPTO_LOCK) {
308 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100309 HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200310 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100311 HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200312 }
313 else {
314 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100315 HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200316 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100317 HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200318 }
319}
320
321static int ssl_locking_init(void)
322{
323 int i;
324
325 ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
326 if (!ssl_rwlocks)
327 return -1;
328
329 for (i = 0 ; i < CRYPTO_num_locks() ; i++)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100330 HA_RWLOCK_INIT(&ssl_rwlocks[i]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200331
332 CRYPTO_set_id_callback(ssl_id_function);
333 CRYPTO_set_locking_callback(ssl_locking_function);
334
335 return 0;
336}
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100337
Emeric Brun821bb9b2017-06-15 16:37:39 +0200338#endif
339
Willy Tarreauaf613e82020-06-05 08:40:51 +0200340__decl_thread(HA_SPINLOCK_T ckch_lock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200341
William Lallemandbc6ca7c2019-10-29 23:48:19 +0100342
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200343
344/* mimic what X509_STORE_load_locations do with store_ctx */
345static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
346{
Remi Tricot-Le Bretond75b99e2021-05-17 11:45:55 +0200347 X509_STORE *store = NULL;
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +0100348 struct cafile_entry *ca_e = ssl_store_get_cafile_entry(path, 0);
349 if (ca_e)
350 store = ca_e->ca_store;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200351 if (store_ctx && store) {
352 int i;
353 X509_OBJECT *obj;
354 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
355 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
356 obj = sk_X509_OBJECT_value(objs, i);
357 switch (X509_OBJECT_get_type(obj)) {
358 case X509_LU_X509:
359 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
360 break;
361 case X509_LU_CRL:
362 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
363 break;
364 default:
365 break;
366 }
367 }
368 return 1;
369 }
370 return 0;
371}
372
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500373/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200374static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
375{
376 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
377 return ssl_set_cert_crl_file(store_ctx, path);
378}
379
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200380/*
381 Extract CA_list from CA_file already in tree.
382 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
383 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
384*/
385static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
386{
387 struct ebmb_node *eb;
388 struct cafile_entry *ca_e;
389
390 eb = ebst_lookup(&cafile_tree, path);
391 if (!eb)
392 return NULL;
393 ca_e = ebmb_entry(eb, struct cafile_entry, node);
394
395 if (ca_e->ca_list == NULL) {
396 int i;
397 unsigned long key;
398 struct eb_root ca_name_tree = EB_ROOT;
399 struct eb64_node *node, *back;
400 struct {
401 struct eb64_node node;
402 X509_NAME *xname;
403 } *ca_name;
404 STACK_OF(X509_OBJECT) *objs;
405 STACK_OF(X509_NAME) *skn;
406 X509 *x;
407 X509_NAME *xn;
408
409 skn = sk_X509_NAME_new_null();
410 /* take x509 from cafile_tree */
411 objs = X509_STORE_get0_objects(ca_e->ca_store);
412 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
413 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
414 if (!x)
415 continue;
416 xn = X509_get_subject_name(x);
417 if (!xn)
418 continue;
419 /* Check for duplicates. */
420 key = X509_NAME_hash(xn);
421 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
422 node && ca_name == NULL;
423 node = eb64_next(node)) {
424 ca_name = container_of(node, typeof(*ca_name), node);
425 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
426 ca_name = NULL;
427 }
428 /* find a duplicate */
429 if (ca_name)
430 continue;
431 ca_name = calloc(1, sizeof *ca_name);
432 xn = X509_NAME_dup(xn);
433 if (!ca_name ||
434 !xn ||
435 !sk_X509_NAME_push(skn, xn)) {
436 free(ca_name);
437 X509_NAME_free(xn);
438 sk_X509_NAME_pop_free(skn, X509_NAME_free);
439 sk_X509_NAME_free(skn);
440 skn = NULL;
441 break;
442 }
443 ca_name->node.key = key;
444 ca_name->xname = xn;
445 eb64_insert(&ca_name_tree, &ca_name->node);
446 }
447 ca_e->ca_list = skn;
448 /* remove temporary ca_name tree */
449 node = eb64_first(&ca_name_tree);
450 while (node) {
451 ca_name = container_of(node, typeof(*ca_name), node);
452 back = eb64_next(node);
453 eb64_delete(node);
454 free(ca_name);
455 node = back;
456 }
457 }
458 return ca_e->ca_list;
459}
460
Willy Tarreauff882702021-04-10 17:23:00 +0200461struct pool_head *pool_head_ssl_capture __read_mostly = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200462int ssl_capture_ptr_index = -1;
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +0100463int ssl_app_data_index = -1;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +0100464#ifdef USE_QUIC
465int ssl_qc_app_data_index = -1;
466#endif /* USE_QUIC */
Willy Tarreauef934602016-12-22 23:12:01 +0100467
William Lallemand722180a2021-06-09 16:46:12 +0200468#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200469int ssl_keylog_index = -1;
Willy Tarreauff882702021-04-10 17:23:00 +0200470struct pool_head *pool_head_ssl_keylog __read_mostly = NULL;
471struct pool_head *pool_head_ssl_keylog_str __read_mostly = NULL;
William Lallemand7d42ef52020-07-06 11:41:30 +0200472#endif
473
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +0200474int ssl_client_crt_ref_index = -1;
475
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100476/* Used to store the client's SNI in case of ClientHello callback error */
477int ssl_client_sni_index = -1;
478
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200479#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
480struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
481#endif
482
William Lallemandd7bfbe22022-04-11 18:41:24 +0200483#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200484unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000485struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
486struct ssl_engine_list {
487 struct list list;
488 ENGINE *e;
489};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200490#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000491
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +0200492#ifdef HAVE_SSL_PROVIDERS
493struct list openssl_providers = LIST_HEAD_INIT(openssl_providers);
494struct ssl_provider_list {
495 struct list list;
496 OSSL_PROVIDER *provider;
497};
498#endif
499
Remi Gacogne8de54152014-07-15 11:36:40 +0200500#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200501static int ssl_dh_ptr_index = -1;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +0100502static HASSL_DH *global_dh = NULL;
503static HASSL_DH *local_dh_1024 = NULL;
504static HASSL_DH *local_dh_2048 = NULL;
505static HASSL_DH *local_dh_4096 = NULL;
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100506#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +0100507static DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100508#else
509static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey);
510#endif
Remi Gacogne8de54152014-07-15 11:36:40 +0200511#endif /* OPENSSL_NO_DH */
512
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100513#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200514/* X509V3 Extensions that will be added on generated certificates */
515#define X509V3_EXT_SIZE 5
516static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
517 "basicConstraints",
518 "nsComment",
519 "subjectKeyIdentifier",
520 "authorityKeyIdentifier",
521 "keyUsage",
522};
523static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
524 "CA:FALSE",
525 "\"OpenSSL Generated Certificate\"",
526 "hash",
527 "keyid,issuer:always",
528 "nonRepudiation,digitalSignature,keyEncipherment"
529};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200530/* LRU cache to store generated certificate */
531static struct lru64_head *ssl_ctx_lru_tree = NULL;
532static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200533static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100534__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200535
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200536#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
537
yanbzhube2774d2015-12-10 15:07:30 -0500538/* The order here matters for picking a default context,
539 * keep the most common keytype at the bottom of the list
540 */
541const char *SSL_SOCK_KEYTYPE_NAMES[] = {
542 "dsa",
543 "ecdsa",
544 "rsa"
545};
yanbzhube2774d2015-12-10 15:07:30 -0500546
William Lallemandc3cd35f2017-11-28 11:04:43 +0100547static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100548static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
549
Dragan Dosen9ac98092020-05-11 15:51:45 +0200550/* Dedicated callback functions for heartbeat and clienthello.
551 */
552#ifdef TLS1_RT_HEARTBEAT
553static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
554 int content_type, const void *buf, size_t len,
555 SSL *ssl);
556#endif
557static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
558 int content_type, const void *buf, size_t len,
559 SSL *ssl);
560
William Lallemand722180a2021-06-09 16:46:12 +0200561#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200562static void ssl_init_keylog(struct connection *conn, int write_p, int version,
563 int content_type, const void *buf, size_t len,
564 SSL *ssl);
565#endif
566
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200567/* List head of all registered SSL/TLS protocol message callbacks. */
568struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
569
570/* Registers the function <func> in order to be called on SSL/TLS protocol
571 * message processing. It will return 0 if the function <func> is not set
572 * or if it fails to allocate memory.
573 */
574int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
575{
576 struct ssl_sock_msg_callback *cbk;
577
578 if (!func)
579 return 0;
580
581 cbk = calloc(1, sizeof(*cbk));
582 if (!cbk) {
583 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
584 return 0;
585 }
586
587 cbk->func = func;
588
Willy Tarreau2b718102021-04-21 07:32:39 +0200589 LIST_APPEND(&ssl_sock_msg_callbacks, &cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200590
591 return 1;
592}
593
Dragan Dosen9ac98092020-05-11 15:51:45 +0200594/* Used to register dedicated SSL/TLS protocol message callbacks.
595 */
596static int ssl_sock_register_msg_callbacks(void)
597{
598#ifdef TLS1_RT_HEARTBEAT
599 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
600 return ERR_ABORT;
601#endif
Marcin Deranek310a2602021-07-13 19:04:24 +0200602 if (global_ssl.capture_buffer_size > 0) {
Dragan Dosen9ac98092020-05-11 15:51:45 +0200603 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
604 return ERR_ABORT;
605 }
William Lallemand722180a2021-06-09 16:46:12 +0200606#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200607 if (global_ssl.keylog > 0) {
608 if (!ssl_sock_register_msg_callback(ssl_init_keylog))
609 return ERR_ABORT;
610 }
611#endif
612
Christopher Fauletfc633b62020-11-06 15:24:23 +0100613 return ERR_NONE;
Dragan Dosen9ac98092020-05-11 15:51:45 +0200614}
615
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200616/* Used to free all SSL/TLS protocol message callbacks that were
617 * registered by using ssl_sock_register_msg_callback().
618 */
619static void ssl_sock_unregister_msg_callbacks(void)
620{
621 struct ssl_sock_msg_callback *cbk, *cbkback;
622
623 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +0200624 LIST_DELETE(&cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200625 free(cbk);
626 }
627}
628
Willy Tarreaude827952022-04-11 10:43:28 +0200629static struct ssl_sock_ctx *ssl_sock_get_ctx(struct connection *conn)
630{
631 if (!conn || conn->xprt != xprt_get(XPRT_SSL) || !conn->xprt_ctx)
632 return NULL;
633
634 return (struct ssl_sock_ctx *)conn->xprt_ctx;
635}
636
Dragan Doseneb607fe2020-05-11 17:17:06 +0200637SSL *ssl_sock_get_ssl_object(struct connection *conn)
638{
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200639 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dragan Doseneb607fe2020-05-11 17:17:06 +0200640
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200641 return ctx ? ctx->ssl : NULL;
Dragan Doseneb607fe2020-05-11 17:17:06 +0200642}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100643/*
644 * This function gives the detail of the SSL error. It is used only
645 * if the debug mode and the verbose mode are activated. It dump all
646 * the SSL error until the stack was empty.
647 */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +0200648static forceinline void ssl_sock_dump_errors(struct connection *conn,
649 struct quic_conn *qc)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100650{
651 unsigned long ret;
652
653 if (unlikely(global.mode & MODE_DEBUG)) {
654 while(1) {
Remi Tricot-Le Breton1effd9a2022-02-11 12:04:44 +0100655 const char *func = NULL;
656 ERR_peek_error_func(&func);
657
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100658 ret = ERR_get_error();
659 if (ret == 0)
660 return;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +0200661 if (conn) {
662 fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
663 conn_fd(conn), ret,
664 func, ERR_reason_error_string(ret));
665 }
666#ifdef USE_QUIC
667 else {
668 /* TODO: we are not sure <conn> is always initialized for QUIC connections */
669 fprintf(stderr, "qc @%p OpenSSL error[0x%lx] %s: %s\n", qc, ret,
670 func, ERR_reason_error_string(ret));
671 }
672#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100673 }
674 }
675}
676
yanbzhube2774d2015-12-10 15:07:30 -0500677
William Lallemandd7bfbe22022-04-11 18:41:24 +0200678#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200679int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000680{
681 int err_code = ERR_ABORT;
682 ENGINE *engine;
683 struct ssl_engine_list *el;
684
685 /* grab the structural reference to the engine */
686 engine = ENGINE_by_id(engine_id);
687 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100688 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000689 goto fail_get;
690 }
691
692 if (!ENGINE_init(engine)) {
693 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100694 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000695 goto fail_init;
696 }
697
698 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100699 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000700 goto fail_set_method;
701 }
702
703 el = calloc(1, sizeof(*el));
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200704 if (!el)
705 goto fail_alloc;
Grant Zhang872f9c22017-01-21 01:10:18 +0000706 el->e = engine;
Willy Tarreau2b718102021-04-21 07:32:39 +0200707 LIST_INSERT(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100708 nb_engines++;
709 if (global_ssl.async)
710 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000711 return 0;
712
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200713fail_alloc:
Grant Zhang872f9c22017-01-21 01:10:18 +0000714fail_set_method:
715 /* release the functional reference from ENGINE_init() */
716 ENGINE_finish(engine);
717
718fail_init:
719 /* release the structural reference from ENGINE_by_id() */
720 ENGINE_free(engine);
721
722fail_get:
723 return err_code;
724}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200725#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000726
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +0200727#ifdef HAVE_SSL_PROVIDERS
728int ssl_init_provider(const char *provider_name)
729{
730 int err_code = ERR_ABORT;
731 struct ssl_provider_list *prov = NULL;
732
733 prov = calloc(1, sizeof(*prov));
734 if (!prov) {
735 ha_alert("ssl-provider %s: memory allocation failure\n", provider_name);
736 goto error;
737 }
738
739 if ((prov->provider = OSSL_PROVIDER_load(NULL, provider_name)) == NULL) {
740 ha_alert("ssl-provider %s: unknown provider\n", provider_name);
741 goto error;
742 }
743
744 LIST_INSERT(&openssl_providers, &prov->list);
745
746 return 0;
747
748error:
749 ha_free(&prov);
750 return err_code;
751}
752#endif /* HAVE_SSL_PROVIDERS */
753
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +0500754#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +0200755/*
756 * openssl async fd handler
757 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200758void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000759{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200760 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000761
Emeric Brun3854e012017-05-17 20:42:48 +0200762 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000763 * to poll this fd until it is requested
764 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000765 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000766 fd_cant_recv(fd);
767
768 /* crypto engine is available, let's notify the associated
769 * connection that it can pursue its processing.
770 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200771 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000772}
773
Emeric Brun3854e012017-05-17 20:42:48 +0200774/*
775 * openssl async delayed SSL_free handler
776 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200777void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000778{
779 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200780 OSSL_ASYNC_FD all_fd[32];
781 size_t num_all_fds = 0;
782 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000783
Emeric Brun3854e012017-05-17 20:42:48 +0200784 /* We suppose that the async job for a same SSL *
785 * are serialized. So if we are awake it is
786 * because the running job has just finished
787 * and we can remove all async fds safely
788 */
789 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
790 if (num_all_fds > 32) {
791 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
792 return;
793 }
794
795 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
Emeric Brun7d392a52022-07-01 17:36:50 +0200796 for (i=0 ; i < num_all_fds ; i++) {
797 /* We want to remove the fd from the fdtab
798 * but we flag it to disown because the
799 * close is performed by the engine itself
800 */
801 fdtab[all_fd[i]].state |= FD_DISOWN;
802 fd_delete(all_fd[i]);
803 }
Emeric Brun3854e012017-05-17 20:42:48 +0200804
805 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000806 SSL_free(ssl);
Willy Tarreau82531f62021-10-06 12:15:18 +0200807 _HA_ATOMIC_DEC(&global.sslconns);
Willy Tarreau4781b152021-04-06 13:53:36 +0200808 _HA_ATOMIC_DEC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000809}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000810/*
Emeric Brun3854e012017-05-17 20:42:48 +0200811 * function used to manage a returned SSL_ERROR_WANT_ASYNC
812 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000813 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200814static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000815{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100816 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200817 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200818 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000819 size_t num_add_fds = 0;
820 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200821 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000822
823 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
824 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200825 if (num_add_fds > 32 || num_del_fds > 32) {
826 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 +0000827 return;
828 }
829
Emeric Brun3854e012017-05-17 20:42:48 +0200830 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000831
Emeric Brun3854e012017-05-17 20:42:48 +0200832 /* We remove unused fds from the fdtab */
Emeric Brun7d392a52022-07-01 17:36:50 +0200833 for (i=0 ; i < num_del_fds ; i++) {
834 /* We want to remove the fd from the fdtab
835 * but we flag it to disown because the
836 * close is performed by the engine itself
837 */
838 fdtab[del_fd[i]].state |= FD_DISOWN;
839 fd_delete(del_fd[i]);
840 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000841
Emeric Brun3854e012017-05-17 20:42:48 +0200842 /* We add new fds to the fdtab */
843 for (i=0 ; i < num_add_fds ; i++) {
Willy Tarreau27a32452022-07-07 08:29:00 +0200844 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tgid, ti->ltid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000845 }
846
Emeric Brun3854e012017-05-17 20:42:48 +0200847 num_add_fds = 0;
848 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
849 if (num_add_fds > 32) {
850 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
851 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000852 }
Emeric Brun3854e012017-05-17 20:42:48 +0200853
854 /* We activate the polling for all known async fds */
855 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000856 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200857 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000858 /* To ensure that the fd cache won't be used
859 * We'll prefer to catch a real RD event
860 * because handling an EAGAIN on this fd will
861 * result in a context switch and also
862 * some engines uses a fd in blocking mode.
863 */
864 fd_cant_recv(add_fd[i]);
865 }
Emeric Brun3854e012017-05-17 20:42:48 +0200866
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000867}
868#endif
869
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100870
871/*
872 * Initialize an HMAC context <hctx> using the <key> and <md> parameters.
873 * Returns -1 in case of error, 1 otherwise.
874 */
875static int ssl_hmac_init(MAC_CTX *hctx, unsigned char *key, int key_len, const EVP_MD *md)
876{
877#ifdef HAVE_OSSL_PARAM
878 OSSL_PARAM params[3];
879
880 params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, key, key_len);
881 params[1] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, (char*)EVP_MD_name(md), 0);
882 params[2] = OSSL_PARAM_construct_end();
883 if (EVP_MAC_CTX_set_params(hctx, params) == 0)
884 return -1; /* error in mac initialisation */
885
886#else
887 HMAC_Init_ex(hctx, key, key_len, md, NULL);
888#endif
889 return 1;
890}
891
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100892#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +0100893
894static 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 +0100895{
Frédéric Lécaille6aec1f32022-09-06 17:04:55 +0200896 struct tls_keys_ref *ref = NULL;
Emeric Brun9e754772019-01-10 17:51:55 +0100897 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100898 int head;
899 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +0100900 int ret = -1; /* error by default */
Frédéric Lécaille6aec1f32022-09-06 17:04:55 +0200901 struct connection *conn = SSL_get_ex_data(s, ssl_app_data_index);
902#ifdef USE_QUIC
903 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
904#endif
905
906 if (conn)
907 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
908#ifdef USE_QUIC
909 else if (qc)
910 ref = qc->li->bind_conf->keys_ref;
911#endif
912
913 if (!ref) {
914 /* must never happen */
915 ABORT_NOW();
916 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100917
Christopher Faulet16f45c82018-02-16 11:23:49 +0100918 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
919
920 keys = ref->tlskeys;
921 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100922
923 if (enc) {
924 memcpy(key_name, keys[head].name, 16);
925
926 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +0100927 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100928
Emeric Brun9e754772019-01-10 17:51:55 +0100929 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100930
Emeric Brun9e754772019-01-10 17:51:55 +0100931 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
932 goto end;
933
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100934 if (ssl_hmac_init(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
935 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100936 ret = 1;
937 }
938 else if (ref->key_size_bits == 256 ) {
939
940 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
941 goto end;
942
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100943 if (ssl_hmac_init(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
944 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100945 ret = 1;
946 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100947 } else {
948 for (i = 0; i < TLS_TICKETS_NO; i++) {
949 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
950 goto found;
951 }
Christopher Faulet16f45c82018-02-16 11:23:49 +0100952 ret = 0;
953 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100954
Christopher Faulet16f45c82018-02-16 11:23:49 +0100955 found:
Emeric Brun9e754772019-01-10 17:51:55 +0100956 if (ref->key_size_bits == 128) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100957 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
958 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100959 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
960 goto end;
961 /* 2 for key renewal, 1 if current key is still valid */
962 ret = i ? 2 : 1;
963 }
964 else if (ref->key_size_bits == 256) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100965 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
966 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100967 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
968 goto end;
969 /* 2 for key renewal, 1 if current key is still valid */
970 ret = i ? 2 : 1;
971 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100972 }
Emeric Brun9e754772019-01-10 17:51:55 +0100973
Christopher Faulet16f45c82018-02-16 11:23:49 +0100974 end:
975 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
976 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200977}
978
979struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
980{
981 struct tls_keys_ref *ref;
982
983 list_for_each_entry(ref, &tlskeys_reference, list)
984 if (ref->filename && strcmp(filename, ref->filename) == 0)
985 return ref;
986 return NULL;
987}
988
989struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
990{
991 struct tls_keys_ref *ref;
992
993 list_for_each_entry(ref, &tlskeys_reference, list)
994 if (ref->unique_id == unique_id)
995 return ref;
996 return NULL;
997}
998
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500999/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001000 * match existing ones, this function returns -1
1001 * else it returns 0 on success.
1002 */
1003int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001004 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001005{
Emeric Brun9e754772019-01-10 17:51:55 +01001006 if (ref->key_size_bits == 128) {
1007 if (tlskey->data != sizeof(struct tls_sess_key_128))
1008 return -1;
1009 }
1010 else if (ref->key_size_bits == 256) {
1011 if (tlskey->data != sizeof(struct tls_sess_key_256))
1012 return -1;
1013 }
1014 else
1015 return -1;
1016
Christopher Faulet16f45c82018-02-16 11:23:49 +01001017 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001018 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1019 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001020 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1021 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001022
1023 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001024}
1025
Willy Tarreau83061a82018-07-13 11:56:34 +02001026int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001027{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001028 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1029
1030 if(!ref) {
1031 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1032 return 1;
1033 }
Emeric Brun9e754772019-01-10 17:51:55 +01001034 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1035 memprintf(err, "Invalid key size");
1036 return 1;
1037 }
1038
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001039 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001040}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001041
1042/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001043 * automatic ids. It's called just after the basic checks. It returns
1044 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001045 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001046static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001047{
1048 int i = 0;
1049 struct tls_keys_ref *ref, *ref2, *ref3;
1050 struct list tkr = LIST_HEAD_INIT(tkr);
1051
1052 list_for_each_entry(ref, &tlskeys_reference, list) {
1053 if (ref->unique_id == -1) {
1054 /* Look for the first free id. */
1055 while (1) {
1056 list_for_each_entry(ref2, &tlskeys_reference, list) {
1057 if (ref2->unique_id == i) {
1058 i++;
1059 break;
1060 }
1061 }
1062 if (&ref2->list == &tlskeys_reference)
1063 break;
1064 }
1065
1066 /* Uses the unique id and increment it for the next entry. */
1067 ref->unique_id = i;
1068 i++;
1069 }
1070 }
1071
1072 /* This sort the reference list by id. */
1073 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001074 LIST_DELETE(&ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001075 list_for_each_entry(ref3, &tkr, list) {
1076 if (ref->unique_id < ref3->unique_id) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001077 LIST_APPEND(&ref3->list, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001078 break;
1079 }
1080 }
1081 if (&ref3->list == &tkr)
Willy Tarreau2b718102021-04-21 07:32:39 +02001082 LIST_APPEND(&tkr, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001083 }
1084
1085 /* swap root */
Willy Tarreau2b718102021-04-21 07:32:39 +02001086 LIST_INSERT(&tkr, &tlskeys_reference);
1087 LIST_DELETE(&tkr);
Christopher Fauletfc633b62020-11-06 15:24:23 +01001088 return ERR_NONE;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001089}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001090#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1091
William Lallemand4a660132019-10-14 14:51:41 +02001092
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001093#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001094/*
1095 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001096 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1097 * status extension, the issuer's certificate is mandatory. It should be
1098 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001099 *
William Lallemand246c0242019-10-11 08:59:13 +02001100 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1101 * OCSP response. If file is empty or content is not a valid OCSP response,
1102 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1103 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001104 *
1105 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001106 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001107 */
Remi Tricot-Le Breton0c96ee42023-03-01 16:11:50 +01001108static int ssl_sock_load_ocsp(const char *path, SSL_CTX *ctx, struct ckch_data *data, STACK_OF(X509) *chain)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001109{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001110 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001111 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001112 struct certificate_ocsp *ocsp = NULL, *iocsp;
1113 char *warn = NULL;
1114 unsigned char *p;
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01001115#ifndef USE_OPENSSL_WOLFSSL
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001116 void (*callback) (void);
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01001117#else
1118 tlsextStatusCb callback;
1119#endif
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001120 struct buffer *ocsp_uri = get_trash_chunk();
Remi Tricot-Le Bretona6c0a592023-03-13 15:56:32 +01001121 char *err = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001122
Emeric Brun4147b2e2014-06-16 18:36:30 +02001123
William Lallemand52ddd992022-11-22 11:51:53 +01001124 x = data->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001125 if (!x)
1126 goto out;
1127
Remi Tricot-Le Bretona6c0a592023-03-13 15:56:32 +01001128 ssl_ocsp_get_uri_from_cert(x, ocsp_uri, &err);
1129 /* We should have an "OCSP URI" field in order for auto update to work. */
1130 if (data->ocsp_update_mode == SSL_SOCK_OCSP_UPDATE_ON && b_data(ocsp_uri) == 0)
1131 goto out;
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001132
1133 /* In case of ocsp update mode set to 'on', this function might be
1134 * called with no known ocsp response. If no ocsp uri can be found in
1135 * the certificate, nothing needs to be done here. */
1136 if (!data->ocsp_response) {
1137 if (data->ocsp_update_mode != SSL_SOCK_OCSP_UPDATE_ON || b_data(ocsp_uri) == 0) {
1138 ret = 0;
1139 goto out;
1140 }
1141 }
1142
William Lallemand52ddd992022-11-22 11:51:53 +01001143 issuer = data->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001144 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1145 if (chain) {
1146 /* check if one of the certificate of the chain is the issuer */
1147 for (i = 0; i < sk_X509_num(chain); i++) {
1148 X509 *ti = sk_X509_value(chain, i);
1149 if (X509_check_issued(ti, x) == X509_V_OK) {
1150 issuer = ti;
1151 break;
1152 }
1153 }
1154 }
William Lallemand246c0242019-10-11 08:59:13 +02001155 if (!issuer)
1156 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001157
Remi Tricot-Le Breton2d1daa82023-01-09 12:02:47 +01001158 if (!data->ocsp_cid)
1159 data->ocsp_cid = OCSP_cert_to_id(0, x, issuer);
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001160 if (!data->ocsp_cid)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001161 goto out;
1162
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001163 i = i2d_OCSP_CERTID(data->ocsp_cid, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001164 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1165 goto out;
1166
Remi Tricot-Le Breton0c96ee42023-03-01 16:11:50 +01001167 ocsp = calloc(1, sizeof(*ocsp)+strlen(path)+1);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001168 if (!ocsp)
1169 goto out;
1170
1171 p = ocsp->key_data;
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001172 ocsp->key_length = i2d_OCSP_CERTID(data->ocsp_cid, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001173
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001174 HA_SPIN_LOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001175 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1176 if (iocsp == ocsp)
1177 ocsp = NULL;
1178
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001179#ifndef SSL_CTX_get_tlsext_status_cb
1180# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1181 *cb = (void (*) (void))ctx->tlsext_status_cb;
1182#endif
1183 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1184
1185 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001186 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001187 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001188
William Lallemanda560c062020-07-31 11:43:20 +02001189 cb_arg = calloc(1, sizeof(*cb_arg));
1190 if (!cb_arg)
1191 goto out;
1192
yanbzhube2774d2015-12-10 15:07:30 -05001193 cb_arg->is_single = 1;
1194 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001195 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001196
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001197 pkey = X509_get_pubkey(x);
1198 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1199 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001200
1201 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001202 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 */
1203
yanbzhube2774d2015-12-10 15:07:30 -05001204 } else {
1205 /*
1206 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1207 * Update that cb_arg with the new cert's staple
1208 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001209 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001210 struct certificate_ocsp *tmp_ocsp;
1211 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001212 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001213 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001214
William Lallemand76b4a122020-08-04 17:41:39 +02001215 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001216
1217 /*
1218 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1219 * the order of operations below matter, take care when changing it
1220 */
1221 tmp_ocsp = cb_arg->s_ocsp;
1222 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1223 cb_arg->s_ocsp = NULL;
1224 cb_arg->m_ocsp[index] = tmp_ocsp;
1225 cb_arg->is_single = 0;
1226 cb_arg->single_kt = 0;
1227
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001228 pkey = X509_get_pubkey(x);
1229 key_type = EVP_PKEY_base_id(pkey);
1230 EVP_PKEY_free(pkey);
1231
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001232 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001233 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001234 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001235 iocsp->refcount++;
1236 }
yanbzhube2774d2015-12-10 15:07:30 -05001237 }
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001238 HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001239
1240 ret = 0;
1241
1242 warn = NULL;
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001243 if (data->ocsp_response && ssl_sock_load_ocsp_response(data->ocsp_response, iocsp, data->ocsp_cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001244 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001245 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001246 }
1247
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001248
Remi Tricot-Le Bretona6c0a592023-03-13 15:56:32 +01001249 /* Do not insert the same certificate_ocsp structure in the
1250 * update tree more than once. */
1251 if (!ocsp) {
1252 /* Issuer certificate is not included in the certificate
1253 * chain, it will have to be treated separately during
1254 * ocsp response validation. */
1255 if (issuer == data->ocsp_issuer) {
1256 iocsp->issuer = issuer;
1257 X509_up_ref(issuer);
1258 }
1259 if (data->chain)
1260 iocsp->chain = X509_chain_up_ref(data->chain);
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001261
Remi Tricot-Le Bretona6c0a592023-03-13 15:56:32 +01001262 iocsp->uri = calloc(1, sizeof(*iocsp->uri));
1263 if (!chunk_dup(iocsp->uri, ocsp_uri)) {
1264 ha_free(&iocsp->uri);
1265 goto out;
1266 }
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001267
Remi Tricot-Le Bretona6c0a592023-03-13 15:56:32 +01001268 strcpy(iocsp->path, path);
Remi Tricot-Le Breton0c96ee42023-03-01 16:11:50 +01001269
Remi Tricot-Le Bretona6c0a592023-03-13 15:56:32 +01001270 if (data->ocsp_update_mode == SSL_SOCK_OCSP_UPDATE_ON) {
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001271 ssl_ocsp_update_insert(iocsp);
Remi Tricot-Le Breton86d1e0b2023-03-02 15:49:53 +01001272 /* If we are during init the update task is not
1273 * scheduled yet so a wakeup won't do anything.
1274 * Otherwise, if the OCSP was added through the CLI, we
1275 * wake the task up to manage the case of a new entry
1276 * that needs to be updated before the previous first
1277 * entry.
1278 */
1279 if (ocsp_update_task)
1280 task_wakeup(ocsp_update_task, TASK_WOKEN_MSG);
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001281 }
1282 }
1283
Emeric Brun4147b2e2014-06-16 18:36:30 +02001284out:
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001285 if (ret && data->ocsp_cid)
1286 OCSP_CERTID_free(data->ocsp_cid);
1287
1288 if (!ret && data->ocsp_response) {
1289 ha_free(&data->ocsp_response->area);
1290 ha_free(&data->ocsp_response);
1291 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001292
1293 if (ocsp)
Remi Tricot-Le Bretonaa529f72022-11-03 15:16:49 +01001294 ssl_sock_free_ocsp(ocsp);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001295
1296 if (warn)
1297 free(warn);
1298
Emeric Brun4147b2e2014-06-16 18:36:30 +02001299 return ret;
1300}
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01001301
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001302#endif
1303
1304#ifdef OPENSSL_IS_BORINGSSL
Remi Tricot-Le Breton0c96ee42023-03-01 16:11:50 +01001305static int ssl_sock_load_ocsp(const char *path, SSL_CTX *ctx, struct ckch_data *data, STACK_OF(X509) *chain)
Emmanuel Hocdet2c32d8f2017-05-22 14:58:00 +02001306{
William Lallemand4a660132019-10-14 14:51:41 +02001307 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 +02001308}
1309#endif
1310
William Lallemand4a660132019-10-14 14:51:41 +02001311
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001312#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001313
1314#define CT_EXTENSION_TYPE 18
1315
William Lallemand03c331c2020-05-13 10:10:01 +02001316int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001317
1318int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1319{
Willy Tarreau83061a82018-07-13 11:56:34 +02001320 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001321
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001322 *out = (unsigned char *) sctl->area;
1323 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001324
1325 return 1;
1326}
1327
1328int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1329{
1330 return 1;
1331}
1332
William Lallemanda17f4112019-10-10 15:16:44 +02001333static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001334{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001335 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001336
William Lallemanda17f4112019-10-10 15:16:44 +02001337 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 +01001338 goto out;
1339
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001340 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1341
1342 ret = 0;
1343
1344out:
1345 return ret;
1346}
1347
1348#endif
1349
Emeric Brune1f38db2012-09-03 20:36:47 +02001350void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1351{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001352 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001353#ifdef USE_QUIC
1354 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1355#endif /* USE_QUIC */
1356 struct ssl_sock_ctx *ctx = NULL;
1357
Emeric Brund8b2bb52014-01-28 15:43:53 +01001358 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001359 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001360
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001361 if (conn)
Willy Tarreau939b0bf2022-04-11 11:29:11 +02001362 ctx = conn_get_ssl_sock_ctx(conn);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001363#ifdef USE_QUIC
1364 else if (qc)
1365 ctx = qc->xprt_ctx;
1366#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01001367
1368 if (!ctx) {
1369 /* must never happen */
1370 ABORT_NOW();
1371 return;
1372 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001373
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001374#ifndef SSL_OP_NO_RENEGOTIATION
1375 /* Please note that BoringSSL defines this macro to zero so don't
1376 * change this to #if and do not assign a default value to this macro!
1377 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001378 if (where & SSL_CB_HANDSHAKE_START) {
1379 /* Disable renegotiation (CVE-2009-3555) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001380 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 +02001381 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001382 conn->err_code = CO_ER_SSL_RENEG;
1383 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001384 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001385#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001386
1387 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001388 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001389 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001390 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001391 consider that the buffering was activated,
1392 so we rise the output buffer size from 4k
1393 to 16k */
1394 write_bio = SSL_get_wbio(ssl);
1395 if (write_bio != SSL_get_rbio(ssl)) {
1396 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001397 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001398 }
1399 }
1400 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001401}
1402
Emeric Brune64aef12012-09-21 13:15:06 +02001403/* Callback is called for each certificate of the chain during a verify
1404 ok is set to 1 if preverify detect no error on current certificate.
1405 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001406int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001407{
1408 SSL *ssl;
1409 struct connection *conn;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001410 struct ssl_sock_ctx *ctx = NULL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001411 int err, depth;
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001412 X509 *client_crt;
1413 STACK_OF(X509) *certs;
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001414 struct bind_conf *bind_conf = NULL;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001415 struct quic_conn *qc = NULL;
Emeric Brune64aef12012-09-21 13:15:06 +02001416
1417 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001418 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001419 client_crt = SSL_get_ex_data(ssl, ssl_client_crt_ref_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001420
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001421 if (conn) {
1422 bind_conf = __objt_listener(conn->target)->bind_conf;
1423 ctx = __conn_get_ssl_sock_ctx(conn);
1424 }
1425#ifdef USE_QUIC
1426 else {
1427 qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
Amaury Denoyelleba303de2022-10-17 18:46:49 +02001428 BUG_ON(!qc); /* Must never happen */
1429 bind_conf = qc->li->bind_conf;
1430 ctx = qc->xprt_ctx;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001431 }
1432#endif
1433
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001434 BUG_ON(!ctx || !bind_conf);
Christopher Faulet881cce92022-11-23 09:27:13 +01001435 ALREADY_CHECKED(ctx);
1436 ALREADY_CHECKED(bind_conf);
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001437
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001438 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001439
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001440 depth = X509_STORE_CTX_get_error_depth(x_store);
1441 err = X509_STORE_CTX_get_error(x_store);
1442
Emeric Brun81c00f02012-09-21 14:31:21 +02001443 if (ok) /* no errors */
1444 return ok;
1445
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001446 /* Keep a reference to the client's certificate in order to be able to
1447 * dump some fetches values in a log even when the verification process
1448 * fails. */
1449 if (depth == 0) {
1450 X509_free(client_crt);
1451 client_crt = X509_STORE_CTX_get0_cert(x_store);
1452 if (client_crt) {
1453 X509_up_ref(client_crt);
1454 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
1455 }
1456 }
1457 else {
1458 /* An error occurred on a CA certificate of the certificate
1459 * chain, we might never call this verify callback on the client
1460 * certificate's depth (which is 0) so we try to store the
1461 * reference right now. */
Remi Tricot-Le Bretonf95c2952021-08-20 09:51:23 +02001462 certs = X509_STORE_CTX_get1_chain(x_store);
1463 if (certs) {
1464 client_crt = sk_X509_value(certs, 0);
1465 if (client_crt) {
1466 X509_up_ref(client_crt);
1467 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001468 }
1469 sk_X509_pop_free(certs, X509_free);
1470 }
1471 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001472
1473 /* check if CA error needs to be ignored */
1474 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001475 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1476 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1477 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001478 }
1479
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01001480 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01001481 cert_ignerr_bitfield_get(bind_conf->ca_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001482 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02001483
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001484 /* TODO: for QUIC connection, this error code is lost */
1485 if (conn)
1486 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001487 return 0;
1488 }
1489
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001490 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1491 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001492
Emeric Brun81c00f02012-09-21 14:31:21 +02001493 /* check if certificate error needs to be ignored */
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01001494 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01001495 cert_ignerr_bitfield_get(bind_conf->crt_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001496 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02001497
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001498 /* TODO: for QUIC connection, this error code is lost */
1499 if (conn)
1500 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001501 return 0;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001502
1503 err_ignored:
1504 ssl_sock_dump_errors(conn, qc);
1505 ERR_clear_error();
1506 return 1;
Emeric Brune64aef12012-09-21 13:15:06 +02001507}
1508
Dragan Dosen9ac98092020-05-11 15:51:45 +02001509#ifdef TLS1_RT_HEARTBEAT
1510static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1511 int content_type, const void *buf, size_t len,
1512 SSL *ssl)
1513{
1514 /* test heartbeat received (write_p is set to 0
1515 for a received record) */
1516 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02001517 struct ssl_sock_ctx *ctx = __conn_get_ssl_sock_ctx(conn);
Dragan Dosen9ac98092020-05-11 15:51:45 +02001518 const unsigned char *p = buf;
1519 unsigned int payload;
1520
1521 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1522
1523 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1524 if (*p != TLS1_HB_REQUEST)
1525 return;
1526
1527 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1528 goto kill_it;
1529
1530 payload = (p[1] * 256) + p[2];
1531 if (3 + payload + 16 <= len)
1532 return; /* OK no problem */
1533 kill_it:
1534 /* We have a clear heartbleed attack (CVE-2014-0160), the
1535 * advertised payload is larger than the advertised packet
1536 * length, so we have garbage in the buffer between the
1537 * payload and the end of the buffer (p+len). We can't know
1538 * if the SSL stack is patched, and we don't know if we can
1539 * safely wipe out the area between p+3+len and payload.
1540 * So instead, we prevent the response from being sent by
1541 * setting the max_send_fragment to 0 and we report an SSL
1542 * error, which will kill this connection. It will be reported
1543 * above as SSL_ERROR_SSL while an other handshake failure with
1544 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1545 */
1546 ssl->max_send_fragment = 0;
1547 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1548 }
1549}
1550#endif
1551
1552static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1553 int content_type, const void *buf, size_t len,
1554 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001555{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001556 struct ssl_capture *capture;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001557 uchar *msg;
1558 uchar *end;
1559 uchar *extensions_end;
1560 uchar *ec_start = NULL;
1561 uchar *ec_formats_start = NULL;
1562 uchar *list_end;
1563 ushort protocol_version;
1564 ushort extension_id;
1565 ushort ec_len = 0;
1566 uchar ec_formats_len = 0;
1567 int offset = 0;
1568 int rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001569
1570 /* This function is called for "from client" and "to server"
1571 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001572 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001573 */
1574
1575 /* "write_p" is set to 0 is the bytes are received messages,
1576 * otherwise it is set to 1.
1577 */
1578 if (write_p != 0)
1579 return;
1580
1581 /* content_type contains the type of message received or sent
1582 * according with the SSL/TLS protocol spec. This message is
1583 * encoded with one byte. The value 256 (two bytes) is used
1584 * for designing the SSL/TLS record layer. According with the
1585 * rfc6101, the expected message (other than 256) are:
1586 * - change_cipher_spec(20)
1587 * - alert(21)
1588 * - handshake(22)
1589 * - application_data(23)
1590 * - (255)
1591 * We are interessed by the handshake and specially the client
1592 * hello.
1593 */
1594 if (content_type != 22)
1595 return;
1596
1597 /* The message length is at least 4 bytes, containing the
1598 * message type and the message length.
1599 */
1600 if (len < 4)
1601 return;
1602
1603 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001604 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001605 * - hello_request(0)
1606 * - client_hello(1)
1607 * - server_hello(2)
1608 * - certificate(11)
1609 * - server_key_exchange (12)
1610 * - certificate_request(13)
1611 * - server_hello_done(14)
1612 * We are interested by the client hello.
1613 */
1614 msg = (unsigned char *)buf;
1615 if (msg[0] != 1)
1616 return;
1617
1618 /* Next three bytes are the length of the message. The total length
1619 * must be this decoded length + 4. If the length given as argument
1620 * is not the same, we abort the protocol dissector.
1621 */
1622 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1623 if (len < rec_len + 4)
1624 return;
1625 msg += 4;
1626 end = msg + rec_len;
1627 if (end < msg)
1628 return;
1629
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001630 /* Expect 2 bytes for protocol version
1631 * (1 byte for major and 1 byte for minor)
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001632 */
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001633 if (msg + 2 > end)
1634 return;
1635 protocol_version = (msg[0] << 8) + msg[1];
1636 msg += 2;
1637
1638 /* Expect the random, composed by 4 bytes for the unix time and
1639 * 28 bytes for unix payload. So we jump 4 + 28.
1640 */
1641 msg += 4 + 28;
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001642 if (msg > end)
1643 return;
1644
1645 /* Next, is session id:
1646 * if present, we have to jump by length + 1 for the size information
1647 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001648 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001649 if (msg[0] > 0)
1650 msg += msg[0];
1651 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001652 if (msg > end)
1653 return;
1654
1655 /* Next two bytes are the ciphersuite length. */
1656 if (msg + 2 > end)
1657 return;
1658 rec_len = (msg[0] << 8) + msg[1];
1659 msg += 2;
1660 if (msg + rec_len > end || msg + rec_len < msg)
1661 return;
1662
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001663 capture = pool_zalloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001664 if (!capture)
1665 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001666 /* Compute the xxh64 of the ciphersuite. */
1667 capture->xxh64 = XXH64(msg, rec_len, 0);
1668
1669 /* Capture the ciphersuite. */
Marcin Deranek310a2602021-07-13 19:04:24 +02001670 capture->ciphersuite_len = MIN(global_ssl.capture_buffer_size, rec_len);
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001671 capture->ciphersuite_offset = 0;
1672 memcpy(capture->data, msg, capture->ciphersuite_len);
1673 msg += rec_len;
1674 offset += capture->ciphersuite_len;
1675
1676 /* Initialize other data */
1677 capture->protocol_version = protocol_version;
1678
1679 /* Next, compression methods:
1680 * if present, we have to jump by length + 1 for the size information
1681 * if not present, we have to jump by 1 only
1682 */
1683 if (msg[0] > 0)
1684 msg += msg[0];
1685 msg += 1;
1686 if (msg > end)
1687 goto store_capture;
1688
1689 /* We reached extensions */
1690 if (msg + 2 > end)
1691 goto store_capture;
1692 rec_len = (msg[0] << 8) + msg[1];
1693 msg += 2;
1694 if (msg + rec_len > end || msg + rec_len < msg)
1695 goto store_capture;
1696 extensions_end = msg + rec_len;
1697 capture->extensions_offset = offset;
1698
1699 /* Parse each extension */
1700 while (msg + 4 < extensions_end) {
1701 /* Add 2 bytes of extension_id */
Marcin Deranek310a2602021-07-13 19:04:24 +02001702 if (global_ssl.capture_buffer_size >= offset + 2) {
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001703 capture->data[offset++] = msg[0];
1704 capture->data[offset++] = msg[1];
1705 capture->extensions_len += 2;
1706 }
1707 else
1708 break;
1709 extension_id = (msg[0] << 8) + msg[1];
1710 /* Length of the extension */
1711 rec_len = (msg[2] << 8) + msg[3];
1712
1713 /* Expect 2 bytes extension id + 2 bytes extension size */
1714 msg += 2 + 2;
1715 if (msg + rec_len > extensions_end || msg + rec_len < msg)
1716 goto store_capture;
1717 /* TLS Extensions
1718 * https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml */
1719 if (extension_id == 0x000a) {
1720 /* Elliptic Curves:
1721 * https://www.rfc-editor.org/rfc/rfc8422.html
1722 * https://www.rfc-editor.org/rfc/rfc7919.html */
1723 list_end = msg + rec_len;
1724 if (msg + 2 > list_end)
1725 goto store_capture;
1726 rec_len = (msg[0] << 8) + msg[1];
1727 msg += 2;
1728
1729 if (msg + rec_len > list_end || msg + rec_len < msg)
1730 goto store_capture;
1731 /* Store location/size of the list */
1732 ec_start = msg;
1733 ec_len = rec_len;
1734 }
1735 else if (extension_id == 0x000b) {
1736 /* Elliptic Curves Point Formats:
1737 * https://www.rfc-editor.org/rfc/rfc8422.html */
1738 list_end = msg + rec_len;
1739 if (msg + 1 > list_end)
1740 goto store_capture;
1741 rec_len = msg[0];
1742 msg += 1;
1743
1744 if (msg + rec_len > list_end || msg + rec_len < msg)
1745 goto store_capture;
1746 /* Store location/size of the list */
1747 ec_formats_start = msg;
1748 ec_formats_len = rec_len;
1749 }
1750 msg += rec_len;
1751 }
1752
1753 if (ec_start) {
1754 rec_len = ec_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001755 if (offset + rec_len > global_ssl.capture_buffer_size)
1756 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001757 memcpy(capture->data + offset, ec_start, rec_len);
1758 capture->ec_offset = offset;
1759 capture->ec_len = rec_len;
1760 offset += rec_len;
1761 }
1762 if (ec_formats_start) {
1763 rec_len = ec_formats_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001764 if (offset + rec_len > global_ssl.capture_buffer_size)
1765 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001766 memcpy(capture->data + offset, ec_formats_start, rec_len);
1767 capture->ec_formats_offset = offset;
1768 capture->ec_formats_len = rec_len;
1769 offset += rec_len;
1770 }
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001771
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001772 store_capture:
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001773 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001774}
William Lallemand7d42ef52020-07-06 11:41:30 +02001775
1776
William Lallemand722180a2021-06-09 16:46:12 +02001777#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001778static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1779 int content_type, const void *buf, size_t len,
1780 SSL *ssl)
1781{
1782 struct ssl_keylog *keylog;
1783
1784 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1785 return;
1786
Willy Tarreauf208ac02021-03-22 21:10:12 +01001787 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02001788 if (!keylog)
1789 return;
1790
William Lallemand7d42ef52020-07-06 11:41:30 +02001791 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
1792 pool_free(pool_head_ssl_keylog, keylog);
1793 return;
1794 }
1795}
1796#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001797
Emeric Brun29f037d2014-04-25 19:05:36 +02001798/* Callback is called for ssl protocol analyse */
1799void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1800{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001801 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1802 struct ssl_sock_msg_callback *cbk;
1803
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001804 /* Try to call all callback functions that were registered by using
1805 * ssl_sock_register_msg_callback().
1806 */
1807 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1808 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1809 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001810}
1811
Bernard Spil13c53f82018-02-15 13:34:58 +01001812#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001813static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1814 const unsigned char *in, unsigned int inlen,
1815 void *arg)
1816{
1817 struct server *srv = arg;
1818
1819 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1820 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1821 return SSL_TLSEXT_ERR_OK;
1822 return SSL_TLSEXT_ERR_NOACK;
1823}
1824#endif
1825
1826#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001827/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001828 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001829 */
1830static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1831 unsigned int *len, void *arg)
1832{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001833 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001834
1835 *data = (const unsigned char *)conf->npn_str;
1836 *len = conf->npn_len;
1837 return SSL_TLSEXT_ERR_OK;
1838}
1839#endif
1840
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001841#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001842/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001843 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001844 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001845static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1846 unsigned char *outlen,
1847 const unsigned char *server,
1848 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001849{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001850 struct ssl_bind_conf *conf = arg;
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001851#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001852 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001853#endif
Willy Tarreauab861d32013-04-02 02:30:41 +02001854
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001855 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1856 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01001857#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001858 if (qc)
1859 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01001860#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001861 return SSL_TLSEXT_ERR_NOACK;
1862 }
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001863
1864#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001865 if (qc && !quic_set_app_ops(qc, *out, *outlen)) {
1866 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001867 return SSL_TLSEXT_ERR_NOACK;
1868 }
1869#endif
1870
Willy Tarreauab861d32013-04-02 02:30:41 +02001871 return SSL_TLSEXT_ERR_OK;
1872}
1873#endif
1874
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001875#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001876#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001877
cui flitera94bedc2022-08-29 14:42:57 +08001878/* Configure a DNS SAN extension on a certificate. */
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001879int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
1880 int failure = 0;
1881 X509_EXTENSION *san_ext = NULL;
1882 CONF *conf = NULL;
1883 struct buffer *san_name = get_trash_chunk();
1884
1885 conf = NCONF_new(NULL);
1886 if (!conf) {
1887 failure = 1;
1888 goto cleanup;
1889 }
1890
1891 /* Build an extension based on the DNS entry above */
1892 chunk_appendf(san_name, "DNS:%s", servername);
1893 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
1894 if (!san_ext) {
1895 failure = 1;
1896 goto cleanup;
1897 }
1898
1899 /* Add the extension */
1900 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
1901 failure = 1;
1902 goto cleanup;
1903 }
1904
1905 /* Success */
1906 failure = 0;
1907
1908cleanup:
1909 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
1910 if (NULL != conf) NCONF_free(conf);
1911
1912 return failure;
1913}
1914
Christopher Faulet30548802015-06-11 13:39:32 +02001915/* Create a X509 certificate with the specified servername and serial. This
1916 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001917static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001918ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001919{
Shimi Gersner5846c492020-08-23 13:58:12 +03001920 X509 *cacert = bind_conf->ca_sign_ckch->cert;
1921 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001922 SSL_CTX *ssl_ctx = NULL;
1923 X509 *newcrt = NULL;
1924 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001925 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001926 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001927 X509_NAME *name;
1928 const EVP_MD *digest;
1929 X509V3_CTX ctx;
1930 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001931 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001932
Christopher Faulet48a83322017-07-28 16:56:09 +02001933 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05001934#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001935 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1936#else
1937 tmp_ssl = SSL_new(bind_conf->default_ctx);
1938 if (tmp_ssl)
1939 pkey = SSL_get_privatekey(tmp_ssl);
1940#endif
1941 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001942 goto mkcert_error;
1943
1944 /* Create the certificate */
1945 if (!(newcrt = X509_new()))
1946 goto mkcert_error;
1947
1948 /* Set version number for the certificate (X509v3) and the serial
1949 * number */
1950 if (X509_set_version(newcrt, 2L) != 1)
1951 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02001952 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001953
1954 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001955 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1956 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001957 goto mkcert_error;
1958
1959 /* set public key in the certificate */
1960 if (X509_set_pubkey(newcrt, pkey) != 1)
1961 goto mkcert_error;
1962
1963 /* Set issuer name from the CA */
1964 if (!(name = X509_get_subject_name(cacert)))
1965 goto mkcert_error;
1966 if (X509_set_issuer_name(newcrt, name) != 1)
1967 goto mkcert_error;
1968
1969 /* Set the subject name using the same, but the CN */
1970 name = X509_NAME_dup(name);
1971 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1972 (const unsigned char *)servername,
1973 -1, -1, 0) != 1) {
1974 X509_NAME_free(name);
1975 goto mkcert_error;
1976 }
1977 if (X509_set_subject_name(newcrt, name) != 1) {
1978 X509_NAME_free(name);
1979 goto mkcert_error;
1980 }
1981 X509_NAME_free(name);
1982
1983 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001984 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001985 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1986 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1987 X509_EXTENSION *ext;
1988
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001989 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001990 goto mkcert_error;
1991 if (!X509_add_ext(newcrt, ext, -1)) {
1992 X509_EXTENSION_free(ext);
1993 goto mkcert_error;
1994 }
1995 X509_EXTENSION_free(ext);
1996 }
1997
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001998 /* Add SAN extension */
1999 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
2000 goto mkcert_error;
2001 }
2002
Christopher Faulet31af49d2015-06-09 17:29:50 +02002003 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002004
2005 key_type = EVP_PKEY_base_id(capkey);
2006
2007 if (key_type == EVP_PKEY_DSA)
2008 digest = EVP_sha1();
2009 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002010 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002011 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02002012 digest = EVP_sha256();
2013 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05002014#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02002015 int nid;
2016
2017 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
2018 goto mkcert_error;
2019 if (!(digest = EVP_get_digestbynid(nid)))
2020 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02002021#else
2022 goto mkcert_error;
2023#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02002024 }
2025
Christopher Faulet31af49d2015-06-09 17:29:50 +02002026 if (!(X509_sign(newcrt, capkey, digest)))
2027 goto mkcert_error;
2028
2029 /* Create and set the new SSL_CTX */
2030 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
2031 goto mkcert_error;
2032 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
2033 goto mkcert_error;
2034 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
2035 goto mkcert_error;
2036 if (!SSL_CTX_check_private_key(ssl_ctx))
2037 goto mkcert_error;
2038
Shimi Gersner5846c492020-08-23 13:58:12 +03002039 /* Build chaining the CA cert and the rest of the chain, keep these order */
2040#if defined(SSL_CTX_add1_chain_cert)
2041 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
2042 goto mkcert_error;
2043 }
2044
2045 if (bind_conf->ca_sign_ckch->chain) {
2046 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2047 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2048 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2049 goto mkcert_error;
2050 }
2051 }
2052 }
2053#endif
2054
Christopher Faulet31af49d2015-06-09 17:29:50 +02002055 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002056
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002057#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002058#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002059 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002060#else
2061 ssl_sock_set_tmp_dh_from_pkey(ssl_ctx, pkey);
2062#endif
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002063#endif
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002064
2065#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
2066#if defined(SSL_CTX_set1_curves_list)
2067 {
2068 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
2069 if (!SSL_CTX_set1_curves_list(ssl_ctx, ecdhe))
2070 goto end;
2071 }
2072#endif
2073#else
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002074#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2075 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002076 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002077 EC_KEY *ecc;
2078 int nid;
2079
2080 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2081 goto end;
2082 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2083 goto end;
2084 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2085 EC_KEY_free(ecc);
2086 }
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002087#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
2088#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002089 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002090 return ssl_ctx;
2091
2092 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002093 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002094 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002095 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2096 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002097 return NULL;
2098}
2099
Christopher Faulet7969a332015-10-09 11:15:03 +02002100
Christopher Faulet30548802015-06-11 13:39:32 +02002101/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002102 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002103SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002104ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002105{
2106 struct lru64 *lru = NULL;
2107
2108 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002109 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002110 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002111 if (lru && lru->domain) {
2112 if (ssl)
2113 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002114 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002115 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002116 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002117 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002118 }
2119 return NULL;
2120}
2121
Emeric Brun821bb9b2017-06-15 16:37:39 +02002122/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2123 * function is not thread-safe, it should only be used to check if a certificate
2124 * exists in the lru cache (with no warranty it will not be removed by another
2125 * thread). It is kept for backward compatibility. */
2126SSL_CTX *
2127ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2128{
2129 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2130}
2131
Christopher Fauletd2cab922015-07-28 16:03:47 +02002132/* Set a certificate int the LRU cache used to store generated
2133 * certificate. Return 0 on success, otherwise -1 */
2134int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002135ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002136{
2137 struct lru64 *lru = NULL;
2138
2139 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002140 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002141 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002142 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002143 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002144 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002145 }
Christopher Faulet30548802015-06-11 13:39:32 +02002146 if (lru->domain && lru->data)
2147 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002148 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002149 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002150 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002151 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002152 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002153}
2154
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002155/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002156unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002157ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002158{
2159 return XXH32(data, len, ssl_ctx_lru_seed);
2160}
2161
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002162/* Generate a cert and immediately assign it to the SSL session so that the cert's
2163 * refcount is maintained regardless of the cert's presence in the LRU cache.
2164 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002165static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002166ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002167{
Shimi Gersner5846c492020-08-23 13:58:12 +03002168 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002169 SSL_CTX *ssl_ctx = NULL;
2170 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002171 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002172
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002173 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002174 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002175 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002176 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002177 if (lru && lru->domain)
2178 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002179 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002180 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002181 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002182 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002183 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002184 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002185 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002186 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002187 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002188 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002189 SSL_set_SSL_CTX(ssl, ssl_ctx);
2190 /* No LRU cache, this CTX will be released as soon as the session dies */
2191 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002192 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002193 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002194 return 0;
2195}
2196static int
2197ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2198{
2199 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002200 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002201
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002202 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002203 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002204 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002205 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002206 }
2207 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002208}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002209#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002210
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002211#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002212
2213static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002214{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002215#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002216 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002217 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2218#endif
2219}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002220static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2221 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002222 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2223}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002224static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002225#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002226 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002227 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2228#endif
2229}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002230static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002231#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002232 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002233 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2234#endif
2235}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002236/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002237static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2238/* Unusable in this context. */
2239static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2240static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2241static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2242static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2243static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002244#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002245
2246static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2247 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002248 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2249}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002250static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2251 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2252 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2253}
2254static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2255 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002256 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2257}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002258static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2259 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2260 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2261}
2262static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2263 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002264 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2265}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002266static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2267 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2268 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2269}
2270static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2271 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002272 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2273}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002274static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2275 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2276 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2277}
2278static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002279#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002280 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002281 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2282#endif
2283}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002284static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002285#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002286 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2287 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002288#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002289}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002290#endif
2291static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2292static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002293
William Lallemand7fd8b452020-05-07 15:20:43 +02002294struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002295 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2296 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2297 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2298 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2299 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2300 {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 +02002301};
2302
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002303static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2304{
2305 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2306 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2307 SSL_set_SSL_CTX(ssl, ctx);
2308}
2309
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002310#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002311
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002312int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002313{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002314 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002315 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002316
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002317 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || (s->options & BC_O_GENERATE_CERTS))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002318 return SSL_TLSEXT_ERR_OK;
2319 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002320}
2321
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002322#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002323int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002324{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002325 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002326#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002327int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002328{
2329#endif
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002330 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2331#ifdef USE_QUIC
2332 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2333#endif /* USE_QUIC */
2334 struct bind_conf *s = NULL;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002335 const uint8_t *extension_data;
2336 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002337 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002338
2339 char *wildp = NULL;
2340 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002341 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002342 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002343 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002344 int i;
2345
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002346 if (conn)
2347 s = __objt_listener(conn->target)->bind_conf;
2348#ifdef USE_QUIC
2349 else if (qc)
2350 s = qc->li->bind_conf;
2351#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01002352
2353 if (!s) {
2354 /* must never happen */
2355 ABORT_NOW();
2356 return 0;
2357 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002358
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002359#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002360 if (qc) {
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002361 /* Look for the QUIC transport parameters. */
2362#ifdef OPENSSL_IS_BORINGSSL
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002363 if (!SSL_early_callback_ctx_extension_get(ctx, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002364 &extension_data, &extension_len))
2365#else
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002366 if (!SSL_client_hello_get0_ext(ssl, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002367 &extension_data, &extension_len))
2368#endif
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002369 {
2370 /* This is not redundant. It we only return 0 without setting
2371 * <*al>, this has as side effect to generate another TLS alert
2372 * which would be set after calling quic_set_tls_alert().
2373 */
2374 *al = SSL_AD_MISSING_EXTENSION;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002375 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002376 return 0;
2377 }
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002378
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002379 if (!quic_transport_params_store(qc, 0, extension_data,
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002380 extension_data + extension_len))
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002381 goto abort;
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002382
2383 qc->flags |= QUIC_FL_CONN_TX_TP_RECEIVED;
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002384 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002385#endif /* USE_QUIC */
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002386
Olivier Houchard9679ac92017-10-27 14:58:08 +02002387 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002388 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002389#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002390 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2391 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002392#else
2393 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2394#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002395 /*
2396 * The server_name extension was given too much extensibility when it
2397 * was written, so parsing the normal case is a bit complex.
2398 */
2399 size_t len;
2400 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002401 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002402 /* Extract the length of the supplied list of names. */
2403 len = (*extension_data++) << 8;
2404 len |= *extension_data++;
2405 if (len + 2 != extension_len)
2406 goto abort;
2407 /*
2408 * The list in practice only has a single element, so we only consider
2409 * the first one.
2410 */
2411 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2412 goto abort;
2413 extension_len = len - 1;
2414 /* Now we can finally pull out the byte array with the actual hostname. */
2415 if (extension_len <= 2)
2416 goto abort;
2417 len = (*extension_data++) << 8;
2418 len |= *extension_data++;
2419 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2420 || memchr(extension_data, 0, len) != NULL)
2421 goto abort;
2422 servername = extension_data;
2423 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002424 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002425#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002426 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002427 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002428 }
2429#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002430 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002431 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002432 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002433 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002434 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002435 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002436 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002437 goto abort;
2438 }
2439
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002440 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002441#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002442 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002443#else
2444 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2445#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002446 uint8_t sign;
2447 size_t len;
2448 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002449 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002450 len = (*extension_data++) << 8;
2451 len |= *extension_data++;
2452 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002453 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002454 if (len % 2 != 0)
2455 goto abort;
2456 for (; len > 0; len -= 2) {
2457 extension_data++; /* hash */
2458 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002459 switch (sign) {
2460 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002461 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002462 break;
2463 case TLSEXT_signature_ecdsa:
2464 has_ecdsa_sig = 1;
2465 break;
2466 default:
2467 continue;
2468 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002469 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002470 break;
2471 }
2472 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002473 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002474 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002475 }
2476 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002477 const SSL_CIPHER *cipher;
2478 size_t len;
2479 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002480 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002481#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002482 len = ctx->cipher_suites_len;
2483 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002484#else
2485 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2486#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002487 if (len % 2 != 0)
2488 goto abort;
2489 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002490#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002491 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002492 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002493#else
2494 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2495#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002496 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002497 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002498 break;
2499 }
2500 }
2501 }
2502
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002503 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002504 trash.area[i] = tolower(servername[i]);
2505 if (!wildp && (trash.area[i] == '.'))
2506 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002507 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002508 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002509
William Lallemand150bfa82019-09-19 17:12:49 +02002510 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002511
William Lallemand94bd3192020-08-14 14:43:35 +02002512 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2513 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002514 for (i = 0; i < 2; i++) {
2515 if (i == 0) /* lookup in full qualified names */
2516 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002517 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002518 node = ebst_lookup(&s->sni_w_ctx, wildp);
2519 else
2520 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002521
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002522 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002523
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002524 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002525 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002526 struct sni_ctx *sni, *sni_tmp;
2527 int skip = 0;
2528
2529 if (i == 1 && wildp) { /* wildcard */
2530 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2531 sni = container_of(n, struct sni_ctx, name);
2532 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002533 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002534 skip = 1;
2535 break;
2536 }
2537 }
2538 if (skip)
2539 continue;
2540 }
2541
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002542 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002543 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002544 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002545 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002546 break;
2547 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002548 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002549 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002550 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002551 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002552 if (!node_anonymous)
2553 node_anonymous = n;
2554 break;
2555 }
2556 }
2557 }
William Lallemand94bd3192020-08-14 14:43:35 +02002558 }
2559 /* Once the certificates are found, select them depending on what is
2560 * supported in the client and by key_signature priority order: EDSA >
2561 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002562 if (has_ecdsa_sig && node_ecdsa)
2563 node = node_ecdsa;
2564 else if (has_rsa_sig && node_rsa)
2565 node = node_rsa;
2566 else if (node_anonymous)
2567 node = node_anonymous;
2568 else if (node_ecdsa)
2569 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2570 else
2571 node = node_rsa; /* no rsa signature case (far far away) */
2572
William Lallemand94bd3192020-08-14 14:43:35 +02002573 if (node) {
2574 /* switch ctx */
2575 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2576 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2577 if (conf) {
2578 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2579 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2580 if (conf->early_data)
2581 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002582 }
William Lallemand94bd3192020-08-14 14:43:35 +02002583 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2584 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002585 }
William Lallemand150bfa82019-09-19 17:12:49 +02002586
William Lallemand02010472019-10-18 11:02:19 +02002587 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002588#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002589 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002590 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002591 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002592 }
2593#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002594 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002595 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002596 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002597 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002598 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
William Lallemand7980dff2021-11-18 17:46:26 +01002599 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002600 }
William Lallemand7980dff2021-11-18 17:46:26 +01002601
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01002602 /* We are about to raise an handshake error so the servername extension
2603 * callback will never be called and the SNI will never be stored in the
2604 * SSL context. In order for the ssl_fc_sni sample fetch to still work
2605 * in such a case, we store the SNI ourselves as an ex_data information
2606 * in the SSL context.
2607 */
2608 {
2609 char *client_sni = pool_alloc(ssl_sock_client_sni_pool);
2610 if (client_sni) {
2611 strncpy(client_sni, trash.area, TLSEXT_MAXLEN_host_name);
2612 client_sni[TLSEXT_MAXLEN_host_name] = '\0';
2613 SSL_set_ex_data(ssl, ssl_client_sni_index, client_sni);
2614 }
2615 }
2616
William Lallemand7980dff2021-11-18 17:46:26 +01002617 /* other cases fallback on abort, if strict-sni is set but no node was found */
2618
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002619 abort:
2620 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002621 if (conn)
2622 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002623#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002624 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002625#else
2626 *al = SSL_AD_UNRECOGNIZED_NAME;
2627 return 0;
2628#endif
William Lallemand7980dff2021-11-18 17:46:26 +01002629
2630allow_early:
2631#ifdef OPENSSL_IS_BORINGSSL
2632 if (allow_early)
2633 SSL_set_early_data_enabled(ssl, 1);
2634#else
2635 if (!allow_early)
2636 SSL_set_max_early_data(ssl, 0);
2637#endif
2638 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002639}
2640
William Lallemand002e2062021-11-18 15:25:16 +01002641#else /* ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002642
Emeric Brunfc0421f2012-09-07 17:30:07 +02002643/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2644 * warning when no match is found, which implies the default (first) cert
2645 * will keep being used.
2646 */
William Lallemand844009d2022-09-02 15:27:32 +02002647int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002648{
2649 const char *servername;
2650 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002651 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002652 struct bind_conf *s = priv;
William Lallemand70a6e632022-09-07 11:21:34 +02002653#ifdef USE_QUIC
2654 const uint8_t *extension_data;
2655 size_t extension_len;
2656 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2657#endif /* USE_QUIC */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002658 int i;
2659 (void)al; /* shut gcc stupid warning */
2660
William Lallemand70a6e632022-09-07 11:21:34 +02002661#ifdef USE_QUIC
2662 if (qc) {
2663
2664 /* Look for the QUIC transport parameters. */
2665 SSL_get_peer_quic_transport_params(ssl, &extension_data, &extension_len);
2666 if (extension_len == 0) {
2667 /* This is not redundant. It we only return 0 without setting
2668 * <*al>, this has as side effect to generate another TLS alert
2669 * which would be set after calling quic_set_tls_alert().
2670 */
2671 *al = SSL_AD_MISSING_EXTENSION;
2672 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
2673 return SSL_TLSEXT_ERR_NOACK;
2674 }
2675
2676 if (!quic_transport_params_store(qc, 0, extension_data,
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002677 extension_data + extension_len))
William Lallemand70a6e632022-09-07 11:21:34 +02002678 return SSL_TLSEXT_ERR_NOACK;
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002679
2680 qc->flags |= QUIC_FL_CONN_TX_TP_RECEIVED;
William Lallemand70a6e632022-09-07 11:21:34 +02002681 }
2682#endif /* USE_QUIC */
2683
Emeric Brunfc0421f2012-09-07 17:30:07 +02002684 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002685 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002686#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002687 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002688 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002689#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002690 if (s->strict_sni)
2691 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002692 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002693 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002694 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002695 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002696 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002697
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002698 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002699 if (!servername[i])
2700 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002701 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002702 if (!wildp && (trash.area[i] == '.'))
2703 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002704 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002705 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002706
William Lallemand150bfa82019-09-19 17:12:49 +02002707 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002708 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002709 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002710 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2711 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002712 if (!container_of(n, struct sni_ctx, name)->neg) {
2713 node = n;
2714 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002715 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002716 }
2717 if (!node && wildp) {
2718 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002719 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2720 /* lookup a not neg filter */
2721 if (!container_of(n, struct sni_ctx, name)->neg) {
2722 node = n;
2723 break;
2724 }
2725 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002726 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002727 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002728#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002729 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(servername, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002730 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002731 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002732 return SSL_TLSEXT_ERR_OK;
2733 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002734#endif
William Lallemand21724f02019-11-04 17:56:13 +01002735 if (s->strict_sni) {
2736 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002737 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002738 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002739 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002740 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002741 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002742 }
2743
2744 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002745 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002746 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002747 return SSL_TLSEXT_ERR_OK;
2748}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002749#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002750#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2751
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002752#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002753
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002754static inline HASSL_DH *ssl_new_dh_fromdata(BIGNUM *p, BIGNUM *g)
2755{
2756#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2757 OSSL_PARAM_BLD *tmpl = NULL;
2758 OSSL_PARAM *params = NULL;
2759 EVP_PKEY_CTX *ctx = NULL;
2760 EVP_PKEY *pkey = NULL;
2761
2762 if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
2763 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
2764 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)
2765 || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
2766 goto end;
2767 }
2768 ctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2769 if (ctx == NULL
2770 || !EVP_PKEY_fromdata_init(ctx)
2771 || !EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params)) {
2772 goto end;
2773 }
2774
2775end:
2776 EVP_PKEY_CTX_free(ctx);
2777 OSSL_PARAM_free(params);
2778 OSSL_PARAM_BLD_free(tmpl);
Remi Tricot-Le Bretona2c21db2022-11-03 15:16:47 +01002779 BN_free(p);
2780 BN_free(g);
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002781 return pkey;
2782#else
2783
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002784 HASSL_DH *dh = DH_new();
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002785
2786 if (!dh)
2787 return NULL;
2788
2789 DH_set0_pqg(dh, p, NULL, g);
2790
2791 return dh;
2792#endif
2793}
2794
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02002795#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002796static inline HASSL_DH *ssl_get_dh_by_nid(int nid)
2797{
2798#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2799 OSSL_PARAM params[2];
2800 EVP_PKEY *pkey = NULL;
2801 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2802 const char *named_group = NULL;
2803
2804 if (!pctx)
2805 goto end;
2806
2807 named_group = OBJ_nid2ln(nid);
2808
2809 if (!named_group)
2810 goto end;
2811
2812 params[0] = OSSL_PARAM_construct_utf8_string("group", (char*)named_group, 0);
2813 params[1] = OSSL_PARAM_construct_end();
2814
2815 if (EVP_PKEY_keygen_init(pctx) && EVP_PKEY_CTX_set_params(pctx, params))
2816 EVP_PKEY_generate(pctx, &pkey);
2817
2818end:
2819 EVP_PKEY_CTX_free(pctx);
2820 return pkey;
2821#else
2822
2823 HASSL_DH *dh = NULL;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002824 dh = DH_new_by_nid(nid);
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002825 return dh;
2826#endif
2827}
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02002828#endif
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002829
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002830
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002831static HASSL_DH * ssl_get_dh_1024(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002832{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002833 static unsigned char dh1024_p[]={
2834 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2835 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2836 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2837 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2838 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2839 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2840 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2841 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2842 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2843 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2844 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2845 };
2846 static unsigned char dh1024_g[]={
2847 0x02,
2848 };
2849
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002850 BIGNUM *p;
2851 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002852
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002853 HASSL_DH *dh = NULL;
2854
2855 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2856 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
2857
2858 if (p && g)
2859 dh = ssl_new_dh_fromdata(p, g);
2860
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002861 return dh;
2862}
2863
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002864static HASSL_DH *ssl_get_dh_2048(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002865{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002866#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02002867 static unsigned char dh2048_p[]={
2868 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2869 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2870 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2871 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2872 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2873 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2874 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2875 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2876 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2877 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2878 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2879 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2880 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2881 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2882 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2883 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2884 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2885 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2886 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2887 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2888 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2889 0xB7,0x1F,0x77,0xF3,
2890 };
2891 static unsigned char dh2048_g[]={
2892 0x02,
2893 };
2894
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002895 BIGNUM *p;
2896 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002897
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002898 HASSL_DH *dh = NULL;
2899
2900 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2901 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
2902
2903 if (p && g)
2904 dh = ssl_new_dh_fromdata(p, g);
2905
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002906 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002907#else
2908 return ssl_get_dh_by_nid(NID_ffdhe2048);
2909#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002910}
2911
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002912static HASSL_DH *ssl_get_dh_4096(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002913{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002914#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02002915 static unsigned char dh4096_p[]={
2916 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2917 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2918 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2919 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2920 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2921 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2922 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2923 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2924 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2925 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2926 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2927 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2928 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2929 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2930 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2931 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2932 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2933 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2934 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2935 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2936 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2937 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2938 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2939 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2940 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2941 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2942 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2943 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2944 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2945 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2946 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2947 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2948 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2949 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2950 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2951 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2952 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2953 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2954 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2955 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2956 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2957 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2958 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002959 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002960 static unsigned char dh4096_g[]={
2961 0x02,
2962 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002963
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002964 BIGNUM *p;
2965 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002966
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002967 HASSL_DH *dh = NULL;
2968
2969 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2970 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
2971
2972 if (p && g)
2973 dh = ssl_new_dh_fromdata(p, g);
2974
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002975 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002976#else
2977 return ssl_get_dh_by_nid(NID_ffdhe4096);
2978#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002979}
2980
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002981static HASSL_DH *ssl_get_tmp_dh(EVP_PKEY *pkey)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002982{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002983 HASSL_DH *dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002984 int type;
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002985 int keylen = 0;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002986
2987 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002988
Ilya Shipitsin52f2ff52022-07-23 23:55:19 +05002989 if (type == EVP_PKEY_EC) {
2990 keylen = global_ssl.default_dh_param;
2991 }
2992
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002993 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2994 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2995 */
2996 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2997 keylen = EVP_PKEY_bits(pkey);
2998 }
2999
Willy Tarreauef934602016-12-22 23:12:01 +01003000 if (keylen > global_ssl.default_dh_param) {
3001 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003002 }
3003
Remi Gacogned3a341a2015-05-29 16:26:17 +02003004 if (keylen >= 4096) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003005 if (!local_dh_4096)
3006 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02003007 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003008 }
3009 else if (keylen >= 2048) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003010 if (!local_dh_2048)
3011 local_dh_2048 = ssl_get_dh_2048();
Remi Gacogne8de54152014-07-15 11:36:40 +02003012 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003013 }
3014 else {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003015 if (!local_dh_1024)
3016 local_dh_1024 = ssl_get_dh_1024();
Remi Gacogne8de54152014-07-15 11:36:40 +02003017 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003018 }
3019
3020 return dh;
3021}
3022
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003023#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003024/* Returns Diffie-Hellman parameters matching the private key length
3025 but not exceeding global_ssl.default_dh_param */
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003026static HASSL_DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003027{
3028 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
3029
3030 return ssl_get_tmp_dh(pkey);
3031}
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003032#endif
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003033
Remi Tricot-Le Breton846eda92022-02-11 12:04:50 +01003034static int ssl_sock_set_tmp_dh(SSL_CTX *ctx, HASSL_DH *dh)
3035{
3036#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
3037 return SSL_CTX_set_tmp_dh(ctx, dh);
3038#else
3039 int retval = 0;
3040 HASSL_DH_up_ref(dh);
3041
3042 retval = SSL_CTX_set0_tmp_dh_pkey(ctx, dh);
3043
3044 if (!retval)
3045 HASSL_DH_free(dh);
3046
3047 return retval;
3048#endif
3049}
3050
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003051#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3052static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey)
3053{
3054 HASSL_DH *dh = NULL;
3055 if (pkey && (dh = ssl_get_tmp_dh(pkey))) {
3056 HASSL_DH_up_ref(dh);
3057 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dh))
3058 HASSL_DH_free(dh);
3059 }
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003060}
3061#endif
3062
Remi Tricot-Le Breton09ebb332022-02-11 12:04:48 +01003063HASSL_DH *ssl_sock_get_dh_from_bio(BIO *bio)
3064{
3065#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3066 HASSL_DH *dh = NULL;
3067 OSSL_DECODER_CTX *dctx = NULL;
3068 const char *format = "PEM";
3069 const char *keytype = "DH";
3070
3071 dctx = OSSL_DECODER_CTX_new_for_pkey(&dh, format, NULL, keytype,
3072 OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
3073 NULL, NULL);
3074
3075 if (dctx == NULL || OSSL_DECODER_CTX_get_num_decoders(dctx) == 0)
3076 goto end;
3077
3078 /* The DH parameters might not be the first section found in the PEM
3079 * file so we need to iterate over all of them until we find the right
3080 * one.
3081 */
3082 while (!BIO_eof(bio) && !dh)
3083 OSSL_DECODER_from_bio(dctx, bio);
3084
3085end:
3086 OSSL_DECODER_CTX_free(dctx);
3087 return dh;
3088#else
3089 HASSL_DH *dh = NULL;
3090
3091 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3092
3093 return dh;
3094#endif
3095}
3096
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003097static HASSL_DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003098{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003099 HASSL_DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02003100 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003101
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003102 if (in == NULL)
3103 goto end;
3104
Remi Gacogne47783ef2015-05-29 15:53:22 +02003105 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003106 goto end;
3107
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003108 dh = ssl_sock_get_dh_from_bio(in);
Remi Gacogne47783ef2015-05-29 15:53:22 +02003109
3110end:
3111 if (in)
3112 BIO_free(in);
3113
Emeric Brune1b4ed42018-08-16 15:14:12 +02003114 ERR_clear_error();
3115
Remi Gacogne47783ef2015-05-29 15:53:22 +02003116 return dh;
3117}
3118
3119int ssl_sock_load_global_dh_param_from_file(const char *filename)
3120{
3121 global_dh = ssl_sock_get_dh_from_file(filename);
3122
3123 if (global_dh) {
3124 return 0;
3125 }
3126
3127 return -1;
3128}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003129#endif
3130
William Lallemand9117de92019-10-04 00:29:42 +02003131/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02003132static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02003133 struct bind_conf *s, struct ssl_bind_conf *conf,
3134 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003135{
3136 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003137 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003138
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003139 if (*name == '!') {
3140 neg = 1;
3141 name++;
3142 }
3143 if (*name == '*') {
3144 wild = 1;
3145 name++;
3146 }
3147 /* !* filter is a nop */
3148 if (neg && wild)
3149 return order;
3150 if (*name) {
3151 int j, len;
3152 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003153 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02003154 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003155 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02003156 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003157 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003158
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003159 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02003160 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02003161 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003162 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02003163 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003164 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003165 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003166 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003167 sc->order = order++;
3168 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02003169 sc->wild = wild;
3170 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01003171 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02003172 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003173 }
3174 return order;
3175}
3176
William Lallemand6af03992019-07-23 15:00:54 +02003177/*
William Lallemand1d29c742019-10-04 00:53:29 +02003178 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
3179 * This function can't return an error.
3180 *
3181 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
3182 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003183void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02003184{
3185
3186 struct sni_ctx *sc0, *sc0b, *sc1;
3187 struct ebmb_node *node;
3188
3189 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
3190
3191 /* ignore if sc0 was already inserted in a tree */
3192 if (sc0->name.node.leaf_p)
3193 continue;
3194
3195 /* Check for duplicates. */
3196 if (sc0->wild)
3197 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
3198 else
3199 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
3200
3201 for (; node; node = ebmb_next_dup(node)) {
3202 sc1 = ebmb_entry(node, struct sni_ctx, name);
3203 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
3204 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
3205 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02003206 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02003207 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003208 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02003209 break;
William Lallemand1d29c742019-10-04 00:53:29 +02003210 }
3211 }
3212
3213 /* if duplicate, ignore the insertion */
3214 if (!sc0)
3215 continue;
3216
3217 if (sc0->wild)
3218 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
3219 else
3220 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003221 }
William Lallemand21724f02019-11-04 17:56:13 +01003222
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003223 /* replace the default_ctx if required with the instance's ctx. */
3224 if (ckch_inst->is_default) {
3225 SSL_CTX_free(bind_conf->default_ctx);
3226 SSL_CTX_up_ref(ckch_inst->ctx);
3227 bind_conf->default_ctx = ckch_inst->ctx;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003228 bind_conf->default_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02003229 }
3230}
3231
3232/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003233 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02003234 */
William Lallemande3af8fb2019-10-08 11:36:53 +02003235struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02003236
William Lallemand2954c472020-03-06 21:54:13 +01003237/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02003238struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02003239
Emeric Brun7a883362019-10-17 13:27:40 +02003240/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003241 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02003242 * DH parameter is loaded into the SSL_CTX and if there is no
3243 * DH parameter available in ckchs nor in global, the default
3244 * DH parameters are applied on the SSL_CTX.
3245 * Returns a bitfield containing the flags:
3246 * ERR_FATAL in any fatal error case
3247 * ERR_ALERT if a reason of the error is availabine in err
3248 * ERR_WARN if a warning is available into err
3249 * The value 0 means there is no error nor warning and
3250 * the operation succeed.
3251 */
William Lallemandfa892222019-07-23 16:06:08 +02003252#ifndef OPENSSL_NO_DH
William Lallemand52ddd992022-11-22 11:51:53 +01003253static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct ckch_data *data,
Emeric Brun7a883362019-10-17 13:27:40 +02003254 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02003255{
Emeric Brun7a883362019-10-17 13:27:40 +02003256 int ret = 0;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003257 HASSL_DH *dh = NULL;
William Lallemandfa892222019-07-23 16:06:08 +02003258
William Lallemand52ddd992022-11-22 11:51:53 +01003259 if (data && data->dh) {
3260 dh = data->dh;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003261 if (!ssl_sock_set_tmp_dh(ctx, dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003262 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
3263 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003264 memprintf(err, "%s, DH ciphers won't be available.\n",
3265 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003266 ret |= ERR_WARN;
3267 goto end;
3268 }
William Lallemandfa892222019-07-23 16:06:08 +02003269
3270 if (ssl_dh_ptr_index >= 0) {
3271 /* store a pointer to the DH params to avoid complaining about
3272 ssl-default-dh-param not being set for this SSL_CTX */
3273 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
3274 }
3275 }
3276 else if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003277 if (!ssl_sock_set_tmp_dh(ctx, global_dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003278 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
3279 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003280 memprintf(err, "%s, DH ciphers won't be available.\n",
3281 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003282 ret |= ERR_WARN;
3283 goto end;
3284 }
William Lallemandfa892222019-07-23 16:06:08 +02003285 }
3286 else {
3287 /* Clear openssl global errors stack */
3288 ERR_clear_error();
3289
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003290 /* We do not want DHE ciphers to be added to the cipher list
3291 * unless there is an explicit global dh option in the conf.
3292 */
3293 if (global_ssl.default_dh_param) {
3294 if (global_ssl.default_dh_param <= 1024) {
3295 /* we are limited to DH parameter of 1024 bits anyway */
3296 if (local_dh_1024 == NULL)
3297 local_dh_1024 = ssl_get_dh_1024();
William Lallemandfa892222019-07-23 16:06:08 +02003298
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003299 if (local_dh_1024 == NULL) {
3300 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3301 err && *err ? *err : "", path);
3302 ret |= ERR_ALERT | ERR_FATAL;
3303 goto end;
3304 }
William Lallemandfa892222019-07-23 16:06:08 +02003305
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003306 if (!ssl_sock_set_tmp_dh(ctx, local_dh_1024)) {
3307 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3308 err && *err ? *err : "", path);
3309 memprintf(err, "%s, DH ciphers won't be available.\n",
3310 err && *err ? *err : "");
3311 ret |= ERR_WARN;
3312 goto end;
3313 }
Emeric Bruna9363eb2019-10-17 14:53:03 +02003314 }
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003315 else {
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003316#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003317 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003318#else
William Lallemand52ddd992022-11-22 11:51:53 +01003319 ssl_sock_set_tmp_dh_from_pkey(ctx, data ? data->key : NULL);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003320#endif
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003321 }
William Lallemandfa892222019-07-23 16:06:08 +02003322 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003323 }
3324
William Lallemandf9568fc2019-10-16 18:27:58 +02003325end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003326 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003327 return ret;
3328}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003329#endif
William Lallemandfa892222019-07-23 16:06:08 +02003330
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003331
3332/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003333 * Returns a bitfield containing the flags:
3334 * ERR_FATAL in any fatal error case
3335 * ERR_ALERT if the reason of the error is available in err
3336 * ERR_WARN if a warning is available into err
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003337 * The caller is responsible of freeing the newly built or newly refcounted
3338 * find_chain element.
Emeric Bruna96b5822019-10-17 13:25:14 +02003339 * The value 0 means there is no error nor warning and
3340 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003341 */
William Lallemand52ddd992022-11-22 11:51:53 +01003342static int ssl_sock_load_cert_chain(const char *path, const struct ckch_data *data,
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003343 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003344{
Emeric Bruna96b5822019-10-17 13:25:14 +02003345 int errcode = 0;
William Lallemand45fed2c2022-11-15 16:56:03 +01003346 int ret;
3347
3348 ERR_clear_error();
Emeric Bruna96b5822019-10-17 13:25:14 +02003349
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003350 if (find_chain == NULL) {
3351 errcode |= ERR_FATAL;
3352 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003353 }
3354
William Lallemand52ddd992022-11-22 11:51:53 +01003355 if (!SSL_CTX_use_certificate(ctx, data->cert)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003356 ret = ERR_get_error();
3357 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s': %s.\n",
3358 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Emeric Bruna96b5822019-10-17 13:25:14 +02003359 errcode |= ERR_ALERT | ERR_FATAL;
3360 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003361 }
3362
William Lallemand52ddd992022-11-22 11:51:53 +01003363 if (data->chain) {
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003364 *find_chain = X509_chain_up_ref(data->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003365 } else {
3366 /* Find Certificate Chain in global */
3367 struct issuer_chain *issuer;
William Lallemand52ddd992022-11-22 11:51:53 +01003368 issuer = ssl_get0_issuer_chain(data->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003369 if (issuer)
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003370 *find_chain = X509_chain_up_ref(issuer->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003371 }
William Lallemand85888572020-02-27 14:48:35 +01003372
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003373 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003374 /* always put a null chain stack in the SSL_CTX so it does not
3375 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003376 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003377 }
3378
William Lallemand52ddd992022-11-22 11:51:53 +01003379 /* Load all certs in the data into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003380#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003381 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003382 ret = ERR_get_error();
3383 memprintf(err, "%sunable to load chain certificate into SSL Context '%s': %s. Make sure you are linking against Openssl >= 1.0.2.\n",
3384 err && *err ? *err : "", path, ERR_reason_error_string(ret));
William Lallemand935d8292020-08-12 20:02:10 +02003385 errcode |= ERR_ALERT | ERR_FATAL;
3386 goto end;
3387 }
William Lallemandf187ce62020-06-02 18:27:20 +02003388#else
3389 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003390 X509 *ca;
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003391 while ((ca = sk_X509_shift(*find_chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003392 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003393 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3394 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003395 X509_free(ca);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003396 errcode |= ERR_ALERT | ERR_FATAL;
3397 goto end;
3398 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003399 }
William Lallemandf187ce62020-06-02 18:27:20 +02003400#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003401
William Lallemand9a1d8392020-08-10 17:28:23 +02003402#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003403 /* remove the Root CA from the SSL_CTX if the option is activated */
3404 if (global_ssl.skip_self_issued_ca) {
3405 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3406 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3407 err && *err ? *err : "", path);
3408 errcode |= ERR_ALERT | ERR_FATAL;
3409 goto end;
3410 }
3411 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003412#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003413
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003414end:
3415 return errcode;
3416}
3417
3418
3419/* Loads the info in ckch into ctx
3420 * Returns a bitfield containing the flags:
3421 * ERR_FATAL in any fatal error case
3422 * ERR_ALERT if the reason of the error is available in err
3423 * ERR_WARN if a warning is available into err
3424 * The value 0 means there is no error nor warning and
3425 * the operation succeed.
3426 */
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01003427static 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 +01003428{
3429 int errcode = 0;
3430 STACK_OF(X509) *find_chain = NULL;
3431
William Lallemand5de49512022-10-27 14:41:07 +02003432 ERR_clear_error();
3433
William Lallemand52ddd992022-11-22 11:51:53 +01003434 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
William Lallemand5de49512022-10-27 14:41:07 +02003435 int ret;
3436
3437 ret = ERR_get_error();
3438 memprintf(err, "%sunable to load SSL private key into SSL Context '%s': %s.\n",
3439 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003440 errcode |= ERR_ALERT | ERR_FATAL;
3441 return errcode;
3442 }
3443
3444 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01003445 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003446 if (errcode & ERR_CODE)
3447 goto end;
3448
William Lallemandfa892222019-07-23 16:06:08 +02003449#ifndef OPENSSL_NO_DH
3450 /* store a NULL pointer to indicate we have not yet loaded
3451 a custom DH param file */
3452 if (ssl_dh_ptr_index >= 0) {
3453 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3454 }
3455
William Lallemand52ddd992022-11-22 11:51:53 +01003456 errcode |= ssl_sock_load_dh_params(ctx, data, path, err);
Emeric Brun7a883362019-10-17 13:27:40 +02003457 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003458 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3459 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003460 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003461 }
3462#endif
3463
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003464#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemand52ddd992022-11-22 11:51:53 +01003465 if (sctl_ex_index >= 0 && data->sctl) {
3466 if (ssl_sock_load_sctl(ctx, data->sctl) < 0) {
William Lallemanda17f4112019-10-10 15:16:44 +02003467 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003468 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003469 errcode |= ERR_ALERT | ERR_FATAL;
3470 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003471 }
3472 }
3473#endif
3474
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003475#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 +01003476 /* Load OCSP Info into context
3477 * If OCSP update mode is set to 'on', an entry will be created in the
3478 * ocsp tree even if no ocsp_response was known during init, unless the
3479 * frontend's conf disables ocsp update explicitely.
3480 */
Remi Tricot-Le Breton0c96ee42023-03-01 16:11:50 +01003481 if (ssl_sock_load_ocsp(path, ctx, data, find_chain) < 0) {
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01003482 if (data->ocsp_response)
Tim Duesterhus93128532019-11-23 23:45:10 +01003483 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 +01003484 err && *err ? *err : "", path);
3485 else
3486 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",
3487 err && *err ? *err : "", path);
3488 errcode |= ERR_ALERT | ERR_FATAL;
3489 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003490 }
William Lallemand246c0242019-10-11 08:59:13 +02003491#endif
3492
Emeric Bruna96b5822019-10-17 13:25:14 +02003493 end:
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003494 sk_X509_pop_free(find_chain, X509_free);
Emeric Bruna96b5822019-10-17 13:25:14 +02003495 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003496}
3497
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003498
3499/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
3500 * Returns a bitfield containing the flags:
3501 * ERR_FATAL in any fatal error case
3502 * ERR_ALERT if the reason of the error is available in err
3503 * ERR_WARN if a warning is available into err
3504 * The value 0 means there is no error nor warning and
3505 * the operation succeed.
3506 */
William Lallemand52ddd992022-11-22 11:51:53 +01003507static 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 +01003508 SSL_CTX *ctx, char **err)
3509{
3510 int errcode = 0;
3511 STACK_OF(X509) *find_chain = NULL;
3512
3513 /* Load the private key */
William Lallemand52ddd992022-11-22 11:51:53 +01003514 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003515 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3516 err && *err ? *err : "", path);
3517 errcode |= ERR_ALERT | ERR_FATAL;
3518 }
3519
3520 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01003521 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003522 if (errcode & ERR_CODE)
3523 goto end;
3524
3525 if (SSL_CTX_check_private_key(ctx) <= 0) {
3526 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3527 err && *err ? *err : "", path);
3528 errcode |= ERR_ALERT | ERR_FATAL;
3529 }
3530
3531end:
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003532 sk_X509_pop_free(find_chain, X509_free);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003533 return errcode;
3534}
3535
3536
William Lallemand614ca0d2019-10-07 13:52:11 +02003537/*
3538 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003539 *
3540 * Returns a bitfield containing the flags:
3541 * ERR_FATAL in any fatal error case
3542 * ERR_ALERT if the reason of the error is available in err
3543 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003544 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003545int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003546 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003547{
William Lallemandc9402072019-05-15 15:33:54 +02003548 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003549 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003550 int order = 0;
3551 X509_NAME *xname;
3552 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003553 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003554 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003555#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3556 STACK_OF(GENERAL_NAME) *names;
3557#endif
William Lallemand52ddd992022-11-22 11:51:53 +01003558 struct ckch_data *data;
William Lallemand614ca0d2019-10-07 13:52:11 +02003559 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003560 int errcode = 0;
3561
3562 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003563
William Lallemand52ddd992022-11-22 11:51:53 +01003564 if (!ckchs || !ckchs->data)
Emeric Brun054563d2019-10-17 13:16:58 +02003565 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003566
William Lallemand52ddd992022-11-22 11:51:53 +01003567 data = ckchs->data;
William Lallemand36b84632019-07-18 19:28:17 +02003568
William Lallemandc9402072019-05-15 15:33:54 +02003569 ctx = SSL_CTX_new(SSLv23_server_method());
3570 if (!ctx) {
3571 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3572 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003573 errcode |= ERR_ALERT | ERR_FATAL;
3574 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003575 }
3576
William Lallemand52ddd992022-11-22 11:51:53 +01003577 errcode |= ssl_sock_put_ckch_into_ctx(path, data, ctx, err);
Emeric Bruna96b5822019-10-17 13:25:14 +02003578 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003579 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003580
3581 ckch_inst = ckch_inst_new();
3582 if (!ckch_inst) {
3583 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3584 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003585 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003586 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003587 }
3588
William Lallemand52ddd992022-11-22 11:51:53 +01003589 pkey = X509_get_pubkey(data->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003590 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003591 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003592 switch(EVP_PKEY_base_id(pkey)) {
3593 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003594 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003595 break;
3596 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003597 kinfo.sig = TLSEXT_signature_ecdsa;
3598 break;
3599 case EVP_PKEY_DSA:
3600 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003601 break;
3602 }
3603 EVP_PKEY_free(pkey);
3604 }
3605
Emeric Brun50bcecc2013-04-22 13:05:23 +02003606 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003607 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003608 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 +02003609 if (order < 0) {
3610 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003611 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003612 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003613 }
3614 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003615 }
3616 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003617#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand52ddd992022-11-22 11:51:53 +01003618 names = X509_get_ext_d2i(data->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003619 if (names) {
3620 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3621 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3622 if (name->type == GEN_DNS) {
3623 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003624 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003625 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003626 if (order < 0) {
3627 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003628 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003629 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003630 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003631 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003632 }
3633 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003634 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003635 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003636#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand52ddd992022-11-22 11:51:53 +01003637 xname = X509_get_subject_name(data->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003638 i = -1;
3639 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3640 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003641 ASN1_STRING *value;
3642
3643 value = X509_NAME_ENTRY_get_data(entry);
3644 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003645 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003646 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003647 if (order < 0) {
3648 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003649 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003650 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003651 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003652 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003653 }
3654 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003655 /* we must not free the SSL_CTX anymore below, since it's already in
3656 * the tree, so it will be discovered and cleaned in time.
3657 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003658
Emeric Brunfc0421f2012-09-07 17:30:07 +02003659#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003660 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003661 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3662 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003663 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003664 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003665 }
3666#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003667 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003668 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003669 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003670 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003671 SSL_CTX_up_ref(ctx);
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003672 bind_conf->default_inst = ckch_inst;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003673 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003674
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003675 /* Always keep a reference to the newly constructed SSL_CTX in the
3676 * instance. This way if the instance has no SNIs, the SSL_CTX will
3677 * still be linked. */
3678 SSL_CTX_up_ref(ctx);
3679 ckch_inst->ctx = ctx;
3680
William Lallemand9117de92019-10-04 00:29:42 +02003681 /* everything succeed, the ckch instance can be used */
3682 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003683 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003684 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003685
William Lallemand02e19a52020-04-08 16:11:26 +02003686 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3687
Emeric Brun054563d2019-10-17 13:16:58 +02003688 *ckchi = ckch_inst;
3689 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003690
3691error:
3692 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003693 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003694 if (ckch_inst->is_default)
3695 SSL_CTX_free(ctx);
3696
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003697 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003698 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003699 }
William Lallemandd9199372019-10-04 15:37:05 +02003700 SSL_CTX_free(ctx);
3701
Emeric Brun054563d2019-10-17 13:16:58 +02003702 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003703}
3704
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003705
3706/*
3707 * This function allocate a ckch_inst that will be used on the backend side
3708 * (server line)
3709 *
3710 * Returns a bitfield containing the flags:
3711 * ERR_FATAL in any fatal error case
3712 * ERR_ALERT if the reason of the error is available in err
3713 * ERR_WARN if a warning is available into err
3714 */
3715int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01003716 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003717{
3718 SSL_CTX *ctx;
William Lallemand52ddd992022-11-22 11:51:53 +01003719 struct ckch_data *data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003720 struct ckch_inst *ckch_inst = NULL;
3721 int errcode = 0;
3722
3723 *ckchi = NULL;
3724
William Lallemand52ddd992022-11-22 11:51:53 +01003725 if (!ckchs || !ckchs->data)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003726 return ERR_FATAL;
3727
William Lallemand52ddd992022-11-22 11:51:53 +01003728 data = ckchs->data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003729
3730 ctx = SSL_CTX_new(SSLv23_client_method());
3731 if (!ctx) {
3732 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3733 err && *err ? *err : "", path);
3734 errcode |= ERR_ALERT | ERR_FATAL;
3735 goto error;
3736 }
3737
William Lallemand52ddd992022-11-22 11:51:53 +01003738 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, data, ctx, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003739 if (errcode & ERR_CODE)
3740 goto error;
3741
3742 ckch_inst = ckch_inst_new();
3743 if (!ckch_inst) {
3744 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3745 err && *err ? *err : "", path);
3746 errcode |= ERR_ALERT | ERR_FATAL;
3747 goto error;
3748 }
3749
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003750 /* everything succeed, the ckch instance can be used */
3751 ckch_inst->bind_conf = NULL;
3752 ckch_inst->ssl_conf = NULL;
3753 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01003754 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003755 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003756
3757 *ckchi = ckch_inst;
3758 return errcode;
3759
3760error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003761 SSL_CTX_free(ctx);
3762
3763 return errcode;
3764}
3765
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003766/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003767static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3768 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003769 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003770{
Emeric Brun054563d2019-10-17 13:16:58 +02003771 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003772
3773 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003774 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 +02003775
Emeric Brun054563d2019-10-17 13:16:58 +02003776 if (errcode & ERR_CODE)
3777 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003778
William Lallemand24bde432020-03-09 16:48:43 +01003779 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003780
3781 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003782 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003783 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003784}
3785
William Lallemanddb26e2b2021-01-26 12:01:46 +01003786/* This function generates a <struct ckch_inst *> for a <struct server *>, and
3787 * fill the SSL_CTX of the server.
3788 *
3789 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003790static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01003791 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003792{
3793 int errcode = 0;
3794
3795 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01003796 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003797
3798 if (errcode & ERR_CODE)
3799 return errcode;
3800
William Lallemanddb26e2b2021-01-26 12:01:46 +01003801 (*ckch_inst)->server = server;
3802 /* Keep the reference to the SSL_CTX in the server. */
3803 SSL_CTX_up_ref((*ckch_inst)->ctx);
3804 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003805 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003806 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003807 return errcode;
3808}
3809
William Lallemand6be66ec2020-03-06 22:26:32 +01003810
William Lallemand4c68bba2020-03-30 18:45:10 +02003811
3812
3813/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3814 * done once. Zero is returned if the operation fails. No error is returned
3815 * if the random is said as not implemented, because we expect that openssl
3816 * will use another method once needed.
3817 */
Amaury Denoyellec593bcd2021-05-19 15:35:29 +02003818int ssl_initialize_random(void)
William Lallemand4c68bba2020-03-30 18:45:10 +02003819{
3820 unsigned char random;
3821 static int random_initialized = 0;
3822
3823 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3824 random_initialized = 1;
3825
3826 return random_initialized;
3827}
3828
William Lallemand2954c472020-03-06 21:54:13 +01003829/* Load a crt-list file, this is done in 2 parts:
3830 * - store the content of the file in a crtlist structure with crtlist_entry structures
3831 * - generate the instances by iterating on entries in the crtlist struct
3832 *
3833 * Nothing is locked there, this function is used in the configuration parser.
3834 *
3835 * Returns a set of ERR_* flags possibly with an error in <err>.
3836 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003837int 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 +01003838{
3839 struct crtlist *crtlist = NULL;
3840 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003841 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003842 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003843 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003844 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003845
William Lallemand79d31ec2020-03-25 15:10:49 +01003846 bind_conf_node = malloc(sizeof(*bind_conf_node));
3847 if (!bind_conf_node) {
3848 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3849 cfgerr |= ERR_FATAL | ERR_ALERT;
3850 goto error;
3851 }
3852 bind_conf_node->next = NULL;
3853 bind_conf_node->bind_conf = bind_conf;
3854
William Lallemand41ca9302020-04-08 13:15:18 +02003855 /* strip trailing slashes, including first one */
3856 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3857 *end = 0;
3858
William Lallemand2954c472020-03-06 21:54:13 +01003859 /* look for an existing crtlist or create one */
3860 eb = ebst_lookup(&crtlists_tree, file);
3861 if (eb) {
3862 crtlist = ebmb_entry(eb, struct crtlist, node);
3863 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003864 /* load a crt-list OR a directory */
3865 if (dir)
3866 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3867 else
3868 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3869
William Lallemand2954c472020-03-06 21:54:13 +01003870 if (!(cfgerr & ERR_CODE))
3871 ebst_insert(&crtlists_tree, &crtlist->node);
3872 }
3873
3874 if (cfgerr & ERR_CODE) {
3875 cfgerr |= ERR_FATAL | ERR_ALERT;
3876 goto error;
3877 }
3878
3879 /* generates ckch instance from the crtlist_entry */
3880 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3881 struct ckch_store *store;
3882 struct ckch_inst *ckch_inst = NULL;
3883
3884 store = entry->node.key;
3885 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3886 if (cfgerr & ERR_CODE) {
3887 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3888 goto error;
3889 }
Willy Tarreau2b718102021-04-21 07:32:39 +02003890 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003891 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003892 }
William Lallemand2954c472020-03-06 21:54:13 +01003893
William Lallemand79d31ec2020-03-25 15:10:49 +01003894 /* add the bind_conf to the list */
3895 bind_conf_node->next = crtlist->bind_conf;
3896 crtlist->bind_conf = bind_conf_node;
3897
William Lallemand2954c472020-03-06 21:54:13 +01003898 return cfgerr;
3899error:
3900 {
William Lallemand49398312020-03-30 17:01:33 +02003901 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003902 struct ckch_inst *inst, *s_inst;
3903
William Lallemand49398312020-03-30 17:01:33 +02003904 lastentry = entry; /* which entry we tried to generate last */
3905 if (lastentry) {
3906 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3907 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3908 break;
3909
3910 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003911
William Lallemand49398312020-03-30 17:01:33 +02003912 /* this was not generated for this bind_conf, skip */
3913 if (inst->bind_conf != bind_conf)
3914 continue;
3915
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003916 /* free the sni_ctx and instance */
3917 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003918 }
William Lallemand2954c472020-03-06 21:54:13 +01003919 }
William Lallemand2954c472020-03-06 21:54:13 +01003920 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003921 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003922 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003923 return cfgerr;
3924}
3925
William Lallemand06b22a82020-03-16 14:45:55 +01003926/* Returns a set of ERR_* flags possibly with an error in <err>. */
3927int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3928{
3929 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01003930 int cfgerr = 0;
3931 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003932 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01003933 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01003934
3935 if ((ckchs = ckchs_lookup(path))) {
3936 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01003937 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3938 found++;
3939 } else if (stat(path, &buf) == 0) {
3940 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01003941 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003942 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003943 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003944 cfgerr |= ERR_ALERT | ERR_FATAL;
3945 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003946 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01003947 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003948 }
3949 } else {
3950 /* stat failed, could be a bundle */
3951 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02003952 char fp[MAXPATHLEN+1] = {0};
3953 int n = 0;
3954
3955 /* Load all possible certs and keys in separate ckch_store */
3956 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3957 struct stat buf;
3958 int ret;
3959
3960 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3961 if (ret > sizeof(fp))
3962 continue;
3963
3964 if ((ckchs = ckchs_lookup(fp))) {
3965 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01003966 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02003967 } else {
3968 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01003969 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003970 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02003971 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003972 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02003973 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3974 }
3975 }
3976 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01003977#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
3978 if (found) {
3979 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
3980 err && *err ? *err : "", path);
3981 cfgerr |= ERR_ALERT | ERR_FATAL;
3982 }
3983#endif
William Lallemand06b22a82020-03-16 14:45:55 +01003984 }
3985 }
William Lallemand06ce84a2020-11-20 15:36:13 +01003986 if (!found) {
3987 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3988 err && *err ? *err : "", path, strerror(errno));
3989 cfgerr |= ERR_ALERT | ERR_FATAL;
3990 }
William Lallemand06b22a82020-03-16 14:45:55 +01003991
3992 return cfgerr;
3993}
3994
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003995
3996/* Create a full ssl context and ckch instance that will be used for a specific
3997 * backend server (server configuration line).
3998 * Returns a set of ERR_* flags possibly with an error in <err>.
3999 */
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004000int 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 +01004001{
4002 struct stat buf;
4003 int cfgerr = 0;
4004 struct ckch_store *ckchs;
4005 int found = 0; /* did we found a file to load ? */
4006
4007 if ((ckchs = ckchs_lookup(path))) {
4008 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01004009 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004010 found++;
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004011 } else {
4012 if (!create_if_none) {
4013 memprintf(err, "%sunable to stat SSL certificate '%s'.\n",
4014 err && *err ? *err : "", path);
4015 cfgerr |= ERR_ALERT | ERR_FATAL;
4016 goto out;
4017 }
4018
4019 if (stat(path, &buf) == 0) {
4020 /* We do not manage directories on backend side. */
4021 if (S_ISDIR(buf.st_mode) == 0) {
4022 ++found;
4023 ckchs = ckchs_load_cert_file(path, err);
4024 if (!ckchs)
4025 cfgerr |= ERR_ALERT | ERR_FATAL;
4026 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
4027 }
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004028 }
4029 }
4030 if (!found) {
4031 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
4032 err && *err ? *err : "", path, strerror(errno));
4033 cfgerr |= ERR_ALERT | ERR_FATAL;
4034 }
4035
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004036out:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004037 return cfgerr;
4038}
4039
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004040/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004041static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004042ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004043{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004044 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004045 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004046 SSL_OP_ALL | /* all known workarounds for bugs */
4047 SSL_OP_NO_SSLv2 |
4048 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02004049 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02004050 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004051 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02004052 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004053 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004054 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004055 SSL_MODE_ENABLE_PARTIAL_WRITE |
4056 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004057 SSL_MODE_RELEASE_BUFFERS |
4058 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004059 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004060 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004061 int flags = MC_SSL_O_ALL;
4062 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02004063 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004064
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004065 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004066 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004067
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004068 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004069 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
4070 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4071 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004072 else
4073 flags = conf_ssl_methods->flags;
4074
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004075 min = conf_ssl_methods->min;
4076 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02004077
4078 /* default minimum is TLSV12, */
4079 if (!min) {
4080 if (!max || (max >= default_min_ver)) {
4081 min = default_min_ver;
4082 } else {
4083 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). "
4084 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
4085 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
4086 min = max;
4087 }
4088 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004089 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004090 if (min)
4091 flags |= (methodVersions[min].flag - 1);
4092 if (max)
4093 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004094 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004095 min = max = CONF_TLSV_NONE;
4096 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004097 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004098 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004099 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004100 if (min) {
4101 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004102 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
4103 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4104 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
4105 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004106 hole = 0;
4107 }
4108 max = i;
4109 }
4110 else {
4111 min = max = i;
4112 }
4113 }
4114 else {
4115 if (min)
4116 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004117 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004118 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004119 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4120 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004121 cfgerr += 1;
4122 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004123 /* save real min/max in bind_conf */
4124 conf_ssl_methods->min = min;
4125 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004126
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004127#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004128 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004129 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004130 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004131 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004132 else
William Lallemandd0712f32020-06-11 17:34:00 +02004133 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
4134 /* clear every version flags in case SSL_CTX_new()
4135 * returns an SSL_CTX with disabled versions */
4136 SSL_CTX_clear_options(ctx, methodVersions[i].option);
4137
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004138 if (flags & methodVersions[i].flag)
4139 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02004140
4141 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004142#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004143 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004144 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4145 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02004146#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004147
4148 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
4149 options |= SSL_OP_NO_TICKET;
4150 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
4151 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08004152
4153#ifdef SSL_OP_NO_RENEGOTIATION
4154 options |= SSL_OP_NO_RENEGOTIATION;
4155#endif
4156
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004157 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004158
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004159#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004160 if (global_ssl.async)
4161 mode |= SSL_MODE_ASYNC;
4162#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004163 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004164 if (global_ssl.life_time)
4165 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004166
4167#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand4b7938d2022-09-07 10:54:17 +02004168# ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004169 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
4170 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004171# elif defined(HAVE_SSL_CLIENT_HELLO_CB)
4172# if defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01004173 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01004174 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
William Lallemand4b7938d2022-09-07 10:54:17 +02004175# endif /* ! SSL_OP_NO_ANTI_REPLAY */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02004176 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
4177 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004178# else /* ! OPENSSL_IS_BORINGSSL && ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004179 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004180# endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02004181 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
William Lallemand4b7938d2022-09-07 10:54:17 +02004182#endif /* ! SSL_CTRL_SET_TLSEXT_HOSTNAME */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004183 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004184}
4185
William Lallemand4f45bb92017-10-30 20:08:51 +01004186
4187static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
4188{
4189 if (first == block) {
4190 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4191 if (first->len > 0)
4192 sh_ssl_sess_tree_delete(sh_ssl_sess);
4193 }
4194}
4195
4196/* return first block from sh_ssl_sess */
4197static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
4198{
4199 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
4200
4201}
4202
4203/* store a session into the cache
4204 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
4205 * data: asn1 encoded session
4206 * data_len: asn1 encoded session length
4207 * Returns 1 id session was stored (else 0)
4208 */
4209static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
4210{
4211 struct shared_block *first;
4212 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
4213
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004214 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01004215 if (!first) {
4216 /* Could not retrieve enough free blocks to store that session */
4217 return 0;
4218 }
4219
4220 /* STORE the key in the first elem */
4221 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4222 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
4223 first->len = sizeof(struct sh_ssl_sess_hdr);
4224
4225 /* it returns the already existing node
4226 or current node if none, never returns null */
4227 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
4228 if (oldsh_ssl_sess != sh_ssl_sess) {
4229 /* NOTE: Row couldn't be in use because we lock read & write function */
4230 /* release the reserved row */
William Lallemand222e5a22023-01-31 14:12:28 +01004231 first->len = 0; /* the len must be liberated in order not to call the release callback on it */
William Lallemand4f45bb92017-10-30 20:08:51 +01004232 shctx_row_dec_hot(ssl_shctx, first);
4233 /* replace the previous session already in the tree */
4234 sh_ssl_sess = oldsh_ssl_sess;
4235 /* ignore the previous session data, only use the header */
4236 first = sh_ssl_sess_first_block(sh_ssl_sess);
4237 shctx_row_inc_hot(ssl_shctx, first);
4238 first->len = sizeof(struct sh_ssl_sess_hdr);
4239 }
4240
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004241 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01004242 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004243 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01004244 }
4245
4246 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004247
4248 return 1;
4249}
William Lallemanded0b5ad2017-10-30 19:36:36 +01004250
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004251/* SSL callback used when a new session is created while connecting to a server */
4252static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4253{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004254 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004255 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004256
Willy Tarreau07d94e42018-09-20 10:57:52 +02004257 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004258
William Lallemand3ce6eed2021-02-08 10:43:44 +01004259 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4260 * one cache per thread, it only prevents to flush it from the CLI in
4261 * another thread */
4262
Olivier Houcharde6060c52017-11-16 17:42:52 +01004263 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4264 int len;
4265 unsigned char *ptr;
William Lallemande18d4e82021-11-17 02:59:21 +01004266 const char *sni;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004267
Olivier Houcharde6060c52017-11-16 17:42:52 +01004268 len = i2d_SSL_SESSION(sess, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01004269 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004270 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004271 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4272 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4273 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004274 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
4275 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004276 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4277 }
4278 if (s->ssl_ctx.reused_sess[tid].ptr) {
4279 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4280 &ptr);
4281 }
William Lallemande18d4e82021-11-17 02:59:21 +01004282
4283 if (s->ssl_ctx.reused_sess[tid].sni) {
4284 /* if the new sni is empty or isn' t the same as the old one */
4285 if ((!sni) || strcmp(s->ssl_ctx.reused_sess[tid].sni, sni) != 0) {
4286 ha_free(&s->ssl_ctx.reused_sess[tid].sni);
4287 if (sni)
4288 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4289 }
4290 } else if (sni) {
4291 /* if there wasn't an old sni but there is a new one */
4292 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4293 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004294 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004295 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004296 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004297 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004298 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004299 }
4300
4301 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004302}
4303
Olivier Houcharde6060c52017-11-16 17:42:52 +01004304
William Lallemanded0b5ad2017-10-30 19:36:36 +01004305/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004306int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004307{
4308 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4309 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4310 unsigned char *p;
4311 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004312 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004313 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004314
4315 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004316 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004317 * note: SSL_SESSION_set1_id is using
4318 * a memcpy so we need to use a different pointer
4319 * than sid_data or sid_ctx_data to avoid valgrind
4320 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004321 */
4322
4323 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004324
4325 /* copy value in an other buffer */
4326 memcpy(encid, sid_data, sid_length);
4327
4328 /* pad with 0 */
4329 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4330 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4331
4332 /* force length to zero to avoid ASN1 encoding */
4333 SSL_SESSION_set1_id(sess, encid, 0);
4334
4335 /* force length to zero to avoid ASN1 encoding */
4336 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004337
4338 /* check if buffer is large enough for the ASN1 encoded session */
4339 data_len = i2d_SSL_SESSION(sess, NULL);
4340 if (data_len > SHSESS_MAX_DATA_LEN)
4341 goto err;
4342
4343 p = encsess;
4344
4345 /* process ASN1 session encoding before the lock */
4346 i2d_SSL_SESSION(sess, &p);
4347
William Lallemanded0b5ad2017-10-30 19:36:36 +01004348
William Lallemanda3c77cf2017-10-30 23:44:40 +01004349 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004350 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004351 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004352 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004353err:
4354 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004355 SSL_SESSION_set1_id(sess, encid, sid_length);
4356 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004357
4358 return 0; /* do not increment session reference count */
4359}
4360
4361/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004362SSL_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 +01004363{
William Lallemand4f45bb92017-10-30 20:08:51 +01004364 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004365 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4366 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004367 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004368 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004369
Willy Tarreau4c19e992021-06-15 16:39:22 +02004370 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004371
4372 /* allow the session to be freed automatically by openssl */
4373 *do_copy = 0;
4374
4375 /* tree key is zeros padded sessionid */
4376 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4377 memcpy(tmpkey, key, key_len);
4378 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4379 key = tmpkey;
4380 }
4381
4382 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004383 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004384
4385 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004386 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4387 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004388 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004389 shctx_unlock(ssl_shctx);
Willy Tarreau4c19e992021-06-15 16:39:22 +02004390 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004391 return NULL;
4392 }
4393
William Lallemand4f45bb92017-10-30 20:08:51 +01004394 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4395 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004396
William Lallemand4f45bb92017-10-30 20:08:51 +01004397 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 +01004398
William Lallemanda3c77cf2017-10-30 23:44:40 +01004399 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004400
4401 /* decode ASN1 session */
4402 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004403 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004404 /* Reset session id and session id contenxt */
4405 if (sess) {
4406 SSL_SESSION_set1_id(sess, key, key_len);
4407 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4408 }
4409
4410 return sess;
4411}
4412
William Lallemand4f45bb92017-10-30 20:08:51 +01004413
William Lallemanded0b5ad2017-10-30 19:36:36 +01004414/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004415void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004416{
William Lallemand4f45bb92017-10-30 20:08:51 +01004417 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004418 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4419 unsigned int sid_length;
4420 const unsigned char *sid_data;
4421 (void)ctx;
4422
4423 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4424 /* tree key is zeros padded sessionid */
4425 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4426 memcpy(tmpkey, sid_data, sid_length);
4427 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4428 sid_data = tmpkey;
4429 }
4430
William Lallemanda3c77cf2017-10-30 23:44:40 +01004431 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004432
4433 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004434 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4435 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004436 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004437 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004438 }
4439
4440 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004441 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004442}
4443
4444/* Set session cache mode to server and disable openssl internal cache.
4445 * Set shared cache callbacks on an ssl context.
4446 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004447void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004448{
4449 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4450
4451 if (!ssl_shctx) {
4452 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4453 return;
4454 }
4455
4456 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4457 SSL_SESS_CACHE_NO_INTERNAL |
4458 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4459
4460 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004461 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4462 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4463 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004464}
William Lallemand7d42ef52020-07-06 11:41:30 +02004465
4466/*
4467 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4468 *
4469 * The format is:
4470 * * <Label> <space> <ClientRandom> <space> <Secret>
4471 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4472 */
4473
William Lallemand722180a2021-06-09 16:46:12 +02004474#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004475void SSL_CTX_keylog(const SSL *ssl, const char *line)
4476{
4477 struct ssl_keylog *keylog;
4478 char *lastarg = NULL;
4479 char *dst = NULL;
4480
4481 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4482 if (!keylog)
4483 return;
4484
4485 lastarg = strrchr(line, ' ');
4486 if (lastarg == NULL || ++lastarg == NULL)
4487 return;
4488
4489 dst = pool_alloc(pool_head_ssl_keylog_str);
4490 if (!dst)
4491 return;
4492
4493 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4494 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4495
4496 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4497 if (keylog->client_random)
4498 goto error;
4499 keylog->client_random = dst;
4500
4501 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4502 if (keylog->client_early_traffic_secret)
4503 goto error;
4504 keylog->client_early_traffic_secret = dst;
4505
4506 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4507 if(keylog->client_handshake_traffic_secret)
4508 goto error;
4509 keylog->client_handshake_traffic_secret = dst;
4510
4511 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4512 if (keylog->server_handshake_traffic_secret)
4513 goto error;
4514 keylog->server_handshake_traffic_secret = dst;
4515
4516 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4517 if (keylog->client_traffic_secret_0)
4518 goto error;
4519 keylog->client_traffic_secret_0 = dst;
4520
4521 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4522 if (keylog->server_traffic_secret_0)
4523 goto error;
4524 keylog->server_traffic_secret_0 = dst;
4525
4526 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4527 if (keylog->early_exporter_secret)
4528 goto error;
4529 keylog->early_exporter_secret = dst;
4530
4531 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4532 if (keylog->exporter_secret)
4533 goto error;
4534 keylog->exporter_secret = dst;
4535 } else {
4536 goto error;
4537 }
4538
4539 return;
4540
4541error:
4542 pool_free(pool_head_ssl_keylog_str, dst);
4543
4544 return;
4545}
4546#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004547
William Lallemand8b453912019-11-21 15:48:10 +01004548/*
4549 * This function applies the SSL configuration on a SSL_CTX
4550 * It returns an error code and fills the <err> buffer
4551 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004552static 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 +01004553{
4554 struct proxy *curproxy = bind_conf->frontend;
4555 int cfgerr = 0;
4556 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004557 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004558 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004559#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004560 const char *conf_ciphersuites;
4561#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004562 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004563
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004564 if (ssl_conf) {
4565 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4566 int i, min, max;
4567 int flags = MC_SSL_O_ALL;
4568
4569 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004570 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4571 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004572 if (min)
4573 flags |= (methodVersions[min].flag - 1);
4574 if (max)
4575 flags |= ~((methodVersions[max].flag << 1) - 1);
4576 min = max = CONF_TLSV_NONE;
4577 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4578 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4579 if (min)
4580 max = i;
4581 else
4582 min = max = i;
4583 }
4584 /* save real min/max */
4585 conf_ssl_methods->min = min;
4586 conf_ssl_methods->max = max;
4587 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004588 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4589 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004590 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004591 }
4592 }
4593
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004594 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004595 case SSL_SOCK_VERIFY_NONE:
4596 verify = SSL_VERIFY_NONE;
4597 break;
4598 case SSL_SOCK_VERIFY_OPTIONAL:
4599 verify = SSL_VERIFY_PEER;
4600 break;
4601 case SSL_SOCK_VERIFY_REQUIRED:
4602 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4603 break;
4604 }
4605 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4606 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004607 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 +01004608 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 +01004609 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 +01004610 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004611 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004612 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004613 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004614 err && *err ? *err : "", curproxy->id, ca_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 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004617 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4618 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4619 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4620 cfgerr |= ERR_ALERT | ERR_FATAL;
4621 }
4622 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004623 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004624 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 +02004625 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004626 }
Emeric Brun850efd52014-01-29 12:24:34 +01004627 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004628 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4629 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004630 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004631 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004632#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004633 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004634 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4635
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004636 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004637 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4638 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004639 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004640 }
Emeric Brun561e5742012-10-02 15:20:55 +02004641 else {
4642 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4643 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004644 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004645#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004646 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004647 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004648#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004649 if(bind_conf->keys_ref) {
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +01004650 if (!SSL_CTX_set_tlsext_ticket_key_evp_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004651 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4652 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004653 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004654 }
4655 }
4656#endif
4657
William Lallemand4f45bb92017-10-30 20:08:51 +01004658 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004659 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4660 if (conf_ciphers &&
4661 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004662 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4663 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004664 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004665 }
4666
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004667#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004668 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4669 if (conf_ciphersuites &&
4670 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004671 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4672 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004673 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004674 }
4675#endif
4676
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004677#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02004678 if (!local_dh_1024)
4679 local_dh_1024 = ssl_get_dh_1024();
4680 if (!local_dh_2048)
4681 local_dh_2048 = ssl_get_dh_2048();
4682 if (!local_dh_4096)
4683 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02004684#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004685
Emeric Brunfc0421f2012-09-07 17:30:07 +02004686 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004687#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004688 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004689#endif
William Lallemand722180a2021-06-09 16:46:12 +02004690#ifdef HAVE_SSL_KEYLOG
William Lallemandb60a77b2022-11-18 15:00:15 +01004691 /* only activate the keylog callback if it was required to prevent performance loss */
4692 if (global_ssl.keylog > 0)
4693 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02004694#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004695
Bernard Spil13c53f82018-02-15 13:34:58 +01004696#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004697 ssl_conf_cur = NULL;
4698 if (ssl_conf && ssl_conf->npn_str)
4699 ssl_conf_cur = ssl_conf;
4700 else if (bind_conf->ssl_conf.npn_str)
4701 ssl_conf_cur = &bind_conf->ssl_conf;
4702 if (ssl_conf_cur)
4703 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004704#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004705#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004706 ssl_conf_cur = NULL;
4707 if (ssl_conf && ssl_conf->alpn_str)
4708 ssl_conf_cur = ssl_conf;
4709 else if (bind_conf->ssl_conf.alpn_str)
4710 ssl_conf_cur = &bind_conf->ssl_conf;
4711 if (ssl_conf_cur)
4712 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004713#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004714#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004715 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4716 if (conf_curves) {
4717 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004718 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4719 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004720 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004721 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004722 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004723 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004724#endif /* defined(SSL_CTX_set1_curves_list) */
4725
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004726 if (!conf_curves) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004727#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004728#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004729 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004730 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4731 NULL);
4732
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004733 if (ecdhe && SSL_CTX_set1_curves_list(ctx, ecdhe) == 0) {
4734 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4735 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
4736 cfgerr |= ERR_ALERT | ERR_FATAL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02004737 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004738#endif /* defined(SSL_CTX_set1_curves_list) */
Olivier Houchardc2aae742017-09-22 18:26:28 +02004739#else
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004740#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
4741 int i;
4742 EC_KEY *ecdh;
4743
Olivier Houchardc2aae742017-09-22 18:26:28 +02004744 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4745 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4746 ECDHE_DEFAULT_CURVE);
Emeric Brun2b58d042012-09-20 17:10:03 +02004747
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004748 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004749 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004750 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 +01004751 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004752 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004753 }
4754 else {
4755 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4756 EC_KEY_free(ecdh);
4757 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004758#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
4759#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Emeric Brun2b58d042012-09-20 17:10:03 +02004760 }
Emeric Brun2b58d042012-09-20 17:10:03 +02004761
Emeric Brunfc0421f2012-09-07 17:30:07 +02004762 return cfgerr;
4763}
4764
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004765
4766/*
4767 * Prepare the SSL_CTX based on the bind line configuration.
4768 * Since the CA file loading is made depending on the verify option of the bind
4769 * line, the link between the SSL_CTX and the CA file tree entry is made here.
4770 * If we want to create a link between the CA file entry and the corresponding
4771 * ckch instance (for CA file hot update), it needs to be done after
4772 * ssl_sock_prepare_ctx.
4773 * Returns 0 in case of success.
4774 */
4775int ssl_sock_prep_ctx_and_inst(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
4776 SSL_CTX *ctx, struct ckch_inst *ckch_inst, char **err)
4777{
4778 int errcode = 0;
4779
4780 errcode |= ssl_sock_prepare_ctx(bind_conf, ssl_conf, ctx, err);
4781 if (!errcode && ckch_inst)
4782 ckch_inst_add_cafile_link(ckch_inst, bind_conf, ssl_conf, NULL);
4783
4784 return errcode;
4785}
4786
Evan Broderbe554312013-06-27 00:05:25 -07004787static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4788{
4789 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4790 size_t prefixlen, suffixlen;
4791
4792 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004793 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004794 return 1;
4795
Evan Broderbe554312013-06-27 00:05:25 -07004796 /* The rest of this logic is based on RFC 6125, section 6.4.3
4797 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4798
Emeric Bruna848dae2013-10-08 11:27:28 +02004799 pattern_wildcard = NULL;
4800 pattern_left_label_end = pattern;
4801 while (*pattern_left_label_end != '.') {
4802 switch (*pattern_left_label_end) {
4803 case 0:
4804 /* End of label not found */
4805 return 0;
4806 case '*':
4807 /* If there is more than one wildcards */
4808 if (pattern_wildcard)
4809 return 0;
4810 pattern_wildcard = pattern_left_label_end;
4811 break;
4812 }
4813 pattern_left_label_end++;
4814 }
4815
4816 /* If it's not trivial and there is no wildcard, it can't
4817 * match */
4818 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004819 return 0;
4820
4821 /* Make sure all labels match except the leftmost */
4822 hostname_left_label_end = strchr(hostname, '.');
4823 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004824 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004825 return 0;
4826
4827 /* Make sure the leftmost label of the hostname is long enough
4828 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004829 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004830 return 0;
4831
4832 /* Finally compare the string on either side of the
4833 * wildcard */
4834 prefixlen = pattern_wildcard - pattern;
4835 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004836 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4837 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004838 return 0;
4839
4840 return 1;
4841}
4842
4843static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4844{
4845 SSL *ssl;
4846 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004847 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004848 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004849 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004850
4851 int depth;
4852 X509 *cert;
4853 STACK_OF(GENERAL_NAME) *alt_names;
4854 int i;
4855 X509_NAME *cert_subject;
4856 char *str;
4857
4858 if (ok == 0)
4859 return ok;
4860
4861 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004862 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02004863 ssl_ctx = __conn_get_ssl_sock_ctx(conn);
Evan Broderbe554312013-06-27 00:05:25 -07004864
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004865 /* We're checking if the provided hostnames match the desired one. The
4866 * desired hostname comes from the SNI we presented if any, or if not
4867 * provided then it may have been explicitly stated using a "verifyhost"
4868 * directive. If neither is set, we don't care about the name so the
4869 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004870 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004871 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004872 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004873 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004874 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004875 if (!servername)
4876 return ok;
4877 }
Evan Broderbe554312013-06-27 00:05:25 -07004878
4879 /* We only need to verify the CN on the actual server cert,
4880 * not the indirect CAs */
4881 depth = X509_STORE_CTX_get_error_depth(ctx);
4882 if (depth != 0)
4883 return ok;
4884
4885 /* At this point, the cert is *not* OK unless we can find a
4886 * hostname match */
4887 ok = 0;
4888
4889 cert = X509_STORE_CTX_get_current_cert(ctx);
4890 /* It seems like this might happen if verify peer isn't set */
4891 if (!cert)
4892 return ok;
4893
4894 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4895 if (alt_names) {
4896 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4897 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4898 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004899#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004900 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4901#else
Evan Broderbe554312013-06-27 00:05:25 -07004902 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004903#endif
Evan Broderbe554312013-06-27 00:05:25 -07004904 ok = ssl_sock_srv_hostcheck(str, servername);
4905 OPENSSL_free(str);
4906 }
4907 }
4908 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004909 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004910 }
4911
4912 cert_subject = X509_get_subject_name(cert);
4913 i = -1;
4914 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4915 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004916 ASN1_STRING *value;
4917 value = X509_NAME_ENTRY_get_data(entry);
4918 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004919 ok = ssl_sock_srv_hostcheck(str, servername);
4920 OPENSSL_free(str);
4921 }
4922 }
4923
Willy Tarreau71d058c2017-07-26 20:09:56 +02004924 /* report the mismatch and indicate if SNI was used or not */
4925 if (!ok && !conn->err_code)
4926 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004927 return ok;
4928}
4929
Emeric Brun94324a42012-10-11 14:00:19 +02004930/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004931int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004932{
4933 int cfgerr = 0;
William Lallemand2c776f12021-12-28 18:47:17 +01004934 SSL_CTX *ctx;
William Lallemand0adafb32022-12-13 18:17:44 +01004935 /* Automatic memory computations need to know we use SSL there
4936 * If this is an internal proxy, don't use it for the computation */
William Lallemand04007cb2022-12-14 10:34:36 +01004937 if (!(srv->proxy->cap & PR_CAP_INT))
William Lallemand0adafb32022-12-13 18:17:44 +01004938 global.ssl_used_backend = 1;
Willy Tarreaufce03112015-01-15 21:32:40 +01004939
4940 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004941 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004942 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004943 ha_alert("out of memory.\n");
Emeric Brun821bb9b2017-06-15 16:37:39 +02004944 cfgerr++;
4945 return cfgerr;
4946 }
4947 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004948 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004949 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004950
William Lallemand2c776f12021-12-28 18:47:17 +01004951 if (srv->ssl_ctx.client_crt) {
4952 const int create_if_none = srv->flags & SRV_F_DYNAMIC ? 0 : 1;
4953 char *err = NULL;
4954 int err_code = 0;
4955
4956 /* If there is a crt keyword there, the SSL_CTX will be created here. */
4957 err_code = ssl_sock_load_srv_cert(srv->ssl_ctx.client_crt, srv, create_if_none, &err);
4958 if (err_code != ERR_NONE) {
4959 if ((err_code & ERR_WARN) && !(err_code & ERR_ALERT))
4960 ha_warning("%s", err);
4961 else
4962 ha_alert("%s", err);
4963
4964 if (err_code & (ERR_FATAL|ERR_ABORT))
4965 cfgerr++;
4966 }
4967 ha_free(&err);
4968 }
4969
4970 ctx = srv->ssl_ctx.ctx;
4971
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004972 /* The context will be uninitialized if there wasn't any "cert" option
4973 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004974 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004975 ctx = SSL_CTX_new(SSLv23_client_method());
4976 if (!ctx) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004977 ha_alert("unable to allocate ssl context.\n");
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004978 cfgerr++;
4979 return cfgerr;
4980 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004981
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004982 srv->ssl_ctx.ctx = ctx;
4983 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004984
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004985 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 +01004986
4987 return cfgerr;
4988}
4989
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004990/* Initialize an SSL context that will be used on the backend side.
4991 * Returns an error count.
4992 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004993static int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004994{
4995 struct proxy *curproxy = srv->proxy;
4996 int cfgerr = 0;
4997 long options =
4998 SSL_OP_ALL | /* all known workarounds for bugs */
4999 SSL_OP_NO_SSLv2 |
5000 SSL_OP_NO_COMPRESSION;
5001 long mode =
5002 SSL_MODE_ENABLE_PARTIAL_WRITE |
5003 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
5004 SSL_MODE_RELEASE_BUFFERS |
5005 SSL_MODE_SMALL_BUFFERS;
5006 int verify = SSL_VERIFY_NONE;
5007 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
5008 int i, min, max, hole;
5009 int flags = MC_SSL_O_ALL;
5010
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005011 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005012 ha_warning("no-sslv3/no-tlsv1x are ignored for this server. "
5013 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n");
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005014 else
5015 flags = conf_ssl_methods->flags;
5016
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005017 /* Real min and max should be determinate with configuration and openssl's capabilities */
5018 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005019 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005020 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005021 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005022
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005023 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005024 min = max = CONF_TLSV_NONE;
5025 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005026 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005027 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005028 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005029 if (min) {
5030 if (hole) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005031 ha_warning("%s '%s': SSL/TLS versions range not contiguous for server '%s'. "
Christopher Faulet767a84b2017-11-24 16:50:31 +01005032 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
5033 proxy_type_str(curproxy), curproxy->id, srv->id,
5034 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005035 hole = 0;
5036 }
5037 max = i;
5038 }
5039 else {
5040 min = max = i;
5041 }
5042 }
5043 else {
5044 if (min)
5045 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005046 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005047 if (!min) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005048 ha_alert("%s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01005049 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005050 cfgerr += 1;
5051 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005052
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005053#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005054 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08005055 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005056 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005057 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005058 else
5059 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
5060 if (flags & methodVersions[i].flag)
5061 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005062#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005063 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005064 methodVersions[min].ctx_set_version(ctx, SET_MIN);
5065 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005066#endif
5067
5068 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
5069 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005070 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005071
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005072#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005073 if (global_ssl.async)
5074 mode |= SSL_MODE_ASYNC;
5075#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005076 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005077
Emeric Brun850efd52014-01-29 12:24:34 +01005078 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
5079 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01005080 switch (srv->ssl_ctx.verify) {
5081 case SSL_SOCK_VERIFY_NONE:
5082 verify = SSL_VERIFY_NONE;
5083 break;
5084 case SSL_SOCK_VERIFY_REQUIRED:
5085 verify = SSL_VERIFY_PEER;
5086 break;
5087 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005088 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02005089 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01005090 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02005091 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02005092 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005093 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005094 ha_alert("unable to set CA file '%s'.\n",
5095 srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005096 cfgerr++;
5097 }
5098 }
Emeric Brun850efd52014-01-29 12:24:34 +01005099 else {
5100 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005101 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 +01005102 else
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005103 ha_alert("verify is enabled but no CA file specified.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01005104 cfgerr++;
5105 }
Emeric Brunef42d922012-10-11 16:11:36 +02005106#ifdef X509_V_FLAG_CRL_CHECK
5107 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005108 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02005109
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01005110 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005111 ha_alert("unable to configure CRL file '%s'.\n",
5112 srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005113 cfgerr++;
5114 }
5115 else {
5116 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5117 }
5118 }
5119#endif
5120 }
5121
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005122 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5123 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02005124 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005125 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005126 ha_alert("unable to set SSL cipher list to '%s'.\n",
5127 srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02005128 cfgerr++;
5129 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005130
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05005131#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005132 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005133 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005134 ha_alert("unable to set TLS 1.3 cipher suites to '%s'.\n",
5135 srv->ssl_ctx.ciphersuites);
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005136 cfgerr++;
5137 }
5138#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01005139#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
5140 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005141 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01005142#endif
5143#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5144 if (srv->ssl_ctx.alpn_str)
5145 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
5146#endif
5147
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005148
5149 return cfgerr;
5150}
5151
5152/*
5153 * Prepare the frontend's SSL_CTX based on the server line configuration.
5154 * Since the CA file loading is made depending on the verify option of the
5155 * server line, the link between the SSL_CTX and the CA file tree entry is
5156 * made here.
5157 * If we want to create a link between the CA file entry and the corresponding
5158 * ckch instance (for CA file hot update), it needs to be done after
5159 * ssl_sock_prepare_srv_ssl_ctx.
5160 * Returns an error count.
5161 */
5162int ssl_sock_prep_srv_ctx_and_inst(const struct server *srv, SSL_CTX *ctx,
5163 struct ckch_inst *ckch_inst)
5164{
5165 int cfgerr = 0;
5166
5167 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, ctx);
5168 if (!cfgerr && ckch_inst)
5169 ckch_inst_add_cafile_link(ckch_inst, NULL, NULL, srv);
Emeric Brun94324a42012-10-11 14:00:19 +02005170
5171 return cfgerr;
5172}
5173
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005174
Frédéric Lécailleec216522020-11-23 14:33:30 +01005175/*
5176 * Create an initial CTX used to start the SSL connections.
5177 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
5178 * Returns 0 if succeeded, or something >0 if not.
5179 */
5180#ifdef USE_QUIC
5181static int ssl_initial_ctx(struct bind_conf *bind_conf)
5182{
5183 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
5184 return ssl_quic_initial_ctx(bind_conf);
5185 else
5186 return ssl_sock_initial_ctx(bind_conf);
5187}
5188#else
5189static int ssl_initial_ctx(struct bind_conf *bind_conf)
5190{
5191 return ssl_sock_initial_ctx(bind_conf);
5192}
5193#endif
5194
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005195/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005196 * be NULL, in which case nothing is done. Returns the number of errors
5197 * encountered.
5198 */
Willy Tarreau03209342016-12-22 17:08:28 +01005199int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005200{
5201 struct ebmb_node *node;
5202 struct sni_ctx *sni;
5203 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01005204 int errcode = 0;
5205 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02005206
Willy Tarreaufce03112015-01-15 21:32:40 +01005207 /* Automatic memory computations need to know we use SSL there */
5208 global.ssl_used_frontend = 1;
5209
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005210 /* Create initial_ctx used to start the ssl connection before do switchctx */
5211 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01005212 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005213 /* It should not be necessary to call this function, but it's
5214 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01005215 to initial_ctx in ssl_initial_ctx. */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005216 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, NULL, bind_conf->initial_ctx, NULL, &errmsg);
5217 }
5218 if (bind_conf->default_ctx) {
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005219 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 +01005220 }
Emeric Brun0bed9942014-10-30 19:25:24 +01005221
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005222 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005223 while (node) {
5224 sni = ebmb_entry(node, struct sni_ctx, name);
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005225 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005226 /* only initialize the CTX on its first occurrence and
5227 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005228 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
5229 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005230 node = ebmb_next(node);
5231 }
5232
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005233 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005234 while (node) {
5235 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01005236 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005237 /* only initialize the CTX on its first occurrence and
5238 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005239 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005240 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005241 node = ebmb_next(node);
5242 }
William Lallemand8b453912019-11-21 15:48:10 +01005243
5244 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005245 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005246 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005247 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005248 err++;
5249 }
5250
5251 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005252 return err;
5253}
5254
Willy Tarreau55d37912016-12-21 23:38:39 +01005255/* Prepares all the contexts for a bind_conf and allocates the shared SSL
5256 * context if needed. Returns < 0 on error, 0 on success. The warnings and
5257 * alerts are directly emitted since the rest of the stack does it below.
5258 */
5259int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
5260{
5261 struct proxy *px = bind_conf->frontend;
5262 int alloc_ctx;
5263 int err;
5264
Willy Tarreau11ba4042022-05-20 15:56:32 +02005265 if (!(bind_conf->options & BC_O_USE_SSL)) {
Willy Tarreau55d37912016-12-21 23:38:39 +01005266 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005267 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
5268 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01005269 }
5270 return 0;
5271 }
5272 if (!bind_conf->default_ctx) {
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005273 if (bind_conf->strict_sni && !(bind_conf->options & BC_O_GENERATE_CERTS)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005274 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5275 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005276 }
5277 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005278 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5279 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005280 return -1;
5281 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005282 }
William Lallemandc61c0b32017-12-04 18:46:39 +01005283 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005284 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02005285 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
Willy Tarreau91358592021-06-15 08:08:04 +02005286 sizeof(*sh_ssl_sess_tree), (global.nbthread > 1));
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02005287 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005288 if (alloc_ctx == SHCTX_E_INIT_LOCK)
5289 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");
5290 else
5291 ha_alert("Unable to allocate SSL session cache.\n");
5292 return -1;
5293 }
5294 /* free block callback */
5295 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5296 /* init the root tree within the extra space */
5297 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5298 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01005299 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005300 err = 0;
5301 /* initialize all certificate contexts */
5302 err += ssl_sock_prepare_all_ctx(bind_conf);
5303
5304 /* initialize CA variables if the certificates generation is enabled */
5305 err += ssl_sock_load_ca(bind_conf);
5306
5307 return -err;
5308}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005309
William Lallemand231610a2021-12-30 11:25:43 +01005310/* release ssl context allocated for servers. Most of the field free here
5311 * must also be allocated in srv_ssl_settings_cpy() */
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005312void ssl_sock_free_srv_ctx(struct server *srv)
5313{
Olivier Houchardc7566002018-11-20 23:33:50 +01005314#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
William Lallemand231610a2021-12-30 11:25:43 +01005315 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005316#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005317#ifdef OPENSSL_NPN_NEGOTIATED
William Lallemand231610a2021-12-30 11:25:43 +01005318 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005319#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005320 if (srv->ssl_ctx.reused_sess) {
5321 int i;
5322
William Lallemande18d4e82021-11-17 02:59:21 +01005323 for (i = 0; i < global.nbthread; i++) {
Willy Tarreaue709e822021-02-26 21:06:32 +01005324 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
William Lallemande18d4e82021-11-17 02:59:21 +01005325 ha_free(&srv->ssl_ctx.reused_sess[i].sni);
5326 }
Willy Tarreaue709e822021-02-26 21:06:32 +01005327 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005328 }
5329
Willy Tarreaue709e822021-02-26 21:06:32 +01005330 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005331 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005332 srv->ssl_ctx.ctx = NULL;
5333 }
William Lallemand231610a2021-12-30 11:25:43 +01005334
5335 ha_free(&srv->ssl_ctx.ca_file);
5336 ha_free(&srv->ssl_ctx.crl_file);
5337 ha_free(&srv->ssl_ctx.client_crt);
5338 ha_free(&srv->ssl_ctx.verify_host);
5339#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5340 ha_free(&srv->sni_expr);
William Lallemand43c2ce42022-03-16 17:48:19 +01005341 release_sample_expr(srv->ssl_ctx.sni);
5342 srv->ssl_ctx.sni = NULL;
William Lallemand231610a2021-12-30 11:25:43 +01005343#endif
5344 ha_free(&srv->ssl_ctx.ciphers);
5345#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
5346 ha_free(&srv->ssl_ctx.ciphersuites);
5347#endif
William Lallemande69563f2021-12-30 14:45:19 +01005348 /* If there is a certificate we must unlink the ckch instance */
5349 ckch_inst_free(srv->ssl_ctx.inst);
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005350}
5351
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005352/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005353 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5354 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005355void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005356{
5357 struct ebmb_node *node, *back;
5358 struct sni_ctx *sni;
5359
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005360 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005361 while (node) {
5362 sni = ebmb_entry(node, struct sni_ctx, name);
5363 back = ebmb_next(node);
5364 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005365 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005366 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005367 free(sni);
5368 node = back;
5369 }
5370
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005371 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005372 while (node) {
5373 sni = ebmb_entry(node, struct sni_ctx, name);
5374 back = ebmb_next(node);
5375 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005376 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005377 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005378 free(sni);
5379 node = back;
5380 }
William Lallemandb2408692020-06-24 09:54:29 +02005381
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005382 SSL_CTX_free(bind_conf->initial_ctx);
5383 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005384 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005385 bind_conf->default_ctx = NULL;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005386 bind_conf->default_inst = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005387 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005388}
William Lallemandb2408692020-06-24 09:54:29 +02005389
5390
5391void ssl_sock_deinit()
5392{
5393 crtlist_deinit(); /* must be free'd before the ckchs */
5394 ckch_deinit();
5395}
5396REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005397
Willy Tarreau795cdab2016-12-22 17:30:54 +01005398/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5399void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5400{
5401 ssl_sock_free_ca(bind_conf);
5402 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005403 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005404 free(bind_conf->ca_sign_file);
5405 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005406 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005407 free(bind_conf->keys_ref->filename);
5408 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005409 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005410 free(bind_conf->keys_ref);
5411 }
5412 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005413 bind_conf->ca_sign_pass = NULL;
5414 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005415}
5416
Christopher Faulet31af49d2015-06-09 17:29:50 +02005417/* Load CA cert file and private key used to generate certificates */
5418int
Willy Tarreau03209342016-12-22 17:08:28 +01005419ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005420{
Willy Tarreau03209342016-12-22 17:08:28 +01005421 struct proxy *px = bind_conf->frontend;
William Lallemand52ddd992022-11-22 11:51:53 +01005422 struct ckch_data *data = NULL;
Shimi Gersner5846c492020-08-23 13:58:12 +03005423 int ret = 0;
5424 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005425
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005426 if (!(bind_conf->options & BC_O_GENERATE_CERTS))
Shimi Gersner5846c492020-08-23 13:58:12 +03005427 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005428
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005429#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005430 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005431 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005432 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005433 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005434 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005435#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005436
Christopher Faulet31af49d2015-06-09 17:29:50 +02005437 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005438 ha_alert("Proxy '%s': cannot enable certificate generation, "
5439 "no CA certificate File configured at [%s:%d].\n",
5440 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005441 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005442 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005443
Shimi Gersner5846c492020-08-23 13:58:12 +03005444 /* Allocate cert structure */
William Lallemand52ddd992022-11-22 11:51:53 +01005445 data = calloc(1, sizeof(*data));
5446 if (!data) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005447 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5448 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5449 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005450 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005451
5452 /* Try to parse file */
William Lallemand52ddd992022-11-22 11:51:53 +01005453 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, data, &err)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005454 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5455 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005456 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005457 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005458 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005459
5460 /* Fail if missing cert or pkey */
William Lallemand52ddd992022-11-22 11:51:53 +01005461 if ((!data->cert) || (!data->key)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005462 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5463 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5464 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005465 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005466
Shimi Gersner5846c492020-08-23 13:58:12 +03005467 /* Final assignment to bind */
William Lallemand52ddd992022-11-22 11:51:53 +01005468 bind_conf->ca_sign_ckch = data;
Shimi Gersner5846c492020-08-23 13:58:12 +03005469 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005470
Shimi Gersner5846c492020-08-23 13:58:12 +03005471 failed:
William Lallemand52ddd992022-11-22 11:51:53 +01005472 if (data) {
5473 ssl_sock_free_cert_key_and_chain_contents(data);
5474 free(data);
Shimi Gersner5846c492020-08-23 13:58:12 +03005475 }
5476
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005477 bind_conf->options &= ~BC_O_GENERATE_CERTS;
Shimi Gersner5846c492020-08-23 13:58:12 +03005478 ret++;
5479 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005480}
5481
5482/* Release CA cert and private key used to generate certificated */
5483void
5484ssl_sock_free_ca(struct bind_conf *bind_conf)
5485{
Shimi Gersner5846c492020-08-23 13:58:12 +03005486 if (bind_conf->ca_sign_ckch) {
5487 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005488 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005489 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005490}
5491
Emeric Brun46591952012-05-18 15:47:34 +02005492/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005493 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5494 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5495 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5496 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005497 * 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 +01005498 * as parameters to this function.
5499 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5500 * CO_ER_SSL_NO_MEM.
5501 */
5502int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5503 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5504{
5505 int retry = 1;
5506
5507 retry:
5508 /* Alloc a new SSL session. */
5509 *ssl = SSL_new(ssl_ctx);
5510 if (!*ssl) {
5511 if (!retry--)
5512 goto err;
5513
5514 pool_gc(NULL);
5515 goto retry;
5516 }
5517
5518 *bio = BIO_new(bio_meth);
5519 if (!*bio) {
5520 SSL_free(*ssl);
5521 *ssl = NULL;
5522 if (!retry--)
5523 goto err;
5524
5525 pool_gc(NULL);
5526 goto retry;
5527 }
5528
5529 BIO_set_data(*bio, ctx);
5530 SSL_set_bio(*ssl, *bio, *bio);
5531
5532 /* set connection pointer. */
5533 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5534 SSL_free(*ssl);
5535 *ssl = NULL;
5536 if (!retry--)
5537 goto err;
5538
5539 pool_gc(NULL);
5540 goto retry;
5541 }
5542
5543 return 0;
5544
5545 err:
5546 conn->err_code = CO_ER_SSL_NO_MEM;
5547 return -1;
5548}
5549
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005550/* This function is called when all the XPRT have been initialized. We can
5551 * now attempt to start the SSL handshake.
5552 */
5553static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5554{
5555 struct ssl_sock_ctx *ctx = xprt_ctx;
5556
5557 if (ctx->xprt->start) {
5558 int ret;
5559
5560 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5561 if (ret < 0)
5562 return ret;
5563 }
5564 tasklet_wakeup(ctx->wait_event.tasklet);
5565
5566 return 0;
5567}
5568
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005569/*
Emeric Brun46591952012-05-18 15:47:34 +02005570 * This function is called if SSL * context is not yet allocated. The function
5571 * is designed to be called before any other data-layer operation and sets the
5572 * handshake flag on the connection. It is safe to call it multiple times.
5573 * It returns 0 on success and -1 in error case.
5574 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005575static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005576{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005577 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005578 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005579 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005580 return 0;
5581
Olivier Houchard66ab4982019-02-26 18:37:15 +01005582 ctx = pool_alloc(ssl_sock_ctx_pool);
5583 if (!ctx) {
5584 conn->err_code = CO_ER_SSL_NO_MEM;
5585 return -1;
5586 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005587 ctx->wait_event.tasklet = tasklet_new();
5588 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005589 conn->err_code = CO_ER_SSL_NO_MEM;
5590 pool_free(ssl_sock_ctx_pool, ctx);
5591 return -1;
5592 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005593 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5594 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005595 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005596 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005597 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005598 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005599 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005600 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005601 ctx->xprt_st = 0;
5602 ctx->xprt_ctx = NULL;
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005603 ctx->error_code = 0;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005604
5605 /* Only work with sockets for now, this should be adapted when we'll
5606 * add QUIC support.
5607 */
5608 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005609 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005610 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5611 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005612 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005613
Willy Tarreau82531f62021-10-06 12:15:18 +02005614 if (global.maxsslconn && global.sslconns >= global.maxsslconn) {
Willy Tarreau20879a02012-12-03 16:32:10 +01005615 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005616 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005617 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005618
Emeric Brun46591952012-05-18 15:47:34 +02005619 /* If it is in client mode initiate SSL session
5620 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005621 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005622 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5623 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005624 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005625
Olivier Houchard66ab4982019-02-26 18:37:15 +01005626 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005627 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005628 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5629 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5630 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 +01005631 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005632 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005633 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005634 } else if (sess) {
5635 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005636 }
5637 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005638 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005639
Emeric Brun46591952012-05-18 15:47:34 +02005640 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005641 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005642
Willy Tarreau82531f62021-10-06 12:15:18 +02005643 _HA_ATOMIC_INC(&global.sslconns);
5644 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005645 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005646 return 0;
5647 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005648 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005649 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005650
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005651 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5652 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005653 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005654
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005655#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005656 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005657 b_alloc(&ctx->early_buf);
5658 SSL_set_max_early_data(ctx->ssl,
5659 /* Only allow early data if we managed to allocate
5660 * a buffer.
5661 */
5662 (!b_is_null(&ctx->early_buf)) ?
5663 global.tune.bufsize - global.tune.maxrewrite : 0);
5664 }
5665#endif
5666
Olivier Houchard66ab4982019-02-26 18:37:15 +01005667 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005668
Emeric Brun46591952012-05-18 15:47:34 +02005669 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005670 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005671#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005672 if (bc->ssl_conf.early_data)
5673 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005674#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005675
Willy Tarreau82531f62021-10-06 12:15:18 +02005676 _HA_ATOMIC_INC(&global.sslconns);
5677 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005678 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005679 return 0;
5680 }
5681 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005682 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005683err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005684 if (ctx && ctx->wait_event.tasklet)
5685 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005686 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005687 return -1;
5688}
5689
5690
5691/* This is the callback which is used when an SSL handshake is pending. It
5692 * updates the FD status if it wants some polling before being called again.
5693 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5694 * otherwise it returns non-zero and removes itself from the connection's
5695 * flags (the bit is provided in <flag> by the caller).
5696 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005697static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005698{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005699 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Emeric Brun46591952012-05-18 15:47:34 +02005700 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005701 struct ssl_counters *counters = NULL;
5702 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005703 struct listener *li;
5704 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005705 socklen_t lskerr;
5706 int skerr;
5707
Emeric Brun46591952012-05-18 15:47:34 +02005708
Willy Tarreau3c728722014-01-23 13:50:42 +01005709 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005710 return 0;
5711
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005712 /* get counters */
5713 switch (obj_type(conn->target)) {
5714 case OBJ_TYPE_LISTENER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005715 li = __objt_listener(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005716 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5717 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5718 &ssl_stats_module);
5719 break;
5720
5721 case OBJ_TYPE_SERVER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005722 srv = __objt_server(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005723 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5724 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5725 &ssl_stats_module);
5726 break;
5727
5728 default:
5729 break;
5730 }
5731
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005732 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005733 goto out_error;
5734
Willy Tarreau06300382021-02-02 15:42:25 +01005735 /* don't start calculating a handshake on a dead connection */
5736 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5737 goto out_error;
5738
5739 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5740 * status from the lower layers, so let's check the FD directly. Ideally
5741 * the xprt layers should provide some status indicating their knowledge
5742 * of shutdowns or error.
5743 */
Willy Tarreau07ecfc52022-04-11 18:07:03 +02005744 BUG_ON(conn->flags & CO_FL_FDLESS);
5745
Willy Tarreau06300382021-02-02 15:42:25 +01005746 skerr = 0;
5747 lskerr = sizeof(skerr);
5748 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5749 skerr != 0)
5750 goto out_error;
5751
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005752#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005753 /*
5754 * Check if we have early data. If we do, we have to read them
5755 * before SSL_do_handshake() is called, And there's no way to
5756 * detect early data, except to try to read them
5757 */
5758 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005759 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005760
Olivier Houchard54907bb2019-12-19 15:02:39 +01005761 while (1) {
5762 ret = SSL_read_early_data(ctx->ssl,
5763 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5764 &read_data);
5765 if (ret == SSL_READ_EARLY_DATA_ERROR)
5766 goto check_error;
5767 if (read_data > 0) {
5768 conn->flags |= CO_FL_EARLY_DATA;
5769 b_add(&ctx->early_buf, read_data);
5770 }
5771 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5772 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5773 if (!b_data(&ctx->early_buf))
5774 b_free(&ctx->early_buf);
5775 break;
5776 }
5777 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005778 }
5779#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005780 /* If we use SSL_do_handshake to process a reneg initiated by
5781 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5782 * Usually SSL_write and SSL_read are used and process implicitly
5783 * the reneg handshake.
5784 * Here we use SSL_peek as a workaround for reneg.
5785 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005786 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005787 char c;
5788
Olivier Houchard66ab4982019-02-26 18:37:15 +01005789 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005790 if (ret <= 0) {
5791 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005792 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005793
Emeric Brun674b7432012-11-08 19:21:55 +01005794 if (ret == SSL_ERROR_WANT_WRITE) {
5795 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005796 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005797 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005798 return 0;
5799 }
5800 else if (ret == SSL_ERROR_WANT_READ) {
5801 /* handshake may have been completed but we have
5802 * no more data to read.
5803 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005804 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005805 ret = 1;
5806 goto reneg_ok;
5807 }
5808 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005809 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005810 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005811 return 0;
5812 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005813#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005814 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005815 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005816 return 0;
5817 }
5818#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005819 else if (ret == SSL_ERROR_SYSCALL) {
5820 /* if errno is null, then connection was successfully established */
5821 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5822 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005823 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005824#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5825 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005826 conn->err_code = CO_ER_SSL_HANDSHAKE;
5827#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005828 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005829#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005830 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005831 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005832 empty_handshake = state == TLS_ST_BEFORE;
5833#else
Lukas Tribus49799162019-07-08 14:29:15 +02005834 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5835 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005836#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005837 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005838 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005839 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005840 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5841 else
5842 conn->err_code = CO_ER_SSL_EMPTY;
5843 }
5844 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005845 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005846 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5847 else
5848 conn->err_code = CO_ER_SSL_ABORT;
5849 }
5850 }
5851 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005852 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005853 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005854 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005855 conn->err_code = CO_ER_SSL_HANDSHAKE;
5856 }
Lukas Tribus49799162019-07-08 14:29:15 +02005857#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005858 }
Emeric Brun674b7432012-11-08 19:21:55 +01005859 goto out_error;
5860 }
5861 else {
5862 /* Fail on all other handshake errors */
5863 /* Note: OpenSSL may leave unread bytes in the socket's
5864 * buffer, causing an RST to be emitted upon close() on
5865 * TCP sockets. We first try to drain possibly pending
5866 * data to avoid this as much as possible.
5867 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005868 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005869 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005870 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005871 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005872 goto out_error;
5873 }
5874 }
5875 /* read some data: consider handshake completed */
5876 goto reneg_ok;
5877 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005878 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005879check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005880 if (ret != 1) {
5881 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005882 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005883
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005884 if (!ctx->error_code)
5885 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton7c6898e2021-07-29 09:45:51 +02005886
Emeric Brun46591952012-05-18 15:47:34 +02005887 if (ret == SSL_ERROR_WANT_WRITE) {
5888 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005889 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005890 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005891 return 0;
5892 }
5893 else if (ret == SSL_ERROR_WANT_READ) {
5894 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005895 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005896 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5897 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005898 return 0;
5899 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005900#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005901 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005902 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005903 return 0;
5904 }
5905#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005906 else if (ret == SSL_ERROR_SYSCALL) {
5907 /* if errno is null, then connection was successfully established */
5908 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5909 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005910 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005911#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5912 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005913 conn->err_code = CO_ER_SSL_HANDSHAKE;
5914#else
5915 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005916#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005917 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005918 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005919 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005920#else
Lukas Tribus49799162019-07-08 14:29:15 +02005921 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5922 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005923#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005924 if (empty_handshake) {
5925 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005926 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005927 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5928 else
5929 conn->err_code = CO_ER_SSL_EMPTY;
5930 }
5931 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005932 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005933 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5934 else
5935 conn->err_code = CO_ER_SSL_ABORT;
5936 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005937 }
5938 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005939 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005940 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5941 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005942 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005943 }
Lukas Tribus49799162019-07-08 14:29:15 +02005944#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005945 }
Willy Tarreau89230192012-09-28 20:22:13 +02005946 goto out_error;
5947 }
Emeric Brun46591952012-05-18 15:47:34 +02005948 else {
5949 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005950 /* Note: OpenSSL may leave unread bytes in the socket's
5951 * buffer, causing an RST to be emitted upon close() on
5952 * TCP sockets. We first try to drain possibly pending
5953 * data to avoid this as much as possible.
5954 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005955 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005956 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005957 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005958 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005959 goto out_error;
5960 }
5961 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005962#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005963 else {
5964 /*
5965 * If the server refused the early data, we have to send a
5966 * 425 to the client, as we no longer have the data to sent
5967 * them again.
5968 */
5969 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005970 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005971 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5972 goto out_error;
5973 }
5974 }
5975 }
5976#endif
5977
Emeric Brun46591952012-05-18 15:47:34 +02005978
Emeric Brun674b7432012-11-08 19:21:55 +01005979reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005980
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005981#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00005982 /* ASYNC engine API doesn't support moving read/write
5983 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005984 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005985 */
5986 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005987 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005988#endif
Emeric Brun46591952012-05-18 15:47:34 +02005989 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005990 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005991 if (objt_server(conn->target)) {
5992 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5993 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5994 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005995 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005996 else {
5997 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5998 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5999 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
6000 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006001
Willy Tarreau42995282020-11-06 13:19:18 +01006002 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006003 HA_ATOMIC_INC(&counters->sess);
6004 HA_ATOMIC_INC(&counters_px->sess);
Willy Tarreau42995282020-11-06 13:19:18 +01006005 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006006 }
Willy Tarreau42995282020-11-06 13:19:18 +01006007 else if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006008 HA_ATOMIC_INC(&counters->reused_sess);
6009 HA_ATOMIC_INC(&counters_px->reused_sess);
Emeric Brun46591952012-05-18 15:47:34 +02006010 }
6011
6012 /* The connection is now established at both layers, it's time to leave */
6013 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
6014 return 1;
6015
6016 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006017 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006018 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006019 ERR_clear_error();
6020
Emeric Brun9fa89732012-10-04 17:09:56 +02006021 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01006022 if (objt_server(conn->target)) {
6023 struct server *s = __objt_server(conn->target);
6024 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
6025 * one cache per thread, it only prevents to flush it from the CLI in
6026 * another thread */
6027
6028 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01006029 if (s->ssl_ctx.reused_sess[tid].ptr)
6030 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01006031 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02006032 }
6033
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006034 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006035 HA_ATOMIC_INC(&counters->failed_handshake);
6036 HA_ATOMIC_INC(&counters_px->failed_handshake);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006037 }
6038
Emeric Brun46591952012-05-18 15:47:34 +02006039 /* Fail on all other handshake errors */
6040 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01006041 if (!conn->err_code)
6042 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006043 return 0;
6044}
6045
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006046/* Called from the upper layer, to subscribe <es> to events <event_type>. The
6047 * event subscriber <es> is not allowed to change from a previous call as long
6048 * as at least one event is still subscribed. The <event_type> must only be a
6049 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
6050 * unless the transport layer was already released.
6051 */
6052static int ssl_subscribe(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
Olivier Houchard0ff28652019-06-24 18:57:39 +02006056 if (!ctx)
6057 return -1;
6058
Willy Tarreau113d52b2020-01-10 09:20:26 +01006059 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006060 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006061
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006062 ctx->subs = es;
6063 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006064
6065 /* we may have to subscribe to lower layers for new events */
6066 event_type &= ~ctx->wait_event.events;
6067 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
6068 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006069 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006070}
6071
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006072/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
6073 * The <es> pointer is not allowed to differ from the one passed to the
6074 * subscribe() call. It always returns zero.
6075 */
6076static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006077{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006078 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006079
Willy Tarreau113d52b2020-01-10 09:20:26 +01006080 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006081 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006082
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006083 es->events &= ~event_type;
6084 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01006085 ctx->subs = NULL;
6086
6087 /* If we subscribed, and we're not doing the handshake,
6088 * then we subscribed because the upper layer asked for it,
6089 * as the upper layer is no longer interested, we can
6090 * unsubscribe too.
6091 */
6092 event_type &= ctx->wait_event.events;
6093 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
6094 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006095
6096 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006097}
6098
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006099/* The connection has been taken over, so destroy the old tasklet and create
6100 * a new one. The original thread ID must be passed into orig_tid
6101 * It should be called with the takeover lock for the old thread held.
6102 * Returns 0 on success, and -1 on failure
6103 */
6104static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
6105{
6106 struct ssl_sock_ctx *ctx = xprt_ctx;
6107 struct tasklet *tl = tasklet_new();
6108
6109 if (!tl)
6110 return -1;
6111
6112 ctx->wait_event.tasklet->context = NULL;
6113 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
6114 ctx->wait_event.tasklet = tl;
6115 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
6116 ctx->wait_event.tasklet->context = ctx;
6117 return 0;
6118}
6119
Willy Tarreau41491682021-03-02 17:29:56 +01006120/* notify the next xprt that the connection is about to become idle and that it
6121 * may be stolen at any time after the function returns and that any tasklet in
6122 * the chain must be careful before dereferencing its context.
6123 */
6124static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
6125{
6126 struct ssl_sock_ctx *ctx = xprt_ctx;
6127
6128 if (!ctx || !ctx->wait_event.tasklet)
6129 return;
6130
6131 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6132 if (ctx->xprt)
6133 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
6134}
6135
6136/* notify the next xprt that the connection is not idle anymore and that it may
6137 * not be stolen before the next xprt_set_idle().
6138 */
6139static void ssl_set_used(struct connection *conn, void *xprt_ctx)
6140{
6141 struct ssl_sock_ctx *ctx = xprt_ctx;
6142
6143 if (!ctx || !ctx->wait_event.tasklet)
6144 return;
6145
6146 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6147 if (ctx->xprt)
6148 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
6149}
6150
Olivier Houchard2e055482019-05-27 19:50:12 +02006151/* Use the provided XPRT as an underlying XPRT, and provide the old one.
6152 * Returns 0 on success, and non-zero on failure.
6153 */
6154static 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)
6155{
6156 struct ssl_sock_ctx *ctx = xprt_ctx;
6157
6158 if (oldxprt_ops != NULL)
6159 *oldxprt_ops = ctx->xprt;
6160 if (oldxprt_ctx != NULL)
6161 *oldxprt_ctx = ctx->xprt_ctx;
6162 ctx->xprt = toadd_ops;
6163 ctx->xprt_ctx = toadd_ctx;
6164 return 0;
6165}
6166
Olivier Houchard5149b592019-05-23 17:47:36 +02006167/* Remove the specified xprt. If if it our underlying XPRT, remove it and
6168 * return 0, otherwise just call the remove_xprt method from the underlying
6169 * XPRT.
6170 */
6171static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
6172{
6173 struct ssl_sock_ctx *ctx = xprt_ctx;
6174
6175 if (ctx->xprt_ctx == toremove_ctx) {
6176 ctx->xprt_ctx = newctx;
6177 ctx->xprt = newops;
6178 return 0;
6179 }
6180 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
6181}
6182
Willy Tarreau144f84a2021-03-02 16:09:26 +01006183struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02006184{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006185 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006186 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006187 struct connection *conn;
6188 int conn_in_list;
6189 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006190
Willy Tarreau41491682021-03-02 17:29:56 +01006191 if (state & TASK_F_USR1) {
6192 /* the tasklet was idling on an idle connection, it might have
6193 * been stolen, let's be careful!
6194 */
6195 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6196 if (tl->context == NULL) {
6197 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6198 tasklet_free(tl);
6199 return NULL;
6200 }
6201 conn = ctx->conn;
Christopher Faulet3a7b5392023-03-16 11:43:05 +01006202 conn_in_list = conn_get_idle_flag(conn);
Willy Tarreau41491682021-03-02 17:29:56 +01006203 if (conn_in_list)
6204 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006205 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01006206 } else {
6207 conn = ctx->conn;
6208 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006209 }
Willy Tarreau41491682021-03-02 17:29:56 +01006210
Olivier Houchardea8dd942019-05-20 14:02:16 +02006211 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01006212 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006213 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006214 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
6215 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01006216 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006217 }
6218 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006219 /* If we had an error, or the handshake is done and I/O is available,
6220 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01006221 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02006222 * we can't be sure conn_fd_handler() will be called again.
6223 */
6224 if ((ctx->conn->flags & CO_FL_ERROR) ||
6225 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006226 int woke = 0;
6227
6228 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006229 if (ctx->subs) {
6230 tasklet_wakeup(ctx->subs->tasklet);
6231 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006232 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006233 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006234 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006235
Olivier Houchardea8dd942019-05-20 14:02:16 +02006236 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01006237 * upper layers know. If we have no mux, create it,
6238 * and once we have a mux, call its wake method if we didn't
6239 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02006240 */
6241 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01006242 if (!ctx->conn->mux)
6243 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006244 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006245 ret = ctx->conn->mux->wake(ctx->conn);
6246 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006247 }
6248 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006249#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006250 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006251 else if (b_data(&ctx->early_buf) && ctx->subs &&
6252 ctx->subs->events & SUB_RETRY_RECV) {
6253 tasklet_wakeup(ctx->subs->tasklet);
6254 ctx->subs->events &= ~SUB_RETRY_RECV;
6255 if (!ctx->subs->events)
6256 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01006257 }
6258#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006259leave:
6260 if (!ret && conn_in_list) {
6261 struct server *srv = objt_server(conn->target);
6262
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006263 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006264 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau85223482022-09-29 20:32:43 +02006265 eb64_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006266 else
Willy Tarreau85223482022-09-29 20:32:43 +02006267 eb64_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006268 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006269 }
Willy Tarreau74163142021-03-13 11:30:19 +01006270 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006271}
6272
Emeric Brun46591952012-05-18 15:47:34 +02006273/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01006274 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02006275 * buffer wraps, in which case a second call may be performed. The connection's
6276 * flags are updated with whatever special event is detected (error, read0,
6277 * empty). The caller is responsible for taking care of those events and
6278 * avoiding the call if inappropriate. The function does not call the
6279 * connection's polling update function, so the caller is responsible for this.
6280 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006281static 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 +02006282{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006283 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02006284 ssize_t ret;
6285 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02006286
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006287 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006288 goto out_error;
6289
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006290#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006291 if (b_data(&ctx->early_buf)) {
6292 try = b_contig_space(buf);
6293 if (try > b_data(&ctx->early_buf))
6294 try = b_data(&ctx->early_buf);
6295 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
6296 b_add(buf, try);
6297 b_del(&ctx->early_buf, try);
6298 if (b_data(&ctx->early_buf) == 0)
6299 b_free(&ctx->early_buf);
6300 return try;
6301 }
6302#endif
6303
Willy Tarreau911db9b2020-01-23 16:27:54 +01006304 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006305 /* a handshake was requested */
6306 return 0;
6307
Emeric Brun46591952012-05-18 15:47:34 +02006308 /* read the largest possible block. For this, we perform only one call
6309 * to recv() unless the buffer wraps and we exactly fill the first hunk,
6310 * in which case we accept to do it once again. A new attempt is made on
6311 * EINTR too.
6312 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01006313 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006314
Willy Tarreau591d4452018-06-15 17:21:00 +02006315 try = b_contig_space(buf);
6316 if (!try)
6317 break;
6318
Willy Tarreauabf08d92014-01-14 11:31:27 +01006319 if (try > count)
6320 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02006321
Olivier Houchard66ab4982019-02-26 18:37:15 +01006322 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02006323
Emeric Brune1f38db2012-09-03 20:36:47 +02006324 if (conn->flags & CO_FL_ERROR) {
6325 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006326 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006327 }
Emeric Brun46591952012-05-18 15:47:34 +02006328 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006329 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006330 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006331 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006332 }
Emeric Brun46591952012-05-18 15:47:34 +02006333 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006334 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006335 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006336 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006337 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006338 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006339#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006340 /* Async mode can be re-enabled, because we're leaving data state.*/
6341 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006342 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006343#endif
Emeric Brun46591952012-05-18 15:47:34 +02006344 break;
6345 }
6346 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006347 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006348 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6349 SUB_RETRY_RECV,
6350 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006351 /* handshake is running, and it may need to re-enable read */
6352 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006353#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006354 /* Async mode can be re-enabled, because we're leaving data state.*/
6355 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006356 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006357#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006358 break;
6359 }
Emeric Brun46591952012-05-18 15:47:34 +02006360 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006361 } else if (ret == SSL_ERROR_ZERO_RETURN)
6362 goto read0;
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006363 else if (ret == SSL_ERROR_SSL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006364 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6365 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006366 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006367 conn->err_code = CO_ERR_SSL_FATAL;
6368 }
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006369 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6370 * stack before shutting down the connection for
6371 * reading. */
Willy Tarreauacef5e22022-04-25 20:32:15 +02006372 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN || errno == EWOULDBLOCK))
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006373 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006374 /* otherwise it's a real error */
6375 goto out_error;
6376 }
6377 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006378 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006379 return done;
6380
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006381 clear_ssl_error:
6382 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006383 ssl_sock_dump_errors(conn, NULL);
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006384 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006385 read0:
6386 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006387 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006388
Emeric Brun46591952012-05-18 15:47:34 +02006389 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006390 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006391 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006392 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006393 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006394 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006395}
6396
6397
Willy Tarreau787db9a2018-06-14 18:31:46 +02006398/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6399 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6400 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006401 * Only one call to send() is performed, unless the buffer wraps, in which case
6402 * a second call may be performed. The connection's flags are updated with
6403 * whatever special event is detected (error, empty). The caller is responsible
6404 * for taking care of those events and avoiding the call if inappropriate. The
6405 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006406 * is responsible for this. The buffer's output is not adjusted, it's up to the
6407 * caller to take care of this. It's up to the caller to update the buffer's
6408 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006409 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006410static 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 +02006411{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006412 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006413 ssize_t ret;
6414 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006415
6416 done = 0;
6417
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006418 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006419 goto out_error;
6420
Willy Tarreau911db9b2020-01-23 16:27:54 +01006421 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006422 /* a handshake was requested */
6423 return 0;
6424
6425 /* send the largest possible block. For this we perform only one call
6426 * to send() unless the buffer wraps and we exactly fill the first hunk,
6427 * in which case we accept to do it once again.
6428 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006429 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006430#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006431 size_t written_data;
6432#endif
6433
Willy Tarreau787db9a2018-06-14 18:31:46 +02006434 try = b_contig_data(buf, done);
6435 if (try > count)
6436 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006437
Thomas Prückl10243932022-04-27 13:04:54 +02006438 if (global_ssl.hard_max_record && try > global_ssl.hard_max_record)
6439 try = global_ssl.hard_max_record;
6440
Willy Tarreau7bed9452014-02-02 02:00:24 +01006441 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006442 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006443 global_ssl.max_record && try > global_ssl.max_record) {
6444 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006445 }
6446 else {
6447 /* we need to keep the information about the fact that
6448 * we're not limiting the upcoming send(), because if it
6449 * fails, we'll have to retry with at least as many data.
6450 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006451 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006452 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006453
Willy Tarreauac78c4f2023-03-17 16:13:05 +01006454 if (try < count || flags & CO_SFL_MSG_MORE)
6455 ctx->xprt_st |= SSL_SOCK_SEND_MORE;
6456 else
6457 ctx->xprt_st &= ~SSL_SOCK_SEND_MORE;
6458
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006459#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006460 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006461 unsigned int max_early;
6462
Olivier Houchard522eea72017-11-03 16:27:47 +01006463 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006464 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006465 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006466 if (SSL_get0_session(ctx->ssl))
6467 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006468 else
6469 max_early = 0;
6470 }
6471
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006472 if (try + ctx->sent_early_data > max_early) {
6473 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006474 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006475 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006476 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006477 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006478 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006479 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006480 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006481 if (ret == 1) {
6482 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006483 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006484 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006485 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006486 /* Initiate the handshake, now */
6487 tasklet_wakeup(ctx->wait_event.tasklet);
6488 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006489
Olivier Houchardc2aae742017-09-22 18:26:28 +02006490 }
6491
6492 } else
6493#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006494 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006495
Emeric Brune1f38db2012-09-03 20:36:47 +02006496 if (conn->flags & CO_FL_ERROR) {
6497 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006498 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006499 }
Emeric Brun46591952012-05-18 15:47:34 +02006500 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006501 /* A send succeeded, so we can consider ourself connected */
6502 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006503 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006504 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006505 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006506 }
6507 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006508 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006509
Emeric Brun46591952012-05-18 15:47:34 +02006510 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006511 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006512 /* handshake is running, and it may need to re-enable write */
6513 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006514 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006515#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006516 /* Async mode can be re-enabled, because we're leaving data state.*/
6517 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006518 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006519#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006520 break;
6521 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006522
Emeric Brun46591952012-05-18 15:47:34 +02006523 break;
6524 }
6525 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006526 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006527 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006528 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6529 SUB_RETRY_RECV,
6530 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006531#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006532 /* Async mode can be re-enabled, because we're leaving data state.*/
6533 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006534 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006535#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006536 break;
6537 }
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006538 else if (ret == SSL_ERROR_SSL || ret == SSL_ERROR_SYSCALL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006539 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6540
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02006541 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006542 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006543 conn->err_code = CO_ERR_SSL_FATAL;
6544 }
Emeric Brun46591952012-05-18 15:47:34 +02006545 goto out_error;
6546 }
6547 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006548 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006549 return done;
6550
6551 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006552 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006553 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006554 ERR_clear_error();
6555
Emeric Brun46591952012-05-18 15:47:34 +02006556 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006557 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006558}
6559
Willy Tarreau832e2422021-05-13 10:11:03 +02006560void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006561
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006562 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006563
Olivier Houchardea8dd942019-05-20 14:02:16 +02006564
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006565 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006566 if (ctx->wait_event.events != 0)
6567 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6568 ctx->wait_event.events,
6569 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006570 if (ctx->subs) {
6571 ctx->subs->events = 0;
6572 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006573 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006574
Olivier Houchard692c1d02019-05-23 18:41:47 +02006575 if (ctx->xprt->close)
6576 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006577#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006578 if (global_ssl.async) {
6579 OSSL_ASYNC_FD all_fd[32], afd;
6580 size_t num_all_fds = 0;
6581 int i;
6582
Olivier Houchard66ab4982019-02-26 18:37:15 +01006583 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006584 if (num_all_fds > 32) {
6585 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6586 return;
6587 }
6588
Olivier Houchard66ab4982019-02-26 18:37:15 +01006589 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006590
6591 /* If an async job is pending, we must try to
6592 to catch the end using polling before calling
6593 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006594 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006595 for (i=0 ; i < num_all_fds ; i++) {
6596 /* switch on an handler designed to
6597 * handle the SSL_free
6598 */
6599 afd = all_fd[i];
6600 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006601 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006602 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006603 /* To ensure that the fd cache won't be used
6604 * and we'll catch a real RD event.
6605 */
6606 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006607 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006608 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006609 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006610 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006611 return;
6612 }
Emeric Brun3854e012017-05-17 20:42:48 +02006613 /* Else we can remove the fds from the fdtab
6614 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006615 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006616 * because the fd is owned by the engine.
6617 * the engine is responsible to close
6618 */
Emeric Brun7d392a52022-07-01 17:36:50 +02006619 for (i=0 ; i < num_all_fds ; i++) {
6620 /* We want to remove the fd from the fdtab
6621 * but we flag it to disown because the
6622 * close is performed by the engine itself
6623 */
6624 fdtab[all_fd[i]].state |= FD_DISOWN;
6625 fd_delete(all_fd[i]);
6626 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006627 }
6628#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006629 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006630 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006631 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006632 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau82531f62021-10-06 12:15:18 +02006633 _HA_ATOMIC_DEC(&global.sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006634 }
Emeric Brun46591952012-05-18 15:47:34 +02006635}
6636
6637/* This function tries to perform a clean shutdown on an SSL connection, and in
6638 * any case, flags the connection as reusable if no handshake was in progress.
6639 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006640static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006641{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006642 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006643
Willy Tarreau911db9b2020-01-23 16:27:54 +01006644 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006645 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006646 if (!clean)
6647 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006648 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006649 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006650 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006651 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006652 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006653 ERR_clear_error();
6654 }
Emeric Brun46591952012-05-18 15:47:34 +02006655}
6656
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006657
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006658/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006659int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6660{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006661 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemandd4f946c2019-12-05 10:26:40 +01006662 X509 *crt;
6663
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006664 if (!ctx)
William Lallemandd4f946c2019-12-05 10:26:40 +01006665 return 0;
William Lallemandd4f946c2019-12-05 10:26:40 +01006666 crt = SSL_get_certificate(ctx->ssl);
6667 if (!crt)
6668 return 0;
6669
6670 return cert_get_pkey_algo(crt, out);
6671}
6672
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006673/* used for ppv2 cert signature (can be used for logging) */
6674const char *ssl_sock_get_cert_sig(struct connection *conn)
6675{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006676 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006677
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006678 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6679 X509 *crt;
6680
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006681 if (!ctx)
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006682 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006683 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006684 if (!crt)
6685 return NULL;
6686 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6687 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6688}
6689
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006690/* used for ppv2 authority */
6691const char *ssl_sock_get_sni(struct connection *conn)
6692{
6693#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006694 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006695
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006696 if (!ctx)
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006697 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006698 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006699#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006700 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006701#endif
6702}
6703
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006704/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006705const char *ssl_sock_get_cipher_name(struct connection *conn)
6706{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006707 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006708
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006709 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006710 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006711 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006712}
6713
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006714/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006715const char *ssl_sock_get_proto_version(struct connection *conn)
6716{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006717 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006718
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006719 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006720 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006721 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006722}
6723
Olivier Houchardab28a322018-12-21 19:45:40 +01006724void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6725{
6726#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006727 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006728
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006729 if (!ctx)
Olivier Houcharde488ea82019-06-28 14:10:33 +02006730 return;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006731 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006732#endif
6733}
6734
Willy Tarreau119a4082016-12-22 21:58:38 +01006735/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6736 * to disable SNI.
6737 */
Willy Tarreau63076412015-07-10 11:33:32 +02006738void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6739{
6740#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006741 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemande18d4e82021-11-17 02:59:21 +01006742 struct server *s;
Willy Tarreau119a4082016-12-22 21:58:38 +01006743 char *prev_name;
6744
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006745 if (!ctx)
Willy Tarreau63076412015-07-10 11:33:32 +02006746 return;
Willy Tarreau77bfa662021-12-23 11:12:13 +01006747
6748 BUG_ON(!(conn->flags & CO_FL_WAIT_L6_CONN));
6749 BUG_ON(!(conn->flags & CO_FL_SSL_WAIT_HS));
6750
William Lallemande18d4e82021-11-17 02:59:21 +01006751 s = __objt_server(conn->target);
Willy Tarreau63076412015-07-10 11:33:32 +02006752
Willy Tarreau119a4082016-12-22 21:58:38 +01006753 /* if the SNI changes, we must destroy the reusable context so that a
William Lallemande18d4e82021-11-17 02:59:21 +01006754 * new connection will present a new SNI. compare with the SNI
6755 * previously stored in the reused_sess */
6756 /* the RWLOCK is used to ensure that we are not trying to flush the
6757 * cache from the CLI */
6758
6759 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
6760 prev_name = s->ssl_ctx.reused_sess[tid].sni;
Willy Tarreau119a4082016-12-22 21:58:38 +01006761 if ((!prev_name && hostname) ||
6762 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006763 SSL_set_session(ctx->ssl, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01006764 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau119a4082016-12-22 21:58:38 +01006765
Olivier Houchard66ab4982019-02-26 18:37:15 +01006766 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006767#endif
6768}
6769
Emeric Brun0abf8362014-06-24 18:26:41 +02006770/* Extract peer certificate's common name into the chunk dest
6771 * Returns
6772 * the len of the extracted common name
6773 * or 0 if no CN found in DN
6774 * or -1 on error case (i.e. no peer certificate)
6775 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006776int ssl_sock_get_remote_common_name(struct connection *conn,
6777 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006778{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006779 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
David Safb76832014-05-08 23:42:08 -04006780 X509 *crt = NULL;
6781 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006782 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006783 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006784 .area = (char *)&find_cn,
6785 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006786 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006787 int result = -1;
David Safb76832014-05-08 23:42:08 -04006788
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006789 if (!ctx)
Emeric Brun0abf8362014-06-24 18:26:41 +02006790 goto out;
David Safb76832014-05-08 23:42:08 -04006791
6792 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006793 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006794 if (!crt)
6795 goto out;
6796
6797 name = X509_get_subject_name(crt);
6798 if (!name)
6799 goto out;
David Safb76832014-05-08 23:42:08 -04006800
Emeric Brun0abf8362014-06-24 18:26:41 +02006801 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6802out:
David Safb76832014-05-08 23:42:08 -04006803 if (crt)
6804 X509_free(crt);
6805
6806 return result;
6807}
6808
Dave McCowan328fb582014-07-30 10:39:13 -04006809/* returns 1 if client passed a certificate for this session, 0 if not */
6810int ssl_sock_get_cert_used_sess(struct connection *conn)
6811{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006812 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dave McCowan328fb582014-07-30 10:39:13 -04006813 X509 *crt = NULL;
6814
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006815 if (!ctx)
Dave McCowan328fb582014-07-30 10:39:13 -04006816 return 0;
6817
6818 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006819 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006820 if (!crt)
6821 return 0;
6822
6823 X509_free(crt);
6824 return 1;
6825}
6826
6827/* returns 1 if client passed a certificate for this connection, 0 if not */
6828int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006829{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006830 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006831
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006832 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006833 return 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006834 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006835}
6836
6837/* returns result from SSL verify */
6838unsigned int ssl_sock_get_verify_result(struct connection *conn)
6839{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006840 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006841
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006842 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006843 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006844 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006845}
6846
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006847/* Returns the application layer protocol name in <str> and <len> when known.
6848 * Zero is returned if the protocol name was not found, otherwise non-zero is
6849 * returned. The string is allocated in the SSL context and doesn't have to be
6850 * freed by the caller. NPN is also checked if available since older versions
6851 * of openssl (1.0.1) which are more common in field only support this one.
6852 */
Amaury Denoyelle71e588c2021-11-12 11:23:29 +01006853int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006854{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006855#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6856 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006857 struct ssl_sock_ctx *ctx = xprt_ctx;
6858 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006859 return 0;
6860
6861 *str = NULL;
6862
6863#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006864 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006865 if (*str)
6866 return 1;
6867#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006868#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006869 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006870 if (*str)
6871 return 1;
6872#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006873#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006874 return 0;
6875}
6876
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006877/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006878int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006879{
6880 X509 *ca;
6881 X509_NAME *name = NULL;
6882 ASN1_OCTET_STRING *skid = NULL;
6883 STACK_OF(X509) *chain = NULL;
6884 struct issuer_chain *issuer;
6885 struct eb64_node *node;
6886 char *path;
6887 u64 key;
6888 int ret = 0;
6889
6890 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6891 if (chain == NULL) {
6892 chain = sk_X509_new_null();
6893 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6894 name = X509_get_subject_name(ca);
6895 }
6896 if (!sk_X509_push(chain, ca)) {
6897 X509_free(ca);
6898 goto end;
6899 }
6900 }
6901 if (!chain) {
6902 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6903 goto end;
6904 }
6905 if (!skid) {
6906 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6907 goto end;
6908 }
6909 if (!name) {
6910 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6911 goto end;
6912 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01006913 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006914 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006915 issuer = container_of(node, typeof(*issuer), node);
6916 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6917 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6918 goto end;
6919 }
6920 }
6921 issuer = calloc(1, sizeof *issuer);
6922 path = strdup(fp);
6923 if (!issuer || !path) {
6924 free(issuer);
6925 free(path);
6926 goto end;
6927 }
6928 issuer->node.key = key;
6929 issuer->path = path;
6930 issuer->chain = chain;
6931 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006932 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006933 ret = 1;
6934 end:
6935 if (skid)
6936 ASN1_OCTET_STRING_free(skid);
6937 if (chain)
6938 sk_X509_pop_free(chain, X509_free);
6939 return ret;
6940}
6941
William Lallemandda8584c2020-05-14 10:14:37 +02006942 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006943{
6944 AUTHORITY_KEYID *akid;
6945 struct issuer_chain *issuer = NULL;
6946
6947 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01006948 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006949 struct eb64_node *node;
6950 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01006951 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006952 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6953 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6954 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6955 issuer = ti;
6956 break;
6957 }
6958 }
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006959 }
Remi Tricot-Le Breton1621dc12022-11-03 15:16:48 +01006960 AUTHORITY_KEYID_free(akid);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006961 return issuer;
6962}
6963
William Lallemanddad31052020-05-14 17:47:32 +02006964void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006965{
6966 struct eb64_node *node, *back;
6967 struct issuer_chain *issuer;
6968
William Lallemande0f3fd52020-02-25 14:53:06 +01006969 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006970 while (node) {
6971 issuer = container_of(node, typeof(*issuer), node);
6972 back = eb64_next(node);
6973 eb64_delete(node);
6974 free(issuer->path);
6975 sk_X509_pop_free(issuer->chain, X509_free);
6976 free(issuer);
6977 node = back;
6978 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006979}
6980
William Lallemandd7bfbe22022-04-11 18:41:24 +02006981#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006982static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01006983 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006984
Emeric Brun3854e012017-05-17 20:42:48 +02006985 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006986 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006987 err_code = ERR_ABORT;
6988 }
6989 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006990}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006991#endif
6992
Willy Tarreaude5675a2021-01-20 14:41:29 +01006993/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006994 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01006995 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01006996static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01006997{
6998 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006999 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007000
7001 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007002 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007003
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007004 if (sctx->conn != conn) {
7005 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
7006 ret = 1;
7007 }
Christopher Fauletf19c6392023-03-14 15:51:33 +01007008 chunk_appendf(&trash, " xctx.st=%d .err=%ld", sctx->xprt_st, sctx->error_code);
Willy Tarreaude5675a2021-01-20 14:41:29 +01007009
7010 if (sctx->xprt) {
7011 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
7012 if (sctx->xprt_ctx)
7013 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
7014 }
7015
7016 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007017
7018 /* as soon as a shutdown is reported the lower layer unregisters its
7019 * subscriber, so the situations below are transient and rare enough to
7020 * be reported as suspicious. In any case they shouldn't last.
7021 */
7022 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
7023 ret = 1;
7024 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
7025 ret = 1;
7026
Willy Tarreaude5675a2021-01-20 14:41:29 +01007027 chunk_appendf(&trash, " .subs=%p", sctx->subs);
7028 if (sctx->subs) {
7029 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007030 if (sctx->subs->tasklet->calls >= 1000000)
7031 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007032 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
7033 sctx->subs->tasklet->calls,
7034 sctx->subs->tasklet->context);
7035 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
7036 chunk_appendf(&trash, ")");
7037 }
7038 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
7039 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007040 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007041}
7042
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007043#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02007044/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007045 * each reference. The variable <ref> must point to the current node's list
7046 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02007047 */
William Lallemand32af2032016-10-29 18:09:35 +02007048static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007049struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02007050{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007051 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007052 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02007053
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007054 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007055 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007056 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02007057
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007058 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02007059}
7060
7061static inline
7062struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
7063{
7064 int id;
7065 char *error;
7066
7067 /* If the reference starts by a '#', this is numeric id. */
7068 if (reference[0] == '#') {
7069 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
7070 id = strtol(reference + 1, &error, 10);
7071 if (*error != '\0')
7072 return NULL;
7073
7074 /* Perform the unique id lookup. */
7075 return tlskeys_ref_lookupid(id);
7076 }
7077
7078 /* Perform the string lookup. */
7079 return tlskeys_ref_lookup(reference);
7080}
7081#endif
7082
7083
7084#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7085
Willy Tarreaua9380522022-05-05 08:50:17 +02007086/* dumps all tls keys. Relies on the show_keys_ctx context from the appctx. */
Willy Tarreaubd338642022-05-05 08:59:17 +02007087static int cli_io_handler_tlskeys_files(struct appctx *appctx)
7088{
Willy Tarreaua9380522022-05-05 08:50:17 +02007089 struct show_keys_ctx *ctx = appctx->svcctx;
William Lallemand32af2032016-10-29 18:09:35 +02007090
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007091 switch (ctx->state) {
7092 case SHOW_KEYS_INIT:
William Lallemand32af2032016-10-29 18:09:35 +02007093 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08007094 * quit the function with returning 0. The function is called
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007095 * later and restart at the state "SHOW_KEYS_INIT".
William Lallemand32af2032016-10-29 18:09:35 +02007096 */
7097 chunk_reset(&trash);
7098
Willy Tarreaubd338642022-05-05 08:59:17 +02007099 if (ctx->dump_entries)
William Lallemand32af2032016-10-29 18:09:35 +02007100 chunk_appendf(&trash, "# id secret\n");
7101 else
7102 chunk_appendf(&trash, "# id (file)\n");
7103
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007104 if (applet_putchk(appctx, &trash) == -1)
William Lallemand32af2032016-10-29 18:09:35 +02007105 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007106
William Lallemand32af2032016-10-29 18:09:35 +02007107 /* Now, we start the browsing of the references lists.
7108 * Note that the following call to LIST_ELEM return bad pointer. The only
7109 * available field of this pointer is <list>. It is used with the function
7110 * tlskeys_list_get_next() for retruning the first available entry
7111 */
Willy Tarreaua9380522022-05-05 08:50:17 +02007112 if (ctx->next_ref == NULL)
7113 ctx->next_ref = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007114
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007115 ctx->state = SHOW_KEYS_LIST;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007116 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007117
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007118 case SHOW_KEYS_LIST:
Willy Tarreaua9380522022-05-05 08:50:17 +02007119 while (ctx->next_ref) {
7120 struct tls_keys_ref *ref = ctx->next_ref;
William Lallemand32af2032016-10-29 18:09:35 +02007121
7122 chunk_reset(&trash);
Willy Tarreaubd338642022-05-05 08:59:17 +02007123 if (ctx->dump_entries && ctx->next_index == 0)
William Lallemand32af2032016-10-29 18:09:35 +02007124 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007125
Willy Tarreaua9380522022-05-05 08:50:17 +02007126 if (ctx->next_index == 0)
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007127 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
7128
Willy Tarreaubd338642022-05-05 08:59:17 +02007129 if (ctx->dump_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01007130 int head;
7131
7132 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
7133 head = ref->tls_ticket_enc_index;
Willy Tarreaua9380522022-05-05 08:50:17 +02007134 while (ctx->next_index < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02007135 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02007136
7137 chunk_reset(t2);
7138 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01007139 if (ref->key_size_bits == 128) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007140 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007141 sizeof(struct tls_sess_key_128),
7142 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007143 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007144 t2->area);
7145 }
7146 else if (ref->key_size_bits == 256) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007147 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007148 sizeof(struct tls_sess_key_256),
7149 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007150 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007151 t2->area);
7152 }
7153 else {
7154 /* This case should never happen */
Willy Tarreaua9380522022-05-05 08:50:17 +02007155 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, ctx->next_index);
Emeric Brun9e754772019-01-10 17:51:55 +01007156 }
William Lallemand32af2032016-10-29 18:09:35 +02007157
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007158 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007159 /* let's try again later from this stream. We add ourselves into
7160 * this stream's users so that it can remove us upon termination.
7161 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01007162 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
William Lallemand32af2032016-10-29 18:09:35 +02007163 return 0;
7164 }
Willy Tarreaua9380522022-05-05 08:50:17 +02007165 ctx->next_index++;
William Lallemand32af2032016-10-29 18:09:35 +02007166 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01007167 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaua9380522022-05-05 08:50:17 +02007168 ctx->next_index = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007169 }
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007170 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007171 /* let's try again later from this stream. We add ourselves into
7172 * this stream's users so that it can remove us upon termination.
7173 */
William Lallemand32af2032016-10-29 18:09:35 +02007174 return 0;
7175 }
7176
Willy Tarreaua9380522022-05-05 08:50:17 +02007177 if (ctx->names_only == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02007178 break;
7179
7180 /* get next list entry and check the end of the list */
Willy Tarreaua9380522022-05-05 08:50:17 +02007181 ctx->next_ref = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007182 }
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007183 ctx->state = SHOW_KEYS_DONE;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007184 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007185
7186 default:
William Lallemand32af2032016-10-29 18:09:35 +02007187 return 1;
7188 }
7189 return 0;
7190}
7191
Willy Tarreaua9380522022-05-05 08:50:17 +02007192/* Prepares a "show_keys_ctx" and sets the appropriate io_handler if needed */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007193static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007194{
Willy Tarreaua9380522022-05-05 08:50:17 +02007195 struct show_keys_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
7196
William Lallemand32af2032016-10-29 18:09:35 +02007197 /* no parameter, shows only file list */
7198 if (!*args[2]) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007199 ctx->names_only = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007200 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007201 }
7202
7203 if (args[2][0] == '*') {
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007204 /* list every TLS ticket keys */
7205 ctx->names_only = 1;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007206 } else {
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007207 ctx->next_ref = tlskeys_ref_lookup_ref(args[2]);
7208 if (!ctx->next_ref)
7209 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007210 }
7211
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007212 ctx->dump_entries = 1;
7213 return 0;
7214}
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007215
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007216static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
7217{
7218 struct tls_keys_ref *ref;
7219 int ret;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007220
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007221 /* Expect two parameters: the filename and the new new TLS key in encoding */
7222 if (!*args[3] || !*args[4])
7223 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 +02007224
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007225 ref = tlskeys_ref_lookup_ref(args[3]);
7226 if (!ref)
7227 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007228
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007229 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
7230 if (ret < 0)
7231 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007232
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007233 trash.data = ret;
7234 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
7235 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007236
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007237 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007238}
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007239#endif
7240
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007241
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007242#ifdef HAVE_SSL_PROVIDERS
7243struct provider_name {
7244 const char *name;
7245 struct list list;
7246};
7247
7248
7249static int ssl_provider_get_name_cb(OSSL_PROVIDER *provider, void *cbdata)
7250{
7251 struct list *provider_names = cbdata;
7252 struct provider_name *item = NULL;
7253 const char *name = OSSL_PROVIDER_get0_name(provider);
7254
7255 if (!provider_names)
7256 return 0;
7257
7258 item = calloc(1, sizeof(*item));
7259
7260 if (!item)
7261 return 0;
7262
7263 item->name = name;
7264 LIST_APPEND(provider_names, &item->list);
7265
7266 return 1;
7267}
7268
7269static void ssl_provider_get_name_list(struct list *provider_names)
7270{
7271 if (!provider_names)
7272 return;
7273
7274 OSSL_PROVIDER_do_all(NULL, ssl_provider_get_name_cb, provider_names);
7275}
7276
7277static void ssl_provider_clear_name_list(struct list *provider_names)
7278{
7279 struct provider_name *item = NULL, *item_s = NULL;
7280
7281 if (provider_names) {
7282 list_for_each_entry_safe(item, item_s, provider_names, list) {
7283 LIST_DELETE(&item->list);
7284 free(item);
7285 }
7286 }
7287}
7288
7289static int cli_io_handler_show_providers(struct appctx *appctx)
7290{
7291 struct buffer *trash = get_trash_chunk();
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007292 struct list provider_names;
7293 struct provider_name *name;
7294
7295 LIST_INIT(&provider_names);
7296
7297 chunk_appendf(trash, "Loaded providers : \n");
7298
7299 ssl_provider_get_name_list(&provider_names);
7300
7301 list_for_each_entry(name, &provider_names, list) {
7302 chunk_appendf(trash, "\t- %s\n", name->name);
7303 }
7304
7305 ssl_provider_clear_name_list(&provider_names);
7306
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007307 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007308 goto yield;
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007309
7310 return 1;
7311
7312yield:
7313 return 0;
7314}
7315#endif
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01007316
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007317
William Lallemand32af2032016-10-29 18:09:35 +02007318/* register cli keywords */
7319static struct cli_kw_list cli_kws = {{ },{
7320#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01007321 { { "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 },
7322 { { "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 +02007323#endif
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007324#ifdef HAVE_SSL_PROVIDERS
7325 { { "show", "ssl", "providers", NULL }, "show ssl providers : show loaded SSL providers", NULL, cli_io_handler_show_providers },
7326#endif
William Lallemand32af2032016-10-29 18:09:35 +02007327 { { NULL }, NULL, NULL, NULL }
7328}};
7329
Willy Tarreau0108d902018-11-25 19:14:37 +01007330INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02007331
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02007332/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02007333struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02007334 .snd_buf = ssl_sock_from_buf,
7335 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01007336 .subscribe = ssl_subscribe,
7337 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02007338 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02007339 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02007340 .rcv_pipe = NULL,
7341 .snd_pipe = NULL,
7342 .shutr = NULL,
7343 .shutw = ssl_sock_shutw,
7344 .close = ssl_sock_close,
7345 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01007346 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01007347 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01007348 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01007349 .prepare_srv = ssl_sock_prepare_srv_ctx,
7350 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007351 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02007352 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01007353 .set_idle = ssl_set_idle,
7354 .set_used = ssl_set_used,
Willy Tarreaude827952022-04-11 10:43:28 +02007355 .get_ssl_sock_ctx = ssl_sock_get_ctx,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01007356 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01007357 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02007358};
7359
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007360enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
7361 struct session *sess, struct stream *s, int flags)
7362{
7363 struct connection *conn;
7364
7365 conn = objt_conn(sess->origin);
7366
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007367 if (conn) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007368 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007369 sc_ep_set(s->scf, SE_FL_WAIT_FOR_HS);
Christopher Faulet6e1bbc42022-12-12 08:08:15 +01007370 s->req.flags |= CF_READ_EVENT;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007371 return ACT_RET_YIELD;
7372 }
7373 }
7374 return (ACT_RET_CONT);
7375}
7376
7377static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
7378{
7379 rule->action_ptr = ssl_action_wait_for_hs;
7380
7381 return ACT_RET_PRS_OK;
7382}
7383
7384static struct action_kw_list http_req_actions = {ILH, {
7385 { "wait-for-handshake", ssl_parse_wait_for_hs },
7386 { /* END */ }
7387}};
7388
Willy Tarreau0108d902018-11-25 19:14:37 +01007389INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
7390
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007391#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007392
7393static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7394{
7395 if (ptr) {
7396 chunk_destroy(ptr);
7397 free(ptr);
7398 }
7399}
7400
7401#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007402
William Lallemand76b4a122020-08-04 17:41:39 +02007403
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007404static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7405{
Willy Tarreaubafbe012017-11-24 17:34:44 +01007406 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007407}
William Lallemand7d42ef52020-07-06 11:41:30 +02007408
William Lallemand722180a2021-06-09 16:46:12 +02007409#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007410static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7411{
7412 struct ssl_keylog *keylog;
7413
7414 if (!ptr)
7415 return;
7416
7417 keylog = ptr;
7418
7419 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7420 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7421 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7422 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7423 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7424 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7425 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7426 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7427
7428 pool_free(pool_head_ssl_keylog, ptr);
7429}
7430#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007431
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007432static void ssl_sock_clt_crt_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7433{
7434 if (!ptr)
7435 return;
7436
7437 X509_free((X509*)ptr);
7438}
7439
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01007440static void ssl_sock_clt_sni_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7441{
7442 pool_free(ssl_sock_client_sni_pool, ptr);
7443}
7444
Willy Tarreau92faadf2012-10-10 23:04:25 +02007445static void __ssl_sock_init(void)
7446{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007447#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007448 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007449 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007450#endif
Emeric Brun46591952012-05-18 15:47:34 +02007451
Willy Tarreauef934602016-12-22 23:12:01 +01007452 if (global_ssl.listen_default_ciphers)
7453 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7454 if (global_ssl.connect_default_ciphers)
7455 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007456#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007457 if (global_ssl.listen_default_ciphersuites)
7458 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7459 if (global_ssl.connect_default_ciphersuites)
7460 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7461#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007462
Willy Tarreau13e14102016-12-22 20:25:26 +01007463 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007464#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007465 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007466#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007467#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007468 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007469 n = sk_SSL_COMP_num(cm);
7470 while (n--) {
7471 (void) sk_SSL_COMP_pop(cm);
7472 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007473#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007474
Willy Tarreau5db847a2019-05-09 14:13:35 +02007475#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007476 ssl_locking_init();
7477#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007478#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007479 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
7480#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007481
7482#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7483 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
7484#endif
7485
Thierry FOURNIER28962c92018-06-17 21:37:05 +02007486 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02007487 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 +01007488#ifdef USE_QUIC
7489 ssl_qc_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7490#endif /* USE_QUIC */
William Lallemand722180a2021-06-09 16:46:12 +02007491#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007492 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
7493#endif
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007494 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 +01007495 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 +02007496#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00007497 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007498 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007499#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01007500#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7501 hap_register_post_check(tlskeys_finalize_config);
7502#endif
Willy Tarreau80713382018-11-26 10:19:54 +01007503
7504 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
7505 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
7506
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007507 hap_register_post_deinit(ssl_free_global_issuers);
7508
Willy Tarreau80713382018-11-26 10:19:54 +01007509#ifndef OPENSSL_NO_DH
7510 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7511 hap_register_post_deinit(ssl_free_dh);
7512#endif
William Lallemandd7bfbe22022-04-11 18:41:24 +02007513#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Willy Tarreau80713382018-11-26 10:19:54 +01007514 hap_register_post_deinit(ssl_free_engines);
7515#endif
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02007516#ifdef HAVE_SSL_PROVIDERS
7517 hap_register_post_deinit(ssl_unload_providers);
7518#endif
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01007519#if HA_OPENSSL_VERSION_NUMBER < 0x3000000fL
Willy Tarreau80713382018-11-26 10:19:54 +01007520 /* Load SSL string for the verbose & debug mode. */
7521 ERR_load_SSL_strings();
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01007522#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007523 ha_meth = BIO_meth_new(0x666, "ha methods");
7524 BIO_meth_set_write(ha_meth, ha_ssl_write);
7525 BIO_meth_set_read(ha_meth, ha_ssl_read);
7526 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
7527 BIO_meth_set_create(ha_meth, ha_ssl_new);
7528 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
7529 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
7530 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02007531
7532 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007533
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01007534 HA_SPIN_INIT(&ocsp_tree_lock);
7535
Dragan Dosen9ac98092020-05-11 15:51:45 +02007536 /* Try to register dedicated SSL/TLS protocol message callbacks for
7537 * heartbleed attack (CVE-2014-0160) and clienthello.
7538 */
7539 hap_register_post_check(ssl_sock_register_msg_callbacks);
7540
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007541 /* Try to free all callbacks that were registered by using
7542 * ssl_sock_register_msg_callback().
7543 */
7544 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01007545}
Willy Tarreau79367f92022-04-25 19:18:24 +02007546INITCALL0(STG_REGISTER, __ssl_sock_init);
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01007547
Willy Tarreau80713382018-11-26 10:19:54 +01007548/* Compute and register the version string */
7549static void ssl_register_build_options()
7550{
7551 char *ptr = NULL;
7552 int i;
7553
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007554 memprintf(&ptr, "Built with OpenSSL version : "
7555#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007556 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007557#else /* OPENSSL_IS_BORINGSSL */
7558 OPENSSL_VERSION_TEXT
7559 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08007560 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02007561 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007562#endif
7563 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007564#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007565 "no (library version too old)"
7566#elif defined(OPENSSL_NO_TLSEXT)
7567 "no (disabled via OPENSSL_NO_TLSEXT)"
7568#else
7569 "yes"
7570#endif
7571 "", ptr);
7572
7573 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
7574#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
7575 "yes"
7576#else
7577#ifdef OPENSSL_NO_TLSEXT
7578 "no (because of OPENSSL_NO_TLSEXT)"
7579#else
7580 "no (version might be too old, 0.9.8f min needed)"
7581#endif
7582#endif
7583 "", ptr);
7584
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02007585 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
7586 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
7587 if (methodVersions[i].option)
7588 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007589
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007590#ifdef HAVE_SSL_PROVIDERS
7591 {
7592 struct list provider_names;
7593 struct provider_name *name;
7594 LIST_INIT(&provider_names);
7595 ssl_provider_get_name_list(&provider_names);
7596
7597 memprintf(&ptr, "%s\nOpenSSL providers loaded :", ptr);
7598
7599 list_for_each_entry(name, &provider_names, list) {
7600 memprintf(&ptr, "%s %s", ptr, name->name);
7601 }
7602
7603 ssl_provider_clear_name_list(&provider_names);
7604 }
7605#endif
7606
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007607 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01007608}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007609
Willy Tarreau80713382018-11-26 10:19:54 +01007610INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02007611
William Lallemandd7bfbe22022-04-11 18:41:24 +02007612#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00007613void ssl_free_engines(void) {
7614 struct ssl_engine_list *wl, *wlb;
7615 /* free up engine list */
7616 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
7617 ENGINE_finish(wl->e);
7618 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02007619 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00007620 free(wl);
7621 }
7622}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007623#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02007624
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02007625#ifdef HAVE_SSL_PROVIDERS
7626void ssl_unload_providers(void) {
7627 struct ssl_provider_list *prov, *provb;
7628 list_for_each_entry_safe(prov, provb, &openssl_providers, list) {
7629 OSSL_PROVIDER_unload(prov->provider);
7630 LIST_DELETE(&prov->list);
7631 free(prov);
7632 }
7633}
7634#endif
7635
Remi Gacogned3a23c32015-05-28 16:39:47 +02007636#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00007637void ssl_free_dh(void) {
7638 if (local_dh_1024) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007639 HASSL_DH_free(local_dh_1024);
Grant Zhang872f9c22017-01-21 01:10:18 +00007640 local_dh_1024 = NULL;
7641 }
7642 if (local_dh_2048) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007643 HASSL_DH_free(local_dh_2048);
Grant Zhang872f9c22017-01-21 01:10:18 +00007644 local_dh_2048 = NULL;
7645 }
7646 if (local_dh_4096) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007647 HASSL_DH_free(local_dh_4096);
Grant Zhang872f9c22017-01-21 01:10:18 +00007648 local_dh_4096 = NULL;
7649 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02007650 if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007651 HASSL_DH_free(global_dh);
Remi Gacogne47783ef2015-05-29 15:53:22 +02007652 global_dh = NULL;
7653 }
Grant Zhang872f9c22017-01-21 01:10:18 +00007654}
7655#endif
7656
Grant Zhang872f9c22017-01-21 01:10:18 +00007657static void __ssl_sock_deinit(void)
7658{
7659#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007660 if (ssl_ctx_lru_tree) {
7661 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007662 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02007663 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02007664#endif
7665
Willy Tarreau5db847a2019-05-09 14:13:35 +02007666#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007667 ERR_remove_state(0);
7668 ERR_free_strings();
7669
7670 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08007671#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007672
Willy Tarreau5db847a2019-05-09 14:13:35 +02007673#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007674 CRYPTO_cleanup_all_ex_data();
7675#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007676 BIO_meth_free(ha_meth);
Remi Tricot-Le Breton6477bbd2022-12-20 11:11:13 +01007677
7678#if !defined OPENSSL_NO_OCSP
7679 ssl_destroy_ocsp_update_task();
7680#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007681}
Willy Tarreau79367f92022-04-25 19:18:24 +02007682REGISTER_POST_DEINIT(__ssl_sock_deinit);
Remi Gacogned3a23c32015-05-28 16:39:47 +02007683
William Dauchyf6370442020-11-14 19:25:33 +01007684
Emeric Brun46591952012-05-18 15:47:34 +02007685/*
7686 * Local variables:
7687 * c-indent-level: 8
7688 * c-basic-offset: 8
7689 * End:
7690 */