blob: e7f6d41b9b25509e22196287eaf98cdb0d50389e [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;
Willy Tarreau6d4c0c22023-04-07 17:49:37 +02001122 size_t path_len;
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
Willy Tarreau6d4c0c22023-04-07 17:49:37 +02001167 path_len = strlen(path);
1168 ocsp = calloc(1, sizeof(*ocsp) + path_len + 1);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001169 if (!ocsp)
1170 goto out;
1171
1172 p = ocsp->key_data;
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001173 ocsp->key_length = i2d_OCSP_CERTID(data->ocsp_cid, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001174
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001175 HA_SPIN_LOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001176 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1177 if (iocsp == ocsp)
1178 ocsp = NULL;
1179
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001180#ifndef SSL_CTX_get_tlsext_status_cb
1181# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1182 *cb = (void (*) (void))ctx->tlsext_status_cb;
1183#endif
1184 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1185
1186 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001187 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001188 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001189
William Lallemanda560c062020-07-31 11:43:20 +02001190 cb_arg = calloc(1, sizeof(*cb_arg));
1191 if (!cb_arg)
1192 goto out;
1193
yanbzhube2774d2015-12-10 15:07:30 -05001194 cb_arg->is_single = 1;
1195 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001196 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001197
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001198 pkey = X509_get_pubkey(x);
1199 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1200 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001201
1202 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001203 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 */
1204
yanbzhube2774d2015-12-10 15:07:30 -05001205 } else {
1206 /*
1207 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1208 * Update that cb_arg with the new cert's staple
1209 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001210 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001211 struct certificate_ocsp *tmp_ocsp;
1212 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001213 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001214 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001215
William Lallemand76b4a122020-08-04 17:41:39 +02001216 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001217
1218 /*
1219 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1220 * the order of operations below matter, take care when changing it
1221 */
1222 tmp_ocsp = cb_arg->s_ocsp;
1223 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1224 cb_arg->s_ocsp = NULL;
1225 cb_arg->m_ocsp[index] = tmp_ocsp;
1226 cb_arg->is_single = 0;
1227 cb_arg->single_kt = 0;
1228
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001229 pkey = X509_get_pubkey(x);
1230 key_type = EVP_PKEY_base_id(pkey);
1231 EVP_PKEY_free(pkey);
1232
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001233 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001234 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001235 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001236 iocsp->refcount++;
1237 }
yanbzhube2774d2015-12-10 15:07:30 -05001238 }
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001239 HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001240
1241 ret = 0;
1242
1243 warn = NULL;
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001244 if (data->ocsp_response && ssl_sock_load_ocsp_response(data->ocsp_response, iocsp, data->ocsp_cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001245 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001246 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001247 }
1248
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001249
Remi Tricot-Le Bretona6c0a592023-03-13 15:56:32 +01001250 /* Do not insert the same certificate_ocsp structure in the
1251 * update tree more than once. */
1252 if (!ocsp) {
1253 /* Issuer certificate is not included in the certificate
1254 * chain, it will have to be treated separately during
1255 * ocsp response validation. */
1256 if (issuer == data->ocsp_issuer) {
1257 iocsp->issuer = issuer;
1258 X509_up_ref(issuer);
1259 }
1260 if (data->chain)
1261 iocsp->chain = X509_chain_up_ref(data->chain);
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001262
Remi Tricot-Le Bretona6c0a592023-03-13 15:56:32 +01001263 iocsp->uri = calloc(1, sizeof(*iocsp->uri));
1264 if (!chunk_dup(iocsp->uri, ocsp_uri)) {
1265 ha_free(&iocsp->uri);
1266 goto out;
1267 }
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001268
Willy Tarreau6d4c0c22023-04-07 17:49:37 +02001269 /* Note: if we arrive here, ocsp==NULL because iocsp==ocsp
1270 * after the ebmb_insert(), which indicates that we've
1271 * just inserted this new node and that it's the one for
1272 * which we previously allocated enough room for path_len+1
1273 * chars.
1274 */
1275 memcpy(iocsp->path, path, path_len + 1);
Remi Tricot-Le Breton0c96ee42023-03-01 16:11:50 +01001276
Remi Tricot-Le Bretona6c0a592023-03-13 15:56:32 +01001277 if (data->ocsp_update_mode == SSL_SOCK_OCSP_UPDATE_ON) {
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001278 ssl_ocsp_update_insert(iocsp);
Remi Tricot-Le Breton86d1e0b2023-03-02 15:49:53 +01001279 /* If we are during init the update task is not
1280 * scheduled yet so a wakeup won't do anything.
1281 * Otherwise, if the OCSP was added through the CLI, we
1282 * wake the task up to manage the case of a new entry
1283 * that needs to be updated before the previous first
1284 * entry.
1285 */
1286 if (ocsp_update_task)
1287 task_wakeup(ocsp_update_task, TASK_WOKEN_MSG);
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001288 }
1289 }
1290
Emeric Brun4147b2e2014-06-16 18:36:30 +02001291out:
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001292 if (ret && data->ocsp_cid)
1293 OCSP_CERTID_free(data->ocsp_cid);
1294
1295 if (!ret && data->ocsp_response) {
1296 ha_free(&data->ocsp_response->area);
1297 ha_free(&data->ocsp_response);
1298 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001299
1300 if (ocsp)
Remi Tricot-Le Bretonaa529f72022-11-03 15:16:49 +01001301 ssl_sock_free_ocsp(ocsp);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001302
1303 if (warn)
1304 free(warn);
1305
Tim Duesterhusb39c24b2023-03-19 16:07:47 +01001306 free(err);
1307
Emeric Brun4147b2e2014-06-16 18:36:30 +02001308 return ret;
1309}
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01001310
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001311#endif
1312
1313#ifdef OPENSSL_IS_BORINGSSL
Remi Tricot-Le Breton0c96ee42023-03-01 16:11:50 +01001314static 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 +02001315{
William Lallemand4a660132019-10-14 14:51:41 +02001316 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 +02001317}
1318#endif
1319
William Lallemand4a660132019-10-14 14:51:41 +02001320
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001321#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001322
1323#define CT_EXTENSION_TYPE 18
1324
William Lallemand03c331c2020-05-13 10:10:01 +02001325int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001326
1327int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1328{
Willy Tarreau83061a82018-07-13 11:56:34 +02001329 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001330
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001331 *out = (unsigned char *) sctl->area;
1332 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001333
1334 return 1;
1335}
1336
1337int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1338{
1339 return 1;
1340}
1341
William Lallemanda17f4112019-10-10 15:16:44 +02001342static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001343{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001344 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001345
William Lallemanda17f4112019-10-10 15:16:44 +02001346 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 +01001347 goto out;
1348
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001349 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1350
1351 ret = 0;
1352
1353out:
1354 return ret;
1355}
1356
1357#endif
1358
Emeric Brune1f38db2012-09-03 20:36:47 +02001359void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1360{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001361 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001362#ifdef USE_QUIC
1363 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1364#endif /* USE_QUIC */
1365 struct ssl_sock_ctx *ctx = NULL;
1366
Emeric Brund8b2bb52014-01-28 15:43:53 +01001367 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001368 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001369
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001370 if (conn)
Willy Tarreau939b0bf2022-04-11 11:29:11 +02001371 ctx = conn_get_ssl_sock_ctx(conn);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001372#ifdef USE_QUIC
1373 else if (qc)
1374 ctx = qc->xprt_ctx;
1375#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01001376
1377 if (!ctx) {
1378 /* must never happen */
1379 ABORT_NOW();
1380 return;
1381 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001382
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001383#ifndef SSL_OP_NO_RENEGOTIATION
1384 /* Please note that BoringSSL defines this macro to zero so don't
1385 * change this to #if and do not assign a default value to this macro!
1386 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001387 if (where & SSL_CB_HANDSHAKE_START) {
1388 /* Disable renegotiation (CVE-2009-3555) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001389 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 +02001390 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001391 conn->err_code = CO_ER_SSL_RENEG;
1392 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001393 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001394#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001395
1396 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001397 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001398 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001399 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001400 consider that the buffering was activated,
1401 so we rise the output buffer size from 4k
1402 to 16k */
1403 write_bio = SSL_get_wbio(ssl);
1404 if (write_bio != SSL_get_rbio(ssl)) {
1405 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001406 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001407 }
1408 }
1409 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001410}
1411
Emeric Brune64aef12012-09-21 13:15:06 +02001412/* Callback is called for each certificate of the chain during a verify
1413 ok is set to 1 if preverify detect no error on current certificate.
1414 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001415int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001416{
1417 SSL *ssl;
1418 struct connection *conn;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001419 struct ssl_sock_ctx *ctx = NULL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001420 int err, depth;
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001421 X509 *client_crt;
1422 STACK_OF(X509) *certs;
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001423 struct bind_conf *bind_conf = NULL;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001424 struct quic_conn *qc = NULL;
Emeric Brune64aef12012-09-21 13:15:06 +02001425
1426 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001427 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001428 client_crt = SSL_get_ex_data(ssl, ssl_client_crt_ref_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001429
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001430 if (conn) {
1431 bind_conf = __objt_listener(conn->target)->bind_conf;
1432 ctx = __conn_get_ssl_sock_ctx(conn);
1433 }
1434#ifdef USE_QUIC
1435 else {
1436 qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
Amaury Denoyelleba303de2022-10-17 18:46:49 +02001437 BUG_ON(!qc); /* Must never happen */
1438 bind_conf = qc->li->bind_conf;
1439 ctx = qc->xprt_ctx;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001440 }
1441#endif
1442
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001443 BUG_ON(!ctx || !bind_conf);
Christopher Faulet881cce92022-11-23 09:27:13 +01001444 ALREADY_CHECKED(ctx);
1445 ALREADY_CHECKED(bind_conf);
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001446
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001447 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001448
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001449 depth = X509_STORE_CTX_get_error_depth(x_store);
1450 err = X509_STORE_CTX_get_error(x_store);
1451
Emeric Brun81c00f02012-09-21 14:31:21 +02001452 if (ok) /* no errors */
1453 return ok;
1454
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001455 /* Keep a reference to the client's certificate in order to be able to
1456 * dump some fetches values in a log even when the verification process
1457 * fails. */
1458 if (depth == 0) {
1459 X509_free(client_crt);
1460 client_crt = X509_STORE_CTX_get0_cert(x_store);
1461 if (client_crt) {
1462 X509_up_ref(client_crt);
1463 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
1464 }
1465 }
1466 else {
1467 /* An error occurred on a CA certificate of the certificate
1468 * chain, we might never call this verify callback on the client
1469 * certificate's depth (which is 0) so we try to store the
1470 * reference right now. */
Remi Tricot-Le Bretonf95c2952021-08-20 09:51:23 +02001471 certs = X509_STORE_CTX_get1_chain(x_store);
1472 if (certs) {
1473 client_crt = sk_X509_value(certs, 0);
1474 if (client_crt) {
1475 X509_up_ref(client_crt);
1476 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001477 }
1478 sk_X509_pop_free(certs, X509_free);
1479 }
1480 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001481
1482 /* check if CA error needs to be ignored */
1483 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001484 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1485 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1486 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001487 }
1488
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01001489 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01001490 cert_ignerr_bitfield_get(bind_conf->ca_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001491 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02001492
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001493 /* TODO: for QUIC connection, this error code is lost */
1494 if (conn)
1495 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001496 return 0;
1497 }
1498
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001499 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1500 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001501
Emeric Brun81c00f02012-09-21 14:31:21 +02001502 /* check if certificate error needs to be ignored */
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01001503 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01001504 cert_ignerr_bitfield_get(bind_conf->crt_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001505 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02001506
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001507 /* TODO: for QUIC connection, this error code is lost */
1508 if (conn)
1509 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001510 return 0;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001511
1512 err_ignored:
1513 ssl_sock_dump_errors(conn, qc);
1514 ERR_clear_error();
1515 return 1;
Emeric Brune64aef12012-09-21 13:15:06 +02001516}
1517
Dragan Dosen9ac98092020-05-11 15:51:45 +02001518#ifdef TLS1_RT_HEARTBEAT
1519static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1520 int content_type, const void *buf, size_t len,
1521 SSL *ssl)
1522{
1523 /* test heartbeat received (write_p is set to 0
1524 for a received record) */
1525 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02001526 struct ssl_sock_ctx *ctx = __conn_get_ssl_sock_ctx(conn);
Dragan Dosen9ac98092020-05-11 15:51:45 +02001527 const unsigned char *p = buf;
1528 unsigned int payload;
1529
1530 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1531
1532 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1533 if (*p != TLS1_HB_REQUEST)
1534 return;
1535
1536 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1537 goto kill_it;
1538
1539 payload = (p[1] * 256) + p[2];
1540 if (3 + payload + 16 <= len)
1541 return; /* OK no problem */
1542 kill_it:
1543 /* We have a clear heartbleed attack (CVE-2014-0160), the
1544 * advertised payload is larger than the advertised packet
1545 * length, so we have garbage in the buffer between the
1546 * payload and the end of the buffer (p+len). We can't know
1547 * if the SSL stack is patched, and we don't know if we can
1548 * safely wipe out the area between p+3+len and payload.
1549 * So instead, we prevent the response from being sent by
1550 * setting the max_send_fragment to 0 and we report an SSL
1551 * error, which will kill this connection. It will be reported
1552 * above as SSL_ERROR_SSL while an other handshake failure with
1553 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1554 */
1555 ssl->max_send_fragment = 0;
1556 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1557 }
1558}
1559#endif
1560
1561static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1562 int content_type, const void *buf, size_t len,
1563 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001564{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001565 struct ssl_capture *capture;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001566 uchar *msg;
1567 uchar *end;
1568 uchar *extensions_end;
1569 uchar *ec_start = NULL;
1570 uchar *ec_formats_start = NULL;
1571 uchar *list_end;
1572 ushort protocol_version;
1573 ushort extension_id;
1574 ushort ec_len = 0;
1575 uchar ec_formats_len = 0;
1576 int offset = 0;
1577 int rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001578
1579 /* This function is called for "from client" and "to server"
1580 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001581 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001582 */
1583
1584 /* "write_p" is set to 0 is the bytes are received messages,
1585 * otherwise it is set to 1.
1586 */
1587 if (write_p != 0)
1588 return;
1589
1590 /* content_type contains the type of message received or sent
1591 * according with the SSL/TLS protocol spec. This message is
1592 * encoded with one byte. The value 256 (two bytes) is used
1593 * for designing the SSL/TLS record layer. According with the
1594 * rfc6101, the expected message (other than 256) are:
1595 * - change_cipher_spec(20)
1596 * - alert(21)
1597 * - handshake(22)
1598 * - application_data(23)
1599 * - (255)
1600 * We are interessed by the handshake and specially the client
1601 * hello.
1602 */
1603 if (content_type != 22)
1604 return;
1605
1606 /* The message length is at least 4 bytes, containing the
1607 * message type and the message length.
1608 */
1609 if (len < 4)
1610 return;
1611
1612 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001613 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001614 * - hello_request(0)
1615 * - client_hello(1)
1616 * - server_hello(2)
1617 * - certificate(11)
1618 * - server_key_exchange (12)
1619 * - certificate_request(13)
1620 * - server_hello_done(14)
1621 * We are interested by the client hello.
1622 */
1623 msg = (unsigned char *)buf;
1624 if (msg[0] != 1)
1625 return;
1626
1627 /* Next three bytes are the length of the message. The total length
1628 * must be this decoded length + 4. If the length given as argument
1629 * is not the same, we abort the protocol dissector.
1630 */
1631 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1632 if (len < rec_len + 4)
1633 return;
1634 msg += 4;
1635 end = msg + rec_len;
1636 if (end < msg)
1637 return;
1638
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001639 /* Expect 2 bytes for protocol version
1640 * (1 byte for major and 1 byte for minor)
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001641 */
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001642 if (msg + 2 > end)
1643 return;
1644 protocol_version = (msg[0] << 8) + msg[1];
1645 msg += 2;
1646
1647 /* Expect the random, composed by 4 bytes for the unix time and
1648 * 28 bytes for unix payload. So we jump 4 + 28.
1649 */
1650 msg += 4 + 28;
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001651 if (msg > end)
1652 return;
1653
1654 /* Next, is session id:
1655 * if present, we have to jump by length + 1 for the size information
1656 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001657 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001658 if (msg[0] > 0)
1659 msg += msg[0];
1660 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001661 if (msg > end)
1662 return;
1663
1664 /* Next two bytes are the ciphersuite length. */
1665 if (msg + 2 > end)
1666 return;
1667 rec_len = (msg[0] << 8) + msg[1];
1668 msg += 2;
1669 if (msg + rec_len > end || msg + rec_len < msg)
1670 return;
1671
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001672 capture = pool_zalloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001673 if (!capture)
1674 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001675 /* Compute the xxh64 of the ciphersuite. */
1676 capture->xxh64 = XXH64(msg, rec_len, 0);
1677
1678 /* Capture the ciphersuite. */
Marcin Deranek310a2602021-07-13 19:04:24 +02001679 capture->ciphersuite_len = MIN(global_ssl.capture_buffer_size, rec_len);
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001680 capture->ciphersuite_offset = 0;
1681 memcpy(capture->data, msg, capture->ciphersuite_len);
1682 msg += rec_len;
1683 offset += capture->ciphersuite_len;
1684
1685 /* Initialize other data */
1686 capture->protocol_version = protocol_version;
1687
1688 /* Next, compression methods:
1689 * if present, we have to jump by length + 1 for the size information
1690 * if not present, we have to jump by 1 only
1691 */
1692 if (msg[0] > 0)
1693 msg += msg[0];
1694 msg += 1;
1695 if (msg > end)
1696 goto store_capture;
1697
1698 /* We reached extensions */
1699 if (msg + 2 > end)
1700 goto store_capture;
1701 rec_len = (msg[0] << 8) + msg[1];
1702 msg += 2;
1703 if (msg + rec_len > end || msg + rec_len < msg)
1704 goto store_capture;
1705 extensions_end = msg + rec_len;
1706 capture->extensions_offset = offset;
1707
1708 /* Parse each extension */
1709 while (msg + 4 < extensions_end) {
1710 /* Add 2 bytes of extension_id */
Marcin Deranek310a2602021-07-13 19:04:24 +02001711 if (global_ssl.capture_buffer_size >= offset + 2) {
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001712 capture->data[offset++] = msg[0];
1713 capture->data[offset++] = msg[1];
1714 capture->extensions_len += 2;
1715 }
1716 else
1717 break;
1718 extension_id = (msg[0] << 8) + msg[1];
1719 /* Length of the extension */
1720 rec_len = (msg[2] << 8) + msg[3];
1721
1722 /* Expect 2 bytes extension id + 2 bytes extension size */
1723 msg += 2 + 2;
1724 if (msg + rec_len > extensions_end || msg + rec_len < msg)
1725 goto store_capture;
1726 /* TLS Extensions
1727 * https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml */
1728 if (extension_id == 0x000a) {
1729 /* Elliptic Curves:
1730 * https://www.rfc-editor.org/rfc/rfc8422.html
1731 * https://www.rfc-editor.org/rfc/rfc7919.html */
1732 list_end = msg + rec_len;
1733 if (msg + 2 > list_end)
1734 goto store_capture;
1735 rec_len = (msg[0] << 8) + msg[1];
1736 msg += 2;
1737
1738 if (msg + rec_len > list_end || msg + rec_len < msg)
1739 goto store_capture;
1740 /* Store location/size of the list */
1741 ec_start = msg;
1742 ec_len = rec_len;
1743 }
1744 else if (extension_id == 0x000b) {
1745 /* Elliptic Curves Point Formats:
1746 * https://www.rfc-editor.org/rfc/rfc8422.html */
1747 list_end = msg + rec_len;
1748 if (msg + 1 > list_end)
1749 goto store_capture;
1750 rec_len = msg[0];
1751 msg += 1;
1752
1753 if (msg + rec_len > list_end || msg + rec_len < msg)
1754 goto store_capture;
1755 /* Store location/size of the list */
1756 ec_formats_start = msg;
1757 ec_formats_len = rec_len;
1758 }
1759 msg += rec_len;
1760 }
1761
1762 if (ec_start) {
1763 rec_len = ec_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_start, rec_len);
1767 capture->ec_offset = offset;
1768 capture->ec_len = rec_len;
1769 offset += rec_len;
1770 }
1771 if (ec_formats_start) {
1772 rec_len = ec_formats_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001773 if (offset + rec_len > global_ssl.capture_buffer_size)
1774 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001775 memcpy(capture->data + offset, ec_formats_start, rec_len);
1776 capture->ec_formats_offset = offset;
1777 capture->ec_formats_len = rec_len;
1778 offset += rec_len;
1779 }
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001780
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001781 store_capture:
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001782 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001783}
William Lallemand7d42ef52020-07-06 11:41:30 +02001784
1785
William Lallemand722180a2021-06-09 16:46:12 +02001786#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001787static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1788 int content_type, const void *buf, size_t len,
1789 SSL *ssl)
1790{
1791 struct ssl_keylog *keylog;
1792
1793 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1794 return;
1795
Willy Tarreauf208ac02021-03-22 21:10:12 +01001796 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02001797 if (!keylog)
1798 return;
1799
William Lallemand7d42ef52020-07-06 11:41:30 +02001800 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
1801 pool_free(pool_head_ssl_keylog, keylog);
1802 return;
1803 }
1804}
1805#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001806
Emeric Brun29f037d2014-04-25 19:05:36 +02001807/* Callback is called for ssl protocol analyse */
1808void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1809{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001810 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1811 struct ssl_sock_msg_callback *cbk;
1812
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001813 /* Try to call all callback functions that were registered by using
1814 * ssl_sock_register_msg_callback().
1815 */
1816 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1817 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1818 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001819}
1820
Bernard Spil13c53f82018-02-15 13:34:58 +01001821#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001822static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1823 const unsigned char *in, unsigned int inlen,
1824 void *arg)
1825{
1826 struct server *srv = arg;
1827
1828 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1829 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1830 return SSL_TLSEXT_ERR_OK;
1831 return SSL_TLSEXT_ERR_NOACK;
1832}
1833#endif
1834
1835#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001836/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001837 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001838 */
1839static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1840 unsigned int *len, void *arg)
1841{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001842 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001843
1844 *data = (const unsigned char *)conf->npn_str;
1845 *len = conf->npn_len;
1846 return SSL_TLSEXT_ERR_OK;
1847}
1848#endif
1849
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001850#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001851/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001852 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001853 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001854static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1855 unsigned char *outlen,
1856 const unsigned char *server,
1857 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001858{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001859 struct ssl_bind_conf *conf = arg;
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001860#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001861 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001862#endif
Willy Tarreauab861d32013-04-02 02:30:41 +02001863
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001864 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1865 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01001866#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001867 if (qc)
1868 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01001869#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001870 return SSL_TLSEXT_ERR_NOACK;
1871 }
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001872
1873#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001874 if (qc && !quic_set_app_ops(qc, *out, *outlen)) {
1875 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001876 return SSL_TLSEXT_ERR_NOACK;
1877 }
1878#endif
1879
Willy Tarreauab861d32013-04-02 02:30:41 +02001880 return SSL_TLSEXT_ERR_OK;
1881}
1882#endif
1883
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001884#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001885#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001886
cui flitera94bedc2022-08-29 14:42:57 +08001887/* Configure a DNS SAN extension on a certificate. */
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001888int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
1889 int failure = 0;
1890 X509_EXTENSION *san_ext = NULL;
1891 CONF *conf = NULL;
1892 struct buffer *san_name = get_trash_chunk();
1893
1894 conf = NCONF_new(NULL);
1895 if (!conf) {
1896 failure = 1;
1897 goto cleanup;
1898 }
1899
1900 /* Build an extension based on the DNS entry above */
1901 chunk_appendf(san_name, "DNS:%s", servername);
1902 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
1903 if (!san_ext) {
1904 failure = 1;
1905 goto cleanup;
1906 }
1907
1908 /* Add the extension */
1909 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
1910 failure = 1;
1911 goto cleanup;
1912 }
1913
1914 /* Success */
1915 failure = 0;
1916
1917cleanup:
1918 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
1919 if (NULL != conf) NCONF_free(conf);
1920
1921 return failure;
1922}
1923
Christopher Faulet30548802015-06-11 13:39:32 +02001924/* Create a X509 certificate with the specified servername and serial. This
1925 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001926static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001927ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001928{
Shimi Gersner5846c492020-08-23 13:58:12 +03001929 X509 *cacert = bind_conf->ca_sign_ckch->cert;
1930 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001931 SSL_CTX *ssl_ctx = NULL;
1932 X509 *newcrt = NULL;
1933 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001934 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001935 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001936 X509_NAME *name;
1937 const EVP_MD *digest;
1938 X509V3_CTX ctx;
1939 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001940 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001941
Christopher Faulet48a83322017-07-28 16:56:09 +02001942 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05001943#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001944 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1945#else
1946 tmp_ssl = SSL_new(bind_conf->default_ctx);
1947 if (tmp_ssl)
1948 pkey = SSL_get_privatekey(tmp_ssl);
1949#endif
1950 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001951 goto mkcert_error;
1952
1953 /* Create the certificate */
1954 if (!(newcrt = X509_new()))
1955 goto mkcert_error;
1956
1957 /* Set version number for the certificate (X509v3) and the serial
1958 * number */
1959 if (X509_set_version(newcrt, 2L) != 1)
1960 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02001961 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001962
1963 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001964 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1965 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001966 goto mkcert_error;
1967
1968 /* set public key in the certificate */
1969 if (X509_set_pubkey(newcrt, pkey) != 1)
1970 goto mkcert_error;
1971
1972 /* Set issuer name from the CA */
1973 if (!(name = X509_get_subject_name(cacert)))
1974 goto mkcert_error;
1975 if (X509_set_issuer_name(newcrt, name) != 1)
1976 goto mkcert_error;
1977
1978 /* Set the subject name using the same, but the CN */
1979 name = X509_NAME_dup(name);
1980 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1981 (const unsigned char *)servername,
1982 -1, -1, 0) != 1) {
1983 X509_NAME_free(name);
1984 goto mkcert_error;
1985 }
1986 if (X509_set_subject_name(newcrt, name) != 1) {
1987 X509_NAME_free(name);
1988 goto mkcert_error;
1989 }
1990 X509_NAME_free(name);
1991
1992 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001993 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001994 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1995 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1996 X509_EXTENSION *ext;
1997
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001998 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001999 goto mkcert_error;
2000 if (!X509_add_ext(newcrt, ext, -1)) {
2001 X509_EXTENSION_free(ext);
2002 goto mkcert_error;
2003 }
2004 X509_EXTENSION_free(ext);
2005 }
2006
Shimi Gersneradabbfe2020-08-23 13:58:13 +03002007 /* Add SAN extension */
2008 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
2009 goto mkcert_error;
2010 }
2011
Christopher Faulet31af49d2015-06-09 17:29:50 +02002012 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002013
2014 key_type = EVP_PKEY_base_id(capkey);
2015
2016 if (key_type == EVP_PKEY_DSA)
2017 digest = EVP_sha1();
2018 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002019 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002020 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02002021 digest = EVP_sha256();
2022 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05002023#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02002024 int nid;
2025
2026 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
2027 goto mkcert_error;
2028 if (!(digest = EVP_get_digestbynid(nid)))
2029 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02002030#else
2031 goto mkcert_error;
2032#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02002033 }
2034
Christopher Faulet31af49d2015-06-09 17:29:50 +02002035 if (!(X509_sign(newcrt, capkey, digest)))
2036 goto mkcert_error;
2037
2038 /* Create and set the new SSL_CTX */
2039 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
2040 goto mkcert_error;
2041 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
2042 goto mkcert_error;
2043 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
2044 goto mkcert_error;
2045 if (!SSL_CTX_check_private_key(ssl_ctx))
2046 goto mkcert_error;
2047
Shimi Gersner5846c492020-08-23 13:58:12 +03002048 /* Build chaining the CA cert and the rest of the chain, keep these order */
2049#if defined(SSL_CTX_add1_chain_cert)
2050 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
2051 goto mkcert_error;
2052 }
2053
2054 if (bind_conf->ca_sign_ckch->chain) {
2055 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2056 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2057 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2058 goto mkcert_error;
2059 }
2060 }
2061 }
2062#endif
2063
Christopher Faulet31af49d2015-06-09 17:29:50 +02002064 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002065
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002066#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002067#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002068 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002069#else
2070 ssl_sock_set_tmp_dh_from_pkey(ssl_ctx, pkey);
2071#endif
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002072#endif
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002073
2074#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
2075#if defined(SSL_CTX_set1_curves_list)
2076 {
2077 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
2078 if (!SSL_CTX_set1_curves_list(ssl_ctx, ecdhe))
2079 goto end;
2080 }
2081#endif
2082#else
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002083#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2084 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002085 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002086 EC_KEY *ecc;
2087 int nid;
2088
2089 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2090 goto end;
2091 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2092 goto end;
2093 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2094 EC_KEY_free(ecc);
2095 }
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002096#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
2097#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002098 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002099 return ssl_ctx;
2100
2101 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002102 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002103 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002104 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2105 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002106 return NULL;
2107}
2108
Christopher Faulet7969a332015-10-09 11:15:03 +02002109
Christopher Faulet30548802015-06-11 13:39:32 +02002110/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002111 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002112SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002113ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002114{
2115 struct lru64 *lru = NULL;
2116
2117 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002118 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002119 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002120 if (lru && lru->domain) {
2121 if (ssl)
2122 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002123 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002124 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002125 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002126 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002127 }
2128 return NULL;
2129}
2130
Emeric Brun821bb9b2017-06-15 16:37:39 +02002131/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2132 * function is not thread-safe, it should only be used to check if a certificate
2133 * exists in the lru cache (with no warranty it will not be removed by another
2134 * thread). It is kept for backward compatibility. */
2135SSL_CTX *
2136ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2137{
2138 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2139}
2140
Christopher Fauletd2cab922015-07-28 16:03:47 +02002141/* Set a certificate int the LRU cache used to store generated
2142 * certificate. Return 0 on success, otherwise -1 */
2143int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002144ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002145{
2146 struct lru64 *lru = NULL;
2147
2148 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002149 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002150 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002151 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002152 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002153 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002154 }
Christopher Faulet30548802015-06-11 13:39:32 +02002155 if (lru->domain && lru->data)
2156 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002157 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002158 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002159 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002160 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002161 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002162}
2163
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002164/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002165unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002166ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002167{
2168 return XXH32(data, len, ssl_ctx_lru_seed);
2169}
2170
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002171/* Generate a cert and immediately assign it to the SSL session so that the cert's
2172 * refcount is maintained regardless of the cert's presence in the LRU cache.
2173 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002174static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002175ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002176{
Shimi Gersner5846c492020-08-23 13:58:12 +03002177 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002178 SSL_CTX *ssl_ctx = NULL;
2179 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002180 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002181
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002182 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002183 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002184 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002185 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002186 if (lru && lru->domain)
2187 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002188 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002189 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002190 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002191 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002192 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002193 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002194 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002195 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002196 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002197 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002198 SSL_set_SSL_CTX(ssl, ssl_ctx);
2199 /* No LRU cache, this CTX will be released as soon as the session dies */
2200 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002201 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002202 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002203 return 0;
2204}
2205static int
2206ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2207{
2208 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002209 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002210
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002211 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002212 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002213 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002214 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002215 }
2216 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002217}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002218#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002219
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002220#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002221
2222static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002223{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002224#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002225 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002226 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2227#endif
2228}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002229static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2230 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002231 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2232}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002233static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002234#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002235 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002236 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2237#endif
2238}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002239static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002240#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002241 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002242 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2243#endif
2244}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002245/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002246static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2247/* Unusable in this context. */
2248static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2249static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2250static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2251static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2252static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002253#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002254
2255static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2256 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002257 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2258}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002259static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2260 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2261 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2262}
2263static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2264 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002265 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2266}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002267static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2268 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2269 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2270}
2271static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2272 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002273 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2274}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002275static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2276 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2277 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2278}
2279static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2280 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002281 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2282}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002283static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2284 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2285 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2286}
2287static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002288#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002289 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002290 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2291#endif
2292}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002293static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002294#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002295 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2296 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002297#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002298}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002299#endif
2300static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2301static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002302
William Lallemand7fd8b452020-05-07 15:20:43 +02002303struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002304 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2305 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2306 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2307 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2308 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2309 {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 +02002310};
2311
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002312static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2313{
2314 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2315 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2316 SSL_set_SSL_CTX(ssl, ctx);
2317}
2318
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002319#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002320
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002321int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002322{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002323 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002324 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002325
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002326 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || (s->options & BC_O_GENERATE_CERTS))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002327 return SSL_TLSEXT_ERR_OK;
2328 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002329}
2330
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002331#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002332int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002333{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002334 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002335#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002336int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002337{
2338#endif
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002339 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2340#ifdef USE_QUIC
2341 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2342#endif /* USE_QUIC */
2343 struct bind_conf *s = NULL;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002344 const uint8_t *extension_data;
2345 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002346 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002347
2348 char *wildp = NULL;
2349 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002350 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002351 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002352 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002353 int i;
2354
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002355 if (conn)
2356 s = __objt_listener(conn->target)->bind_conf;
2357#ifdef USE_QUIC
2358 else if (qc)
2359 s = qc->li->bind_conf;
2360#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01002361
2362 if (!s) {
2363 /* must never happen */
2364 ABORT_NOW();
2365 return 0;
2366 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002367
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002368#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002369 if (qc) {
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002370 /* Look for the QUIC transport parameters. */
2371#ifdef OPENSSL_IS_BORINGSSL
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002372 if (!SSL_early_callback_ctx_extension_get(ctx, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002373 &extension_data, &extension_len))
2374#else
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002375 if (!SSL_client_hello_get0_ext(ssl, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002376 &extension_data, &extension_len))
2377#endif
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002378 {
2379 /* This is not redundant. It we only return 0 without setting
2380 * <*al>, this has as side effect to generate another TLS alert
2381 * which would be set after calling quic_set_tls_alert().
2382 */
2383 *al = SSL_AD_MISSING_EXTENSION;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002384 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002385 return 0;
2386 }
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002387
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002388 if (!quic_transport_params_store(qc, 0, extension_data,
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002389 extension_data + extension_len))
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002390 goto abort;
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002391
2392 qc->flags |= QUIC_FL_CONN_TX_TP_RECEIVED;
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002393 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002394#endif /* USE_QUIC */
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002395
Olivier Houchard9679ac92017-10-27 14:58:08 +02002396 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002397 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002398#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002399 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2400 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002401#else
2402 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2403#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002404 /*
2405 * The server_name extension was given too much extensibility when it
2406 * was written, so parsing the normal case is a bit complex.
2407 */
2408 size_t len;
2409 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002410 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002411 /* Extract the length of the supplied list of names. */
2412 len = (*extension_data++) << 8;
2413 len |= *extension_data++;
2414 if (len + 2 != extension_len)
2415 goto abort;
2416 /*
2417 * The list in practice only has a single element, so we only consider
2418 * the first one.
2419 */
2420 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2421 goto abort;
2422 extension_len = len - 1;
2423 /* Now we can finally pull out the byte array with the actual hostname. */
2424 if (extension_len <= 2)
2425 goto abort;
2426 len = (*extension_data++) << 8;
2427 len |= *extension_data++;
2428 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2429 || memchr(extension_data, 0, len) != NULL)
2430 goto abort;
2431 servername = extension_data;
2432 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002433 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002434#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002435 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002436 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002437 }
2438#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002439 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002440 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002441 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002442 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002443 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002444 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002445 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002446 goto abort;
2447 }
2448
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002449 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002450#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002451 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002452#else
2453 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2454#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002455 uint8_t sign;
2456 size_t len;
2457 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002458 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002459 len = (*extension_data++) << 8;
2460 len |= *extension_data++;
2461 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002462 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002463 if (len % 2 != 0)
2464 goto abort;
2465 for (; len > 0; len -= 2) {
2466 extension_data++; /* hash */
2467 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002468 switch (sign) {
2469 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002470 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002471 break;
2472 case TLSEXT_signature_ecdsa:
2473 has_ecdsa_sig = 1;
2474 break;
2475 default:
2476 continue;
2477 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002478 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002479 break;
2480 }
2481 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002482 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002483 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002484 }
2485 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002486 const SSL_CIPHER *cipher;
2487 size_t len;
2488 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002489 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002490#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002491 len = ctx->cipher_suites_len;
2492 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002493#else
2494 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2495#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002496 if (len % 2 != 0)
2497 goto abort;
2498 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002499#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002500 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002501 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002502#else
2503 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2504#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002505 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002506 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002507 break;
2508 }
2509 }
2510 }
2511
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002512 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002513 trash.area[i] = tolower(servername[i]);
2514 if (!wildp && (trash.area[i] == '.'))
2515 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002516 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002517 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002518
William Lallemand150bfa82019-09-19 17:12:49 +02002519 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002520
William Lallemand94bd3192020-08-14 14:43:35 +02002521 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2522 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002523 for (i = 0; i < 2; i++) {
2524 if (i == 0) /* lookup in full qualified names */
2525 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002526 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002527 node = ebst_lookup(&s->sni_w_ctx, wildp);
2528 else
2529 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002530
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002531 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002532
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002533 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002534 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002535 struct sni_ctx *sni, *sni_tmp;
2536 int skip = 0;
2537
2538 if (i == 1 && wildp) { /* wildcard */
2539 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2540 sni = container_of(n, struct sni_ctx, name);
2541 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002542 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002543 skip = 1;
2544 break;
2545 }
2546 }
2547 if (skip)
2548 continue;
2549 }
2550
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002551 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002552 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002553 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002554 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002555 break;
2556 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002557 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002558 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002559 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002560 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002561 if (!node_anonymous)
2562 node_anonymous = n;
2563 break;
2564 }
2565 }
2566 }
William Lallemand94bd3192020-08-14 14:43:35 +02002567 }
2568 /* Once the certificates are found, select them depending on what is
2569 * supported in the client and by key_signature priority order: EDSA >
2570 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002571 if (has_ecdsa_sig && node_ecdsa)
2572 node = node_ecdsa;
2573 else if (has_rsa_sig && node_rsa)
2574 node = node_rsa;
2575 else if (node_anonymous)
2576 node = node_anonymous;
2577 else if (node_ecdsa)
2578 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2579 else
2580 node = node_rsa; /* no rsa signature case (far far away) */
2581
William Lallemand94bd3192020-08-14 14:43:35 +02002582 if (node) {
2583 /* switch ctx */
2584 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2585 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2586 if (conf) {
2587 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2588 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2589 if (conf->early_data)
2590 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002591 }
William Lallemand94bd3192020-08-14 14:43:35 +02002592 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2593 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002594 }
William Lallemand150bfa82019-09-19 17:12:49 +02002595
William Lallemand02010472019-10-18 11:02:19 +02002596 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002597#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002598 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002599 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002600 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002601 }
2602#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002603 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002604 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002605 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002606 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002607 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
William Lallemand7980dff2021-11-18 17:46:26 +01002608 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002609 }
William Lallemand7980dff2021-11-18 17:46:26 +01002610
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01002611 /* We are about to raise an handshake error so the servername extension
2612 * callback will never be called and the SNI will never be stored in the
2613 * SSL context. In order for the ssl_fc_sni sample fetch to still work
2614 * in such a case, we store the SNI ourselves as an ex_data information
2615 * in the SSL context.
2616 */
2617 {
2618 char *client_sni = pool_alloc(ssl_sock_client_sni_pool);
2619 if (client_sni) {
2620 strncpy(client_sni, trash.area, TLSEXT_MAXLEN_host_name);
2621 client_sni[TLSEXT_MAXLEN_host_name] = '\0';
2622 SSL_set_ex_data(ssl, ssl_client_sni_index, client_sni);
2623 }
2624 }
2625
William Lallemand7980dff2021-11-18 17:46:26 +01002626 /* other cases fallback on abort, if strict-sni is set but no node was found */
2627
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002628 abort:
2629 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002630 if (conn)
2631 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002632#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002633 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002634#else
2635 *al = SSL_AD_UNRECOGNIZED_NAME;
2636 return 0;
2637#endif
William Lallemand7980dff2021-11-18 17:46:26 +01002638
2639allow_early:
2640#ifdef OPENSSL_IS_BORINGSSL
2641 if (allow_early)
2642 SSL_set_early_data_enabled(ssl, 1);
2643#else
2644 if (!allow_early)
2645 SSL_set_max_early_data(ssl, 0);
2646#endif
2647 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002648}
2649
William Lallemand002e2062021-11-18 15:25:16 +01002650#else /* ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002651
Emeric Brunfc0421f2012-09-07 17:30:07 +02002652/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2653 * warning when no match is found, which implies the default (first) cert
2654 * will keep being used.
2655 */
William Lallemand844009d2022-09-02 15:27:32 +02002656int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002657{
2658 const char *servername;
2659 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002660 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002661 struct bind_conf *s = priv;
William Lallemand70a6e632022-09-07 11:21:34 +02002662#ifdef USE_QUIC
2663 const uint8_t *extension_data;
2664 size_t extension_len;
2665 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2666#endif /* USE_QUIC */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002667 int i;
2668 (void)al; /* shut gcc stupid warning */
2669
William Lallemand70a6e632022-09-07 11:21:34 +02002670#ifdef USE_QUIC
2671 if (qc) {
2672
2673 /* Look for the QUIC transport parameters. */
2674 SSL_get_peer_quic_transport_params(ssl, &extension_data, &extension_len);
2675 if (extension_len == 0) {
2676 /* This is not redundant. It we only return 0 without setting
2677 * <*al>, this has as side effect to generate another TLS alert
2678 * which would be set after calling quic_set_tls_alert().
2679 */
2680 *al = SSL_AD_MISSING_EXTENSION;
2681 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
2682 return SSL_TLSEXT_ERR_NOACK;
2683 }
2684
2685 if (!quic_transport_params_store(qc, 0, extension_data,
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002686 extension_data + extension_len))
William Lallemand70a6e632022-09-07 11:21:34 +02002687 return SSL_TLSEXT_ERR_NOACK;
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002688
2689 qc->flags |= QUIC_FL_CONN_TX_TP_RECEIVED;
William Lallemand70a6e632022-09-07 11:21:34 +02002690 }
2691#endif /* USE_QUIC */
2692
Emeric Brunfc0421f2012-09-07 17:30:07 +02002693 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002694 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002695#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002696 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002697 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002698#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002699 if (s->strict_sni)
2700 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002701 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002702 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002703 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002704 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002705 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002706
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002707 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002708 if (!servername[i])
2709 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002710 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002711 if (!wildp && (trash.area[i] == '.'))
2712 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002713 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002714 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002715
William Lallemand150bfa82019-09-19 17:12:49 +02002716 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002717 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002718 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002719 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2720 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002721 if (!container_of(n, struct sni_ctx, name)->neg) {
2722 node = n;
2723 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002724 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002725 }
2726 if (!node && wildp) {
2727 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002728 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2729 /* lookup a not neg filter */
2730 if (!container_of(n, struct sni_ctx, name)->neg) {
2731 node = n;
2732 break;
2733 }
2734 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002735 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002736 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002737#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002738 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(servername, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002739 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002740 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002741 return SSL_TLSEXT_ERR_OK;
2742 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002743#endif
William Lallemand21724f02019-11-04 17:56:13 +01002744 if (s->strict_sni) {
2745 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002746 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002747 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002748 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002749 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002750 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002751 }
2752
2753 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002754 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002755 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002756 return SSL_TLSEXT_ERR_OK;
2757}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002758#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002759#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2760
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002761#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002762
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002763static inline HASSL_DH *ssl_new_dh_fromdata(BIGNUM *p, BIGNUM *g)
2764{
2765#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2766 OSSL_PARAM_BLD *tmpl = NULL;
2767 OSSL_PARAM *params = NULL;
2768 EVP_PKEY_CTX *ctx = NULL;
2769 EVP_PKEY *pkey = NULL;
2770
2771 if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
2772 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
2773 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)
2774 || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
2775 goto end;
2776 }
2777 ctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2778 if (ctx == NULL
2779 || !EVP_PKEY_fromdata_init(ctx)
2780 || !EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params)) {
2781 goto end;
2782 }
2783
2784end:
2785 EVP_PKEY_CTX_free(ctx);
2786 OSSL_PARAM_free(params);
2787 OSSL_PARAM_BLD_free(tmpl);
Remi Tricot-Le Bretona2c21db2022-11-03 15:16:47 +01002788 BN_free(p);
2789 BN_free(g);
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002790 return pkey;
2791#else
2792
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002793 HASSL_DH *dh = DH_new();
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002794
2795 if (!dh)
2796 return NULL;
2797
2798 DH_set0_pqg(dh, p, NULL, g);
2799
2800 return dh;
2801#endif
2802}
2803
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02002804#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002805static inline HASSL_DH *ssl_get_dh_by_nid(int nid)
2806{
2807#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2808 OSSL_PARAM params[2];
2809 EVP_PKEY *pkey = NULL;
2810 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2811 const char *named_group = NULL;
2812
2813 if (!pctx)
2814 goto end;
2815
2816 named_group = OBJ_nid2ln(nid);
2817
2818 if (!named_group)
2819 goto end;
2820
2821 params[0] = OSSL_PARAM_construct_utf8_string("group", (char*)named_group, 0);
2822 params[1] = OSSL_PARAM_construct_end();
2823
2824 if (EVP_PKEY_keygen_init(pctx) && EVP_PKEY_CTX_set_params(pctx, params))
2825 EVP_PKEY_generate(pctx, &pkey);
2826
2827end:
2828 EVP_PKEY_CTX_free(pctx);
2829 return pkey;
2830#else
2831
2832 HASSL_DH *dh = NULL;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002833 dh = DH_new_by_nid(nid);
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002834 return dh;
2835#endif
2836}
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02002837#endif
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002838
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002839
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002840static HASSL_DH * ssl_get_dh_1024(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002841{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002842 static unsigned char dh1024_p[]={
2843 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2844 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2845 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2846 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2847 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2848 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2849 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2850 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2851 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2852 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2853 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2854 };
2855 static unsigned char dh1024_g[]={
2856 0x02,
2857 };
2858
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002859 BIGNUM *p;
2860 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002861
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002862 HASSL_DH *dh = NULL;
2863
2864 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2865 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
2866
2867 if (p && g)
2868 dh = ssl_new_dh_fromdata(p, g);
2869
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002870 return dh;
2871}
2872
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002873static HASSL_DH *ssl_get_dh_2048(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002874{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002875#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02002876 static unsigned char dh2048_p[]={
2877 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2878 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2879 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2880 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2881 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2882 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2883 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2884 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2885 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2886 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2887 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2888 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2889 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2890 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2891 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2892 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2893 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2894 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2895 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2896 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2897 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2898 0xB7,0x1F,0x77,0xF3,
2899 };
2900 static unsigned char dh2048_g[]={
2901 0x02,
2902 };
2903
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002904 BIGNUM *p;
2905 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002906
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002907 HASSL_DH *dh = NULL;
2908
2909 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2910 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
2911
2912 if (p && g)
2913 dh = ssl_new_dh_fromdata(p, g);
2914
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002915 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002916#else
2917 return ssl_get_dh_by_nid(NID_ffdhe2048);
2918#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002919}
2920
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002921static HASSL_DH *ssl_get_dh_4096(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002922{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002923#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02002924 static unsigned char dh4096_p[]={
2925 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2926 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2927 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2928 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2929 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2930 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2931 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2932 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2933 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2934 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2935 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2936 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2937 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2938 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2939 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2940 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2941 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2942 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2943 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2944 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2945 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2946 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2947 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2948 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2949 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2950 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2951 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2952 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2953 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2954 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2955 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2956 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2957 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2958 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2959 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2960 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2961 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2962 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2963 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2964 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2965 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2966 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2967 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002968 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002969 static unsigned char dh4096_g[]={
2970 0x02,
2971 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002972
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002973 BIGNUM *p;
2974 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002975
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002976 HASSL_DH *dh = NULL;
2977
2978 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2979 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
2980
2981 if (p && g)
2982 dh = ssl_new_dh_fromdata(p, g);
2983
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002984 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002985#else
2986 return ssl_get_dh_by_nid(NID_ffdhe4096);
2987#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002988}
2989
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002990static HASSL_DH *ssl_get_tmp_dh(EVP_PKEY *pkey)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002991{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002992 HASSL_DH *dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002993 int type;
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002994 int keylen = 0;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002995
2996 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002997
Ilya Shipitsin52f2ff52022-07-23 23:55:19 +05002998 if (type == EVP_PKEY_EC) {
2999 keylen = global_ssl.default_dh_param;
3000 }
3001
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003002 /* The keylen supplied by OpenSSL can only be 512 or 1024.
3003 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
3004 */
3005 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
3006 keylen = EVP_PKEY_bits(pkey);
3007 }
3008
Willy Tarreauef934602016-12-22 23:12:01 +01003009 if (keylen > global_ssl.default_dh_param) {
3010 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003011 }
3012
Remi Gacogned3a341a2015-05-29 16:26:17 +02003013 if (keylen >= 4096) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003014 if (!local_dh_4096)
3015 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02003016 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003017 }
3018 else if (keylen >= 2048) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003019 if (!local_dh_2048)
3020 local_dh_2048 = ssl_get_dh_2048();
Remi Gacogne8de54152014-07-15 11:36:40 +02003021 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003022 }
3023 else {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003024 if (!local_dh_1024)
3025 local_dh_1024 = ssl_get_dh_1024();
Remi Gacogne8de54152014-07-15 11:36:40 +02003026 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003027 }
3028
3029 return dh;
3030}
3031
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003032#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003033/* Returns Diffie-Hellman parameters matching the private key length
3034 but not exceeding global_ssl.default_dh_param */
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003035static HASSL_DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003036{
3037 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
3038
3039 return ssl_get_tmp_dh(pkey);
3040}
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003041#endif
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003042
Remi Tricot-Le Breton846eda92022-02-11 12:04:50 +01003043static int ssl_sock_set_tmp_dh(SSL_CTX *ctx, HASSL_DH *dh)
3044{
3045#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
3046 return SSL_CTX_set_tmp_dh(ctx, dh);
3047#else
3048 int retval = 0;
3049 HASSL_DH_up_ref(dh);
3050
3051 retval = SSL_CTX_set0_tmp_dh_pkey(ctx, dh);
3052
3053 if (!retval)
3054 HASSL_DH_free(dh);
3055
3056 return retval;
3057#endif
3058}
3059
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003060#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3061static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey)
3062{
3063 HASSL_DH *dh = NULL;
3064 if (pkey && (dh = ssl_get_tmp_dh(pkey))) {
3065 HASSL_DH_up_ref(dh);
3066 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dh))
3067 HASSL_DH_free(dh);
3068 }
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003069}
3070#endif
3071
Remi Tricot-Le Breton09ebb332022-02-11 12:04:48 +01003072HASSL_DH *ssl_sock_get_dh_from_bio(BIO *bio)
3073{
3074#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3075 HASSL_DH *dh = NULL;
3076 OSSL_DECODER_CTX *dctx = NULL;
3077 const char *format = "PEM";
3078 const char *keytype = "DH";
3079
3080 dctx = OSSL_DECODER_CTX_new_for_pkey(&dh, format, NULL, keytype,
3081 OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
3082 NULL, NULL);
3083
3084 if (dctx == NULL || OSSL_DECODER_CTX_get_num_decoders(dctx) == 0)
3085 goto end;
3086
3087 /* The DH parameters might not be the first section found in the PEM
3088 * file so we need to iterate over all of them until we find the right
3089 * one.
3090 */
3091 while (!BIO_eof(bio) && !dh)
3092 OSSL_DECODER_from_bio(dctx, bio);
3093
3094end:
3095 OSSL_DECODER_CTX_free(dctx);
3096 return dh;
3097#else
3098 HASSL_DH *dh = NULL;
3099
3100 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3101
3102 return dh;
3103#endif
3104}
3105
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003106static HASSL_DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003107{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003108 HASSL_DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02003109 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003110
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003111 if (in == NULL)
3112 goto end;
3113
Remi Gacogne47783ef2015-05-29 15:53:22 +02003114 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003115 goto end;
3116
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003117 dh = ssl_sock_get_dh_from_bio(in);
Remi Gacogne47783ef2015-05-29 15:53:22 +02003118
3119end:
3120 if (in)
3121 BIO_free(in);
3122
Emeric Brune1b4ed42018-08-16 15:14:12 +02003123 ERR_clear_error();
3124
Remi Gacogne47783ef2015-05-29 15:53:22 +02003125 return dh;
3126}
3127
3128int ssl_sock_load_global_dh_param_from_file(const char *filename)
3129{
3130 global_dh = ssl_sock_get_dh_from_file(filename);
3131
3132 if (global_dh) {
3133 return 0;
3134 }
3135
3136 return -1;
3137}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003138#endif
3139
William Lallemand9117de92019-10-04 00:29:42 +02003140/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02003141static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02003142 struct bind_conf *s, struct ssl_bind_conf *conf,
3143 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003144{
3145 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003146 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003147
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003148 if (*name == '!') {
3149 neg = 1;
3150 name++;
3151 }
3152 if (*name == '*') {
3153 wild = 1;
3154 name++;
3155 }
3156 /* !* filter is a nop */
3157 if (neg && wild)
3158 return order;
3159 if (*name) {
3160 int j, len;
3161 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003162 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02003163 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003164 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02003165 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003166 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003167
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003168 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02003169 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02003170 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003171 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02003172 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003173 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003174 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003175 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003176 sc->order = order++;
3177 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02003178 sc->wild = wild;
3179 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01003180 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02003181 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003182 }
3183 return order;
3184}
3185
William Lallemand6af03992019-07-23 15:00:54 +02003186/*
William Lallemand1d29c742019-10-04 00:53:29 +02003187 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
3188 * This function can't return an error.
3189 *
3190 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
3191 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003192void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02003193{
3194
3195 struct sni_ctx *sc0, *sc0b, *sc1;
3196 struct ebmb_node *node;
3197
3198 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
3199
3200 /* ignore if sc0 was already inserted in a tree */
3201 if (sc0->name.node.leaf_p)
3202 continue;
3203
3204 /* Check for duplicates. */
3205 if (sc0->wild)
3206 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
3207 else
3208 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
3209
3210 for (; node; node = ebmb_next_dup(node)) {
3211 sc1 = ebmb_entry(node, struct sni_ctx, name);
3212 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
3213 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
3214 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02003215 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02003216 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003217 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02003218 break;
William Lallemand1d29c742019-10-04 00:53:29 +02003219 }
3220 }
3221
3222 /* if duplicate, ignore the insertion */
3223 if (!sc0)
3224 continue;
3225
3226 if (sc0->wild)
3227 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
3228 else
3229 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003230 }
William Lallemand21724f02019-11-04 17:56:13 +01003231
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003232 /* replace the default_ctx if required with the instance's ctx. */
3233 if (ckch_inst->is_default) {
3234 SSL_CTX_free(bind_conf->default_ctx);
3235 SSL_CTX_up_ref(ckch_inst->ctx);
3236 bind_conf->default_ctx = ckch_inst->ctx;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003237 bind_conf->default_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02003238 }
3239}
3240
3241/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003242 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02003243 */
William Lallemande3af8fb2019-10-08 11:36:53 +02003244struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02003245
William Lallemand2954c472020-03-06 21:54:13 +01003246/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02003247struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02003248
Emeric Brun7a883362019-10-17 13:27:40 +02003249/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003250 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02003251 * DH parameter is loaded into the SSL_CTX and if there is no
3252 * DH parameter available in ckchs nor in global, the default
3253 * DH parameters are applied on the SSL_CTX.
3254 * Returns a bitfield containing the flags:
3255 * ERR_FATAL in any fatal error case
3256 * ERR_ALERT if a reason of the error is availabine in err
3257 * ERR_WARN if a warning is available into err
3258 * The value 0 means there is no error nor warning and
3259 * the operation succeed.
3260 */
William Lallemandfa892222019-07-23 16:06:08 +02003261#ifndef OPENSSL_NO_DH
William Lallemand52ddd992022-11-22 11:51:53 +01003262static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct ckch_data *data,
Emeric Brun7a883362019-10-17 13:27:40 +02003263 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02003264{
Emeric Brun7a883362019-10-17 13:27:40 +02003265 int ret = 0;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003266 HASSL_DH *dh = NULL;
William Lallemandfa892222019-07-23 16:06:08 +02003267
William Lallemand52ddd992022-11-22 11:51:53 +01003268 if (data && data->dh) {
3269 dh = data->dh;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003270 if (!ssl_sock_set_tmp_dh(ctx, dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003271 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
3272 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003273 memprintf(err, "%s, DH ciphers won't be available.\n",
3274 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003275 ret |= ERR_WARN;
3276 goto end;
3277 }
William Lallemandfa892222019-07-23 16:06:08 +02003278
3279 if (ssl_dh_ptr_index >= 0) {
3280 /* store a pointer to the DH params to avoid complaining about
3281 ssl-default-dh-param not being set for this SSL_CTX */
3282 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
3283 }
3284 }
3285 else if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003286 if (!ssl_sock_set_tmp_dh(ctx, global_dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003287 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
3288 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003289 memprintf(err, "%s, DH ciphers won't be available.\n",
3290 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003291 ret |= ERR_WARN;
3292 goto end;
3293 }
William Lallemandfa892222019-07-23 16:06:08 +02003294 }
3295 else {
3296 /* Clear openssl global errors stack */
3297 ERR_clear_error();
3298
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003299 /* We do not want DHE ciphers to be added to the cipher list
3300 * unless there is an explicit global dh option in the conf.
3301 */
3302 if (global_ssl.default_dh_param) {
3303 if (global_ssl.default_dh_param <= 1024) {
3304 /* we are limited to DH parameter of 1024 bits anyway */
3305 if (local_dh_1024 == NULL)
3306 local_dh_1024 = ssl_get_dh_1024();
William Lallemandfa892222019-07-23 16:06:08 +02003307
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003308 if (local_dh_1024 == NULL) {
3309 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3310 err && *err ? *err : "", path);
3311 ret |= ERR_ALERT | ERR_FATAL;
3312 goto end;
3313 }
William Lallemandfa892222019-07-23 16:06:08 +02003314
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003315 if (!ssl_sock_set_tmp_dh(ctx, local_dh_1024)) {
3316 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3317 err && *err ? *err : "", path);
3318 memprintf(err, "%s, DH ciphers won't be available.\n",
3319 err && *err ? *err : "");
3320 ret |= ERR_WARN;
3321 goto end;
3322 }
Emeric Bruna9363eb2019-10-17 14:53:03 +02003323 }
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003324 else {
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003325#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003326 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003327#else
William Lallemand52ddd992022-11-22 11:51:53 +01003328 ssl_sock_set_tmp_dh_from_pkey(ctx, data ? data->key : NULL);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003329#endif
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003330 }
William Lallemandfa892222019-07-23 16:06:08 +02003331 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003332 }
3333
William Lallemandf9568fc2019-10-16 18:27:58 +02003334end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003335 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003336 return ret;
3337}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003338#endif
William Lallemandfa892222019-07-23 16:06:08 +02003339
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003340
3341/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003342 * Returns a bitfield containing the flags:
3343 * ERR_FATAL in any fatal error case
3344 * ERR_ALERT if the reason of the error is available in err
3345 * ERR_WARN if a warning is available into err
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003346 * The caller is responsible of freeing the newly built or newly refcounted
3347 * find_chain element.
Emeric Bruna96b5822019-10-17 13:25:14 +02003348 * The value 0 means there is no error nor warning and
3349 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003350 */
William Lallemand52ddd992022-11-22 11:51:53 +01003351static int ssl_sock_load_cert_chain(const char *path, const struct ckch_data *data,
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003352 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003353{
Emeric Bruna96b5822019-10-17 13:25:14 +02003354 int errcode = 0;
William Lallemand45fed2c2022-11-15 16:56:03 +01003355 int ret;
3356
3357 ERR_clear_error();
Emeric Bruna96b5822019-10-17 13:25:14 +02003358
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003359 if (find_chain == NULL) {
3360 errcode |= ERR_FATAL;
3361 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003362 }
3363
William Lallemand52ddd992022-11-22 11:51:53 +01003364 if (!SSL_CTX_use_certificate(ctx, data->cert)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003365 ret = ERR_get_error();
3366 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s': %s.\n",
3367 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Emeric Bruna96b5822019-10-17 13:25:14 +02003368 errcode |= ERR_ALERT | ERR_FATAL;
3369 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003370 }
3371
William Lallemand52ddd992022-11-22 11:51:53 +01003372 if (data->chain) {
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003373 *find_chain = X509_chain_up_ref(data->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003374 } else {
3375 /* Find Certificate Chain in global */
3376 struct issuer_chain *issuer;
William Lallemand52ddd992022-11-22 11:51:53 +01003377 issuer = ssl_get0_issuer_chain(data->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003378 if (issuer)
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003379 *find_chain = X509_chain_up_ref(issuer->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003380 }
William Lallemand85888572020-02-27 14:48:35 +01003381
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003382 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003383 /* always put a null chain stack in the SSL_CTX so it does not
3384 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003385 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003386 }
3387
William Lallemand52ddd992022-11-22 11:51:53 +01003388 /* Load all certs in the data into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003389#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003390 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003391 ret = ERR_get_error();
William Lallemanda21ca742023-04-17 14:32:25 +02003392 memprintf(err, "%sunable to load chain certificate into SSL Context '%s': %s.\n",
William Lallemand45fed2c2022-11-15 16:56:03 +01003393 err && *err ? *err : "", path, ERR_reason_error_string(ret));
William Lallemand935d8292020-08-12 20:02:10 +02003394 errcode |= ERR_ALERT | ERR_FATAL;
3395 goto end;
3396 }
William Lallemandf187ce62020-06-02 18:27:20 +02003397#else
3398 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003399 X509 *ca;
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003400 while ((ca = sk_X509_shift(*find_chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003401 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003402 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3403 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003404 X509_free(ca);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003405 errcode |= ERR_ALERT | ERR_FATAL;
3406 goto end;
3407 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003408 }
William Lallemandf187ce62020-06-02 18:27:20 +02003409#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003410
William Lallemand9a1d8392020-08-10 17:28:23 +02003411#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003412 /* remove the Root CA from the SSL_CTX if the option is activated */
3413 if (global_ssl.skip_self_issued_ca) {
3414 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3415 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3416 err && *err ? *err : "", path);
3417 errcode |= ERR_ALERT | ERR_FATAL;
3418 goto end;
3419 }
3420 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003421#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003422
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003423end:
3424 return errcode;
3425}
3426
3427
3428/* Loads the info in ckch into ctx
3429 * Returns a bitfield containing the flags:
3430 * ERR_FATAL in any fatal error case
3431 * ERR_ALERT if the reason of the error is available in err
3432 * ERR_WARN if a warning is available into err
3433 * The value 0 means there is no error nor warning and
3434 * the operation succeed.
3435 */
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01003436static 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 +01003437{
3438 int errcode = 0;
3439 STACK_OF(X509) *find_chain = NULL;
3440
William Lallemand5de49512022-10-27 14:41:07 +02003441 ERR_clear_error();
3442
William Lallemand52ddd992022-11-22 11:51:53 +01003443 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
William Lallemand5de49512022-10-27 14:41:07 +02003444 int ret;
3445
3446 ret = ERR_get_error();
3447 memprintf(err, "%sunable to load SSL private key into SSL Context '%s': %s.\n",
3448 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003449 errcode |= ERR_ALERT | ERR_FATAL;
3450 return errcode;
3451 }
3452
3453 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01003454 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003455 if (errcode & ERR_CODE)
3456 goto end;
3457
William Lallemandfa892222019-07-23 16:06:08 +02003458#ifndef OPENSSL_NO_DH
3459 /* store a NULL pointer to indicate we have not yet loaded
3460 a custom DH param file */
3461 if (ssl_dh_ptr_index >= 0) {
3462 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3463 }
3464
William Lallemand52ddd992022-11-22 11:51:53 +01003465 errcode |= ssl_sock_load_dh_params(ctx, data, path, err);
Emeric Brun7a883362019-10-17 13:27:40 +02003466 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003467 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3468 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003469 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003470 }
3471#endif
3472
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003473#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemand52ddd992022-11-22 11:51:53 +01003474 if (sctl_ex_index >= 0 && data->sctl) {
3475 if (ssl_sock_load_sctl(ctx, data->sctl) < 0) {
William Lallemanda17f4112019-10-10 15:16:44 +02003476 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003477 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003478 errcode |= ERR_ALERT | ERR_FATAL;
3479 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003480 }
3481 }
3482#endif
3483
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003484#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 +01003485 /* Load OCSP Info into context
3486 * If OCSP update mode is set to 'on', an entry will be created in the
3487 * ocsp tree even if no ocsp_response was known during init, unless the
Ilya Shipitsin07be66d2023-04-01 12:26:42 +02003488 * frontend's conf disables ocsp update explicitly.
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01003489 */
Remi Tricot-Le Breton0c96ee42023-03-01 16:11:50 +01003490 if (ssl_sock_load_ocsp(path, ctx, data, find_chain) < 0) {
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01003491 if (data->ocsp_response)
Tim Duesterhus93128532019-11-23 23:45:10 +01003492 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 +01003493 err && *err ? *err : "", path);
3494 else
3495 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",
3496 err && *err ? *err : "", path);
3497 errcode |= ERR_ALERT | ERR_FATAL;
3498 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003499 }
William Lallemand246c0242019-10-11 08:59:13 +02003500#endif
3501
Emeric Bruna96b5822019-10-17 13:25:14 +02003502 end:
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003503 sk_X509_pop_free(find_chain, X509_free);
Emeric Bruna96b5822019-10-17 13:25:14 +02003504 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003505}
3506
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003507
3508/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
3509 * Returns a bitfield containing the flags:
3510 * ERR_FATAL in any fatal error case
3511 * ERR_ALERT if the reason of the error is available in err
3512 * ERR_WARN if a warning is available into err
3513 * The value 0 means there is no error nor warning and
3514 * the operation succeed.
3515 */
William Lallemand52ddd992022-11-22 11:51:53 +01003516static 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 +01003517 SSL_CTX *ctx, char **err)
3518{
3519 int errcode = 0;
3520 STACK_OF(X509) *find_chain = NULL;
3521
3522 /* Load the private key */
William Lallemand52ddd992022-11-22 11:51:53 +01003523 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003524 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3525 err && *err ? *err : "", path);
3526 errcode |= ERR_ALERT | ERR_FATAL;
3527 }
3528
3529 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01003530 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003531 if (errcode & ERR_CODE)
3532 goto end;
3533
3534 if (SSL_CTX_check_private_key(ctx) <= 0) {
3535 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3536 err && *err ? *err : "", path);
3537 errcode |= ERR_ALERT | ERR_FATAL;
3538 }
3539
3540end:
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003541 sk_X509_pop_free(find_chain, X509_free);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003542 return errcode;
3543}
3544
3545
William Lallemand614ca0d2019-10-07 13:52:11 +02003546/*
3547 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003548 *
3549 * Returns a bitfield containing the flags:
3550 * ERR_FATAL in any fatal error case
3551 * ERR_ALERT if the reason of the error is available in err
3552 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003553 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003554int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003555 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003556{
William Lallemandc9402072019-05-15 15:33:54 +02003557 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003558 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003559 int order = 0;
3560 X509_NAME *xname;
3561 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003562 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003563 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003564#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3565 STACK_OF(GENERAL_NAME) *names;
3566#endif
William Lallemand52ddd992022-11-22 11:51:53 +01003567 struct ckch_data *data;
William Lallemand614ca0d2019-10-07 13:52:11 +02003568 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003569 int errcode = 0;
3570
3571 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003572
William Lallemand52ddd992022-11-22 11:51:53 +01003573 if (!ckchs || !ckchs->data)
Emeric Brun054563d2019-10-17 13:16:58 +02003574 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003575
William Lallemand52ddd992022-11-22 11:51:53 +01003576 data = ckchs->data;
William Lallemand36b84632019-07-18 19:28:17 +02003577
William Lallemandc9402072019-05-15 15:33:54 +02003578 ctx = SSL_CTX_new(SSLv23_server_method());
3579 if (!ctx) {
3580 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3581 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003582 errcode |= ERR_ALERT | ERR_FATAL;
3583 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003584 }
3585
William Lallemand52ddd992022-11-22 11:51:53 +01003586 errcode |= ssl_sock_put_ckch_into_ctx(path, data, ctx, err);
Emeric Bruna96b5822019-10-17 13:25:14 +02003587 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003588 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003589
3590 ckch_inst = ckch_inst_new();
3591 if (!ckch_inst) {
3592 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3593 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003594 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003595 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003596 }
3597
William Lallemand52ddd992022-11-22 11:51:53 +01003598 pkey = X509_get_pubkey(data->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003599 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003600 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003601 switch(EVP_PKEY_base_id(pkey)) {
3602 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003603 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003604 break;
3605 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003606 kinfo.sig = TLSEXT_signature_ecdsa;
3607 break;
3608 case EVP_PKEY_DSA:
3609 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003610 break;
3611 }
3612 EVP_PKEY_free(pkey);
3613 }
3614
Emeric Brun50bcecc2013-04-22 13:05:23 +02003615 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003616 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003617 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 +02003618 if (order < 0) {
3619 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003620 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003621 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003622 }
3623 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003624 }
3625 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003626#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand52ddd992022-11-22 11:51:53 +01003627 names = X509_get_ext_d2i(data->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003628 if (names) {
3629 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3630 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3631 if (name->type == GEN_DNS) {
3632 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003633 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003634 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003635 if (order < 0) {
3636 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003637 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003638 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003639 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003640 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003641 }
3642 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003643 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003644 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003645#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand52ddd992022-11-22 11:51:53 +01003646 xname = X509_get_subject_name(data->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003647 i = -1;
3648 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3649 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003650 ASN1_STRING *value;
3651
3652 value = X509_NAME_ENTRY_get_data(entry);
3653 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003654 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003655 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003656 if (order < 0) {
3657 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003658 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003659 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003660 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003661 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003662 }
3663 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003664 /* we must not free the SSL_CTX anymore below, since it's already in
3665 * the tree, so it will be discovered and cleaned in time.
3666 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003667
Emeric Brunfc0421f2012-09-07 17:30:07 +02003668#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003669 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003670 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3671 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003672 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003673 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003674 }
3675#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003676 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003677 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003678 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003679 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003680 SSL_CTX_up_ref(ctx);
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003681 bind_conf->default_inst = ckch_inst;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003682 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003683
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003684 /* Always keep a reference to the newly constructed SSL_CTX in the
3685 * instance. This way if the instance has no SNIs, the SSL_CTX will
3686 * still be linked. */
3687 SSL_CTX_up_ref(ctx);
3688 ckch_inst->ctx = ctx;
3689
William Lallemand9117de92019-10-04 00:29:42 +02003690 /* everything succeed, the ckch instance can be used */
3691 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003692 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003693 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003694
William Lallemand02e19a52020-04-08 16:11:26 +02003695 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3696
Emeric Brun054563d2019-10-17 13:16:58 +02003697 *ckchi = ckch_inst;
3698 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003699
3700error:
3701 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003702 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003703 if (ckch_inst->is_default)
3704 SSL_CTX_free(ctx);
3705
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003706 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003707 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003708 }
William Lallemandd9199372019-10-04 15:37:05 +02003709 SSL_CTX_free(ctx);
3710
Emeric Brun054563d2019-10-17 13:16:58 +02003711 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003712}
3713
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003714
3715/*
3716 * This function allocate a ckch_inst that will be used on the backend side
3717 * (server line)
3718 *
3719 * Returns a bitfield containing the flags:
3720 * ERR_FATAL in any fatal error case
3721 * ERR_ALERT if the reason of the error is available in err
3722 * ERR_WARN if a warning is available into err
3723 */
3724int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01003725 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003726{
3727 SSL_CTX *ctx;
William Lallemand52ddd992022-11-22 11:51:53 +01003728 struct ckch_data *data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003729 struct ckch_inst *ckch_inst = NULL;
3730 int errcode = 0;
3731
3732 *ckchi = NULL;
3733
William Lallemand52ddd992022-11-22 11:51:53 +01003734 if (!ckchs || !ckchs->data)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003735 return ERR_FATAL;
3736
William Lallemand52ddd992022-11-22 11:51:53 +01003737 data = ckchs->data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003738
3739 ctx = SSL_CTX_new(SSLv23_client_method());
3740 if (!ctx) {
3741 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3742 err && *err ? *err : "", path);
3743 errcode |= ERR_ALERT | ERR_FATAL;
3744 goto error;
3745 }
3746
William Lallemand52ddd992022-11-22 11:51:53 +01003747 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, data, ctx, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003748 if (errcode & ERR_CODE)
3749 goto error;
3750
3751 ckch_inst = ckch_inst_new();
3752 if (!ckch_inst) {
3753 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3754 err && *err ? *err : "", path);
3755 errcode |= ERR_ALERT | ERR_FATAL;
3756 goto error;
3757 }
3758
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003759 /* everything succeed, the ckch instance can be used */
3760 ckch_inst->bind_conf = NULL;
3761 ckch_inst->ssl_conf = NULL;
3762 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01003763 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003764 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003765
3766 *ckchi = ckch_inst;
3767 return errcode;
3768
3769error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003770 SSL_CTX_free(ctx);
3771
3772 return errcode;
3773}
3774
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003775/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003776static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3777 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003778 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003779{
Emeric Brun054563d2019-10-17 13:16:58 +02003780 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003781
3782 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003783 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 +02003784
Emeric Brun054563d2019-10-17 13:16:58 +02003785 if (errcode & ERR_CODE)
3786 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003787
William Lallemand24bde432020-03-09 16:48:43 +01003788 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003789
3790 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003791 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003792 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003793}
3794
William Lallemanddb26e2b2021-01-26 12:01:46 +01003795/* This function generates a <struct ckch_inst *> for a <struct server *>, and
3796 * fill the SSL_CTX of the server.
3797 *
3798 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003799static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01003800 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003801{
3802 int errcode = 0;
3803
3804 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01003805 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003806
3807 if (errcode & ERR_CODE)
3808 return errcode;
3809
William Lallemanddb26e2b2021-01-26 12:01:46 +01003810 (*ckch_inst)->server = server;
3811 /* Keep the reference to the SSL_CTX in the server. */
3812 SSL_CTX_up_ref((*ckch_inst)->ctx);
3813 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003814 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003815 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003816 return errcode;
3817}
3818
William Lallemand6be66ec2020-03-06 22:26:32 +01003819
William Lallemand4c68bba2020-03-30 18:45:10 +02003820
3821
3822/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3823 * done once. Zero is returned if the operation fails. No error is returned
3824 * if the random is said as not implemented, because we expect that openssl
3825 * will use another method once needed.
3826 */
Amaury Denoyellec593bcd2021-05-19 15:35:29 +02003827int ssl_initialize_random(void)
William Lallemand4c68bba2020-03-30 18:45:10 +02003828{
3829 unsigned char random;
3830 static int random_initialized = 0;
3831
3832 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3833 random_initialized = 1;
3834
3835 return random_initialized;
3836}
3837
William Lallemand2954c472020-03-06 21:54:13 +01003838/* Load a crt-list file, this is done in 2 parts:
3839 * - store the content of the file in a crtlist structure with crtlist_entry structures
3840 * - generate the instances by iterating on entries in the crtlist struct
3841 *
3842 * Nothing is locked there, this function is used in the configuration parser.
3843 *
3844 * Returns a set of ERR_* flags possibly with an error in <err>.
3845 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003846int 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 +01003847{
3848 struct crtlist *crtlist = NULL;
3849 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003850 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003851 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003852 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003853 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003854
William Lallemand79d31ec2020-03-25 15:10:49 +01003855 bind_conf_node = malloc(sizeof(*bind_conf_node));
3856 if (!bind_conf_node) {
3857 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3858 cfgerr |= ERR_FATAL | ERR_ALERT;
3859 goto error;
3860 }
3861 bind_conf_node->next = NULL;
3862 bind_conf_node->bind_conf = bind_conf;
3863
William Lallemand41ca9302020-04-08 13:15:18 +02003864 /* strip trailing slashes, including first one */
3865 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3866 *end = 0;
3867
William Lallemand2954c472020-03-06 21:54:13 +01003868 /* look for an existing crtlist or create one */
3869 eb = ebst_lookup(&crtlists_tree, file);
3870 if (eb) {
3871 crtlist = ebmb_entry(eb, struct crtlist, node);
3872 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003873 /* load a crt-list OR a directory */
3874 if (dir)
3875 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3876 else
3877 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3878
William Lallemand2954c472020-03-06 21:54:13 +01003879 if (!(cfgerr & ERR_CODE))
3880 ebst_insert(&crtlists_tree, &crtlist->node);
3881 }
3882
3883 if (cfgerr & ERR_CODE) {
3884 cfgerr |= ERR_FATAL | ERR_ALERT;
3885 goto error;
3886 }
3887
3888 /* generates ckch instance from the crtlist_entry */
3889 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3890 struct ckch_store *store;
3891 struct ckch_inst *ckch_inst = NULL;
3892
3893 store = entry->node.key;
3894 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3895 if (cfgerr & ERR_CODE) {
3896 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3897 goto error;
3898 }
Willy Tarreau2b718102021-04-21 07:32:39 +02003899 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003900 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003901 }
William Lallemand2954c472020-03-06 21:54:13 +01003902
William Lallemand79d31ec2020-03-25 15:10:49 +01003903 /* add the bind_conf to the list */
3904 bind_conf_node->next = crtlist->bind_conf;
3905 crtlist->bind_conf = bind_conf_node;
3906
William Lallemand2954c472020-03-06 21:54:13 +01003907 return cfgerr;
3908error:
3909 {
William Lallemand49398312020-03-30 17:01:33 +02003910 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003911 struct ckch_inst *inst, *s_inst;
3912
William Lallemand49398312020-03-30 17:01:33 +02003913 lastentry = entry; /* which entry we tried to generate last */
3914 if (lastentry) {
3915 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3916 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3917 break;
3918
3919 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003920
William Lallemand49398312020-03-30 17:01:33 +02003921 /* this was not generated for this bind_conf, skip */
3922 if (inst->bind_conf != bind_conf)
3923 continue;
3924
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003925 /* free the sni_ctx and instance */
3926 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003927 }
William Lallemand2954c472020-03-06 21:54:13 +01003928 }
William Lallemand2954c472020-03-06 21:54:13 +01003929 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003930 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003931 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003932 return cfgerr;
3933}
3934
William Lallemand06b22a82020-03-16 14:45:55 +01003935/* Returns a set of ERR_* flags possibly with an error in <err>. */
3936int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3937{
3938 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01003939 int cfgerr = 0;
3940 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003941 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01003942 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01003943
3944 if ((ckchs = ckchs_lookup(path))) {
3945 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01003946 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3947 found++;
3948 } else if (stat(path, &buf) == 0) {
3949 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01003950 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003951 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003952 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003953 cfgerr |= ERR_ALERT | ERR_FATAL;
3954 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003955 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01003956 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003957 }
3958 } else {
3959 /* stat failed, could be a bundle */
3960 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02003961 char fp[MAXPATHLEN+1] = {0};
3962 int n = 0;
3963
3964 /* Load all possible certs and keys in separate ckch_store */
3965 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3966 struct stat buf;
3967 int ret;
3968
3969 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3970 if (ret > sizeof(fp))
3971 continue;
3972
3973 if ((ckchs = ckchs_lookup(fp))) {
3974 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01003975 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02003976 } else {
3977 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01003978 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003979 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02003980 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003981 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02003982 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3983 }
3984 }
3985 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01003986#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
3987 if (found) {
3988 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
3989 err && *err ? *err : "", path);
3990 cfgerr |= ERR_ALERT | ERR_FATAL;
3991 }
3992#endif
William Lallemand06b22a82020-03-16 14:45:55 +01003993 }
3994 }
William Lallemand06ce84a2020-11-20 15:36:13 +01003995 if (!found) {
3996 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3997 err && *err ? *err : "", path, strerror(errno));
3998 cfgerr |= ERR_ALERT | ERR_FATAL;
3999 }
William Lallemand06b22a82020-03-16 14:45:55 +01004000
4001 return cfgerr;
4002}
4003
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004004
4005/* Create a full ssl context and ckch instance that will be used for a specific
4006 * backend server (server configuration line).
4007 * Returns a set of ERR_* flags possibly with an error in <err>.
4008 */
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004009int 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 +01004010{
4011 struct stat buf;
4012 int cfgerr = 0;
4013 struct ckch_store *ckchs;
4014 int found = 0; /* did we found a file to load ? */
4015
4016 if ((ckchs = ckchs_lookup(path))) {
4017 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01004018 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004019 found++;
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004020 } else {
4021 if (!create_if_none) {
4022 memprintf(err, "%sunable to stat SSL certificate '%s'.\n",
4023 err && *err ? *err : "", path);
4024 cfgerr |= ERR_ALERT | ERR_FATAL;
4025 goto out;
4026 }
4027
4028 if (stat(path, &buf) == 0) {
4029 /* We do not manage directories on backend side. */
4030 if (S_ISDIR(buf.st_mode) == 0) {
4031 ++found;
4032 ckchs = ckchs_load_cert_file(path, err);
4033 if (!ckchs)
4034 cfgerr |= ERR_ALERT | ERR_FATAL;
4035 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
4036 }
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004037 }
4038 }
4039 if (!found) {
4040 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
4041 err && *err ? *err : "", path, strerror(errno));
4042 cfgerr |= ERR_ALERT | ERR_FATAL;
4043 }
4044
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004045out:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004046 return cfgerr;
4047}
4048
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004049/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004050static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004051ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004052{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004053 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004054 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004055 SSL_OP_ALL | /* all known workarounds for bugs */
4056 SSL_OP_NO_SSLv2 |
4057 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02004058 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02004059 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004060 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02004061 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004062 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004063 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004064 SSL_MODE_ENABLE_PARTIAL_WRITE |
4065 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004066 SSL_MODE_RELEASE_BUFFERS |
4067 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004068 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004069 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004070 int flags = MC_SSL_O_ALL;
4071 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02004072 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004073
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004074 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004075 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004076
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004077 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004078 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
4079 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4080 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004081 else
4082 flags = conf_ssl_methods->flags;
4083
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004084 min = conf_ssl_methods->min;
4085 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02004086
4087 /* default minimum is TLSV12, */
4088 if (!min) {
4089 if (!max || (max >= default_min_ver)) {
4090 min = default_min_ver;
4091 } else {
4092 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). "
4093 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
4094 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
4095 min = max;
4096 }
4097 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004098 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004099 if (min)
4100 flags |= (methodVersions[min].flag - 1);
4101 if (max)
4102 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004103 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004104 min = max = CONF_TLSV_NONE;
4105 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004106 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004107 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004108 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004109 if (min) {
4110 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004111 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
4112 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4113 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
4114 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004115 hole = 0;
4116 }
4117 max = i;
4118 }
4119 else {
4120 min = max = i;
4121 }
4122 }
4123 else {
4124 if (min)
4125 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004126 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004127 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004128 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4129 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004130 cfgerr += 1;
4131 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004132 /* save real min/max in bind_conf */
4133 conf_ssl_methods->min = min;
4134 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004135
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004136#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004137 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004138 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004139 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004140 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004141 else
William Lallemandd0712f32020-06-11 17:34:00 +02004142 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
4143 /* clear every version flags in case SSL_CTX_new()
4144 * returns an SSL_CTX with disabled versions */
4145 SSL_CTX_clear_options(ctx, methodVersions[i].option);
4146
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004147 if (flags & methodVersions[i].flag)
4148 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02004149
4150 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004151#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004152 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004153 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4154 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02004155#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004156
4157 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
4158 options |= SSL_OP_NO_TICKET;
4159 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
4160 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08004161
4162#ifdef SSL_OP_NO_RENEGOTIATION
4163 options |= SSL_OP_NO_RENEGOTIATION;
4164#endif
4165
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004166 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004167
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004168#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004169 if (global_ssl.async)
4170 mode |= SSL_MODE_ASYNC;
4171#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004172 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004173 if (global_ssl.life_time)
4174 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004175
4176#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand4b7938d2022-09-07 10:54:17 +02004177# ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004178 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
4179 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004180# elif defined(HAVE_SSL_CLIENT_HELLO_CB)
4181# if defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01004182 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01004183 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
William Lallemand4b7938d2022-09-07 10:54:17 +02004184# endif /* ! SSL_OP_NO_ANTI_REPLAY */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02004185 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
4186 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004187# else /* ! OPENSSL_IS_BORINGSSL && ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004188 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004189# endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02004190 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
William Lallemand4b7938d2022-09-07 10:54:17 +02004191#endif /* ! SSL_CTRL_SET_TLSEXT_HOSTNAME */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004192 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004193}
4194
William Lallemand4f45bb92017-10-30 20:08:51 +01004195
4196static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
4197{
4198 if (first == block) {
4199 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4200 if (first->len > 0)
4201 sh_ssl_sess_tree_delete(sh_ssl_sess);
4202 }
4203}
4204
4205/* return first block from sh_ssl_sess */
4206static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
4207{
Ilya Shipitsin2ca01582023-04-15 23:39:43 +02004208 return (struct shared_block *)((unsigned char *)sh_ssl_sess - offsetof(struct shared_block, data));
William Lallemand4f45bb92017-10-30 20:08:51 +01004209
4210}
4211
4212/* store a session into the cache
4213 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
4214 * data: asn1 encoded session
4215 * data_len: asn1 encoded session length
4216 * Returns 1 id session was stored (else 0)
4217 */
4218static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
4219{
4220 struct shared_block *first;
4221 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
4222
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004223 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01004224 if (!first) {
4225 /* Could not retrieve enough free blocks to store that session */
4226 return 0;
4227 }
4228
4229 /* STORE the key in the first elem */
4230 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4231 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
4232 first->len = sizeof(struct sh_ssl_sess_hdr);
4233
4234 /* it returns the already existing node
4235 or current node if none, never returns null */
4236 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
4237 if (oldsh_ssl_sess != sh_ssl_sess) {
4238 /* NOTE: Row couldn't be in use because we lock read & write function */
4239 /* release the reserved row */
William Lallemand222e5a22023-01-31 14:12:28 +01004240 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 +01004241 shctx_row_dec_hot(ssl_shctx, first);
4242 /* replace the previous session already in the tree */
4243 sh_ssl_sess = oldsh_ssl_sess;
4244 /* ignore the previous session data, only use the header */
4245 first = sh_ssl_sess_first_block(sh_ssl_sess);
4246 shctx_row_inc_hot(ssl_shctx, first);
4247 first->len = sizeof(struct sh_ssl_sess_hdr);
4248 }
4249
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004250 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01004251 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004252 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01004253 }
4254
4255 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004256
4257 return 1;
4258}
William Lallemanded0b5ad2017-10-30 19:36:36 +01004259
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004260/* SSL callback used when a new session is created while connecting to a server */
4261static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4262{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004263 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004264 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004265
Willy Tarreau07d94e42018-09-20 10:57:52 +02004266 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004267
William Lallemand3ce6eed2021-02-08 10:43:44 +01004268 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4269 * one cache per thread, it only prevents to flush it from the CLI in
4270 * another thread */
4271
Olivier Houcharde6060c52017-11-16 17:42:52 +01004272 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4273 int len;
4274 unsigned char *ptr;
William Lallemande18d4e82021-11-17 02:59:21 +01004275 const char *sni;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004276
Olivier Houcharde6060c52017-11-16 17:42:52 +01004277 len = i2d_SSL_SESSION(sess, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01004278 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004279 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004280 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4281 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4282 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004283 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
4284 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004285 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4286 }
4287 if (s->ssl_ctx.reused_sess[tid].ptr) {
4288 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4289 &ptr);
4290 }
William Lallemande18d4e82021-11-17 02:59:21 +01004291
4292 if (s->ssl_ctx.reused_sess[tid].sni) {
4293 /* if the new sni is empty or isn' t the same as the old one */
4294 if ((!sni) || strcmp(s->ssl_ctx.reused_sess[tid].sni, sni) != 0) {
4295 ha_free(&s->ssl_ctx.reused_sess[tid].sni);
4296 if (sni)
4297 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4298 }
4299 } else if (sni) {
4300 /* if there wasn't an old sni but there is a new one */
4301 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4302 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004303 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004304 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004305 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004306 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004307 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004308 }
4309
4310 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004311}
4312
Olivier Houcharde6060c52017-11-16 17:42:52 +01004313
William Lallemanded0b5ad2017-10-30 19:36:36 +01004314/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004315int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004316{
4317 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4318 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4319 unsigned char *p;
4320 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004321 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004322 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004323
4324 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004325 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004326 * note: SSL_SESSION_set1_id is using
4327 * a memcpy so we need to use a different pointer
4328 * than sid_data or sid_ctx_data to avoid valgrind
4329 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004330 */
4331
4332 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004333
4334 /* copy value in an other buffer */
4335 memcpy(encid, sid_data, sid_length);
4336
4337 /* pad with 0 */
4338 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4339 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4340
4341 /* force length to zero to avoid ASN1 encoding */
4342 SSL_SESSION_set1_id(sess, encid, 0);
4343
4344 /* force length to zero to avoid ASN1 encoding */
4345 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004346
4347 /* check if buffer is large enough for the ASN1 encoded session */
4348 data_len = i2d_SSL_SESSION(sess, NULL);
4349 if (data_len > SHSESS_MAX_DATA_LEN)
4350 goto err;
4351
4352 p = encsess;
4353
4354 /* process ASN1 session encoding before the lock */
4355 i2d_SSL_SESSION(sess, &p);
4356
William Lallemanded0b5ad2017-10-30 19:36:36 +01004357
William Lallemanda3c77cf2017-10-30 23:44:40 +01004358 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004359 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004360 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004361 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004362err:
4363 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004364 SSL_SESSION_set1_id(sess, encid, sid_length);
4365 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004366
4367 return 0; /* do not increment session reference count */
4368}
4369
4370/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004371SSL_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 +01004372{
William Lallemand4f45bb92017-10-30 20:08:51 +01004373 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004374 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4375 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004376 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004377 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004378
Willy Tarreau4c19e992021-06-15 16:39:22 +02004379 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004380
4381 /* allow the session to be freed automatically by openssl */
4382 *do_copy = 0;
4383
4384 /* tree key is zeros padded sessionid */
4385 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4386 memcpy(tmpkey, key, key_len);
4387 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4388 key = tmpkey;
4389 }
4390
4391 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004392 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004393
4394 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004395 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4396 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004397 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004398 shctx_unlock(ssl_shctx);
Willy Tarreau4c19e992021-06-15 16:39:22 +02004399 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004400 return NULL;
4401 }
4402
William Lallemand4f45bb92017-10-30 20:08:51 +01004403 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4404 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004405
William Lallemand4f45bb92017-10-30 20:08:51 +01004406 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 +01004407
William Lallemanda3c77cf2017-10-30 23:44:40 +01004408 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004409
4410 /* decode ASN1 session */
4411 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004412 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004413 /* Reset session id and session id contenxt */
4414 if (sess) {
4415 SSL_SESSION_set1_id(sess, key, key_len);
4416 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4417 }
4418
4419 return sess;
4420}
4421
William Lallemand4f45bb92017-10-30 20:08:51 +01004422
William Lallemanded0b5ad2017-10-30 19:36:36 +01004423/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004424void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004425{
William Lallemand4f45bb92017-10-30 20:08:51 +01004426 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004427 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4428 unsigned int sid_length;
4429 const unsigned char *sid_data;
4430 (void)ctx;
4431
4432 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4433 /* tree key is zeros padded sessionid */
4434 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4435 memcpy(tmpkey, sid_data, sid_length);
4436 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4437 sid_data = tmpkey;
4438 }
4439
William Lallemanda3c77cf2017-10-30 23:44:40 +01004440 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004441
4442 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004443 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4444 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004445 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004446 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004447 }
4448
4449 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004450 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004451}
4452
4453/* Set session cache mode to server and disable openssl internal cache.
4454 * Set shared cache callbacks on an ssl context.
4455 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004456void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004457{
4458 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4459
4460 if (!ssl_shctx) {
4461 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4462 return;
4463 }
4464
4465 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4466 SSL_SESS_CACHE_NO_INTERNAL |
4467 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4468
4469 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004470 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4471 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4472 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004473}
William Lallemand7d42ef52020-07-06 11:41:30 +02004474
4475/*
4476 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4477 *
4478 * The format is:
4479 * * <Label> <space> <ClientRandom> <space> <Secret>
4480 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4481 */
4482
William Lallemand722180a2021-06-09 16:46:12 +02004483#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004484void SSL_CTX_keylog(const SSL *ssl, const char *line)
4485{
4486 struct ssl_keylog *keylog;
4487 char *lastarg = NULL;
4488 char *dst = NULL;
4489
4490 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4491 if (!keylog)
4492 return;
4493
4494 lastarg = strrchr(line, ' ');
4495 if (lastarg == NULL || ++lastarg == NULL)
4496 return;
4497
4498 dst = pool_alloc(pool_head_ssl_keylog_str);
4499 if (!dst)
4500 return;
4501
4502 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4503 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4504
4505 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4506 if (keylog->client_random)
4507 goto error;
4508 keylog->client_random = dst;
4509
4510 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4511 if (keylog->client_early_traffic_secret)
4512 goto error;
4513 keylog->client_early_traffic_secret = dst;
4514
4515 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4516 if(keylog->client_handshake_traffic_secret)
4517 goto error;
4518 keylog->client_handshake_traffic_secret = dst;
4519
4520 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4521 if (keylog->server_handshake_traffic_secret)
4522 goto error;
4523 keylog->server_handshake_traffic_secret = dst;
4524
4525 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4526 if (keylog->client_traffic_secret_0)
4527 goto error;
4528 keylog->client_traffic_secret_0 = dst;
4529
4530 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4531 if (keylog->server_traffic_secret_0)
4532 goto error;
4533 keylog->server_traffic_secret_0 = dst;
4534
4535 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4536 if (keylog->early_exporter_secret)
4537 goto error;
4538 keylog->early_exporter_secret = dst;
4539
4540 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4541 if (keylog->exporter_secret)
4542 goto error;
4543 keylog->exporter_secret = dst;
4544 } else {
4545 goto error;
4546 }
4547
4548 return;
4549
4550error:
4551 pool_free(pool_head_ssl_keylog_str, dst);
4552
4553 return;
4554}
4555#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004556
William Lallemand8b453912019-11-21 15:48:10 +01004557/*
4558 * This function applies the SSL configuration on a SSL_CTX
4559 * It returns an error code and fills the <err> buffer
4560 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004561static 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 +01004562{
4563 struct proxy *curproxy = bind_conf->frontend;
4564 int cfgerr = 0;
4565 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004566 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004567 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004568#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004569 const char *conf_ciphersuites;
4570#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004571 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004572
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004573 if (ssl_conf) {
4574 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4575 int i, min, max;
4576 int flags = MC_SSL_O_ALL;
4577
4578 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004579 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4580 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004581 if (min)
4582 flags |= (methodVersions[min].flag - 1);
4583 if (max)
4584 flags |= ~((methodVersions[max].flag << 1) - 1);
4585 min = max = CONF_TLSV_NONE;
4586 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4587 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4588 if (min)
4589 max = i;
4590 else
4591 min = max = i;
4592 }
4593 /* save real min/max */
4594 conf_ssl_methods->min = min;
4595 conf_ssl_methods->max = max;
4596 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004597 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4598 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004599 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004600 }
4601 }
4602
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004603 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004604 case SSL_SOCK_VERIFY_NONE:
4605 verify = SSL_VERIFY_NONE;
4606 break;
4607 case SSL_SOCK_VERIFY_OPTIONAL:
4608 verify = SSL_VERIFY_PEER;
4609 break;
4610 case SSL_SOCK_VERIFY_REQUIRED:
4611 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4612 break;
4613 }
4614 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4615 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004616 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 +01004617 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 +01004618 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 +01004619 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004620 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004621 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004622 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004623 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004624 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004625 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004626 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4627 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4628 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4629 cfgerr |= ERR_ALERT | ERR_FATAL;
4630 }
4631 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004632 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004633 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 +02004634 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004635 }
Emeric Brun850efd52014-01-29 12:24:34 +01004636 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004637 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4638 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004639 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004640 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004641#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004642 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004643 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4644
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004645 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004646 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4647 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004648 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004649 }
Emeric Brun561e5742012-10-02 15:20:55 +02004650 else {
4651 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4652 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004653 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004654#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004655 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004656 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004657#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004658 if(bind_conf->keys_ref) {
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +01004659 if (!SSL_CTX_set_tlsext_ticket_key_evp_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004660 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4661 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004662 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004663 }
4664 }
4665#endif
4666
William Lallemand4f45bb92017-10-30 20:08:51 +01004667 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004668 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4669 if (conf_ciphers &&
4670 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004671 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4672 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004673 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004674 }
4675
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004676#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004677 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4678 if (conf_ciphersuites &&
4679 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004680 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4681 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004682 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004683 }
4684#endif
4685
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004686#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02004687 if (!local_dh_1024)
4688 local_dh_1024 = ssl_get_dh_1024();
4689 if (!local_dh_2048)
4690 local_dh_2048 = ssl_get_dh_2048();
4691 if (!local_dh_4096)
4692 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02004693#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004694
Emeric Brunfc0421f2012-09-07 17:30:07 +02004695 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004696#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004697 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004698#endif
William Lallemand722180a2021-06-09 16:46:12 +02004699#ifdef HAVE_SSL_KEYLOG
William Lallemandb60a77b2022-11-18 15:00:15 +01004700 /* only activate the keylog callback if it was required to prevent performance loss */
4701 if (global_ssl.keylog > 0)
4702 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02004703#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004704
Bernard Spil13c53f82018-02-15 13:34:58 +01004705#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004706 ssl_conf_cur = NULL;
4707 if (ssl_conf && ssl_conf->npn_str)
4708 ssl_conf_cur = ssl_conf;
4709 else if (bind_conf->ssl_conf.npn_str)
4710 ssl_conf_cur = &bind_conf->ssl_conf;
4711 if (ssl_conf_cur)
4712 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004713#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004714#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004715 ssl_conf_cur = NULL;
4716 if (ssl_conf && ssl_conf->alpn_str)
4717 ssl_conf_cur = ssl_conf;
4718 else if (bind_conf->ssl_conf.alpn_str)
4719 ssl_conf_cur = &bind_conf->ssl_conf;
Willy Tarreaua2a09552023-04-19 09:05:49 +02004720 if (ssl_conf_cur && ssl_conf_cur->alpn_len)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004721 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004722#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004723#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004724 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4725 if (conf_curves) {
4726 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004727 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4728 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004729 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004730 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004731 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004732 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004733#endif /* defined(SSL_CTX_set1_curves_list) */
4734
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004735 if (!conf_curves) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004736#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004737#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004738 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004739 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4740 NULL);
4741
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004742 if (ecdhe && SSL_CTX_set1_curves_list(ctx, ecdhe) == 0) {
4743 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4744 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
4745 cfgerr |= ERR_ALERT | ERR_FATAL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02004746 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004747#endif /* defined(SSL_CTX_set1_curves_list) */
Olivier Houchardc2aae742017-09-22 18:26:28 +02004748#else
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004749#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
4750 int i;
4751 EC_KEY *ecdh;
4752
Olivier Houchardc2aae742017-09-22 18:26:28 +02004753 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4754 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4755 ECDHE_DEFAULT_CURVE);
Emeric Brun2b58d042012-09-20 17:10:03 +02004756
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004757 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004758 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004759 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 +01004760 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004761 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004762 }
4763 else {
4764 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4765 EC_KEY_free(ecdh);
4766 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004767#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
4768#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Emeric Brun2b58d042012-09-20 17:10:03 +02004769 }
Emeric Brun2b58d042012-09-20 17:10:03 +02004770
Emeric Brunfc0421f2012-09-07 17:30:07 +02004771 return cfgerr;
4772}
4773
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004774
4775/*
4776 * Prepare the SSL_CTX based on the bind line configuration.
4777 * Since the CA file loading is made depending on the verify option of the bind
4778 * line, the link between the SSL_CTX and the CA file tree entry is made here.
4779 * If we want to create a link between the CA file entry and the corresponding
4780 * ckch instance (for CA file hot update), it needs to be done after
4781 * ssl_sock_prepare_ctx.
4782 * Returns 0 in case of success.
4783 */
4784int ssl_sock_prep_ctx_and_inst(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
4785 SSL_CTX *ctx, struct ckch_inst *ckch_inst, char **err)
4786{
4787 int errcode = 0;
4788
4789 errcode |= ssl_sock_prepare_ctx(bind_conf, ssl_conf, ctx, err);
4790 if (!errcode && ckch_inst)
4791 ckch_inst_add_cafile_link(ckch_inst, bind_conf, ssl_conf, NULL);
4792
4793 return errcode;
4794}
4795
Evan Broderbe554312013-06-27 00:05:25 -07004796static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4797{
4798 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4799 size_t prefixlen, suffixlen;
4800
4801 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004802 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004803 return 1;
4804
Evan Broderbe554312013-06-27 00:05:25 -07004805 /* The rest of this logic is based on RFC 6125, section 6.4.3
4806 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4807
Emeric Bruna848dae2013-10-08 11:27:28 +02004808 pattern_wildcard = NULL;
4809 pattern_left_label_end = pattern;
4810 while (*pattern_left_label_end != '.') {
4811 switch (*pattern_left_label_end) {
4812 case 0:
4813 /* End of label not found */
4814 return 0;
4815 case '*':
4816 /* If there is more than one wildcards */
4817 if (pattern_wildcard)
4818 return 0;
4819 pattern_wildcard = pattern_left_label_end;
4820 break;
4821 }
4822 pattern_left_label_end++;
4823 }
4824
4825 /* If it's not trivial and there is no wildcard, it can't
4826 * match */
4827 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004828 return 0;
4829
4830 /* Make sure all labels match except the leftmost */
4831 hostname_left_label_end = strchr(hostname, '.');
4832 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004833 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004834 return 0;
4835
4836 /* Make sure the leftmost label of the hostname is long enough
4837 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004838 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004839 return 0;
4840
4841 /* Finally compare the string on either side of the
4842 * wildcard */
4843 prefixlen = pattern_wildcard - pattern;
4844 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004845 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4846 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004847 return 0;
4848
4849 return 1;
4850}
4851
4852static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4853{
4854 SSL *ssl;
4855 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004856 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004857 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004858 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004859
4860 int depth;
4861 X509 *cert;
4862 STACK_OF(GENERAL_NAME) *alt_names;
4863 int i;
4864 X509_NAME *cert_subject;
4865 char *str;
4866
4867 if (ok == 0)
4868 return ok;
4869
4870 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004871 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02004872 ssl_ctx = __conn_get_ssl_sock_ctx(conn);
Evan Broderbe554312013-06-27 00:05:25 -07004873
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004874 /* We're checking if the provided hostnames match the desired one. The
4875 * desired hostname comes from the SNI we presented if any, or if not
4876 * provided then it may have been explicitly stated using a "verifyhost"
4877 * directive. If neither is set, we don't care about the name so the
4878 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004879 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004880 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004881 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004882 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004883 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004884 if (!servername)
4885 return ok;
4886 }
Evan Broderbe554312013-06-27 00:05:25 -07004887
4888 /* We only need to verify the CN on the actual server cert,
4889 * not the indirect CAs */
4890 depth = X509_STORE_CTX_get_error_depth(ctx);
4891 if (depth != 0)
4892 return ok;
4893
4894 /* At this point, the cert is *not* OK unless we can find a
4895 * hostname match */
4896 ok = 0;
4897
4898 cert = X509_STORE_CTX_get_current_cert(ctx);
4899 /* It seems like this might happen if verify peer isn't set */
4900 if (!cert)
4901 return ok;
4902
4903 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4904 if (alt_names) {
4905 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4906 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4907 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004908#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004909 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4910#else
Evan Broderbe554312013-06-27 00:05:25 -07004911 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004912#endif
Evan Broderbe554312013-06-27 00:05:25 -07004913 ok = ssl_sock_srv_hostcheck(str, servername);
4914 OPENSSL_free(str);
4915 }
4916 }
4917 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004918 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004919 }
4920
4921 cert_subject = X509_get_subject_name(cert);
4922 i = -1;
4923 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4924 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004925 ASN1_STRING *value;
4926 value = X509_NAME_ENTRY_get_data(entry);
4927 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004928 ok = ssl_sock_srv_hostcheck(str, servername);
4929 OPENSSL_free(str);
4930 }
4931 }
4932
Willy Tarreau71d058c2017-07-26 20:09:56 +02004933 /* report the mismatch and indicate if SNI was used or not */
4934 if (!ok && !conn->err_code)
4935 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004936 return ok;
4937}
4938
Emeric Brun94324a42012-10-11 14:00:19 +02004939/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004940int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004941{
4942 int cfgerr = 0;
William Lallemand2c776f12021-12-28 18:47:17 +01004943 SSL_CTX *ctx;
William Lallemand0adafb32022-12-13 18:17:44 +01004944 /* Automatic memory computations need to know we use SSL there
4945 * If this is an internal proxy, don't use it for the computation */
William Lallemand04007cb2022-12-14 10:34:36 +01004946 if (!(srv->proxy->cap & PR_CAP_INT))
William Lallemand0adafb32022-12-13 18:17:44 +01004947 global.ssl_used_backend = 1;
Willy Tarreaufce03112015-01-15 21:32:40 +01004948
4949 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004950 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004951 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004952 ha_alert("out of memory.\n");
Emeric Brun821bb9b2017-06-15 16:37:39 +02004953 cfgerr++;
4954 return cfgerr;
4955 }
4956 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004957 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004958 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004959
William Lallemand2c776f12021-12-28 18:47:17 +01004960 if (srv->ssl_ctx.client_crt) {
4961 const int create_if_none = srv->flags & SRV_F_DYNAMIC ? 0 : 1;
4962 char *err = NULL;
4963 int err_code = 0;
4964
4965 /* If there is a crt keyword there, the SSL_CTX will be created here. */
4966 err_code = ssl_sock_load_srv_cert(srv->ssl_ctx.client_crt, srv, create_if_none, &err);
4967 if (err_code != ERR_NONE) {
4968 if ((err_code & ERR_WARN) && !(err_code & ERR_ALERT))
4969 ha_warning("%s", err);
4970 else
4971 ha_alert("%s", err);
4972
4973 if (err_code & (ERR_FATAL|ERR_ABORT))
4974 cfgerr++;
4975 }
4976 ha_free(&err);
4977 }
4978
4979 ctx = srv->ssl_ctx.ctx;
4980
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004981 /* The context will be uninitialized if there wasn't any "cert" option
4982 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004983 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004984 ctx = SSL_CTX_new(SSLv23_client_method());
4985 if (!ctx) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004986 ha_alert("unable to allocate ssl context.\n");
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004987 cfgerr++;
4988 return cfgerr;
4989 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004990
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004991 srv->ssl_ctx.ctx = ctx;
4992 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004993
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004994 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 +01004995
4996 return cfgerr;
4997}
4998
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004999/* Initialize an SSL context that will be used on the backend side.
5000 * Returns an error count.
5001 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005002static int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005003{
5004 struct proxy *curproxy = srv->proxy;
5005 int cfgerr = 0;
5006 long options =
5007 SSL_OP_ALL | /* all known workarounds for bugs */
5008 SSL_OP_NO_SSLv2 |
5009 SSL_OP_NO_COMPRESSION;
5010 long mode =
5011 SSL_MODE_ENABLE_PARTIAL_WRITE |
5012 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
5013 SSL_MODE_RELEASE_BUFFERS |
5014 SSL_MODE_SMALL_BUFFERS;
5015 int verify = SSL_VERIFY_NONE;
5016 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
5017 int i, min, max, hole;
5018 int flags = MC_SSL_O_ALL;
5019
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005020 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005021 ha_warning("no-sslv3/no-tlsv1x are ignored for this server. "
5022 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n");
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005023 else
5024 flags = conf_ssl_methods->flags;
5025
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005026 /* Real min and max should be determinate with configuration and openssl's capabilities */
5027 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005028 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005029 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005030 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005031
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005032 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005033 min = max = CONF_TLSV_NONE;
5034 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005035 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005036 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005037 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005038 if (min) {
5039 if (hole) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005040 ha_warning("%s '%s': SSL/TLS versions range not contiguous for server '%s'. "
Christopher Faulet767a84b2017-11-24 16:50:31 +01005041 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
5042 proxy_type_str(curproxy), curproxy->id, srv->id,
5043 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005044 hole = 0;
5045 }
5046 max = i;
5047 }
5048 else {
5049 min = max = i;
5050 }
5051 }
5052 else {
5053 if (min)
5054 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005055 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005056 if (!min) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005057 ha_alert("%s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01005058 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005059 cfgerr += 1;
5060 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005061
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005062#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005063 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08005064 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005065 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005066 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005067 else
5068 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
5069 if (flags & methodVersions[i].flag)
5070 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005071#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005072 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005073 methodVersions[min].ctx_set_version(ctx, SET_MIN);
5074 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005075#endif
5076
5077 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
5078 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005079 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005080
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005081#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005082 if (global_ssl.async)
5083 mode |= SSL_MODE_ASYNC;
5084#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005085 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005086
Emeric Brun850efd52014-01-29 12:24:34 +01005087 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
5088 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01005089 switch (srv->ssl_ctx.verify) {
5090 case SSL_SOCK_VERIFY_NONE:
5091 verify = SSL_VERIFY_NONE;
5092 break;
5093 case SSL_SOCK_VERIFY_REQUIRED:
5094 verify = SSL_VERIFY_PEER;
5095 break;
5096 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005097 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02005098 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01005099 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02005100 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02005101 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005102 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005103 ha_alert("unable to set CA file '%s'.\n",
5104 srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005105 cfgerr++;
5106 }
5107 }
Emeric Brun850efd52014-01-29 12:24:34 +01005108 else {
5109 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005110 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 +01005111 else
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005112 ha_alert("verify is enabled but no CA file specified.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01005113 cfgerr++;
5114 }
Emeric Brunef42d922012-10-11 16:11:36 +02005115#ifdef X509_V_FLAG_CRL_CHECK
5116 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005117 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02005118
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01005119 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005120 ha_alert("unable to configure CRL file '%s'.\n",
5121 srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005122 cfgerr++;
5123 }
5124 else {
5125 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5126 }
5127 }
5128#endif
5129 }
5130
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005131 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5132 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02005133 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005134 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005135 ha_alert("unable to set SSL cipher list to '%s'.\n",
5136 srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02005137 cfgerr++;
5138 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005139
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05005140#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005141 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005142 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005143 ha_alert("unable to set TLS 1.3 cipher suites to '%s'.\n",
5144 srv->ssl_ctx.ciphersuites);
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005145 cfgerr++;
5146 }
5147#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01005148#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
5149 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005150 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01005151#endif
5152#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreaua2a09552023-04-19 09:05:49 +02005153 if (srv->ssl_ctx.alpn_str && srv->ssl_ctx.alpn_len)
Olivier Houchardc7566002018-11-20 23:33:50 +01005154 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
5155#endif
5156
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005157
5158 return cfgerr;
5159}
5160
5161/*
5162 * Prepare the frontend's SSL_CTX based on the server line configuration.
5163 * Since the CA file loading is made depending on the verify option of the
5164 * server line, the link between the SSL_CTX and the CA file tree entry is
5165 * made here.
5166 * If we want to create a link between the CA file entry and the corresponding
5167 * ckch instance (for CA file hot update), it needs to be done after
5168 * ssl_sock_prepare_srv_ssl_ctx.
5169 * Returns an error count.
5170 */
5171int ssl_sock_prep_srv_ctx_and_inst(const struct server *srv, SSL_CTX *ctx,
5172 struct ckch_inst *ckch_inst)
5173{
5174 int cfgerr = 0;
5175
5176 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, ctx);
5177 if (!cfgerr && ckch_inst)
5178 ckch_inst_add_cafile_link(ckch_inst, NULL, NULL, srv);
Emeric Brun94324a42012-10-11 14:00:19 +02005179
5180 return cfgerr;
5181}
5182
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005183
Frédéric Lécailleec216522020-11-23 14:33:30 +01005184/*
5185 * Create an initial CTX used to start the SSL connections.
5186 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
5187 * Returns 0 if succeeded, or something >0 if not.
5188 */
5189#ifdef USE_QUIC
5190static int ssl_initial_ctx(struct bind_conf *bind_conf)
5191{
5192 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
5193 return ssl_quic_initial_ctx(bind_conf);
5194 else
5195 return ssl_sock_initial_ctx(bind_conf);
5196}
5197#else
5198static int ssl_initial_ctx(struct bind_conf *bind_conf)
5199{
5200 return ssl_sock_initial_ctx(bind_conf);
5201}
5202#endif
5203
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005204/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005205 * be NULL, in which case nothing is done. Returns the number of errors
5206 * encountered.
5207 */
Willy Tarreau03209342016-12-22 17:08:28 +01005208int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005209{
5210 struct ebmb_node *node;
5211 struct sni_ctx *sni;
5212 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01005213 int errcode = 0;
5214 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02005215
Willy Tarreaufce03112015-01-15 21:32:40 +01005216 /* Automatic memory computations need to know we use SSL there */
5217 global.ssl_used_frontend = 1;
5218
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005219 /* Create initial_ctx used to start the ssl connection before do switchctx */
5220 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01005221 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005222 /* It should not be necessary to call this function, but it's
5223 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01005224 to initial_ctx in ssl_initial_ctx. */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005225 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, NULL, bind_conf->initial_ctx, NULL, &errmsg);
5226 }
5227 if (bind_conf->default_ctx) {
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005228 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 +01005229 }
Emeric Brun0bed9942014-10-30 19:25:24 +01005230
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005231 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005232 while (node) {
5233 sni = ebmb_entry(node, struct sni_ctx, name);
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005234 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005235 /* only initialize the CTX on its first occurrence and
5236 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005237 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
5238 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005239 node = ebmb_next(node);
5240 }
5241
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005242 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005243 while (node) {
5244 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01005245 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005246 /* only initialize the CTX on its first occurrence and
5247 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005248 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005249 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005250 node = ebmb_next(node);
5251 }
William Lallemand8b453912019-11-21 15:48:10 +01005252
5253 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005254 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005255 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005256 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005257 err++;
5258 }
5259
5260 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005261 return err;
5262}
5263
Willy Tarreau55d37912016-12-21 23:38:39 +01005264/* Prepares all the contexts for a bind_conf and allocates the shared SSL
5265 * context if needed. Returns < 0 on error, 0 on success. The warnings and
5266 * alerts are directly emitted since the rest of the stack does it below.
5267 */
5268int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
5269{
5270 struct proxy *px = bind_conf->frontend;
5271 int alloc_ctx;
5272 int err;
5273
Willy Tarreau11ba4042022-05-20 15:56:32 +02005274 if (!(bind_conf->options & BC_O_USE_SSL)) {
Willy Tarreau55d37912016-12-21 23:38:39 +01005275 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005276 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
5277 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01005278 }
5279 return 0;
5280 }
5281 if (!bind_conf->default_ctx) {
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005282 if (bind_conf->strict_sni && !(bind_conf->options & BC_O_GENERATE_CERTS)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005283 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5284 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005285 }
5286 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005287 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5288 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005289 return -1;
5290 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005291 }
William Lallemandc61c0b32017-12-04 18:46:39 +01005292 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005293 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02005294 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
Willy Tarreau91358592021-06-15 08:08:04 +02005295 sizeof(*sh_ssl_sess_tree), (global.nbthread > 1));
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02005296 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005297 if (alloc_ctx == SHCTX_E_INIT_LOCK)
5298 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");
5299 else
5300 ha_alert("Unable to allocate SSL session cache.\n");
5301 return -1;
5302 }
5303 /* free block callback */
5304 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5305 /* init the root tree within the extra space */
5306 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5307 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01005308 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005309 err = 0;
5310 /* initialize all certificate contexts */
5311 err += ssl_sock_prepare_all_ctx(bind_conf);
5312
5313 /* initialize CA variables if the certificates generation is enabled */
5314 err += ssl_sock_load_ca(bind_conf);
5315
5316 return -err;
5317}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005318
William Lallemand231610a2021-12-30 11:25:43 +01005319/* release ssl context allocated for servers. Most of the field free here
5320 * must also be allocated in srv_ssl_settings_cpy() */
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005321void ssl_sock_free_srv_ctx(struct server *srv)
5322{
Olivier Houchardc7566002018-11-20 23:33:50 +01005323#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
William Lallemand231610a2021-12-30 11:25:43 +01005324 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005325#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005326#ifdef OPENSSL_NPN_NEGOTIATED
William Lallemand231610a2021-12-30 11:25:43 +01005327 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005328#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005329 if (srv->ssl_ctx.reused_sess) {
5330 int i;
5331
William Lallemande18d4e82021-11-17 02:59:21 +01005332 for (i = 0; i < global.nbthread; i++) {
Willy Tarreaue709e822021-02-26 21:06:32 +01005333 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
William Lallemande18d4e82021-11-17 02:59:21 +01005334 ha_free(&srv->ssl_ctx.reused_sess[i].sni);
5335 }
Willy Tarreaue709e822021-02-26 21:06:32 +01005336 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005337 }
5338
Willy Tarreaue709e822021-02-26 21:06:32 +01005339 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005340 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005341 srv->ssl_ctx.ctx = NULL;
5342 }
William Lallemand231610a2021-12-30 11:25:43 +01005343
5344 ha_free(&srv->ssl_ctx.ca_file);
5345 ha_free(&srv->ssl_ctx.crl_file);
5346 ha_free(&srv->ssl_ctx.client_crt);
5347 ha_free(&srv->ssl_ctx.verify_host);
5348#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5349 ha_free(&srv->sni_expr);
William Lallemand43c2ce42022-03-16 17:48:19 +01005350 release_sample_expr(srv->ssl_ctx.sni);
5351 srv->ssl_ctx.sni = NULL;
William Lallemand231610a2021-12-30 11:25:43 +01005352#endif
5353 ha_free(&srv->ssl_ctx.ciphers);
5354#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
5355 ha_free(&srv->ssl_ctx.ciphersuites);
5356#endif
William Lallemande69563f2021-12-30 14:45:19 +01005357 /* If there is a certificate we must unlink the ckch instance */
5358 ckch_inst_free(srv->ssl_ctx.inst);
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005359}
5360
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005361/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005362 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5363 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005364void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005365{
5366 struct ebmb_node *node, *back;
5367 struct sni_ctx *sni;
5368
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005369 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005370 while (node) {
5371 sni = ebmb_entry(node, struct sni_ctx, name);
5372 back = ebmb_next(node);
5373 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005374 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005375 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005376 free(sni);
5377 node = back;
5378 }
5379
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005380 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005381 while (node) {
5382 sni = ebmb_entry(node, struct sni_ctx, name);
5383 back = ebmb_next(node);
5384 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005385 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005386 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005387 free(sni);
5388 node = back;
5389 }
William Lallemandb2408692020-06-24 09:54:29 +02005390
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005391 SSL_CTX_free(bind_conf->initial_ctx);
5392 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005393 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005394 bind_conf->default_ctx = NULL;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005395 bind_conf->default_inst = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005396 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005397}
William Lallemandb2408692020-06-24 09:54:29 +02005398
5399
5400void ssl_sock_deinit()
5401{
5402 crtlist_deinit(); /* must be free'd before the ckchs */
5403 ckch_deinit();
5404}
5405REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005406
Willy Tarreau795cdab2016-12-22 17:30:54 +01005407/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5408void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5409{
5410 ssl_sock_free_ca(bind_conf);
5411 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005412 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005413 free(bind_conf->ca_sign_file);
5414 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005415 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005416 free(bind_conf->keys_ref->filename);
5417 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005418 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005419 free(bind_conf->keys_ref);
5420 }
5421 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005422 bind_conf->ca_sign_pass = NULL;
5423 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005424}
5425
Christopher Faulet31af49d2015-06-09 17:29:50 +02005426/* Load CA cert file and private key used to generate certificates */
5427int
Willy Tarreau03209342016-12-22 17:08:28 +01005428ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005429{
Willy Tarreau03209342016-12-22 17:08:28 +01005430 struct proxy *px = bind_conf->frontend;
William Lallemand52ddd992022-11-22 11:51:53 +01005431 struct ckch_data *data = NULL;
Shimi Gersner5846c492020-08-23 13:58:12 +03005432 int ret = 0;
5433 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005434
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005435 if (!(bind_conf->options & BC_O_GENERATE_CERTS))
Shimi Gersner5846c492020-08-23 13:58:12 +03005436 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005437
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005438#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005439 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005440 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005441 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005442 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005443 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005444#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005445
Christopher Faulet31af49d2015-06-09 17:29:50 +02005446 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005447 ha_alert("Proxy '%s': cannot enable certificate generation, "
5448 "no CA certificate File configured at [%s:%d].\n",
5449 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005450 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005451 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005452
Shimi Gersner5846c492020-08-23 13:58:12 +03005453 /* Allocate cert structure */
William Lallemand52ddd992022-11-22 11:51:53 +01005454 data = calloc(1, sizeof(*data));
5455 if (!data) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005456 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5457 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5458 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005459 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005460
5461 /* Try to parse file */
William Lallemand52ddd992022-11-22 11:51:53 +01005462 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, data, &err)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005463 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5464 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005465 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005466 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005467 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005468
5469 /* Fail if missing cert or pkey */
William Lallemand52ddd992022-11-22 11:51:53 +01005470 if ((!data->cert) || (!data->key)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005471 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5472 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5473 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005474 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005475
Shimi Gersner5846c492020-08-23 13:58:12 +03005476 /* Final assignment to bind */
William Lallemand52ddd992022-11-22 11:51:53 +01005477 bind_conf->ca_sign_ckch = data;
Shimi Gersner5846c492020-08-23 13:58:12 +03005478 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005479
Shimi Gersner5846c492020-08-23 13:58:12 +03005480 failed:
William Lallemand52ddd992022-11-22 11:51:53 +01005481 if (data) {
5482 ssl_sock_free_cert_key_and_chain_contents(data);
5483 free(data);
Shimi Gersner5846c492020-08-23 13:58:12 +03005484 }
5485
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005486 bind_conf->options &= ~BC_O_GENERATE_CERTS;
Shimi Gersner5846c492020-08-23 13:58:12 +03005487 ret++;
5488 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005489}
5490
5491/* Release CA cert and private key used to generate certificated */
5492void
5493ssl_sock_free_ca(struct bind_conf *bind_conf)
5494{
Shimi Gersner5846c492020-08-23 13:58:12 +03005495 if (bind_conf->ca_sign_ckch) {
5496 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005497 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005498 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005499}
5500
Emeric Brun46591952012-05-18 15:47:34 +02005501/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005502 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5503 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5504 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5505 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005506 * 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 +01005507 * as parameters to this function.
5508 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5509 * CO_ER_SSL_NO_MEM.
5510 */
5511int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5512 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5513{
5514 int retry = 1;
5515
5516 retry:
5517 /* Alloc a new SSL session. */
5518 *ssl = SSL_new(ssl_ctx);
5519 if (!*ssl) {
5520 if (!retry--)
5521 goto err;
5522
5523 pool_gc(NULL);
5524 goto retry;
5525 }
5526
5527 *bio = BIO_new(bio_meth);
5528 if (!*bio) {
5529 SSL_free(*ssl);
5530 *ssl = NULL;
5531 if (!retry--)
5532 goto err;
5533
5534 pool_gc(NULL);
5535 goto retry;
5536 }
5537
5538 BIO_set_data(*bio, ctx);
5539 SSL_set_bio(*ssl, *bio, *bio);
5540
5541 /* set connection pointer. */
5542 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5543 SSL_free(*ssl);
5544 *ssl = NULL;
5545 if (!retry--)
5546 goto err;
5547
5548 pool_gc(NULL);
5549 goto retry;
5550 }
5551
5552 return 0;
5553
5554 err:
5555 conn->err_code = CO_ER_SSL_NO_MEM;
5556 return -1;
5557}
5558
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005559/* This function is called when all the XPRT have been initialized. We can
5560 * now attempt to start the SSL handshake.
5561 */
5562static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5563{
5564 struct ssl_sock_ctx *ctx = xprt_ctx;
5565
5566 if (ctx->xprt->start) {
5567 int ret;
5568
5569 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5570 if (ret < 0)
5571 return ret;
5572 }
5573 tasklet_wakeup(ctx->wait_event.tasklet);
5574
5575 return 0;
5576}
5577
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005578/*
Emeric Brun46591952012-05-18 15:47:34 +02005579 * This function is called if SSL * context is not yet allocated. The function
5580 * is designed to be called before any other data-layer operation and sets the
5581 * handshake flag on the connection. It is safe to call it multiple times.
5582 * It returns 0 on success and -1 in error case.
5583 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005584static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005585{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005586 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005587 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005588 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005589 return 0;
5590
Olivier Houchard66ab4982019-02-26 18:37:15 +01005591 ctx = pool_alloc(ssl_sock_ctx_pool);
5592 if (!ctx) {
5593 conn->err_code = CO_ER_SSL_NO_MEM;
5594 return -1;
5595 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005596 ctx->wait_event.tasklet = tasklet_new();
5597 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005598 conn->err_code = CO_ER_SSL_NO_MEM;
5599 pool_free(ssl_sock_ctx_pool, ctx);
5600 return -1;
5601 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005602 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5603 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005604 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005605 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005606 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005607 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005608 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005609 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005610 ctx->xprt_st = 0;
5611 ctx->xprt_ctx = NULL;
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005612 ctx->error_code = 0;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005613
5614 /* Only work with sockets for now, this should be adapted when we'll
5615 * add QUIC support.
5616 */
5617 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005618 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005619 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5620 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005621 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005622
Willy Tarreau82531f62021-10-06 12:15:18 +02005623 if (global.maxsslconn && global.sslconns >= global.maxsslconn) {
Willy Tarreau20879a02012-12-03 16:32:10 +01005624 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005625 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005626 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005627
Emeric Brun46591952012-05-18 15:47:34 +02005628 /* If it is in client mode initiate SSL session
5629 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005630 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005631 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5632 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005633 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005634
Olivier Houchard66ab4982019-02-26 18:37:15 +01005635 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005636 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005637 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5638 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5639 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 +01005640 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005641 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005642 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005643 } else if (sess) {
5644 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005645 }
5646 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005647 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005648
Emeric Brun46591952012-05-18 15:47:34 +02005649 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005650 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005651
Willy Tarreau82531f62021-10-06 12:15:18 +02005652 _HA_ATOMIC_INC(&global.sslconns);
5653 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005654 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005655 return 0;
5656 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005657 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005658 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005659
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005660 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5661 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005662 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005663
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005664#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005665 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005666 b_alloc(&ctx->early_buf);
5667 SSL_set_max_early_data(ctx->ssl,
5668 /* Only allow early data if we managed to allocate
5669 * a buffer.
5670 */
5671 (!b_is_null(&ctx->early_buf)) ?
5672 global.tune.bufsize - global.tune.maxrewrite : 0);
5673 }
5674#endif
5675
Olivier Houchard66ab4982019-02-26 18:37:15 +01005676 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005677
Emeric Brun46591952012-05-18 15:47:34 +02005678 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005679 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005680#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005681 if (bc->ssl_conf.early_data)
5682 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005683#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005684
Willy Tarreau82531f62021-10-06 12:15:18 +02005685 _HA_ATOMIC_INC(&global.sslconns);
5686 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005687 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005688 return 0;
5689 }
5690 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005691 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005692err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005693 if (ctx && ctx->wait_event.tasklet)
5694 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005695 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005696 return -1;
5697}
5698
5699
5700/* This is the callback which is used when an SSL handshake is pending. It
5701 * updates the FD status if it wants some polling before being called again.
5702 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5703 * otherwise it returns non-zero and removes itself from the connection's
5704 * flags (the bit is provided in <flag> by the caller).
5705 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005706static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005707{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005708 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Emeric Brun46591952012-05-18 15:47:34 +02005709 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005710 struct ssl_counters *counters = NULL;
5711 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005712 struct listener *li;
5713 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005714 socklen_t lskerr;
5715 int skerr;
5716
Emeric Brun46591952012-05-18 15:47:34 +02005717
Willy Tarreau3c728722014-01-23 13:50:42 +01005718 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005719 return 0;
5720
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005721 /* get counters */
5722 switch (obj_type(conn->target)) {
5723 case OBJ_TYPE_LISTENER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005724 li = __objt_listener(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005725 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5726 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5727 &ssl_stats_module);
5728 break;
5729
5730 case OBJ_TYPE_SERVER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005731 srv = __objt_server(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005732 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5733 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5734 &ssl_stats_module);
5735 break;
5736
5737 default:
5738 break;
5739 }
5740
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005741 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005742 goto out_error;
5743
Willy Tarreau06300382021-02-02 15:42:25 +01005744 /* don't start calculating a handshake on a dead connection */
5745 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5746 goto out_error;
5747
5748 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5749 * status from the lower layers, so let's check the FD directly. Ideally
5750 * the xprt layers should provide some status indicating their knowledge
5751 * of shutdowns or error.
5752 */
Willy Tarreau07ecfc52022-04-11 18:07:03 +02005753 BUG_ON(conn->flags & CO_FL_FDLESS);
5754
Willy Tarreau06300382021-02-02 15:42:25 +01005755 skerr = 0;
5756 lskerr = sizeof(skerr);
5757 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5758 skerr != 0)
5759 goto out_error;
5760
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005761#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005762 /*
5763 * Check if we have early data. If we do, we have to read them
5764 * before SSL_do_handshake() is called, And there's no way to
5765 * detect early data, except to try to read them
5766 */
5767 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005768 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005769
Olivier Houchard54907bb2019-12-19 15:02:39 +01005770 while (1) {
5771 ret = SSL_read_early_data(ctx->ssl,
5772 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5773 &read_data);
5774 if (ret == SSL_READ_EARLY_DATA_ERROR)
5775 goto check_error;
5776 if (read_data > 0) {
5777 conn->flags |= CO_FL_EARLY_DATA;
5778 b_add(&ctx->early_buf, read_data);
5779 }
5780 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5781 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5782 if (!b_data(&ctx->early_buf))
5783 b_free(&ctx->early_buf);
5784 break;
5785 }
5786 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005787 }
5788#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005789 /* If we use SSL_do_handshake to process a reneg initiated by
5790 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5791 * Usually SSL_write and SSL_read are used and process implicitly
5792 * the reneg handshake.
5793 * Here we use SSL_peek as a workaround for reneg.
5794 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005795 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005796 char c;
5797
Olivier Houchard66ab4982019-02-26 18:37:15 +01005798 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005799 if (ret <= 0) {
5800 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005801 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005802
Emeric Brun674b7432012-11-08 19:21:55 +01005803 if (ret == SSL_ERROR_WANT_WRITE) {
5804 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005805 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005806 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005807 return 0;
5808 }
5809 else if (ret == SSL_ERROR_WANT_READ) {
5810 /* handshake may have been completed but we have
5811 * no more data to read.
5812 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005813 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005814 ret = 1;
5815 goto reneg_ok;
5816 }
5817 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005818 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005819 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005820 return 0;
5821 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005822#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005823 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005824 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005825 return 0;
5826 }
5827#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005828 else if (ret == SSL_ERROR_SYSCALL) {
5829 /* if errno is null, then connection was successfully established */
5830 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5831 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005832 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005833#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5834 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005835 conn->err_code = CO_ER_SSL_HANDSHAKE;
5836#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005837 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005838#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005839 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005840 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005841 empty_handshake = state == TLS_ST_BEFORE;
5842#else
Lukas Tribus49799162019-07-08 14:29:15 +02005843 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5844 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005845#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005846 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005847 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005848 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005849 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5850 else
5851 conn->err_code = CO_ER_SSL_EMPTY;
5852 }
5853 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005854 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005855 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5856 else
5857 conn->err_code = CO_ER_SSL_ABORT;
5858 }
5859 }
5860 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005861 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005862 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005863 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005864 conn->err_code = CO_ER_SSL_HANDSHAKE;
5865 }
Lukas Tribus49799162019-07-08 14:29:15 +02005866#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005867 }
Emeric Brun674b7432012-11-08 19:21:55 +01005868 goto out_error;
5869 }
5870 else {
5871 /* Fail on all other handshake errors */
5872 /* Note: OpenSSL may leave unread bytes in the socket's
5873 * buffer, causing an RST to be emitted upon close() on
5874 * TCP sockets. We first try to drain possibly pending
5875 * data to avoid this as much as possible.
5876 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005877 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005878 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005879 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005880 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005881 goto out_error;
5882 }
5883 }
5884 /* read some data: consider handshake completed */
5885 goto reneg_ok;
5886 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005887 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005888check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005889 if (ret != 1) {
5890 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005891 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005892
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005893 if (!ctx->error_code)
5894 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton7c6898e2021-07-29 09:45:51 +02005895
Emeric Brun46591952012-05-18 15:47:34 +02005896 if (ret == SSL_ERROR_WANT_WRITE) {
5897 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005898 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005899 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005900 return 0;
5901 }
5902 else if (ret == SSL_ERROR_WANT_READ) {
5903 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005904 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005905 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5906 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005907 return 0;
5908 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005909#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005910 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005911 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005912 return 0;
5913 }
5914#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005915 else if (ret == SSL_ERROR_SYSCALL) {
5916 /* if errno is null, then connection was successfully established */
5917 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5918 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005919 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005920#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5921 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005922 conn->err_code = CO_ER_SSL_HANDSHAKE;
5923#else
5924 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005925#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005926 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005927 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005928 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005929#else
Lukas Tribus49799162019-07-08 14:29:15 +02005930 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5931 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005932#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005933 if (empty_handshake) {
5934 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005935 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005936 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5937 else
5938 conn->err_code = CO_ER_SSL_EMPTY;
5939 }
5940 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005941 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005942 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5943 else
5944 conn->err_code = CO_ER_SSL_ABORT;
5945 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005946 }
5947 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005948 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005949 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5950 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005951 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005952 }
Lukas Tribus49799162019-07-08 14:29:15 +02005953#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005954 }
Willy Tarreau89230192012-09-28 20:22:13 +02005955 goto out_error;
5956 }
Emeric Brun46591952012-05-18 15:47:34 +02005957 else {
5958 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005959 /* Note: OpenSSL may leave unread bytes in the socket's
5960 * buffer, causing an RST to be emitted upon close() on
5961 * TCP sockets. We first try to drain possibly pending
5962 * data to avoid this as much as possible.
5963 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005964 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005965 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005966 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005967 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005968 goto out_error;
5969 }
5970 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005971#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005972 else {
5973 /*
5974 * If the server refused the early data, we have to send a
5975 * 425 to the client, as we no longer have the data to sent
5976 * them again.
5977 */
5978 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005979 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005980 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5981 goto out_error;
5982 }
5983 }
5984 }
5985#endif
5986
Emeric Brun46591952012-05-18 15:47:34 +02005987
Emeric Brun674b7432012-11-08 19:21:55 +01005988reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005989
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005990#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00005991 /* ASYNC engine API doesn't support moving read/write
5992 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005993 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005994 */
5995 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005996 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005997#endif
Emeric Brun46591952012-05-18 15:47:34 +02005998 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005999 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02006000 if (objt_server(conn->target)) {
6001 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
6002 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
6003 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02006004 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02006005 else {
6006 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
6007 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
6008 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
6009 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006010
Willy Tarreau42995282020-11-06 13:19:18 +01006011 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006012 HA_ATOMIC_INC(&counters->sess);
6013 HA_ATOMIC_INC(&counters_px->sess);
Willy Tarreau42995282020-11-06 13:19:18 +01006014 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006015 }
Willy Tarreau42995282020-11-06 13:19:18 +01006016 else if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006017 HA_ATOMIC_INC(&counters->reused_sess);
6018 HA_ATOMIC_INC(&counters_px->reused_sess);
Emeric Brun46591952012-05-18 15:47:34 +02006019 }
6020
6021 /* The connection is now established at both layers, it's time to leave */
6022 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
6023 return 1;
6024
6025 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006026 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006027 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006028 ERR_clear_error();
6029
Emeric Brun9fa89732012-10-04 17:09:56 +02006030 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01006031 if (objt_server(conn->target)) {
6032 struct server *s = __objt_server(conn->target);
6033 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
6034 * one cache per thread, it only prevents to flush it from the CLI in
6035 * another thread */
6036
6037 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01006038 if (s->ssl_ctx.reused_sess[tid].ptr)
6039 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01006040 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02006041 }
6042
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006043 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006044 HA_ATOMIC_INC(&counters->failed_handshake);
6045 HA_ATOMIC_INC(&counters_px->failed_handshake);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006046 }
6047
Emeric Brun46591952012-05-18 15:47:34 +02006048 /* Fail on all other handshake errors */
6049 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01006050 if (!conn->err_code)
6051 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006052 return 0;
6053}
6054
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006055/* Called from the upper layer, to subscribe <es> to events <event_type>. The
6056 * event subscriber <es> is not allowed to change from a previous call as long
6057 * as at least one event is still subscribed. The <event_type> must only be a
6058 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
6059 * unless the transport layer was already released.
6060 */
6061static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006062{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006063 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006064
Olivier Houchard0ff28652019-06-24 18:57:39 +02006065 if (!ctx)
6066 return -1;
6067
Willy Tarreau113d52b2020-01-10 09:20:26 +01006068 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006069 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006070
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006071 ctx->subs = es;
6072 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006073
6074 /* we may have to subscribe to lower layers for new events */
6075 event_type &= ~ctx->wait_event.events;
6076 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
6077 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006078 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006079}
6080
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006081/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
6082 * The <es> pointer is not allowed to differ from the one passed to the
6083 * subscribe() call. It always returns zero.
6084 */
6085static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006086{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006087 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006088
Willy Tarreau113d52b2020-01-10 09:20:26 +01006089 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006090 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006091
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006092 es->events &= ~event_type;
6093 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01006094 ctx->subs = NULL;
6095
6096 /* If we subscribed, and we're not doing the handshake,
6097 * then we subscribed because the upper layer asked for it,
6098 * as the upper layer is no longer interested, we can
6099 * unsubscribe too.
6100 */
6101 event_type &= ctx->wait_event.events;
6102 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
6103 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006104
6105 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006106}
6107
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006108/* The connection has been taken over, so destroy the old tasklet and create
6109 * a new one. The original thread ID must be passed into orig_tid
6110 * It should be called with the takeover lock for the old thread held.
6111 * Returns 0 on success, and -1 on failure
6112 */
6113static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
6114{
6115 struct ssl_sock_ctx *ctx = xprt_ctx;
6116 struct tasklet *tl = tasklet_new();
6117
6118 if (!tl)
6119 return -1;
6120
6121 ctx->wait_event.tasklet->context = NULL;
6122 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
6123 ctx->wait_event.tasklet = tl;
6124 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
6125 ctx->wait_event.tasklet->context = ctx;
6126 return 0;
6127}
6128
Willy Tarreau41491682021-03-02 17:29:56 +01006129/* notify the next xprt that the connection is about to become idle and that it
6130 * may be stolen at any time after the function returns and that any tasklet in
6131 * the chain must be careful before dereferencing its context.
6132 */
6133static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
6134{
6135 struct ssl_sock_ctx *ctx = xprt_ctx;
6136
6137 if (!ctx || !ctx->wait_event.tasklet)
6138 return;
6139
6140 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6141 if (ctx->xprt)
6142 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
6143}
6144
6145/* notify the next xprt that the connection is not idle anymore and that it may
6146 * not be stolen before the next xprt_set_idle().
6147 */
6148static void ssl_set_used(struct connection *conn, void *xprt_ctx)
6149{
6150 struct ssl_sock_ctx *ctx = xprt_ctx;
6151
6152 if (!ctx || !ctx->wait_event.tasklet)
6153 return;
6154
6155 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6156 if (ctx->xprt)
6157 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
6158}
6159
Olivier Houchard2e055482019-05-27 19:50:12 +02006160/* Use the provided XPRT as an underlying XPRT, and provide the old one.
6161 * Returns 0 on success, and non-zero on failure.
6162 */
6163static 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)
6164{
6165 struct ssl_sock_ctx *ctx = xprt_ctx;
6166
6167 if (oldxprt_ops != NULL)
6168 *oldxprt_ops = ctx->xprt;
6169 if (oldxprt_ctx != NULL)
6170 *oldxprt_ctx = ctx->xprt_ctx;
6171 ctx->xprt = toadd_ops;
6172 ctx->xprt_ctx = toadd_ctx;
6173 return 0;
6174}
6175
Olivier Houchard5149b592019-05-23 17:47:36 +02006176/* Remove the specified xprt. If if it our underlying XPRT, remove it and
6177 * return 0, otherwise just call the remove_xprt method from the underlying
6178 * XPRT.
6179 */
6180static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
6181{
6182 struct ssl_sock_ctx *ctx = xprt_ctx;
6183
6184 if (ctx->xprt_ctx == toremove_ctx) {
6185 ctx->xprt_ctx = newctx;
6186 ctx->xprt = newops;
6187 return 0;
6188 }
6189 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
6190}
6191
Willy Tarreau144f84a2021-03-02 16:09:26 +01006192struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02006193{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006194 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006195 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006196 struct connection *conn;
6197 int conn_in_list;
6198 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006199
Willy Tarreau41491682021-03-02 17:29:56 +01006200 if (state & TASK_F_USR1) {
6201 /* the tasklet was idling on an idle connection, it might have
6202 * been stolen, let's be careful!
6203 */
6204 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6205 if (tl->context == NULL) {
6206 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6207 tasklet_free(tl);
6208 return NULL;
6209 }
6210 conn = ctx->conn;
Christopher Faulet3a7b5392023-03-16 11:43:05 +01006211 conn_in_list = conn_get_idle_flag(conn);
Willy Tarreau41491682021-03-02 17:29:56 +01006212 if (conn_in_list)
6213 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006214 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01006215 } else {
6216 conn = ctx->conn;
6217 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006218 }
Willy Tarreau41491682021-03-02 17:29:56 +01006219
Olivier Houchardea8dd942019-05-20 14:02:16 +02006220 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01006221 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006222 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006223 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
6224 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01006225 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006226 }
6227 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006228 /* If we had an error, or the handshake is done and I/O is available,
6229 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01006230 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02006231 * we can't be sure conn_fd_handler() will be called again.
6232 */
6233 if ((ctx->conn->flags & CO_FL_ERROR) ||
6234 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006235 int woke = 0;
6236
6237 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006238 if (ctx->subs) {
6239 tasklet_wakeup(ctx->subs->tasklet);
6240 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006241 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006242 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006243 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006244
Olivier Houchardea8dd942019-05-20 14:02:16 +02006245 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01006246 * upper layers know. If we have no mux, create it,
6247 * and once we have a mux, call its wake method if we didn't
6248 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02006249 */
6250 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01006251 if (!ctx->conn->mux)
6252 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006253 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006254 ret = ctx->conn->mux->wake(ctx->conn);
6255 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006256 }
6257 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006258#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006259 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006260 else if (b_data(&ctx->early_buf) && ctx->subs &&
6261 ctx->subs->events & SUB_RETRY_RECV) {
6262 tasklet_wakeup(ctx->subs->tasklet);
6263 ctx->subs->events &= ~SUB_RETRY_RECV;
6264 if (!ctx->subs->events)
6265 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01006266 }
6267#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006268leave:
6269 if (!ret && conn_in_list) {
6270 struct server *srv = objt_server(conn->target);
6271
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006272 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006273 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau85223482022-09-29 20:32:43 +02006274 eb64_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006275 else
Willy Tarreau85223482022-09-29 20:32:43 +02006276 eb64_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006277 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006278 }
Willy Tarreau74163142021-03-13 11:30:19 +01006279 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006280}
6281
Emeric Brun46591952012-05-18 15:47:34 +02006282/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01006283 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02006284 * buffer wraps, in which case a second call may be performed. The connection's
6285 * flags are updated with whatever special event is detected (error, read0,
6286 * empty). The caller is responsible for taking care of those events and
6287 * avoiding the call if inappropriate. The function does not call the
6288 * connection's polling update function, so the caller is responsible for this.
6289 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006290static 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 +02006291{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006292 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02006293 ssize_t ret;
6294 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02006295
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006296 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006297 goto out_error;
6298
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006299#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006300 if (b_data(&ctx->early_buf)) {
6301 try = b_contig_space(buf);
6302 if (try > b_data(&ctx->early_buf))
6303 try = b_data(&ctx->early_buf);
6304 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
6305 b_add(buf, try);
6306 b_del(&ctx->early_buf, try);
6307 if (b_data(&ctx->early_buf) == 0)
6308 b_free(&ctx->early_buf);
6309 return try;
6310 }
6311#endif
6312
Willy Tarreau911db9b2020-01-23 16:27:54 +01006313 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006314 /* a handshake was requested */
6315 return 0;
6316
Emeric Brun46591952012-05-18 15:47:34 +02006317 /* read the largest possible block. For this, we perform only one call
6318 * to recv() unless the buffer wraps and we exactly fill the first hunk,
6319 * in which case we accept to do it once again. A new attempt is made on
6320 * EINTR too.
6321 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01006322 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006323
Willy Tarreau591d4452018-06-15 17:21:00 +02006324 try = b_contig_space(buf);
6325 if (!try)
6326 break;
6327
Willy Tarreauabf08d92014-01-14 11:31:27 +01006328 if (try > count)
6329 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02006330
Olivier Houchard66ab4982019-02-26 18:37:15 +01006331 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02006332
Emeric Brune1f38db2012-09-03 20:36:47 +02006333 if (conn->flags & CO_FL_ERROR) {
6334 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006335 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006336 }
Emeric Brun46591952012-05-18 15:47:34 +02006337 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006338 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006339 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006340 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006341 }
Emeric Brun46591952012-05-18 15:47:34 +02006342 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006343 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006344 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006345 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006346 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006347 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006348#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006349 /* Async mode can be re-enabled, because we're leaving data state.*/
6350 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006351 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006352#endif
Emeric Brun46591952012-05-18 15:47:34 +02006353 break;
6354 }
6355 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006356 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006357 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6358 SUB_RETRY_RECV,
6359 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006360 /* handshake is running, and it may need to re-enable read */
6361 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006362#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006363 /* Async mode can be re-enabled, because we're leaving data state.*/
6364 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006365 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006366#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006367 break;
6368 }
Emeric Brun46591952012-05-18 15:47:34 +02006369 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006370 } else if (ret == SSL_ERROR_ZERO_RETURN)
6371 goto read0;
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006372 else if (ret == SSL_ERROR_SSL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006373 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6374 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006375 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006376 conn->err_code = CO_ERR_SSL_FATAL;
6377 }
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006378 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6379 * stack before shutting down the connection for
6380 * reading. */
Willy Tarreauacef5e22022-04-25 20:32:15 +02006381 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN || errno == EWOULDBLOCK))
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006382 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006383 /* otherwise it's a real error */
6384 goto out_error;
6385 }
6386 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006387 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006388 return done;
6389
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006390 clear_ssl_error:
6391 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006392 ssl_sock_dump_errors(conn, NULL);
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006393 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006394 read0:
6395 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006396 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006397
Emeric Brun46591952012-05-18 15:47:34 +02006398 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006399 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006400 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006401 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006402 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006403 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006404}
6405
6406
Willy Tarreau787db9a2018-06-14 18:31:46 +02006407/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6408 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6409 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006410 * Only one call to send() is performed, unless the buffer wraps, in which case
6411 * a second call may be performed. The connection's flags are updated with
6412 * whatever special event is detected (error, empty). The caller is responsible
6413 * for taking care of those events and avoiding the call if inappropriate. The
6414 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006415 * is responsible for this. The buffer's output is not adjusted, it's up to the
6416 * caller to take care of this. It's up to the caller to update the buffer's
6417 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006418 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006419static 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 +02006420{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006421 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006422 ssize_t ret;
6423 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006424
6425 done = 0;
6426
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006427 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006428 goto out_error;
6429
Willy Tarreau911db9b2020-01-23 16:27:54 +01006430 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006431 /* a handshake was requested */
6432 return 0;
6433
6434 /* send the largest possible block. For this we perform only one call
6435 * to send() unless the buffer wraps and we exactly fill the first hunk,
6436 * in which case we accept to do it once again.
6437 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006438 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006439#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006440 size_t written_data;
6441#endif
6442
Willy Tarreau787db9a2018-06-14 18:31:46 +02006443 try = b_contig_data(buf, done);
6444 if (try > count)
6445 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006446
Thomas Prückl10243932022-04-27 13:04:54 +02006447 if (global_ssl.hard_max_record && try > global_ssl.hard_max_record)
6448 try = global_ssl.hard_max_record;
6449
Willy Tarreau7bed9452014-02-02 02:00:24 +01006450 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006451 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006452 global_ssl.max_record && try > global_ssl.max_record) {
6453 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006454 }
6455 else {
6456 /* we need to keep the information about the fact that
6457 * we're not limiting the upcoming send(), because if it
6458 * fails, we'll have to retry with at least as many data.
6459 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006460 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006461 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006462
Willy Tarreauac78c4f2023-03-17 16:13:05 +01006463 if (try < count || flags & CO_SFL_MSG_MORE)
6464 ctx->xprt_st |= SSL_SOCK_SEND_MORE;
6465 else
6466 ctx->xprt_st &= ~SSL_SOCK_SEND_MORE;
6467
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006468#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006469 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006470 unsigned int max_early;
6471
Olivier Houchard522eea72017-11-03 16:27:47 +01006472 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006473 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006474 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006475 if (SSL_get0_session(ctx->ssl))
6476 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006477 else
6478 max_early = 0;
6479 }
6480
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006481 if (try + ctx->sent_early_data > max_early) {
6482 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006483 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006484 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006485 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006486 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006487 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006488 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006489 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006490 if (ret == 1) {
6491 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006492 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006493 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006494 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006495 /* Initiate the handshake, now */
6496 tasklet_wakeup(ctx->wait_event.tasklet);
6497 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006498
Olivier Houchardc2aae742017-09-22 18:26:28 +02006499 }
6500
6501 } else
6502#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006503 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006504
Emeric Brune1f38db2012-09-03 20:36:47 +02006505 if (conn->flags & CO_FL_ERROR) {
6506 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006507 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006508 }
Emeric Brun46591952012-05-18 15:47:34 +02006509 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006510 /* A send succeeded, so we can consider ourself connected */
6511 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006512 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006513 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006514 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006515 }
6516 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006517 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006518
Emeric Brun46591952012-05-18 15:47:34 +02006519 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006520 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006521 /* handshake is running, and it may need to re-enable write */
6522 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006523 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006524#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006525 /* Async mode can be re-enabled, because we're leaving data state.*/
6526 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006527 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006528#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006529 break;
6530 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006531
Emeric Brun46591952012-05-18 15:47:34 +02006532 break;
6533 }
6534 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006535 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006536 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006537 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6538 SUB_RETRY_RECV,
6539 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006540#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006541 /* Async mode can be re-enabled, because we're leaving data state.*/
6542 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006543 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006544#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006545 break;
6546 }
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006547 else if (ret == SSL_ERROR_SSL || ret == SSL_ERROR_SYSCALL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006548 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6549
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02006550 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006551 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006552 conn->err_code = CO_ERR_SSL_FATAL;
6553 }
Emeric Brun46591952012-05-18 15:47:34 +02006554 goto out_error;
6555 }
6556 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006557 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006558 return done;
6559
6560 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006561 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006562 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006563 ERR_clear_error();
6564
Emeric Brun46591952012-05-18 15:47:34 +02006565 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006566 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006567}
6568
Willy Tarreau832e2422021-05-13 10:11:03 +02006569void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006570
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006571 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006572
Olivier Houchardea8dd942019-05-20 14:02:16 +02006573
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006574 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006575 if (ctx->wait_event.events != 0)
6576 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6577 ctx->wait_event.events,
6578 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006579 if (ctx->subs) {
6580 ctx->subs->events = 0;
6581 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006582 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006583
Olivier Houchard692c1d02019-05-23 18:41:47 +02006584 if (ctx->xprt->close)
6585 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006586#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006587 if (global_ssl.async) {
6588 OSSL_ASYNC_FD all_fd[32], afd;
6589 size_t num_all_fds = 0;
6590 int i;
6591
Olivier Houchard66ab4982019-02-26 18:37:15 +01006592 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006593 if (num_all_fds > 32) {
6594 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6595 return;
6596 }
6597
Olivier Houchard66ab4982019-02-26 18:37:15 +01006598 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006599
6600 /* If an async job is pending, we must try to
6601 to catch the end using polling before calling
6602 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006603 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006604 for (i=0 ; i < num_all_fds ; i++) {
6605 /* switch on an handler designed to
6606 * handle the SSL_free
6607 */
6608 afd = all_fd[i];
6609 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006610 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006611 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006612 /* To ensure that the fd cache won't be used
6613 * and we'll catch a real RD event.
6614 */
6615 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006616 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006617 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006618 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006619 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006620 return;
6621 }
Emeric Brun3854e012017-05-17 20:42:48 +02006622 /* Else we can remove the fds from the fdtab
6623 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006624 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006625 * because the fd is owned by the engine.
6626 * the engine is responsible to close
6627 */
Emeric Brun7d392a52022-07-01 17:36:50 +02006628 for (i=0 ; i < num_all_fds ; i++) {
6629 /* We want to remove the fd from the fdtab
6630 * but we flag it to disown because the
6631 * close is performed by the engine itself
6632 */
6633 fdtab[all_fd[i]].state |= FD_DISOWN;
6634 fd_delete(all_fd[i]);
6635 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006636 }
6637#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006638 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006639 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006640 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006641 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau82531f62021-10-06 12:15:18 +02006642 _HA_ATOMIC_DEC(&global.sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006643 }
Emeric Brun46591952012-05-18 15:47:34 +02006644}
6645
6646/* This function tries to perform a clean shutdown on an SSL connection, and in
6647 * any case, flags the connection as reusable if no handshake was in progress.
6648 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006649static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006650{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006651 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006652
Willy Tarreau911db9b2020-01-23 16:27:54 +01006653 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006654 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006655 if (!clean)
6656 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006657 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006658 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006659 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006660 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006661 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006662 ERR_clear_error();
6663 }
Emeric Brun46591952012-05-18 15:47:34 +02006664}
6665
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006666
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006667/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006668int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6669{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006670 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemandd4f946c2019-12-05 10:26:40 +01006671 X509 *crt;
6672
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006673 if (!ctx)
William Lallemandd4f946c2019-12-05 10:26:40 +01006674 return 0;
William Lallemandd4f946c2019-12-05 10:26:40 +01006675 crt = SSL_get_certificate(ctx->ssl);
6676 if (!crt)
6677 return 0;
6678
6679 return cert_get_pkey_algo(crt, out);
6680}
6681
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006682/* used for ppv2 cert signature (can be used for logging) */
6683const char *ssl_sock_get_cert_sig(struct connection *conn)
6684{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006685 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006686
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006687 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6688 X509 *crt;
6689
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006690 if (!ctx)
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006691 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006692 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006693 if (!crt)
6694 return NULL;
6695 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6696 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6697}
6698
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006699/* used for ppv2 authority */
6700const char *ssl_sock_get_sni(struct connection *conn)
6701{
6702#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006703 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006704
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006705 if (!ctx)
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006706 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006707 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006708#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006709 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006710#endif
6711}
6712
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006713/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006714const char *ssl_sock_get_cipher_name(struct connection *conn)
6715{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006716 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006717
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006718 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006719 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006720 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006721}
6722
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006723/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006724const char *ssl_sock_get_proto_version(struct connection *conn)
6725{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006726 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006727
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006728 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006729 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006730 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006731}
6732
Olivier Houchardab28a322018-12-21 19:45:40 +01006733void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6734{
6735#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006736 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006737
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006738 if (!ctx)
Olivier Houcharde488ea82019-06-28 14:10:33 +02006739 return;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006740 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006741#endif
6742}
6743
Willy Tarreau119a4082016-12-22 21:58:38 +01006744/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6745 * to disable SNI.
6746 */
Willy Tarreau63076412015-07-10 11:33:32 +02006747void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6748{
6749#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006750 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemande18d4e82021-11-17 02:59:21 +01006751 struct server *s;
Willy Tarreau119a4082016-12-22 21:58:38 +01006752 char *prev_name;
6753
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006754 if (!ctx)
Willy Tarreau63076412015-07-10 11:33:32 +02006755 return;
Willy Tarreau77bfa662021-12-23 11:12:13 +01006756
6757 BUG_ON(!(conn->flags & CO_FL_WAIT_L6_CONN));
6758 BUG_ON(!(conn->flags & CO_FL_SSL_WAIT_HS));
6759
William Lallemande18d4e82021-11-17 02:59:21 +01006760 s = __objt_server(conn->target);
Willy Tarreau63076412015-07-10 11:33:32 +02006761
Willy Tarreau119a4082016-12-22 21:58:38 +01006762 /* if the SNI changes, we must destroy the reusable context so that a
William Lallemande18d4e82021-11-17 02:59:21 +01006763 * new connection will present a new SNI. compare with the SNI
6764 * previously stored in the reused_sess */
6765 /* the RWLOCK is used to ensure that we are not trying to flush the
6766 * cache from the CLI */
6767
6768 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
6769 prev_name = s->ssl_ctx.reused_sess[tid].sni;
Willy Tarreau119a4082016-12-22 21:58:38 +01006770 if ((!prev_name && hostname) ||
6771 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006772 SSL_set_session(ctx->ssl, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01006773 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau119a4082016-12-22 21:58:38 +01006774
Olivier Houchard66ab4982019-02-26 18:37:15 +01006775 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006776#endif
6777}
6778
Emeric Brun0abf8362014-06-24 18:26:41 +02006779/* Extract peer certificate's common name into the chunk dest
6780 * Returns
6781 * the len of the extracted common name
6782 * or 0 if no CN found in DN
6783 * or -1 on error case (i.e. no peer certificate)
6784 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006785int ssl_sock_get_remote_common_name(struct connection *conn,
6786 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006787{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006788 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
David Safb76832014-05-08 23:42:08 -04006789 X509 *crt = NULL;
6790 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006791 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006792 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006793 .area = (char *)&find_cn,
6794 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006795 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006796 int result = -1;
David Safb76832014-05-08 23:42:08 -04006797
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006798 if (!ctx)
Emeric Brun0abf8362014-06-24 18:26:41 +02006799 goto out;
David Safb76832014-05-08 23:42:08 -04006800
6801 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006802 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006803 if (!crt)
6804 goto out;
6805
6806 name = X509_get_subject_name(crt);
6807 if (!name)
6808 goto out;
David Safb76832014-05-08 23:42:08 -04006809
Emeric Brun0abf8362014-06-24 18:26:41 +02006810 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6811out:
David Safb76832014-05-08 23:42:08 -04006812 if (crt)
6813 X509_free(crt);
6814
6815 return result;
6816}
6817
Dave McCowan328fb582014-07-30 10:39:13 -04006818/* returns 1 if client passed a certificate for this session, 0 if not */
6819int ssl_sock_get_cert_used_sess(struct connection *conn)
6820{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006821 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dave McCowan328fb582014-07-30 10:39:13 -04006822 X509 *crt = NULL;
6823
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006824 if (!ctx)
Dave McCowan328fb582014-07-30 10:39:13 -04006825 return 0;
6826
6827 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006828 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006829 if (!crt)
6830 return 0;
6831
6832 X509_free(crt);
6833 return 1;
6834}
6835
6836/* returns 1 if client passed a certificate for this connection, 0 if not */
6837int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006838{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006839 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006840
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006841 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006842 return 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006843 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006844}
6845
6846/* returns result from SSL verify */
6847unsigned int ssl_sock_get_verify_result(struct connection *conn)
6848{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006849 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006850
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006851 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006852 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006853 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006854}
6855
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006856/* Returns the application layer protocol name in <str> and <len> when known.
6857 * Zero is returned if the protocol name was not found, otherwise non-zero is
6858 * returned. The string is allocated in the SSL context and doesn't have to be
6859 * freed by the caller. NPN is also checked if available since older versions
6860 * of openssl (1.0.1) which are more common in field only support this one.
6861 */
Amaury Denoyelle71e588c2021-11-12 11:23:29 +01006862int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006863{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006864#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6865 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006866 struct ssl_sock_ctx *ctx = xprt_ctx;
6867 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006868 return 0;
6869
6870 *str = NULL;
6871
6872#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006873 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006874 if (*str)
6875 return 1;
6876#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006877#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006878 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006879 if (*str)
6880 return 1;
6881#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006882#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006883 return 0;
6884}
6885
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006886/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006887int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006888{
6889 X509 *ca;
6890 X509_NAME *name = NULL;
6891 ASN1_OCTET_STRING *skid = NULL;
6892 STACK_OF(X509) *chain = NULL;
6893 struct issuer_chain *issuer;
6894 struct eb64_node *node;
6895 char *path;
6896 u64 key;
6897 int ret = 0;
6898
6899 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6900 if (chain == NULL) {
6901 chain = sk_X509_new_null();
6902 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6903 name = X509_get_subject_name(ca);
6904 }
6905 if (!sk_X509_push(chain, ca)) {
6906 X509_free(ca);
6907 goto end;
6908 }
6909 }
6910 if (!chain) {
6911 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6912 goto end;
6913 }
6914 if (!skid) {
6915 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6916 goto end;
6917 }
6918 if (!name) {
6919 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6920 goto end;
6921 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01006922 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006923 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006924 issuer = container_of(node, typeof(*issuer), node);
6925 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6926 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6927 goto end;
6928 }
6929 }
6930 issuer = calloc(1, sizeof *issuer);
6931 path = strdup(fp);
6932 if (!issuer || !path) {
6933 free(issuer);
6934 free(path);
6935 goto end;
6936 }
6937 issuer->node.key = key;
6938 issuer->path = path;
6939 issuer->chain = chain;
6940 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006941 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006942 ret = 1;
6943 end:
6944 if (skid)
6945 ASN1_OCTET_STRING_free(skid);
6946 if (chain)
6947 sk_X509_pop_free(chain, X509_free);
6948 return ret;
6949}
6950
William Lallemandda8584c2020-05-14 10:14:37 +02006951 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006952{
6953 AUTHORITY_KEYID *akid;
6954 struct issuer_chain *issuer = NULL;
6955
6956 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01006957 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006958 struct eb64_node *node;
6959 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01006960 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006961 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6962 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6963 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6964 issuer = ti;
6965 break;
6966 }
6967 }
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006968 }
Remi Tricot-Le Breton1621dc12022-11-03 15:16:48 +01006969 AUTHORITY_KEYID_free(akid);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006970 return issuer;
6971}
6972
William Lallemanddad31052020-05-14 17:47:32 +02006973void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006974{
6975 struct eb64_node *node, *back;
6976 struct issuer_chain *issuer;
6977
William Lallemande0f3fd52020-02-25 14:53:06 +01006978 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006979 while (node) {
6980 issuer = container_of(node, typeof(*issuer), node);
6981 back = eb64_next(node);
6982 eb64_delete(node);
6983 free(issuer->path);
6984 sk_X509_pop_free(issuer->chain, X509_free);
6985 free(issuer);
6986 node = back;
6987 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006988}
6989
William Lallemandd7bfbe22022-04-11 18:41:24 +02006990#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006991static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01006992 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006993
Emeric Brun3854e012017-05-17 20:42:48 +02006994 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006995 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006996 err_code = ERR_ABORT;
6997 }
6998 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006999}
Willy Tarreau9ceda382016-12-21 23:13:03 +01007000#endif
7001
Willy Tarreaude5675a2021-01-20 14:41:29 +01007002/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007003 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01007004 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01007005static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01007006{
7007 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007008 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007009
7010 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007011 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007012
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007013 if (sctx->conn != conn) {
7014 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
7015 ret = 1;
7016 }
Christopher Fauletf19c6392023-03-14 15:51:33 +01007017 chunk_appendf(&trash, " xctx.st=%d .err=%ld", sctx->xprt_st, sctx->error_code);
Willy Tarreaude5675a2021-01-20 14:41:29 +01007018
7019 if (sctx->xprt) {
7020 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
7021 if (sctx->xprt_ctx)
7022 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
7023 }
7024
7025 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007026
7027 /* as soon as a shutdown is reported the lower layer unregisters its
7028 * subscriber, so the situations below are transient and rare enough to
7029 * be reported as suspicious. In any case they shouldn't last.
7030 */
7031 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
7032 ret = 1;
7033 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
7034 ret = 1;
7035
Willy Tarreaude5675a2021-01-20 14:41:29 +01007036 chunk_appendf(&trash, " .subs=%p", sctx->subs);
7037 if (sctx->subs) {
7038 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007039 if (sctx->subs->tasklet->calls >= 1000000)
7040 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007041 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
7042 sctx->subs->tasklet->calls,
7043 sctx->subs->tasklet->context);
7044 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
7045 chunk_appendf(&trash, ")");
7046 }
7047 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
7048 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007049 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007050}
7051
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007052#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02007053/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007054 * each reference. The variable <ref> must point to the current node's list
7055 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02007056 */
William Lallemand32af2032016-10-29 18:09:35 +02007057static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007058struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02007059{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007060 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007061 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02007062
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007063 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007064 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007065 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02007066
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007067 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02007068}
7069
7070static inline
7071struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
7072{
7073 int id;
7074 char *error;
7075
7076 /* If the reference starts by a '#', this is numeric id. */
7077 if (reference[0] == '#') {
7078 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
7079 id = strtol(reference + 1, &error, 10);
7080 if (*error != '\0')
7081 return NULL;
7082
7083 /* Perform the unique id lookup. */
7084 return tlskeys_ref_lookupid(id);
7085 }
7086
7087 /* Perform the string lookup. */
7088 return tlskeys_ref_lookup(reference);
7089}
7090#endif
7091
7092
7093#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7094
Willy Tarreaua9380522022-05-05 08:50:17 +02007095/* dumps all tls keys. Relies on the show_keys_ctx context from the appctx. */
Willy Tarreaubd338642022-05-05 08:59:17 +02007096static int cli_io_handler_tlskeys_files(struct appctx *appctx)
7097{
Willy Tarreaua9380522022-05-05 08:50:17 +02007098 struct show_keys_ctx *ctx = appctx->svcctx;
William Lallemand32af2032016-10-29 18:09:35 +02007099
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007100 switch (ctx->state) {
7101 case SHOW_KEYS_INIT:
William Lallemand32af2032016-10-29 18:09:35 +02007102 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08007103 * quit the function with returning 0. The function is called
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007104 * later and restart at the state "SHOW_KEYS_INIT".
William Lallemand32af2032016-10-29 18:09:35 +02007105 */
7106 chunk_reset(&trash);
7107
Willy Tarreaubd338642022-05-05 08:59:17 +02007108 if (ctx->dump_entries)
William Lallemand32af2032016-10-29 18:09:35 +02007109 chunk_appendf(&trash, "# id secret\n");
7110 else
7111 chunk_appendf(&trash, "# id (file)\n");
7112
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007113 if (applet_putchk(appctx, &trash) == -1)
William Lallemand32af2032016-10-29 18:09:35 +02007114 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007115
William Lallemand32af2032016-10-29 18:09:35 +02007116 /* Now, we start the browsing of the references lists.
7117 * Note that the following call to LIST_ELEM return bad pointer. The only
7118 * available field of this pointer is <list>. It is used with the function
7119 * tlskeys_list_get_next() for retruning the first available entry
7120 */
Willy Tarreaua9380522022-05-05 08:50:17 +02007121 if (ctx->next_ref == NULL)
7122 ctx->next_ref = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007123
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007124 ctx->state = SHOW_KEYS_LIST;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007125 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007126
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007127 case SHOW_KEYS_LIST:
Willy Tarreaua9380522022-05-05 08:50:17 +02007128 while (ctx->next_ref) {
7129 struct tls_keys_ref *ref = ctx->next_ref;
William Lallemand32af2032016-10-29 18:09:35 +02007130
7131 chunk_reset(&trash);
Willy Tarreaubd338642022-05-05 08:59:17 +02007132 if (ctx->dump_entries && ctx->next_index == 0)
William Lallemand32af2032016-10-29 18:09:35 +02007133 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007134
Willy Tarreaua9380522022-05-05 08:50:17 +02007135 if (ctx->next_index == 0)
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007136 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
7137
Willy Tarreaubd338642022-05-05 08:59:17 +02007138 if (ctx->dump_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01007139 int head;
7140
7141 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
7142 head = ref->tls_ticket_enc_index;
Willy Tarreaua9380522022-05-05 08:50:17 +02007143 while (ctx->next_index < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02007144 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02007145
7146 chunk_reset(t2);
7147 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01007148 if (ref->key_size_bits == 128) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007149 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007150 sizeof(struct tls_sess_key_128),
7151 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007152 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007153 t2->area);
7154 }
7155 else if (ref->key_size_bits == 256) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007156 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007157 sizeof(struct tls_sess_key_256),
7158 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007159 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007160 t2->area);
7161 }
7162 else {
7163 /* This case should never happen */
Willy Tarreaua9380522022-05-05 08:50:17 +02007164 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, ctx->next_index);
Emeric Brun9e754772019-01-10 17:51:55 +01007165 }
William Lallemand32af2032016-10-29 18:09:35 +02007166
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007167 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007168 /* let's try again later from this stream. We add ourselves into
7169 * this stream's users so that it can remove us upon termination.
7170 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01007171 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
William Lallemand32af2032016-10-29 18:09:35 +02007172 return 0;
7173 }
Willy Tarreaua9380522022-05-05 08:50:17 +02007174 ctx->next_index++;
William Lallemand32af2032016-10-29 18:09:35 +02007175 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01007176 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaua9380522022-05-05 08:50:17 +02007177 ctx->next_index = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007178 }
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007179 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007180 /* let's try again later from this stream. We add ourselves into
7181 * this stream's users so that it can remove us upon termination.
7182 */
William Lallemand32af2032016-10-29 18:09:35 +02007183 return 0;
7184 }
7185
Willy Tarreaua9380522022-05-05 08:50:17 +02007186 if (ctx->names_only == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02007187 break;
7188
7189 /* get next list entry and check the end of the list */
Willy Tarreaua9380522022-05-05 08:50:17 +02007190 ctx->next_ref = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007191 }
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007192 ctx->state = SHOW_KEYS_DONE;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007193 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007194
7195 default:
William Lallemand32af2032016-10-29 18:09:35 +02007196 return 1;
7197 }
7198 return 0;
7199}
7200
Willy Tarreaua9380522022-05-05 08:50:17 +02007201/* Prepares a "show_keys_ctx" and sets the appropriate io_handler if needed */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007202static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007203{
Willy Tarreaua9380522022-05-05 08:50:17 +02007204 struct show_keys_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
7205
William Lallemand32af2032016-10-29 18:09:35 +02007206 /* no parameter, shows only file list */
7207 if (!*args[2]) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007208 ctx->names_only = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007209 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007210 }
7211
7212 if (args[2][0] == '*') {
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007213 /* list every TLS ticket keys */
7214 ctx->names_only = 1;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007215 } else {
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007216 ctx->next_ref = tlskeys_ref_lookup_ref(args[2]);
7217 if (!ctx->next_ref)
7218 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007219 }
7220
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007221 ctx->dump_entries = 1;
7222 return 0;
7223}
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007224
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007225static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
7226{
7227 struct tls_keys_ref *ref;
7228 int ret;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007229
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007230 /* Expect two parameters: the filename and the new new TLS key in encoding */
7231 if (!*args[3] || !*args[4])
7232 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 +02007233
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007234 ref = tlskeys_ref_lookup_ref(args[3]);
7235 if (!ref)
7236 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007237
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007238 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
7239 if (ret < 0)
7240 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007241
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007242 trash.data = ret;
7243 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
7244 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007245
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007246 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007247}
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007248#endif
7249
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007250
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007251#ifdef HAVE_SSL_PROVIDERS
7252struct provider_name {
7253 const char *name;
7254 struct list list;
7255};
7256
7257
7258static int ssl_provider_get_name_cb(OSSL_PROVIDER *provider, void *cbdata)
7259{
7260 struct list *provider_names = cbdata;
7261 struct provider_name *item = NULL;
7262 const char *name = OSSL_PROVIDER_get0_name(provider);
7263
7264 if (!provider_names)
7265 return 0;
7266
7267 item = calloc(1, sizeof(*item));
7268
7269 if (!item)
7270 return 0;
7271
7272 item->name = name;
7273 LIST_APPEND(provider_names, &item->list);
7274
7275 return 1;
7276}
7277
7278static void ssl_provider_get_name_list(struct list *provider_names)
7279{
7280 if (!provider_names)
7281 return;
7282
7283 OSSL_PROVIDER_do_all(NULL, ssl_provider_get_name_cb, provider_names);
7284}
7285
7286static void ssl_provider_clear_name_list(struct list *provider_names)
7287{
7288 struct provider_name *item = NULL, *item_s = NULL;
7289
7290 if (provider_names) {
7291 list_for_each_entry_safe(item, item_s, provider_names, list) {
7292 LIST_DELETE(&item->list);
7293 free(item);
7294 }
7295 }
7296}
7297
7298static int cli_io_handler_show_providers(struct appctx *appctx)
7299{
7300 struct buffer *trash = get_trash_chunk();
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007301 struct list provider_names;
7302 struct provider_name *name;
7303
7304 LIST_INIT(&provider_names);
7305
7306 chunk_appendf(trash, "Loaded providers : \n");
7307
7308 ssl_provider_get_name_list(&provider_names);
7309
7310 list_for_each_entry(name, &provider_names, list) {
7311 chunk_appendf(trash, "\t- %s\n", name->name);
7312 }
7313
7314 ssl_provider_clear_name_list(&provider_names);
7315
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007316 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007317 goto yield;
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007318
7319 return 1;
7320
7321yield:
7322 return 0;
7323}
7324#endif
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01007325
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007326
William Lallemand32af2032016-10-29 18:09:35 +02007327/* register cli keywords */
7328static struct cli_kw_list cli_kws = {{ },{
7329#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01007330 { { "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 },
7331 { { "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 +02007332#endif
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007333#ifdef HAVE_SSL_PROVIDERS
7334 { { "show", "ssl", "providers", NULL }, "show ssl providers : show loaded SSL providers", NULL, cli_io_handler_show_providers },
7335#endif
William Lallemand32af2032016-10-29 18:09:35 +02007336 { { NULL }, NULL, NULL, NULL }
7337}};
7338
Willy Tarreau0108d902018-11-25 19:14:37 +01007339INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02007340
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02007341/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02007342struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02007343 .snd_buf = ssl_sock_from_buf,
7344 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01007345 .subscribe = ssl_subscribe,
7346 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02007347 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02007348 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02007349 .rcv_pipe = NULL,
7350 .snd_pipe = NULL,
7351 .shutr = NULL,
7352 .shutw = ssl_sock_shutw,
7353 .close = ssl_sock_close,
7354 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01007355 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01007356 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01007357 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01007358 .prepare_srv = ssl_sock_prepare_srv_ctx,
7359 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007360 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02007361 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01007362 .set_idle = ssl_set_idle,
7363 .set_used = ssl_set_used,
Willy Tarreaude827952022-04-11 10:43:28 +02007364 .get_ssl_sock_ctx = ssl_sock_get_ctx,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01007365 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01007366 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02007367};
7368
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007369enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
7370 struct session *sess, struct stream *s, int flags)
7371{
7372 struct connection *conn;
7373
7374 conn = objt_conn(sess->origin);
7375
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007376 if (conn) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007377 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007378 sc_ep_set(s->scf, SE_FL_WAIT_FOR_HS);
Christopher Faulet6e1bbc42022-12-12 08:08:15 +01007379 s->req.flags |= CF_READ_EVENT;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007380 return ACT_RET_YIELD;
7381 }
7382 }
7383 return (ACT_RET_CONT);
7384}
7385
7386static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
7387{
7388 rule->action_ptr = ssl_action_wait_for_hs;
7389
7390 return ACT_RET_PRS_OK;
7391}
7392
7393static struct action_kw_list http_req_actions = {ILH, {
7394 { "wait-for-handshake", ssl_parse_wait_for_hs },
7395 { /* END */ }
7396}};
7397
Willy Tarreau0108d902018-11-25 19:14:37 +01007398INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
7399
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007400#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007401
7402static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7403{
7404 if (ptr) {
7405 chunk_destroy(ptr);
7406 free(ptr);
7407 }
7408}
7409
7410#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007411
William Lallemand76b4a122020-08-04 17:41:39 +02007412
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007413static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7414{
Willy Tarreaubafbe012017-11-24 17:34:44 +01007415 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007416}
William Lallemand7d42ef52020-07-06 11:41:30 +02007417
William Lallemand722180a2021-06-09 16:46:12 +02007418#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007419static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7420{
7421 struct ssl_keylog *keylog;
7422
7423 if (!ptr)
7424 return;
7425
7426 keylog = ptr;
7427
7428 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7429 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7430 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7431 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7432 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7433 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7434 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7435 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7436
7437 pool_free(pool_head_ssl_keylog, ptr);
7438}
7439#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007440
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007441static void ssl_sock_clt_crt_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7442{
7443 if (!ptr)
7444 return;
7445
7446 X509_free((X509*)ptr);
7447}
7448
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01007449static void ssl_sock_clt_sni_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7450{
7451 pool_free(ssl_sock_client_sni_pool, ptr);
7452}
7453
Willy Tarreau92faadf2012-10-10 23:04:25 +02007454static void __ssl_sock_init(void)
7455{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007456#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007457 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007458 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007459#endif
Emeric Brun46591952012-05-18 15:47:34 +02007460
Willy Tarreauef934602016-12-22 23:12:01 +01007461 if (global_ssl.listen_default_ciphers)
7462 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7463 if (global_ssl.connect_default_ciphers)
7464 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007465#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007466 if (global_ssl.listen_default_ciphersuites)
7467 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7468 if (global_ssl.connect_default_ciphersuites)
7469 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7470#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007471
Willy Tarreau13e14102016-12-22 20:25:26 +01007472 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007473#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007474 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007475#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007476#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007477 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007478 n = sk_SSL_COMP_num(cm);
7479 while (n--) {
7480 (void) sk_SSL_COMP_pop(cm);
7481 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007482#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007483
Willy Tarreau5db847a2019-05-09 14:13:35 +02007484#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007485 ssl_locking_init();
7486#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007487#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007488 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
7489#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007490
7491#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7492 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
7493#endif
7494
Thierry FOURNIER28962c92018-06-17 21:37:05 +02007495 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02007496 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 +01007497#ifdef USE_QUIC
7498 ssl_qc_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7499#endif /* USE_QUIC */
William Lallemand722180a2021-06-09 16:46:12 +02007500#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007501 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
7502#endif
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007503 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 +01007504 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 +02007505#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00007506 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007507 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007508#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01007509#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7510 hap_register_post_check(tlskeys_finalize_config);
7511#endif
Willy Tarreau80713382018-11-26 10:19:54 +01007512
7513 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
7514 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
7515
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007516 hap_register_post_deinit(ssl_free_global_issuers);
7517
Willy Tarreau80713382018-11-26 10:19:54 +01007518#ifndef OPENSSL_NO_DH
7519 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7520 hap_register_post_deinit(ssl_free_dh);
7521#endif
William Lallemandd7bfbe22022-04-11 18:41:24 +02007522#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Willy Tarreau80713382018-11-26 10:19:54 +01007523 hap_register_post_deinit(ssl_free_engines);
7524#endif
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02007525#ifdef HAVE_SSL_PROVIDERS
7526 hap_register_post_deinit(ssl_unload_providers);
7527#endif
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01007528#if HA_OPENSSL_VERSION_NUMBER < 0x3000000fL
Willy Tarreau80713382018-11-26 10:19:54 +01007529 /* Load SSL string for the verbose & debug mode. */
7530 ERR_load_SSL_strings();
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01007531#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007532 ha_meth = BIO_meth_new(0x666, "ha methods");
7533 BIO_meth_set_write(ha_meth, ha_ssl_write);
7534 BIO_meth_set_read(ha_meth, ha_ssl_read);
7535 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
7536 BIO_meth_set_create(ha_meth, ha_ssl_new);
7537 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
7538 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
7539 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02007540
7541 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007542
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01007543 HA_SPIN_INIT(&ocsp_tree_lock);
7544
Dragan Dosen9ac98092020-05-11 15:51:45 +02007545 /* Try to register dedicated SSL/TLS protocol message callbacks for
7546 * heartbleed attack (CVE-2014-0160) and clienthello.
7547 */
7548 hap_register_post_check(ssl_sock_register_msg_callbacks);
7549
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007550 /* Try to free all callbacks that were registered by using
7551 * ssl_sock_register_msg_callback().
7552 */
7553 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01007554}
Willy Tarreau79367f92022-04-25 19:18:24 +02007555INITCALL0(STG_REGISTER, __ssl_sock_init);
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01007556
Willy Tarreau80713382018-11-26 10:19:54 +01007557/* Compute and register the version string */
7558static void ssl_register_build_options()
7559{
7560 char *ptr = NULL;
7561 int i;
7562
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007563 memprintf(&ptr, "Built with OpenSSL version : "
7564#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007565 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007566#else /* OPENSSL_IS_BORINGSSL */
7567 OPENSSL_VERSION_TEXT
7568 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08007569 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02007570 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007571#endif
7572 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007573#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007574 "no (library version too old)"
7575#elif defined(OPENSSL_NO_TLSEXT)
7576 "no (disabled via OPENSSL_NO_TLSEXT)"
7577#else
7578 "yes"
7579#endif
7580 "", ptr);
7581
7582 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
7583#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
7584 "yes"
7585#else
7586#ifdef OPENSSL_NO_TLSEXT
7587 "no (because of OPENSSL_NO_TLSEXT)"
7588#else
7589 "no (version might be too old, 0.9.8f min needed)"
7590#endif
7591#endif
7592 "", ptr);
7593
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02007594 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
7595 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
7596 if (methodVersions[i].option)
7597 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007598
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007599#ifdef HAVE_SSL_PROVIDERS
7600 {
7601 struct list provider_names;
7602 struct provider_name *name;
7603 LIST_INIT(&provider_names);
7604 ssl_provider_get_name_list(&provider_names);
7605
7606 memprintf(&ptr, "%s\nOpenSSL providers loaded :", ptr);
7607
7608 list_for_each_entry(name, &provider_names, list) {
7609 memprintf(&ptr, "%s %s", ptr, name->name);
7610 }
7611
7612 ssl_provider_clear_name_list(&provider_names);
7613 }
7614#endif
7615
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007616 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01007617}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007618
Willy Tarreau80713382018-11-26 10:19:54 +01007619INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02007620
William Lallemandd7bfbe22022-04-11 18:41:24 +02007621#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00007622void ssl_free_engines(void) {
7623 struct ssl_engine_list *wl, *wlb;
7624 /* free up engine list */
7625 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
7626 ENGINE_finish(wl->e);
7627 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02007628 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00007629 free(wl);
7630 }
7631}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007632#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02007633
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02007634#ifdef HAVE_SSL_PROVIDERS
7635void ssl_unload_providers(void) {
7636 struct ssl_provider_list *prov, *provb;
7637 list_for_each_entry_safe(prov, provb, &openssl_providers, list) {
7638 OSSL_PROVIDER_unload(prov->provider);
7639 LIST_DELETE(&prov->list);
7640 free(prov);
7641 }
7642}
7643#endif
7644
Remi Gacogned3a23c32015-05-28 16:39:47 +02007645#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00007646void ssl_free_dh(void) {
7647 if (local_dh_1024) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007648 HASSL_DH_free(local_dh_1024);
Grant Zhang872f9c22017-01-21 01:10:18 +00007649 local_dh_1024 = NULL;
7650 }
7651 if (local_dh_2048) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007652 HASSL_DH_free(local_dh_2048);
Grant Zhang872f9c22017-01-21 01:10:18 +00007653 local_dh_2048 = NULL;
7654 }
7655 if (local_dh_4096) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007656 HASSL_DH_free(local_dh_4096);
Grant Zhang872f9c22017-01-21 01:10:18 +00007657 local_dh_4096 = NULL;
7658 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02007659 if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007660 HASSL_DH_free(global_dh);
Remi Gacogne47783ef2015-05-29 15:53:22 +02007661 global_dh = NULL;
7662 }
Grant Zhang872f9c22017-01-21 01:10:18 +00007663}
7664#endif
7665
Grant Zhang872f9c22017-01-21 01:10:18 +00007666static void __ssl_sock_deinit(void)
7667{
7668#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007669 if (ssl_ctx_lru_tree) {
7670 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007671 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02007672 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02007673#endif
7674
Willy Tarreau5db847a2019-05-09 14:13:35 +02007675#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007676 ERR_remove_state(0);
7677 ERR_free_strings();
7678
7679 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08007680#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007681
Willy Tarreau5db847a2019-05-09 14:13:35 +02007682#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007683 CRYPTO_cleanup_all_ex_data();
7684#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007685 BIO_meth_free(ha_meth);
Remi Tricot-Le Breton6477bbd2022-12-20 11:11:13 +01007686
7687#if !defined OPENSSL_NO_OCSP
7688 ssl_destroy_ocsp_update_task();
7689#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007690}
Willy Tarreau79367f92022-04-25 19:18:24 +02007691REGISTER_POST_DEINIT(__ssl_sock_deinit);
Remi Gacogned3a23c32015-05-28 16:39:47 +02007692
William Dauchyf6370442020-11-14 19:25:33 +01007693
Emeric Brun46591952012-05-18 15:47:34 +02007694/*
7695 * Local variables:
7696 * c-indent-level: 8
7697 * c-basic-offset: 8
7698 * End:
7699 */