blob: 7c3c152a578304ed4441e556915f6b2800449e8c [file] [log] [blame]
yanbzhu08ce6ab2015-12-02 13:01:29 -05001
Emeric Brun46591952012-05-18 15:47:34 +02002/*
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02003 * SSL/TLS transport layer over SOCK_STREAM sockets
Emeric Brun46591952012-05-18 15:47:34 +02004 *
5 * Copyright (C) 2012 EXCELIANCE, Emeric Brun <ebrun@exceliance.fr>
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version
10 * 2 of the License, or (at your option) any later version.
11 *
Willy Tarreau69845df2012-09-10 09:43:09 +020012 * Acknowledgement:
13 * We'd like to specially thank the Stud project authors for a very clean
14 * and well documented code which helped us understand how the OpenSSL API
15 * ought to be used in non-blocking mode. This is one difficult part which
16 * is not easy to get from the OpenSSL doc, and reading the Stud code made
17 * it much more obvious than the examples in the OpenSSL package. Keep up
18 * the good works, guys !
19 *
20 * Stud is an extremely efficient and scalable SSL/TLS proxy which combines
21 * particularly well with haproxy. For more info about this project, visit :
22 * https://github.com/bumptech/stud
23 *
Emeric Brun46591952012-05-18 15:47:34 +020024 */
25
Willy Tarreau8d164dc2019-05-10 09:35:00 +020026/* Note: do NOT include openssl/xxx.h here, do it in openssl-compat.h */
Emeric Brun46591952012-05-18 15:47:34 +020027#define _GNU_SOURCE
Emeric Brunfc0421f2012-09-07 17:30:07 +020028#include <ctype.h>
29#include <dirent.h>
Emeric Brun46591952012-05-18 15:47:34 +020030#include <errno.h>
Emeric Brun46591952012-05-18 15:47:34 +020031#include <stdio.h>
32#include <stdlib.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020033#include <string.h>
34#include <unistd.h>
Emeric Brun46591952012-05-18 15:47:34 +020035
36#include <sys/socket.h>
37#include <sys/stat.h>
38#include <sys/types.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020039#include <netdb.h>
Emeric Brun46591952012-05-18 15:47:34 +020040#include <netinet/tcp.h>
41
Willy Tarreaub2551052020-06-09 09:07:15 +020042#include <import/ebpttree.h>
43#include <import/ebsttree.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020044#include <import/lru.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020045
Willy Tarreaub2551052020-06-09 09:07:15 +020046#include <haproxy/api.h>
Willy Tarreaua9380522022-05-05 08:50:17 +020047#include <haproxy/applet.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020048#include <haproxy/arg.h>
49#include <haproxy/base64.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020050#include <haproxy/channel.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020051#include <haproxy/chunk.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020052#include <haproxy/cli.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020053#include <haproxy/connection.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020054#include <haproxy/dynbuf.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020055#include <haproxy/errors.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020056#include <haproxy/fd.h>
57#include <haproxy/freq_ctr.h>
Willy Tarreau762d7a52020-06-04 11:23:07 +020058#include <haproxy/frontend.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020059#include <haproxy/global.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020060#include <haproxy/http_rules.h>
Willy Tarreauaeed4a82020-06-04 22:01:04 +020061#include <haproxy/log.h>
Willy Tarreau6019fab2020-05-27 16:26:00 +020062#include <haproxy/openssl-compat.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020063#include <haproxy/pattern-t.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020064#include <haproxy/proto_tcp.h>
Willy Tarreaua264d962020-06-04 22:29:18 +020065#include <haproxy/proxy.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020066#include <haproxy/sample.h>
67#include <haproxy/sc_strm.h>
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020068#include <haproxy/quic_conn.h>
Frédéric Lécaille748ece62022-05-21 23:58:40 +020069#include <haproxy/quic_tp.h>
Willy Tarreau1e56f922020-06-04 23:20:13 +020070#include <haproxy/server.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020071#include <haproxy/shctx.h>
Willy Tarreau47d7f902020-06-04 14:25:47 +020072#include <haproxy/ssl_ckch.h>
Willy Tarreau52d88722020-06-04 14:29:23 +020073#include <haproxy/ssl_crtlist.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020074#include <haproxy/ssl_sock.h>
Willy Tarreaub2bd8652020-06-04 14:21:22 +020075#include <haproxy/ssl_utils.h>
Amaury Denoyelle9963fa72020-11-03 17:10:00 +010076#include <haproxy/stats.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020077#include <haproxy/stconn.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020078#include <haproxy/stream-t.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020079#include <haproxy/task.h>
Willy Tarreauc2f7c582020-06-02 18:15:32 +020080#include <haproxy/ticks.h>
Willy Tarreau92b4f132020-06-01 11:05:15 +020081#include <haproxy/time.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020082#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020083#include <haproxy/vars.h>
Tim Duesterhusd5fc8fc2021-09-11 17:51:13 +020084#include <haproxy/xxhash.h>
Remi Tricot-Le Breton2e7d1eb2022-01-11 10:11:10 +010085#include <haproxy/istbuf.h>
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +010086#include <haproxy/ssl_ocsp.h>
Emeric Brun46591952012-05-18 15:47:34 +020087
Emeric Brun46591952012-05-18 15:47:34 +020088
Willy Tarreau9356dac2019-05-10 09:22:53 +020089/* ***** READ THIS before adding code here! *****
90 *
91 * Due to API incompatibilities between multiple OpenSSL versions and their
92 * derivatives, it's often tempting to add macros to (re-)define certain
93 * symbols. Please do not do this here, and do it in common/openssl-compat.h
94 * exclusively so that the whole code consistently uses the same macros.
95 *
96 * Whenever possible if a macro is missing in certain versions, it's better
97 * to conditionally define it in openssl-compat.h than using lots of ifdefs.
98 */
99
Emeric Brunece0c332017-12-06 13:51:49 +0100100int nb_engines = 0;
Emeric Brune1f38db2012-09-03 20:36:47 +0200101
William Lallemande0f3fd52020-02-25 14:53:06 +0100102static struct eb_root cert_issuer_tree = EB_ROOT; /* issuers tree from "issuers-chain-path" */
103
William Lallemand7fd8b452020-05-07 15:20:43 +0200104struct global_ssl global_ssl = {
Willy Tarreauef934602016-12-22 23:12:01 +0100105#ifdef LISTEN_DEFAULT_CIPHERS
106 .listen_default_ciphers = LISTEN_DEFAULT_CIPHERS,
107#endif
108#ifdef CONNECT_DEFAULT_CIPHERS
109 .connect_default_ciphers = CONNECT_DEFAULT_CIPHERS,
110#endif
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +0500111#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200112 .listen_default_ciphersuites = LISTEN_DEFAULT_CIPHERSUITES,
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200113 .connect_default_ciphersuites = CONNECT_DEFAULT_CIPHERSUITES,
114#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100115 .listen_default_ssloptions = BC_SSL_O_NONE,
116 .connect_default_ssloptions = SRV_SSL_O_NONE,
117
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +0200118 .listen_default_sslmethods.flags = MC_SSL_O_ALL,
119 .listen_default_sslmethods.min = CONF_TLSV_NONE,
120 .listen_default_sslmethods.max = CONF_TLSV_NONE,
121 .connect_default_sslmethods.flags = MC_SSL_O_ALL,
122 .connect_default_sslmethods.min = CONF_TLSV_NONE,
123 .connect_default_sslmethods.max = CONF_TLSV_NONE,
124
Willy Tarreauef934602016-12-22 23:12:01 +0100125#ifdef DEFAULT_SSL_MAX_RECORD
126 .max_record = DEFAULT_SSL_MAX_RECORD,
127#endif
Thomas Prückl10243932022-04-27 13:04:54 +0200128 .hard_max_record = 0,
Willy Tarreauef934602016-12-22 23:12:01 +0100129 .default_dh_param = SSL_DEFAULT_DH_PARAM,
130 .ctx_cache = DEFAULT_SSL_CTX_CACHE,
Marcin Deranek310a2602021-07-13 19:04:24 +0200131 .capture_buffer_size = 0,
William Lallemand3af48e72020-02-03 17:15:52 +0100132 .extra_files = SSL_GF_ALL,
William Lallemand8e8581e2020-10-20 17:36:46 +0200133 .extra_files_noext = 0,
William Lallemand722180a2021-06-09 16:46:12 +0200134#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200135 .keylog = 0
136#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100137};
138
Olivier Houcharda8955d52019-04-07 22:00:38 +0200139static BIO_METHOD *ha_meth;
140
Willy Tarreaub8dec4a2022-06-23 11:02:08 +0200141DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx", sizeof(struct ssl_sock_ctx));
Olivier Houchard66ab4982019-02-26 18:37:15 +0100142
Willy Tarreaub8dec4a2022-06-23 11:02:08 +0200143DECLARE_STATIC_POOL(ssl_sock_client_sni_pool, "ssl_sock_client_sni", TLSEXT_MAXLEN_host_name + 1);
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100144
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100145/* ssl stats module */
146enum {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100147 SSL_ST_SESS,
148 SSL_ST_REUSED_SESS,
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100149 SSL_ST_FAILED_HANDSHAKE,
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100150
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100151 SSL_ST_STATS_COUNT /* must be the last member of the enum */
152};
153
154static struct name_desc ssl_stats[] = {
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100155 [SSL_ST_SESS] = { .name = "ssl_sess",
156 .desc = "Total number of ssl sessions established" },
157 [SSL_ST_REUSED_SESS] = { .name = "ssl_reused_sess",
158 .desc = "Total number of ssl sessions reused" },
159 [SSL_ST_FAILED_HANDSHAKE] = { .name = "ssl_failed_handshake",
160 .desc = "Total number of failed handshake" },
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100161};
162
163static struct ssl_counters {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100164 long long sess;
165 long long reused_sess;
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100166 long long failed_handshake;
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100167} ssl_counters;
168
169static void ssl_fill_stats(void *data, struct field *stats)
170{
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100171 struct ssl_counters *counters = data;
172
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100173 stats[SSL_ST_SESS] = mkf_u64(FN_COUNTER, counters->sess);
174 stats[SSL_ST_REUSED_SESS] = mkf_u64(FN_COUNTER, counters->reused_sess);
175 stats[SSL_ST_FAILED_HANDSHAKE] = mkf_u64(FN_COUNTER, counters->failed_handshake);
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100176}
177
178static struct stats_module ssl_stats_module = {
179 .name = "ssl",
180 .fill_stats = ssl_fill_stats,
181 .stats = ssl_stats,
182 .stats_count = SSL_ST_STATS_COUNT,
183 .counters = &ssl_counters,
184 .counters_size = sizeof(ssl_counters),
185 .domain_flags = MK_STATS_PROXY_DOMAIN(STATS_PX_CAP_FE|STATS_PX_CAP_LI|STATS_PX_CAP_BE|STATS_PX_CAP_SRV),
186 .clearable = 1,
187};
188
189INITCALL1(STG_REGISTER, stats_register_module, &ssl_stats_module);
190
Willy Tarreaua9380522022-05-05 08:50:17 +0200191/* CLI context for "show tls-keys" */
192struct show_keys_ctx {
193 struct tls_keys_ref *next_ref; /* next reference to be dumped */
194 int names_only; /* non-zero = only show file names */
195 int next_index; /* next index to be dumped */
Willy Tarreaubd338642022-05-05 08:59:17 +0200196 int dump_entries; /* dump entries also */
Willy Tarreau9c5a38c2022-05-05 09:03:44 +0200197 enum {
198 SHOW_KEYS_INIT = 0,
199 SHOW_KEYS_LIST,
200 SHOW_KEYS_DONE,
201 } state; /* phase of the current dump */
Willy Tarreaua9380522022-05-05 08:50:17 +0200202};
203
Willy Tarreau691d5032021-01-20 14:55:01 +0100204/* ssl_sock_io_cb is exported to see it resolved in "show fd" */
Willy Tarreau144f84a2021-03-02 16:09:26 +0100205struct task *ssl_sock_io_cb(struct task *, void *, unsigned int);
Olivier Houchard000694c2019-05-23 14:45:12 +0200206static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
Olivier Houchardea8dd942019-05-20 14:02:16 +0200207
Olivier Houcharda8955d52019-04-07 22:00:38 +0200208/* Methods to implement OpenSSL BIO */
209static int ha_ssl_write(BIO *h, const char *buf, int num)
210{
211 struct buffer tmpbuf;
212 struct ssl_sock_ctx *ctx;
213 int ret;
214
215 ctx = BIO_get_data(h);
216 tmpbuf.size = num;
217 tmpbuf.area = (void *)(uintptr_t)buf;
218 tmpbuf.data = num;
219 tmpbuf.head = 0;
220 ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200221 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200222 BIO_set_retry_write(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200223 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200224 } else if (ret == 0)
225 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200226 return ret;
227}
228
229static int ha_ssl_gets(BIO *h, char *buf, int size)
230{
231
232 return 0;
233}
234
235static int ha_ssl_puts(BIO *h, const char *str)
236{
237
238 return ha_ssl_write(h, str, strlen(str));
239}
240
241static int ha_ssl_read(BIO *h, char *buf, int size)
242{
243 struct buffer tmpbuf;
244 struct ssl_sock_ctx *ctx;
245 int ret;
246
247 ctx = BIO_get_data(h);
248 tmpbuf.size = size;
249 tmpbuf.area = buf;
250 tmpbuf.data = 0;
251 tmpbuf.head = 0;
252 ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200253 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200254 BIO_set_retry_read(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200255 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200256 } else if (ret == 0)
257 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200258
259 return ret;
260}
261
262static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
263{
264 int ret = 0;
265 switch (cmd) {
266 case BIO_CTRL_DUP:
267 case BIO_CTRL_FLUSH:
268 ret = 1;
269 break;
270 }
271 return ret;
272}
273
274static int ha_ssl_new(BIO *h)
275{
276 BIO_set_init(h, 1);
277 BIO_set_data(h, NULL);
278 BIO_clear_flags(h, ~0);
279 return 1;
280}
281
282static int ha_ssl_free(BIO *data)
283{
284
285 return 1;
286}
287
288
Willy Tarreau5db847a2019-05-09 14:13:35 +0200289#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100290
Emeric Brun821bb9b2017-06-15 16:37:39 +0200291static HA_RWLOCK_T *ssl_rwlocks;
292
293
294unsigned long ssl_id_function(void)
295{
296 return (unsigned long)tid;
297}
298
299void ssl_locking_function(int mode, int n, const char * file, int line)
300{
301 if (mode & CRYPTO_LOCK) {
302 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100303 HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200304 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100305 HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200306 }
307 else {
308 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100309 HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200310 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100311 HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200312 }
313}
314
315static int ssl_locking_init(void)
316{
317 int i;
318
319 ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
320 if (!ssl_rwlocks)
321 return -1;
322
323 for (i = 0 ; i < CRYPTO_num_locks() ; i++)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100324 HA_RWLOCK_INIT(&ssl_rwlocks[i]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200325
326 CRYPTO_set_id_callback(ssl_id_function);
327 CRYPTO_set_locking_callback(ssl_locking_function);
328
329 return 0;
330}
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100331
Emeric Brun821bb9b2017-06-15 16:37:39 +0200332#endif
333
Willy Tarreauaf613e82020-06-05 08:40:51 +0200334__decl_thread(HA_SPINLOCK_T ckch_lock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200335
William Lallemandbc6ca7c2019-10-29 23:48:19 +0100336
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200337
338/* mimic what X509_STORE_load_locations do with store_ctx */
339static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
340{
Remi Tricot-Le Bretond75b99e2021-05-17 11:45:55 +0200341 X509_STORE *store = NULL;
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +0100342 struct cafile_entry *ca_e = ssl_store_get_cafile_entry(path, 0);
343 if (ca_e)
344 store = ca_e->ca_store;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200345 if (store_ctx && store) {
346 int i;
347 X509_OBJECT *obj;
348 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
349 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
350 obj = sk_X509_OBJECT_value(objs, i);
351 switch (X509_OBJECT_get_type(obj)) {
352 case X509_LU_X509:
353 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
354 break;
355 case X509_LU_CRL:
356 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
357 break;
358 default:
359 break;
360 }
361 }
362 return 1;
363 }
364 return 0;
365}
366
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500367/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200368static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
369{
370 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
371 return ssl_set_cert_crl_file(store_ctx, path);
372}
373
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200374/*
375 Extract CA_list from CA_file already in tree.
376 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
377 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
378*/
379static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
380{
381 struct ebmb_node *eb;
382 struct cafile_entry *ca_e;
383
384 eb = ebst_lookup(&cafile_tree, path);
385 if (!eb)
386 return NULL;
387 ca_e = ebmb_entry(eb, struct cafile_entry, node);
388
389 if (ca_e->ca_list == NULL) {
390 int i;
391 unsigned long key;
392 struct eb_root ca_name_tree = EB_ROOT;
393 struct eb64_node *node, *back;
394 struct {
395 struct eb64_node node;
396 X509_NAME *xname;
397 } *ca_name;
398 STACK_OF(X509_OBJECT) *objs;
399 STACK_OF(X509_NAME) *skn;
400 X509 *x;
401 X509_NAME *xn;
402
403 skn = sk_X509_NAME_new_null();
404 /* take x509 from cafile_tree */
405 objs = X509_STORE_get0_objects(ca_e->ca_store);
406 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
407 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
408 if (!x)
409 continue;
410 xn = X509_get_subject_name(x);
411 if (!xn)
412 continue;
413 /* Check for duplicates. */
414 key = X509_NAME_hash(xn);
415 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
416 node && ca_name == NULL;
417 node = eb64_next(node)) {
418 ca_name = container_of(node, typeof(*ca_name), node);
419 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
420 ca_name = NULL;
421 }
422 /* find a duplicate */
423 if (ca_name)
424 continue;
425 ca_name = calloc(1, sizeof *ca_name);
426 xn = X509_NAME_dup(xn);
427 if (!ca_name ||
428 !xn ||
429 !sk_X509_NAME_push(skn, xn)) {
430 free(ca_name);
431 X509_NAME_free(xn);
432 sk_X509_NAME_pop_free(skn, X509_NAME_free);
433 sk_X509_NAME_free(skn);
434 skn = NULL;
435 break;
436 }
437 ca_name->node.key = key;
438 ca_name->xname = xn;
439 eb64_insert(&ca_name_tree, &ca_name->node);
440 }
441 ca_e->ca_list = skn;
442 /* remove temporary ca_name tree */
443 node = eb64_first(&ca_name_tree);
444 while (node) {
445 ca_name = container_of(node, typeof(*ca_name), node);
446 back = eb64_next(node);
447 eb64_delete(node);
448 free(ca_name);
449 node = back;
450 }
451 }
452 return ca_e->ca_list;
453}
454
Willy Tarreauff882702021-04-10 17:23:00 +0200455struct pool_head *pool_head_ssl_capture __read_mostly = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200456int ssl_capture_ptr_index = -1;
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +0100457int ssl_app_data_index = -1;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +0100458#ifdef USE_QUIC
459int ssl_qc_app_data_index = -1;
460#endif /* USE_QUIC */
Willy Tarreauef934602016-12-22 23:12:01 +0100461
William Lallemand722180a2021-06-09 16:46:12 +0200462#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200463int ssl_keylog_index = -1;
Willy Tarreauff882702021-04-10 17:23:00 +0200464struct pool_head *pool_head_ssl_keylog __read_mostly = NULL;
465struct pool_head *pool_head_ssl_keylog_str __read_mostly = NULL;
William Lallemand7d42ef52020-07-06 11:41:30 +0200466#endif
467
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +0200468int ssl_client_crt_ref_index = -1;
469
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100470/* Used to store the client's SNI in case of ClientHello callback error */
471int ssl_client_sni_index = -1;
472
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200473#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
474struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
475#endif
476
William Lallemandd7bfbe22022-04-11 18:41:24 +0200477#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200478unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000479struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
480struct ssl_engine_list {
481 struct list list;
482 ENGINE *e;
483};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200484#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000485
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +0200486#ifdef HAVE_SSL_PROVIDERS
487struct list openssl_providers = LIST_HEAD_INIT(openssl_providers);
488struct ssl_provider_list {
489 struct list list;
490 OSSL_PROVIDER *provider;
491};
492#endif
493
Remi Gacogne8de54152014-07-15 11:36:40 +0200494#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200495static int ssl_dh_ptr_index = -1;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +0100496static HASSL_DH *global_dh = NULL;
497static HASSL_DH *local_dh_1024 = NULL;
498static HASSL_DH *local_dh_2048 = NULL;
499static HASSL_DH *local_dh_4096 = NULL;
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100500#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +0100501static DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100502#else
503static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey);
504#endif
Remi Gacogne8de54152014-07-15 11:36:40 +0200505#endif /* OPENSSL_NO_DH */
506
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100507#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200508/* X509V3 Extensions that will be added on generated certificates */
509#define X509V3_EXT_SIZE 5
510static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
511 "basicConstraints",
512 "nsComment",
513 "subjectKeyIdentifier",
514 "authorityKeyIdentifier",
515 "keyUsage",
516};
517static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
518 "CA:FALSE",
519 "\"OpenSSL Generated Certificate\"",
520 "hash",
521 "keyid,issuer:always",
522 "nonRepudiation,digitalSignature,keyEncipherment"
523};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200524/* LRU cache to store generated certificate */
525static struct lru64_head *ssl_ctx_lru_tree = NULL;
526static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200527static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100528__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200529
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200530#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
531
yanbzhube2774d2015-12-10 15:07:30 -0500532/* The order here matters for picking a default context,
533 * keep the most common keytype at the bottom of the list
534 */
535const char *SSL_SOCK_KEYTYPE_NAMES[] = {
536 "dsa",
537 "ecdsa",
538 "rsa"
539};
yanbzhube2774d2015-12-10 15:07:30 -0500540
William Lallemandc3cd35f2017-11-28 11:04:43 +0100541static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100542static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
543
Dragan Dosen9ac98092020-05-11 15:51:45 +0200544/* Dedicated callback functions for heartbeat and clienthello.
545 */
546#ifdef TLS1_RT_HEARTBEAT
547static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
548 int content_type, const void *buf, size_t len,
549 SSL *ssl);
550#endif
551static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
552 int content_type, const void *buf, size_t len,
553 SSL *ssl);
554
William Lallemand722180a2021-06-09 16:46:12 +0200555#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200556static void ssl_init_keylog(struct connection *conn, int write_p, int version,
557 int content_type, const void *buf, size_t len,
558 SSL *ssl);
559#endif
560
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200561/* List head of all registered SSL/TLS protocol message callbacks. */
562struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
563
564/* Registers the function <func> in order to be called on SSL/TLS protocol
565 * message processing. It will return 0 if the function <func> is not set
566 * or if it fails to allocate memory.
567 */
568int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
569{
570 struct ssl_sock_msg_callback *cbk;
571
572 if (!func)
573 return 0;
574
575 cbk = calloc(1, sizeof(*cbk));
576 if (!cbk) {
577 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
578 return 0;
579 }
580
581 cbk->func = func;
582
Willy Tarreau2b718102021-04-21 07:32:39 +0200583 LIST_APPEND(&ssl_sock_msg_callbacks, &cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200584
585 return 1;
586}
587
Dragan Dosen9ac98092020-05-11 15:51:45 +0200588/* Used to register dedicated SSL/TLS protocol message callbacks.
589 */
590static int ssl_sock_register_msg_callbacks(void)
591{
592#ifdef TLS1_RT_HEARTBEAT
593 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
594 return ERR_ABORT;
595#endif
Marcin Deranek310a2602021-07-13 19:04:24 +0200596 if (global_ssl.capture_buffer_size > 0) {
Dragan Dosen9ac98092020-05-11 15:51:45 +0200597 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
598 return ERR_ABORT;
599 }
William Lallemand722180a2021-06-09 16:46:12 +0200600#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200601 if (global_ssl.keylog > 0) {
602 if (!ssl_sock_register_msg_callback(ssl_init_keylog))
603 return ERR_ABORT;
604 }
605#endif
606
Christopher Fauletfc633b62020-11-06 15:24:23 +0100607 return ERR_NONE;
Dragan Dosen9ac98092020-05-11 15:51:45 +0200608}
609
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200610/* Used to free all SSL/TLS protocol message callbacks that were
611 * registered by using ssl_sock_register_msg_callback().
612 */
613static void ssl_sock_unregister_msg_callbacks(void)
614{
615 struct ssl_sock_msg_callback *cbk, *cbkback;
616
617 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +0200618 LIST_DELETE(&cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200619 free(cbk);
620 }
621}
622
Willy Tarreaude827952022-04-11 10:43:28 +0200623static struct ssl_sock_ctx *ssl_sock_get_ctx(struct connection *conn)
624{
625 if (!conn || conn->xprt != xprt_get(XPRT_SSL) || !conn->xprt_ctx)
626 return NULL;
627
628 return (struct ssl_sock_ctx *)conn->xprt_ctx;
629}
630
Dragan Doseneb607fe2020-05-11 17:17:06 +0200631SSL *ssl_sock_get_ssl_object(struct connection *conn)
632{
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200633 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dragan Doseneb607fe2020-05-11 17:17:06 +0200634
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200635 return ctx ? ctx->ssl : NULL;
Dragan Doseneb607fe2020-05-11 17:17:06 +0200636}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100637/*
638 * This function gives the detail of the SSL error. It is used only
639 * if the debug mode and the verbose mode are activated. It dump all
640 * the SSL error until the stack was empty.
641 */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +0200642static forceinline void ssl_sock_dump_errors(struct connection *conn,
643 struct quic_conn *qc)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100644{
645 unsigned long ret;
646
647 if (unlikely(global.mode & MODE_DEBUG)) {
648 while(1) {
Remi Tricot-Le Breton1effd9a2022-02-11 12:04:44 +0100649 const char *func = NULL;
650 ERR_peek_error_func(&func);
651
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100652 ret = ERR_get_error();
653 if (ret == 0)
654 return;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +0200655 if (conn) {
656 fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
657 conn_fd(conn), ret,
658 func, ERR_reason_error_string(ret));
659 }
660#ifdef USE_QUIC
661 else {
662 /* TODO: we are not sure <conn> is always initialized for QUIC connections */
663 fprintf(stderr, "qc @%p OpenSSL error[0x%lx] %s: %s\n", qc, ret,
664 func, ERR_reason_error_string(ret));
665 }
666#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100667 }
668 }
669}
670
yanbzhube2774d2015-12-10 15:07:30 -0500671
William Lallemandd7bfbe22022-04-11 18:41:24 +0200672#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200673int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000674{
675 int err_code = ERR_ABORT;
676 ENGINE *engine;
677 struct ssl_engine_list *el;
678
679 /* grab the structural reference to the engine */
680 engine = ENGINE_by_id(engine_id);
681 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100682 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000683 goto fail_get;
684 }
685
686 if (!ENGINE_init(engine)) {
687 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100688 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000689 goto fail_init;
690 }
691
692 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100693 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000694 goto fail_set_method;
695 }
696
697 el = calloc(1, sizeof(*el));
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200698 if (!el)
699 goto fail_alloc;
Grant Zhang872f9c22017-01-21 01:10:18 +0000700 el->e = engine;
Willy Tarreau2b718102021-04-21 07:32:39 +0200701 LIST_INSERT(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100702 nb_engines++;
703 if (global_ssl.async)
704 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000705 return 0;
706
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200707fail_alloc:
Grant Zhang872f9c22017-01-21 01:10:18 +0000708fail_set_method:
709 /* release the functional reference from ENGINE_init() */
710 ENGINE_finish(engine);
711
712fail_init:
713 /* release the structural reference from ENGINE_by_id() */
714 ENGINE_free(engine);
715
716fail_get:
717 return err_code;
718}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200719#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000720
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +0200721#ifdef HAVE_SSL_PROVIDERS
722int ssl_init_provider(const char *provider_name)
723{
724 int err_code = ERR_ABORT;
725 struct ssl_provider_list *prov = NULL;
726
727 prov = calloc(1, sizeof(*prov));
728 if (!prov) {
729 ha_alert("ssl-provider %s: memory allocation failure\n", provider_name);
730 goto error;
731 }
732
733 if ((prov->provider = OSSL_PROVIDER_load(NULL, provider_name)) == NULL) {
734 ha_alert("ssl-provider %s: unknown provider\n", provider_name);
735 goto error;
736 }
737
738 LIST_INSERT(&openssl_providers, &prov->list);
739
740 return 0;
741
742error:
743 ha_free(&prov);
744 return err_code;
745}
746#endif /* HAVE_SSL_PROVIDERS */
747
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +0500748#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +0200749/*
750 * openssl async fd handler
751 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200752void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000753{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200754 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000755
Emeric Brun3854e012017-05-17 20:42:48 +0200756 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000757 * to poll this fd until it is requested
758 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000759 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000760 fd_cant_recv(fd);
761
762 /* crypto engine is available, let's notify the associated
763 * connection that it can pursue its processing.
764 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200765 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000766}
767
Emeric Brun3854e012017-05-17 20:42:48 +0200768/*
769 * openssl async delayed SSL_free handler
770 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200771void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000772{
773 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200774 OSSL_ASYNC_FD all_fd[32];
775 size_t num_all_fds = 0;
776 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000777
Emeric Brun3854e012017-05-17 20:42:48 +0200778 /* We suppose that the async job for a same SSL *
779 * are serialized. So if we are awake it is
780 * because the running job has just finished
781 * and we can remove all async fds safely
782 */
783 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
784 if (num_all_fds > 32) {
785 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
786 return;
787 }
788
789 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
Emeric Brun7d392a52022-07-01 17:36:50 +0200790 for (i=0 ; i < num_all_fds ; i++) {
791 /* We want to remove the fd from the fdtab
792 * but we flag it to disown because the
793 * close is performed by the engine itself
794 */
795 fdtab[all_fd[i]].state |= FD_DISOWN;
796 fd_delete(all_fd[i]);
797 }
Emeric Brun3854e012017-05-17 20:42:48 +0200798
799 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000800 SSL_free(ssl);
Willy Tarreau82531f62021-10-06 12:15:18 +0200801 _HA_ATOMIC_DEC(&global.sslconns);
Willy Tarreau4781b152021-04-06 13:53:36 +0200802 _HA_ATOMIC_DEC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000803}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000804/*
Emeric Brun3854e012017-05-17 20:42:48 +0200805 * function used to manage a returned SSL_ERROR_WANT_ASYNC
806 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000807 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200808static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000809{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100810 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200811 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200812 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000813 size_t num_add_fds = 0;
814 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200815 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000816
817 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
818 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200819 if (num_add_fds > 32 || num_del_fds > 32) {
820 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000821 return;
822 }
823
Emeric Brun3854e012017-05-17 20:42:48 +0200824 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000825
Emeric Brun3854e012017-05-17 20:42:48 +0200826 /* We remove unused fds from the fdtab */
Emeric Brun7d392a52022-07-01 17:36:50 +0200827 for (i=0 ; i < num_del_fds ; i++) {
828 /* We want to remove the fd from the fdtab
829 * but we flag it to disown because the
830 * close is performed by the engine itself
831 */
832 fdtab[del_fd[i]].state |= FD_DISOWN;
833 fd_delete(del_fd[i]);
834 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000835
Emeric Brun3854e012017-05-17 20:42:48 +0200836 /* We add new fds to the fdtab */
837 for (i=0 ; i < num_add_fds ; i++) {
Willy Tarreau27a32452022-07-07 08:29:00 +0200838 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tgid, ti->ltid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000839 }
840
Emeric Brun3854e012017-05-17 20:42:48 +0200841 num_add_fds = 0;
842 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
843 if (num_add_fds > 32) {
844 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
845 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000846 }
Emeric Brun3854e012017-05-17 20:42:48 +0200847
848 /* We activate the polling for all known async fds */
849 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000850 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200851 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000852 /* To ensure that the fd cache won't be used
853 * We'll prefer to catch a real RD event
854 * because handling an EAGAIN on this fd will
855 * result in a context switch and also
856 * some engines uses a fd in blocking mode.
857 */
858 fd_cant_recv(add_fd[i]);
859 }
Emeric Brun3854e012017-05-17 20:42:48 +0200860
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000861}
862#endif
863
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100864
865/*
866 * Initialize an HMAC context <hctx> using the <key> and <md> parameters.
867 * Returns -1 in case of error, 1 otherwise.
868 */
869static int ssl_hmac_init(MAC_CTX *hctx, unsigned char *key, int key_len, const EVP_MD *md)
870{
871#ifdef HAVE_OSSL_PARAM
872 OSSL_PARAM params[3];
873
874 params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, key, key_len);
875 params[1] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, (char*)EVP_MD_name(md), 0);
876 params[2] = OSSL_PARAM_construct_end();
877 if (EVP_MAC_CTX_set_params(hctx, params) == 0)
878 return -1; /* error in mac initialisation */
879
880#else
881 HMAC_Init_ex(hctx, key, key_len, md, NULL);
882#endif
883 return 1;
884}
885
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100886#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +0100887
888static int ssl_tlsext_ticket_key_cb(SSL *s, unsigned char key_name[16], unsigned char *iv, EVP_CIPHER_CTX *ectx, MAC_CTX *hctx, int enc)
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100889{
Frédéric Lécaille6aec1f32022-09-06 17:04:55 +0200890 struct tls_keys_ref *ref = NULL;
Emeric Brun9e754772019-01-10 17:51:55 +0100891 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100892 int head;
893 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +0100894 int ret = -1; /* error by default */
Frédéric Lécaille6aec1f32022-09-06 17:04:55 +0200895 struct connection *conn = SSL_get_ex_data(s, ssl_app_data_index);
896#ifdef USE_QUIC
897 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
898#endif
899
900 if (conn)
901 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
902#ifdef USE_QUIC
903 else if (qc)
904 ref = qc->li->bind_conf->keys_ref;
905#endif
906
907 if (!ref) {
908 /* must never happen */
909 ABORT_NOW();
910 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100911
Christopher Faulet16f45c82018-02-16 11:23:49 +0100912 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
913
914 keys = ref->tlskeys;
915 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100916
917 if (enc) {
918 memcpy(key_name, keys[head].name, 16);
919
920 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +0100921 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100922
Emeric Brun9e754772019-01-10 17:51:55 +0100923 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100924
Emeric Brun9e754772019-01-10 17:51:55 +0100925 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
926 goto end;
927
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100928 if (ssl_hmac_init(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
929 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100930 ret = 1;
931 }
932 else if (ref->key_size_bits == 256 ) {
933
934 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
935 goto end;
936
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100937 if (ssl_hmac_init(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
938 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100939 ret = 1;
940 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100941 } else {
942 for (i = 0; i < TLS_TICKETS_NO; i++) {
943 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
944 goto found;
945 }
Christopher Faulet16f45c82018-02-16 11:23:49 +0100946 ret = 0;
947 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100948
Christopher Faulet16f45c82018-02-16 11:23:49 +0100949 found:
Emeric Brun9e754772019-01-10 17:51:55 +0100950 if (ref->key_size_bits == 128) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100951 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
952 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100953 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
954 goto end;
955 /* 2 for key renewal, 1 if current key is still valid */
956 ret = i ? 2 : 1;
957 }
958 else if (ref->key_size_bits == 256) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100959 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
960 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100961 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
962 goto end;
963 /* 2 for key renewal, 1 if current key is still valid */
964 ret = i ? 2 : 1;
965 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100966 }
Emeric Brun9e754772019-01-10 17:51:55 +0100967
Christopher Faulet16f45c82018-02-16 11:23:49 +0100968 end:
969 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
970 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200971}
972
973struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
974{
975 struct tls_keys_ref *ref;
976
977 list_for_each_entry(ref, &tlskeys_reference, list)
978 if (ref->filename && strcmp(filename, ref->filename) == 0)
979 return ref;
980 return NULL;
981}
982
983struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
984{
985 struct tls_keys_ref *ref;
986
987 list_for_each_entry(ref, &tlskeys_reference, list)
988 if (ref->unique_id == unique_id)
989 return ref;
990 return NULL;
991}
992
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500993/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +0100994 * match existing ones, this function returns -1
995 * else it returns 0 on success.
996 */
997int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +0200998 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +0100999{
Emeric Brun9e754772019-01-10 17:51:55 +01001000 if (ref->key_size_bits == 128) {
1001 if (tlskey->data != sizeof(struct tls_sess_key_128))
1002 return -1;
1003 }
1004 else if (ref->key_size_bits == 256) {
1005 if (tlskey->data != sizeof(struct tls_sess_key_256))
1006 return -1;
1007 }
1008 else
1009 return -1;
1010
Christopher Faulet16f45c82018-02-16 11:23:49 +01001011 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001012 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1013 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001014 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1015 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001016
1017 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001018}
1019
Willy Tarreau83061a82018-07-13 11:56:34 +02001020int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001021{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001022 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1023
1024 if(!ref) {
1025 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1026 return 1;
1027 }
Emeric Brun9e754772019-01-10 17:51:55 +01001028 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1029 memprintf(err, "Invalid key size");
1030 return 1;
1031 }
1032
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001033 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001034}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001035
1036/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001037 * automatic ids. It's called just after the basic checks. It returns
1038 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001039 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001040static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001041{
1042 int i = 0;
1043 struct tls_keys_ref *ref, *ref2, *ref3;
1044 struct list tkr = LIST_HEAD_INIT(tkr);
1045
1046 list_for_each_entry(ref, &tlskeys_reference, list) {
1047 if (ref->unique_id == -1) {
1048 /* Look for the first free id. */
1049 while (1) {
1050 list_for_each_entry(ref2, &tlskeys_reference, list) {
1051 if (ref2->unique_id == i) {
1052 i++;
1053 break;
1054 }
1055 }
1056 if (&ref2->list == &tlskeys_reference)
1057 break;
1058 }
1059
1060 /* Uses the unique id and increment it for the next entry. */
1061 ref->unique_id = i;
1062 i++;
1063 }
1064 }
1065
1066 /* This sort the reference list by id. */
1067 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001068 LIST_DELETE(&ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001069 list_for_each_entry(ref3, &tkr, list) {
1070 if (ref->unique_id < ref3->unique_id) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001071 LIST_APPEND(&ref3->list, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001072 break;
1073 }
1074 }
1075 if (&ref3->list == &tkr)
Willy Tarreau2b718102021-04-21 07:32:39 +02001076 LIST_APPEND(&tkr, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001077 }
1078
1079 /* swap root */
Willy Tarreau2b718102021-04-21 07:32:39 +02001080 LIST_INSERT(&tkr, &tlskeys_reference);
1081 LIST_DELETE(&tkr);
Christopher Fauletfc633b62020-11-06 15:24:23 +01001082 return ERR_NONE;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001083}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001084#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1085
William Lallemand4a660132019-10-14 14:51:41 +02001086
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001087#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001088/*
1089 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001090 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1091 * status extension, the issuer's certificate is mandatory. It should be
1092 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001093 *
William Lallemand246c0242019-10-11 08:59:13 +02001094 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1095 * OCSP response. If file is empty or content is not a valid OCSP response,
1096 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1097 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001098 *
1099 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001100 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001101 */
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001102static int ssl_sock_load_ocsp(SSL_CTX *ctx, struct ckch_data *data, STACK_OF(X509) *chain)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001103{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001104 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001105 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001106 struct certificate_ocsp *ocsp = NULL, *iocsp;
1107 char *warn = NULL;
1108 unsigned char *p;
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01001109#ifndef USE_OPENSSL_WOLFSSL
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001110 void (*callback) (void);
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01001111#else
1112 tlsextStatusCb callback;
1113#endif
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001114 struct buffer *ocsp_uri = get_trash_chunk();
Emeric Brun4147b2e2014-06-16 18:36:30 +02001115
Emeric Brun4147b2e2014-06-16 18:36:30 +02001116
William Lallemand52ddd992022-11-22 11:51:53 +01001117 x = data->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001118 if (!x)
1119 goto out;
1120
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001121 if (data->ocsp_update_mode == SSL_SOCK_OCSP_UPDATE_ON) {
1122 ssl_ocsp_get_uri_from_cert(x, ocsp_uri, NULL);
1123 /* We should have an "OCSP URI" field in order for auto update to work. */
1124 if (b_data(ocsp_uri) == 0)
1125 goto out;
1126 }
1127
1128 /* In case of ocsp update mode set to 'on', this function might be
1129 * called with no known ocsp response. If no ocsp uri can be found in
1130 * the certificate, nothing needs to be done here. */
1131 if (!data->ocsp_response) {
1132 if (data->ocsp_update_mode != SSL_SOCK_OCSP_UPDATE_ON || b_data(ocsp_uri) == 0) {
1133 ret = 0;
1134 goto out;
1135 }
1136 }
1137
William Lallemand52ddd992022-11-22 11:51:53 +01001138 issuer = data->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001139 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1140 if (chain) {
1141 /* check if one of the certificate of the chain is the issuer */
1142 for (i = 0; i < sk_X509_num(chain); i++) {
1143 X509 *ti = sk_X509_value(chain, i);
1144 if (X509_check_issued(ti, x) == X509_V_OK) {
1145 issuer = ti;
1146 break;
1147 }
1148 }
1149 }
William Lallemand246c0242019-10-11 08:59:13 +02001150 if (!issuer)
1151 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001152
Remi Tricot-Le Breton2d1daa82023-01-09 12:02:47 +01001153 if (!data->ocsp_cid)
1154 data->ocsp_cid = OCSP_cert_to_id(0, x, issuer);
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001155 if (!data->ocsp_cid)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001156 goto out;
1157
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001158 i = i2d_OCSP_CERTID(data->ocsp_cid, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001159 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1160 goto out;
1161
Vincent Bernat02779b62016-04-03 13:48:43 +02001162 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001163 if (!ocsp)
1164 goto out;
1165
1166 p = ocsp->key_data;
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001167 ocsp->key_length = i2d_OCSP_CERTID(data->ocsp_cid, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001168
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001169 HA_SPIN_LOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001170 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1171 if (iocsp == ocsp)
1172 ocsp = NULL;
1173
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001174#ifndef SSL_CTX_get_tlsext_status_cb
1175# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1176 *cb = (void (*) (void))ctx->tlsext_status_cb;
1177#endif
1178 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1179
1180 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001181 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001182 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001183
William Lallemanda560c062020-07-31 11:43:20 +02001184 cb_arg = calloc(1, sizeof(*cb_arg));
1185 if (!cb_arg)
1186 goto out;
1187
yanbzhube2774d2015-12-10 15:07:30 -05001188 cb_arg->is_single = 1;
1189 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001190 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001191
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001192 pkey = X509_get_pubkey(x);
1193 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1194 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001195
1196 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001197 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 */
1198
yanbzhube2774d2015-12-10 15:07:30 -05001199 } else {
1200 /*
1201 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1202 * Update that cb_arg with the new cert's staple
1203 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001204 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001205 struct certificate_ocsp *tmp_ocsp;
1206 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001207 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001208 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001209
William Lallemand76b4a122020-08-04 17:41:39 +02001210 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001211
1212 /*
1213 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1214 * the order of operations below matter, take care when changing it
1215 */
1216 tmp_ocsp = cb_arg->s_ocsp;
1217 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1218 cb_arg->s_ocsp = NULL;
1219 cb_arg->m_ocsp[index] = tmp_ocsp;
1220 cb_arg->is_single = 0;
1221 cb_arg->single_kt = 0;
1222
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001223 pkey = X509_get_pubkey(x);
1224 key_type = EVP_PKEY_base_id(pkey);
1225 EVP_PKEY_free(pkey);
1226
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001227 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001228 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001229 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001230 iocsp->refcount++;
1231 }
yanbzhube2774d2015-12-10 15:07:30 -05001232 }
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001233 HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001234
1235 ret = 0;
1236
1237 warn = NULL;
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001238 if (data->ocsp_response && ssl_sock_load_ocsp_response(data->ocsp_response, iocsp, data->ocsp_cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001239 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001240 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001241 }
1242
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001243 if (data->ocsp_update_mode == SSL_SOCK_OCSP_UPDATE_ON) {
1244
1245 /* Do not insert the same certificate_ocsp structure in the
1246 * update tree more than once. */
1247 if (!ocsp) {
Remi Tricot-Le Breton112b16a2023-01-09 12:02:44 +01001248 /* Issuer certificate is not included in the certificate
1249 * chain, it will have to be treated separately during
1250 * ocsp response validation. */
1251 if (issuer == data->ocsp_issuer) {
1252 iocsp->issuer = issuer;
1253 X509_up_ref(issuer);
1254 }
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001255 if (data->chain)
1256 iocsp->chain = X509_chain_up_ref(data->chain);
1257
Remi Tricot-Le Breton648c83e2023-01-09 12:02:48 +01001258 iocsp->uri = calloc(1, sizeof(*iocsp->uri));
1259 if (!chunk_dup(iocsp->uri, ocsp_uri)) {
1260 ha_free(&iocsp->uri);
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001261 goto out;
Remi Tricot-Le Breton648c83e2023-01-09 12:02:48 +01001262 }
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001263
1264 ssl_ocsp_update_insert(iocsp);
1265 }
1266 }
1267
Emeric Brun4147b2e2014-06-16 18:36:30 +02001268out:
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001269 if (ret && data->ocsp_cid)
1270 OCSP_CERTID_free(data->ocsp_cid);
1271
1272 if (!ret && data->ocsp_response) {
1273 ha_free(&data->ocsp_response->area);
1274 ha_free(&data->ocsp_response);
1275 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001276
1277 if (ocsp)
Remi Tricot-Le Bretonaa529f72022-11-03 15:16:49 +01001278 ssl_sock_free_ocsp(ocsp);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001279
1280 if (warn)
1281 free(warn);
1282
Emeric Brun4147b2e2014-06-16 18:36:30 +02001283 return ret;
1284}
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01001285
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001286#endif
1287
1288#ifdef OPENSSL_IS_BORINGSSL
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001289static int ssl_sock_load_ocsp(SSL_CTX *ctx, struct ckch_data *data, STACK_OF(X509) *chain)
Emmanuel Hocdet2c32d8f2017-05-22 14:58:00 +02001290{
William Lallemand4a660132019-10-14 14:51:41 +02001291 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 +02001292}
1293#endif
1294
William Lallemand4a660132019-10-14 14:51:41 +02001295
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001296#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001297
1298#define CT_EXTENSION_TYPE 18
1299
William Lallemand03c331c2020-05-13 10:10:01 +02001300int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001301
1302int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1303{
Willy Tarreau83061a82018-07-13 11:56:34 +02001304 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001305
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001306 *out = (unsigned char *) sctl->area;
1307 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001308
1309 return 1;
1310}
1311
1312int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1313{
1314 return 1;
1315}
1316
William Lallemanda17f4112019-10-10 15:16:44 +02001317static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001318{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001319 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001320
William Lallemanda17f4112019-10-10 15:16:44 +02001321 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 +01001322 goto out;
1323
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001324 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1325
1326 ret = 0;
1327
1328out:
1329 return ret;
1330}
1331
1332#endif
1333
Emeric Brune1f38db2012-09-03 20:36:47 +02001334void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1335{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001336 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001337#ifdef USE_QUIC
1338 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1339#endif /* USE_QUIC */
1340 struct ssl_sock_ctx *ctx = NULL;
1341
Emeric Brund8b2bb52014-01-28 15:43:53 +01001342 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001343 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001344
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001345 if (conn)
Willy Tarreau939b0bf2022-04-11 11:29:11 +02001346 ctx = conn_get_ssl_sock_ctx(conn);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001347#ifdef USE_QUIC
1348 else if (qc)
1349 ctx = qc->xprt_ctx;
1350#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01001351
1352 if (!ctx) {
1353 /* must never happen */
1354 ABORT_NOW();
1355 return;
1356 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001357
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001358#ifndef SSL_OP_NO_RENEGOTIATION
1359 /* Please note that BoringSSL defines this macro to zero so don't
1360 * change this to #if and do not assign a default value to this macro!
1361 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001362 if (where & SSL_CB_HANDSHAKE_START) {
1363 /* Disable renegotiation (CVE-2009-3555) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001364 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 +02001365 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001366 conn->err_code = CO_ER_SSL_RENEG;
1367 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001368 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001369#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001370
1371 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001372 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001373 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001374 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001375 consider that the buffering was activated,
1376 so we rise the output buffer size from 4k
1377 to 16k */
1378 write_bio = SSL_get_wbio(ssl);
1379 if (write_bio != SSL_get_rbio(ssl)) {
1380 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001381 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001382 }
1383 }
1384 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001385}
1386
Emeric Brune64aef12012-09-21 13:15:06 +02001387/* Callback is called for each certificate of the chain during a verify
1388 ok is set to 1 if preverify detect no error on current certificate.
1389 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001390int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001391{
1392 SSL *ssl;
1393 struct connection *conn;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001394 struct ssl_sock_ctx *ctx = NULL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001395 int err, depth;
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001396 X509 *client_crt;
1397 STACK_OF(X509) *certs;
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001398 struct bind_conf *bind_conf = NULL;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001399 struct quic_conn *qc = NULL;
Emeric Brune64aef12012-09-21 13:15:06 +02001400
1401 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001402 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001403 client_crt = SSL_get_ex_data(ssl, ssl_client_crt_ref_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001404
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001405 if (conn) {
1406 bind_conf = __objt_listener(conn->target)->bind_conf;
1407 ctx = __conn_get_ssl_sock_ctx(conn);
1408 }
1409#ifdef USE_QUIC
1410 else {
1411 qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
Amaury Denoyelleba303de2022-10-17 18:46:49 +02001412 BUG_ON(!qc); /* Must never happen */
1413 bind_conf = qc->li->bind_conf;
1414 ctx = qc->xprt_ctx;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001415 }
1416#endif
1417
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001418 BUG_ON(!ctx || !bind_conf);
Christopher Faulet881cce92022-11-23 09:27:13 +01001419 ALREADY_CHECKED(ctx);
1420 ALREADY_CHECKED(bind_conf);
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001421
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001422 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001423
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001424 depth = X509_STORE_CTX_get_error_depth(x_store);
1425 err = X509_STORE_CTX_get_error(x_store);
1426
Emeric Brun81c00f02012-09-21 14:31:21 +02001427 if (ok) /* no errors */
1428 return ok;
1429
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001430 /* Keep a reference to the client's certificate in order to be able to
1431 * dump some fetches values in a log even when the verification process
1432 * fails. */
1433 if (depth == 0) {
1434 X509_free(client_crt);
1435 client_crt = X509_STORE_CTX_get0_cert(x_store);
1436 if (client_crt) {
1437 X509_up_ref(client_crt);
1438 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
1439 }
1440 }
1441 else {
1442 /* An error occurred on a CA certificate of the certificate
1443 * chain, we might never call this verify callback on the client
1444 * certificate's depth (which is 0) so we try to store the
1445 * reference right now. */
Remi Tricot-Le Bretonf95c2952021-08-20 09:51:23 +02001446 certs = X509_STORE_CTX_get1_chain(x_store);
1447 if (certs) {
1448 client_crt = sk_X509_value(certs, 0);
1449 if (client_crt) {
1450 X509_up_ref(client_crt);
1451 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001452 }
1453 sk_X509_pop_free(certs, X509_free);
1454 }
1455 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001456
1457 /* check if CA error needs to be ignored */
1458 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001459 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1460 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1461 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001462 }
1463
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01001464 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01001465 cert_ignerr_bitfield_get(bind_conf->ca_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001466 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02001467
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001468 /* TODO: for QUIC connection, this error code is lost */
1469 if (conn)
1470 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001471 return 0;
1472 }
1473
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001474 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1475 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001476
Emeric Brun81c00f02012-09-21 14:31:21 +02001477 /* check if certificate error needs to be ignored */
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01001478 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01001479 cert_ignerr_bitfield_get(bind_conf->crt_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001480 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02001481
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001482 /* TODO: for QUIC connection, this error code is lost */
1483 if (conn)
1484 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001485 return 0;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001486
1487 err_ignored:
1488 ssl_sock_dump_errors(conn, qc);
1489 ERR_clear_error();
1490 return 1;
Emeric Brune64aef12012-09-21 13:15:06 +02001491}
1492
Dragan Dosen9ac98092020-05-11 15:51:45 +02001493#ifdef TLS1_RT_HEARTBEAT
1494static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1495 int content_type, const void *buf, size_t len,
1496 SSL *ssl)
1497{
1498 /* test heartbeat received (write_p is set to 0
1499 for a received record) */
1500 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02001501 struct ssl_sock_ctx *ctx = __conn_get_ssl_sock_ctx(conn);
Dragan Dosen9ac98092020-05-11 15:51:45 +02001502 const unsigned char *p = buf;
1503 unsigned int payload;
1504
1505 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1506
1507 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1508 if (*p != TLS1_HB_REQUEST)
1509 return;
1510
1511 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1512 goto kill_it;
1513
1514 payload = (p[1] * 256) + p[2];
1515 if (3 + payload + 16 <= len)
1516 return; /* OK no problem */
1517 kill_it:
1518 /* We have a clear heartbleed attack (CVE-2014-0160), the
1519 * advertised payload is larger than the advertised packet
1520 * length, so we have garbage in the buffer between the
1521 * payload and the end of the buffer (p+len). We can't know
1522 * if the SSL stack is patched, and we don't know if we can
1523 * safely wipe out the area between p+3+len and payload.
1524 * So instead, we prevent the response from being sent by
1525 * setting the max_send_fragment to 0 and we report an SSL
1526 * error, which will kill this connection. It will be reported
1527 * above as SSL_ERROR_SSL while an other handshake failure with
1528 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1529 */
1530 ssl->max_send_fragment = 0;
1531 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1532 }
1533}
1534#endif
1535
1536static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1537 int content_type, const void *buf, size_t len,
1538 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001539{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001540 struct ssl_capture *capture;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001541 uchar *msg;
1542 uchar *end;
1543 uchar *extensions_end;
1544 uchar *ec_start = NULL;
1545 uchar *ec_formats_start = NULL;
1546 uchar *list_end;
1547 ushort protocol_version;
1548 ushort extension_id;
1549 ushort ec_len = 0;
1550 uchar ec_formats_len = 0;
1551 int offset = 0;
1552 int rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001553
1554 /* This function is called for "from client" and "to server"
1555 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001556 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001557 */
1558
1559 /* "write_p" is set to 0 is the bytes are received messages,
1560 * otherwise it is set to 1.
1561 */
1562 if (write_p != 0)
1563 return;
1564
1565 /* content_type contains the type of message received or sent
1566 * according with the SSL/TLS protocol spec. This message is
1567 * encoded with one byte. The value 256 (two bytes) is used
1568 * for designing the SSL/TLS record layer. According with the
1569 * rfc6101, the expected message (other than 256) are:
1570 * - change_cipher_spec(20)
1571 * - alert(21)
1572 * - handshake(22)
1573 * - application_data(23)
1574 * - (255)
1575 * We are interessed by the handshake and specially the client
1576 * hello.
1577 */
1578 if (content_type != 22)
1579 return;
1580
1581 /* The message length is at least 4 bytes, containing the
1582 * message type and the message length.
1583 */
1584 if (len < 4)
1585 return;
1586
1587 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001588 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001589 * - hello_request(0)
1590 * - client_hello(1)
1591 * - server_hello(2)
1592 * - certificate(11)
1593 * - server_key_exchange (12)
1594 * - certificate_request(13)
1595 * - server_hello_done(14)
1596 * We are interested by the client hello.
1597 */
1598 msg = (unsigned char *)buf;
1599 if (msg[0] != 1)
1600 return;
1601
1602 /* Next three bytes are the length of the message. The total length
1603 * must be this decoded length + 4. If the length given as argument
1604 * is not the same, we abort the protocol dissector.
1605 */
1606 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1607 if (len < rec_len + 4)
1608 return;
1609 msg += 4;
1610 end = msg + rec_len;
1611 if (end < msg)
1612 return;
1613
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001614 /* Expect 2 bytes for protocol version
1615 * (1 byte for major and 1 byte for minor)
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001616 */
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001617 if (msg + 2 > end)
1618 return;
1619 protocol_version = (msg[0] << 8) + msg[1];
1620 msg += 2;
1621
1622 /* Expect the random, composed by 4 bytes for the unix time and
1623 * 28 bytes for unix payload. So we jump 4 + 28.
1624 */
1625 msg += 4 + 28;
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001626 if (msg > end)
1627 return;
1628
1629 /* Next, is session id:
1630 * if present, we have to jump by length + 1 for the size information
1631 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001632 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001633 if (msg[0] > 0)
1634 msg += msg[0];
1635 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001636 if (msg > end)
1637 return;
1638
1639 /* Next two bytes are the ciphersuite length. */
1640 if (msg + 2 > end)
1641 return;
1642 rec_len = (msg[0] << 8) + msg[1];
1643 msg += 2;
1644 if (msg + rec_len > end || msg + rec_len < msg)
1645 return;
1646
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001647 capture = pool_zalloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001648 if (!capture)
1649 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001650 /* Compute the xxh64 of the ciphersuite. */
1651 capture->xxh64 = XXH64(msg, rec_len, 0);
1652
1653 /* Capture the ciphersuite. */
Marcin Deranek310a2602021-07-13 19:04:24 +02001654 capture->ciphersuite_len = MIN(global_ssl.capture_buffer_size, rec_len);
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001655 capture->ciphersuite_offset = 0;
1656 memcpy(capture->data, msg, capture->ciphersuite_len);
1657 msg += rec_len;
1658 offset += capture->ciphersuite_len;
1659
1660 /* Initialize other data */
1661 capture->protocol_version = protocol_version;
1662
1663 /* Next, compression methods:
1664 * if present, we have to jump by length + 1 for the size information
1665 * if not present, we have to jump by 1 only
1666 */
1667 if (msg[0] > 0)
1668 msg += msg[0];
1669 msg += 1;
1670 if (msg > end)
1671 goto store_capture;
1672
1673 /* We reached extensions */
1674 if (msg + 2 > end)
1675 goto store_capture;
1676 rec_len = (msg[0] << 8) + msg[1];
1677 msg += 2;
1678 if (msg + rec_len > end || msg + rec_len < msg)
1679 goto store_capture;
1680 extensions_end = msg + rec_len;
1681 capture->extensions_offset = offset;
1682
1683 /* Parse each extension */
1684 while (msg + 4 < extensions_end) {
1685 /* Add 2 bytes of extension_id */
Marcin Deranek310a2602021-07-13 19:04:24 +02001686 if (global_ssl.capture_buffer_size >= offset + 2) {
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001687 capture->data[offset++] = msg[0];
1688 capture->data[offset++] = msg[1];
1689 capture->extensions_len += 2;
1690 }
1691 else
1692 break;
1693 extension_id = (msg[0] << 8) + msg[1];
1694 /* Length of the extension */
1695 rec_len = (msg[2] << 8) + msg[3];
1696
1697 /* Expect 2 bytes extension id + 2 bytes extension size */
1698 msg += 2 + 2;
1699 if (msg + rec_len > extensions_end || msg + rec_len < msg)
1700 goto store_capture;
1701 /* TLS Extensions
1702 * https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml */
1703 if (extension_id == 0x000a) {
1704 /* Elliptic Curves:
1705 * https://www.rfc-editor.org/rfc/rfc8422.html
1706 * https://www.rfc-editor.org/rfc/rfc7919.html */
1707 list_end = msg + rec_len;
1708 if (msg + 2 > list_end)
1709 goto store_capture;
1710 rec_len = (msg[0] << 8) + msg[1];
1711 msg += 2;
1712
1713 if (msg + rec_len > list_end || msg + rec_len < msg)
1714 goto store_capture;
1715 /* Store location/size of the list */
1716 ec_start = msg;
1717 ec_len = rec_len;
1718 }
1719 else if (extension_id == 0x000b) {
1720 /* Elliptic Curves Point Formats:
1721 * https://www.rfc-editor.org/rfc/rfc8422.html */
1722 list_end = msg + rec_len;
1723 if (msg + 1 > list_end)
1724 goto store_capture;
1725 rec_len = msg[0];
1726 msg += 1;
1727
1728 if (msg + rec_len > list_end || msg + rec_len < msg)
1729 goto store_capture;
1730 /* Store location/size of the list */
1731 ec_formats_start = msg;
1732 ec_formats_len = rec_len;
1733 }
1734 msg += rec_len;
1735 }
1736
1737 if (ec_start) {
1738 rec_len = ec_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001739 if (offset + rec_len > global_ssl.capture_buffer_size)
1740 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001741 memcpy(capture->data + offset, ec_start, rec_len);
1742 capture->ec_offset = offset;
1743 capture->ec_len = rec_len;
1744 offset += rec_len;
1745 }
1746 if (ec_formats_start) {
1747 rec_len = ec_formats_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001748 if (offset + rec_len > global_ssl.capture_buffer_size)
1749 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001750 memcpy(capture->data + offset, ec_formats_start, rec_len);
1751 capture->ec_formats_offset = offset;
1752 capture->ec_formats_len = rec_len;
1753 offset += rec_len;
1754 }
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001755
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001756 store_capture:
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001757 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001758}
William Lallemand7d42ef52020-07-06 11:41:30 +02001759
1760
William Lallemand722180a2021-06-09 16:46:12 +02001761#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001762static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1763 int content_type, const void *buf, size_t len,
1764 SSL *ssl)
1765{
1766 struct ssl_keylog *keylog;
1767
1768 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1769 return;
1770
Willy Tarreauf208ac02021-03-22 21:10:12 +01001771 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02001772 if (!keylog)
1773 return;
1774
William Lallemand7d42ef52020-07-06 11:41:30 +02001775 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
1776 pool_free(pool_head_ssl_keylog, keylog);
1777 return;
1778 }
1779}
1780#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001781
Emeric Brun29f037d2014-04-25 19:05:36 +02001782/* Callback is called for ssl protocol analyse */
1783void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1784{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001785 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1786 struct ssl_sock_msg_callback *cbk;
1787
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001788 /* Try to call all callback functions that were registered by using
1789 * ssl_sock_register_msg_callback().
1790 */
1791 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1792 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1793 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001794}
1795
Bernard Spil13c53f82018-02-15 13:34:58 +01001796#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001797static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1798 const unsigned char *in, unsigned int inlen,
1799 void *arg)
1800{
1801 struct server *srv = arg;
1802
1803 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1804 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1805 return SSL_TLSEXT_ERR_OK;
1806 return SSL_TLSEXT_ERR_NOACK;
1807}
1808#endif
1809
1810#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001811/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001812 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001813 */
1814static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1815 unsigned int *len, void *arg)
1816{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001817 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001818
1819 *data = (const unsigned char *)conf->npn_str;
1820 *len = conf->npn_len;
1821 return SSL_TLSEXT_ERR_OK;
1822}
1823#endif
1824
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001825#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001826/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001827 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001828 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001829static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1830 unsigned char *outlen,
1831 const unsigned char *server,
1832 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001833{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001834 struct ssl_bind_conf *conf = arg;
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001835#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001836 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001837#endif
Willy Tarreauab861d32013-04-02 02:30:41 +02001838
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001839 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1840 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01001841#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001842 if (qc)
1843 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01001844#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001845 return SSL_TLSEXT_ERR_NOACK;
1846 }
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001847
1848#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001849 if (qc && !quic_set_app_ops(qc, *out, *outlen)) {
1850 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001851 return SSL_TLSEXT_ERR_NOACK;
1852 }
1853#endif
1854
Willy Tarreauab861d32013-04-02 02:30:41 +02001855 return SSL_TLSEXT_ERR_OK;
1856}
1857#endif
1858
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001859#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001860#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001861
cui flitera94bedc2022-08-29 14:42:57 +08001862/* Configure a DNS SAN extension on a certificate. */
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001863int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
1864 int failure = 0;
1865 X509_EXTENSION *san_ext = NULL;
1866 CONF *conf = NULL;
1867 struct buffer *san_name = get_trash_chunk();
1868
1869 conf = NCONF_new(NULL);
1870 if (!conf) {
1871 failure = 1;
1872 goto cleanup;
1873 }
1874
1875 /* Build an extension based on the DNS entry above */
1876 chunk_appendf(san_name, "DNS:%s", servername);
1877 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
1878 if (!san_ext) {
1879 failure = 1;
1880 goto cleanup;
1881 }
1882
1883 /* Add the extension */
1884 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
1885 failure = 1;
1886 goto cleanup;
1887 }
1888
1889 /* Success */
1890 failure = 0;
1891
1892cleanup:
1893 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
1894 if (NULL != conf) NCONF_free(conf);
1895
1896 return failure;
1897}
1898
Christopher Faulet30548802015-06-11 13:39:32 +02001899/* Create a X509 certificate with the specified servername and serial. This
1900 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001901static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001902ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001903{
Shimi Gersner5846c492020-08-23 13:58:12 +03001904 X509 *cacert = bind_conf->ca_sign_ckch->cert;
1905 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001906 SSL_CTX *ssl_ctx = NULL;
1907 X509 *newcrt = NULL;
1908 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001909 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001910 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001911 X509_NAME *name;
1912 const EVP_MD *digest;
1913 X509V3_CTX ctx;
1914 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001915 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001916
Christopher Faulet48a83322017-07-28 16:56:09 +02001917 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05001918#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001919 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1920#else
1921 tmp_ssl = SSL_new(bind_conf->default_ctx);
1922 if (tmp_ssl)
1923 pkey = SSL_get_privatekey(tmp_ssl);
1924#endif
1925 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001926 goto mkcert_error;
1927
1928 /* Create the certificate */
1929 if (!(newcrt = X509_new()))
1930 goto mkcert_error;
1931
1932 /* Set version number for the certificate (X509v3) and the serial
1933 * number */
1934 if (X509_set_version(newcrt, 2L) != 1)
1935 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02001936 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001937
1938 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001939 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1940 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001941 goto mkcert_error;
1942
1943 /* set public key in the certificate */
1944 if (X509_set_pubkey(newcrt, pkey) != 1)
1945 goto mkcert_error;
1946
1947 /* Set issuer name from the CA */
1948 if (!(name = X509_get_subject_name(cacert)))
1949 goto mkcert_error;
1950 if (X509_set_issuer_name(newcrt, name) != 1)
1951 goto mkcert_error;
1952
1953 /* Set the subject name using the same, but the CN */
1954 name = X509_NAME_dup(name);
1955 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1956 (const unsigned char *)servername,
1957 -1, -1, 0) != 1) {
1958 X509_NAME_free(name);
1959 goto mkcert_error;
1960 }
1961 if (X509_set_subject_name(newcrt, name) != 1) {
1962 X509_NAME_free(name);
1963 goto mkcert_error;
1964 }
1965 X509_NAME_free(name);
1966
1967 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001968 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001969 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1970 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1971 X509_EXTENSION *ext;
1972
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001973 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001974 goto mkcert_error;
1975 if (!X509_add_ext(newcrt, ext, -1)) {
1976 X509_EXTENSION_free(ext);
1977 goto mkcert_error;
1978 }
1979 X509_EXTENSION_free(ext);
1980 }
1981
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001982 /* Add SAN extension */
1983 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
1984 goto mkcert_error;
1985 }
1986
Christopher Faulet31af49d2015-06-09 17:29:50 +02001987 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001988
1989 key_type = EVP_PKEY_base_id(capkey);
1990
1991 if (key_type == EVP_PKEY_DSA)
1992 digest = EVP_sha1();
1993 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001994 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001995 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02001996 digest = EVP_sha256();
1997 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05001998#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02001999 int nid;
2000
2001 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
2002 goto mkcert_error;
2003 if (!(digest = EVP_get_digestbynid(nid)))
2004 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02002005#else
2006 goto mkcert_error;
2007#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02002008 }
2009
Christopher Faulet31af49d2015-06-09 17:29:50 +02002010 if (!(X509_sign(newcrt, capkey, digest)))
2011 goto mkcert_error;
2012
2013 /* Create and set the new SSL_CTX */
2014 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
2015 goto mkcert_error;
2016 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
2017 goto mkcert_error;
2018 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
2019 goto mkcert_error;
2020 if (!SSL_CTX_check_private_key(ssl_ctx))
2021 goto mkcert_error;
2022
Shimi Gersner5846c492020-08-23 13:58:12 +03002023 /* Build chaining the CA cert and the rest of the chain, keep these order */
2024#if defined(SSL_CTX_add1_chain_cert)
2025 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
2026 goto mkcert_error;
2027 }
2028
2029 if (bind_conf->ca_sign_ckch->chain) {
2030 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2031 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2032 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2033 goto mkcert_error;
2034 }
2035 }
2036 }
2037#endif
2038
Christopher Faulet31af49d2015-06-09 17:29:50 +02002039 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002040
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002041#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002042#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002043 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002044#else
2045 ssl_sock_set_tmp_dh_from_pkey(ssl_ctx, pkey);
2046#endif
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002047#endif
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002048
2049#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
2050#if defined(SSL_CTX_set1_curves_list)
2051 {
2052 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
2053 if (!SSL_CTX_set1_curves_list(ssl_ctx, ecdhe))
2054 goto end;
2055 }
2056#endif
2057#else
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002058#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2059 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002060 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002061 EC_KEY *ecc;
2062 int nid;
2063
2064 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2065 goto end;
2066 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2067 goto end;
2068 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2069 EC_KEY_free(ecc);
2070 }
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002071#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
2072#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002073 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002074 return ssl_ctx;
2075
2076 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002077 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002078 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002079 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2080 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002081 return NULL;
2082}
2083
Christopher Faulet7969a332015-10-09 11:15:03 +02002084
Christopher Faulet30548802015-06-11 13:39:32 +02002085/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002086 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002087SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002088ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002089{
2090 struct lru64 *lru = NULL;
2091
2092 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002093 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002094 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002095 if (lru && lru->domain) {
2096 if (ssl)
2097 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002098 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002099 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002100 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002101 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002102 }
2103 return NULL;
2104}
2105
Emeric Brun821bb9b2017-06-15 16:37:39 +02002106/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2107 * function is not thread-safe, it should only be used to check if a certificate
2108 * exists in the lru cache (with no warranty it will not be removed by another
2109 * thread). It is kept for backward compatibility. */
2110SSL_CTX *
2111ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2112{
2113 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2114}
2115
Christopher Fauletd2cab922015-07-28 16:03:47 +02002116/* Set a certificate int the LRU cache used to store generated
2117 * certificate. Return 0 on success, otherwise -1 */
2118int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002119ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002120{
2121 struct lru64 *lru = NULL;
2122
2123 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002124 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002125 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002126 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002127 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002128 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002129 }
Christopher Faulet30548802015-06-11 13:39:32 +02002130 if (lru->domain && lru->data)
2131 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002132 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002133 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002134 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002135 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002136 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002137}
2138
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002139/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002140unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002141ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002142{
2143 return XXH32(data, len, ssl_ctx_lru_seed);
2144}
2145
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002146/* Generate a cert and immediately assign it to the SSL session so that the cert's
2147 * refcount is maintained regardless of the cert's presence in the LRU cache.
2148 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002149static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002150ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002151{
Shimi Gersner5846c492020-08-23 13:58:12 +03002152 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002153 SSL_CTX *ssl_ctx = NULL;
2154 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002155 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002156
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002157 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002158 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002159 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002160 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002161 if (lru && lru->domain)
2162 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002163 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002164 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002165 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002166 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002167 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002168 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002169 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002170 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002171 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002172 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002173 SSL_set_SSL_CTX(ssl, ssl_ctx);
2174 /* No LRU cache, this CTX will be released as soon as the session dies */
2175 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002176 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002177 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002178 return 0;
2179}
2180static int
2181ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2182{
2183 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002184 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002185
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002186 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002187 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002188 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002189 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002190 }
2191 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002192}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002193#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002194
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002195#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002196
2197static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002198{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002199#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002200 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002201 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2202#endif
2203}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002204static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2205 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002206 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2207}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002208static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002209#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002210 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002211 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2212#endif
2213}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002214static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002215#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002216 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002217 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2218#endif
2219}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002220/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002221static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2222/* Unusable in this context. */
2223static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2224static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2225static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2226static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2227static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002228#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002229
2230static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2231 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002232 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2233}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002234static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2235 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2236 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2237}
2238static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2239 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002240 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2241}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002242static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2243 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2244 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2245}
2246static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2247 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002248 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2249}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002250static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2251 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2252 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2253}
2254static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2255 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002256 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2257}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002258static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2259 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2260 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2261}
2262static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002263#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002264 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002265 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2266#endif
2267}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002268static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002269#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002270 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2271 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002272#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002273}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002274#endif
2275static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2276static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002277
William Lallemand7fd8b452020-05-07 15:20:43 +02002278struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002279 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2280 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2281 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2282 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2283 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2284 {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 +02002285};
2286
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002287static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2288{
2289 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2290 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2291 SSL_set_SSL_CTX(ssl, ctx);
2292}
2293
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002294#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002295
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002296int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002297{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002298 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002299 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002300
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002301 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || (s->options & BC_O_GENERATE_CERTS))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002302 return SSL_TLSEXT_ERR_OK;
2303 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002304}
2305
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002306#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002307int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002308{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002309 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002310#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002311int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002312{
2313#endif
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002314 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2315#ifdef USE_QUIC
2316 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2317#endif /* USE_QUIC */
2318 struct bind_conf *s = NULL;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002319 const uint8_t *extension_data;
2320 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002321 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002322
2323 char *wildp = NULL;
2324 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002325 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002326 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002327 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002328 int i;
2329
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002330 if (conn)
2331 s = __objt_listener(conn->target)->bind_conf;
2332#ifdef USE_QUIC
2333 else if (qc)
2334 s = qc->li->bind_conf;
2335#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01002336
2337 if (!s) {
2338 /* must never happen */
2339 ABORT_NOW();
2340 return 0;
2341 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002342
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002343#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002344 if (qc) {
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002345 /* Look for the QUIC transport parameters. */
2346#ifdef OPENSSL_IS_BORINGSSL
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002347 if (!SSL_early_callback_ctx_extension_get(ctx, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002348 &extension_data, &extension_len))
2349#else
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002350 if (!SSL_client_hello_get0_ext(ssl, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002351 &extension_data, &extension_len))
2352#endif
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002353 {
2354 /* This is not redundant. It we only return 0 without setting
2355 * <*al>, this has as side effect to generate another TLS alert
2356 * which would be set after calling quic_set_tls_alert().
2357 */
2358 *al = SSL_AD_MISSING_EXTENSION;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002359 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002360 return 0;
2361 }
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002362
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002363 if (!quic_transport_params_store(qc, 0, extension_data,
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002364 extension_data + extension_len))
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002365 goto abort;
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002366
2367 qc->flags |= QUIC_FL_CONN_TX_TP_RECEIVED;
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002368 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002369#endif /* USE_QUIC */
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002370
Olivier Houchard9679ac92017-10-27 14:58:08 +02002371 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002372 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002373#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002374 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2375 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002376#else
2377 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2378#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002379 /*
2380 * The server_name extension was given too much extensibility when it
2381 * was written, so parsing the normal case is a bit complex.
2382 */
2383 size_t len;
2384 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002385 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002386 /* Extract the length of the supplied list of names. */
2387 len = (*extension_data++) << 8;
2388 len |= *extension_data++;
2389 if (len + 2 != extension_len)
2390 goto abort;
2391 /*
2392 * The list in practice only has a single element, so we only consider
2393 * the first one.
2394 */
2395 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2396 goto abort;
2397 extension_len = len - 1;
2398 /* Now we can finally pull out the byte array with the actual hostname. */
2399 if (extension_len <= 2)
2400 goto abort;
2401 len = (*extension_data++) << 8;
2402 len |= *extension_data++;
2403 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2404 || memchr(extension_data, 0, len) != NULL)
2405 goto abort;
2406 servername = extension_data;
2407 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002408 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002409#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002410 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002411 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002412 }
2413#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002414 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002415 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002416 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002417 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002418 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002419 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002420 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002421 goto abort;
2422 }
2423
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002424 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002425#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002426 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002427#else
2428 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2429#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002430 uint8_t sign;
2431 size_t len;
2432 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002433 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002434 len = (*extension_data++) << 8;
2435 len |= *extension_data++;
2436 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002437 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002438 if (len % 2 != 0)
2439 goto abort;
2440 for (; len > 0; len -= 2) {
2441 extension_data++; /* hash */
2442 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002443 switch (sign) {
2444 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002445 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002446 break;
2447 case TLSEXT_signature_ecdsa:
2448 has_ecdsa_sig = 1;
2449 break;
2450 default:
2451 continue;
2452 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002453 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002454 break;
2455 }
2456 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002457 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002458 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002459 }
2460 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002461 const SSL_CIPHER *cipher;
2462 size_t len;
2463 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002464 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002465#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002466 len = ctx->cipher_suites_len;
2467 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002468#else
2469 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2470#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002471 if (len % 2 != 0)
2472 goto abort;
2473 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002474#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002475 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002476 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002477#else
2478 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2479#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002480 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002481 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002482 break;
2483 }
2484 }
2485 }
2486
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002487 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002488 trash.area[i] = tolower(servername[i]);
2489 if (!wildp && (trash.area[i] == '.'))
2490 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002491 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002492 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002493
William Lallemand150bfa82019-09-19 17:12:49 +02002494 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002495
William Lallemand94bd3192020-08-14 14:43:35 +02002496 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2497 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002498 for (i = 0; i < 2; i++) {
2499 if (i == 0) /* lookup in full qualified names */
2500 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002501 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002502 node = ebst_lookup(&s->sni_w_ctx, wildp);
2503 else
2504 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002505
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002506 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002507
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002508 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002509 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002510 struct sni_ctx *sni, *sni_tmp;
2511 int skip = 0;
2512
2513 if (i == 1 && wildp) { /* wildcard */
2514 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2515 sni = container_of(n, struct sni_ctx, name);
2516 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002517 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002518 skip = 1;
2519 break;
2520 }
2521 }
2522 if (skip)
2523 continue;
2524 }
2525
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002526 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002527 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002528 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002529 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002530 break;
2531 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002532 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002533 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002534 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002535 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002536 if (!node_anonymous)
2537 node_anonymous = n;
2538 break;
2539 }
2540 }
2541 }
William Lallemand94bd3192020-08-14 14:43:35 +02002542 }
2543 /* Once the certificates are found, select them depending on what is
2544 * supported in the client and by key_signature priority order: EDSA >
2545 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002546 if (has_ecdsa_sig && node_ecdsa)
2547 node = node_ecdsa;
2548 else if (has_rsa_sig && node_rsa)
2549 node = node_rsa;
2550 else if (node_anonymous)
2551 node = node_anonymous;
2552 else if (node_ecdsa)
2553 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2554 else
2555 node = node_rsa; /* no rsa signature case (far far away) */
2556
William Lallemand94bd3192020-08-14 14:43:35 +02002557 if (node) {
2558 /* switch ctx */
2559 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2560 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2561 if (conf) {
2562 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2563 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2564 if (conf->early_data)
2565 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002566 }
William Lallemand94bd3192020-08-14 14:43:35 +02002567 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2568 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002569 }
William Lallemand150bfa82019-09-19 17:12:49 +02002570
William Lallemand02010472019-10-18 11:02:19 +02002571 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002572#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002573 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002574 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002575 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002576 }
2577#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002578 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002579 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002580 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002581 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002582 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
William Lallemand7980dff2021-11-18 17:46:26 +01002583 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002584 }
William Lallemand7980dff2021-11-18 17:46:26 +01002585
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01002586 /* We are about to raise an handshake error so the servername extension
2587 * callback will never be called and the SNI will never be stored in the
2588 * SSL context. In order for the ssl_fc_sni sample fetch to still work
2589 * in such a case, we store the SNI ourselves as an ex_data information
2590 * in the SSL context.
2591 */
2592 {
2593 char *client_sni = pool_alloc(ssl_sock_client_sni_pool);
2594 if (client_sni) {
2595 strncpy(client_sni, trash.area, TLSEXT_MAXLEN_host_name);
2596 client_sni[TLSEXT_MAXLEN_host_name] = '\0';
2597 SSL_set_ex_data(ssl, ssl_client_sni_index, client_sni);
2598 }
2599 }
2600
William Lallemand7980dff2021-11-18 17:46:26 +01002601 /* other cases fallback on abort, if strict-sni is set but no node was found */
2602
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002603 abort:
2604 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002605 if (conn)
2606 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002607#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002608 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002609#else
2610 *al = SSL_AD_UNRECOGNIZED_NAME;
2611 return 0;
2612#endif
William Lallemand7980dff2021-11-18 17:46:26 +01002613
2614allow_early:
2615#ifdef OPENSSL_IS_BORINGSSL
2616 if (allow_early)
2617 SSL_set_early_data_enabled(ssl, 1);
2618#else
2619 if (!allow_early)
2620 SSL_set_max_early_data(ssl, 0);
2621#endif
2622 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002623}
2624
William Lallemand002e2062021-11-18 15:25:16 +01002625#else /* ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002626
Emeric Brunfc0421f2012-09-07 17:30:07 +02002627/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2628 * warning when no match is found, which implies the default (first) cert
2629 * will keep being used.
2630 */
William Lallemand844009d2022-09-02 15:27:32 +02002631int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002632{
2633 const char *servername;
2634 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002635 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002636 struct bind_conf *s = priv;
William Lallemand70a6e632022-09-07 11:21:34 +02002637#ifdef USE_QUIC
2638 const uint8_t *extension_data;
2639 size_t extension_len;
2640 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2641#endif /* USE_QUIC */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002642 int i;
2643 (void)al; /* shut gcc stupid warning */
2644
William Lallemand70a6e632022-09-07 11:21:34 +02002645#ifdef USE_QUIC
2646 if (qc) {
2647
2648 /* Look for the QUIC transport parameters. */
2649 SSL_get_peer_quic_transport_params(ssl, &extension_data, &extension_len);
2650 if (extension_len == 0) {
2651 /* This is not redundant. It we only return 0 without setting
2652 * <*al>, this has as side effect to generate another TLS alert
2653 * which would be set after calling quic_set_tls_alert().
2654 */
2655 *al = SSL_AD_MISSING_EXTENSION;
2656 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
2657 return SSL_TLSEXT_ERR_NOACK;
2658 }
2659
2660 if (!quic_transport_params_store(qc, 0, extension_data,
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002661 extension_data + extension_len))
William Lallemand70a6e632022-09-07 11:21:34 +02002662 return SSL_TLSEXT_ERR_NOACK;
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002663
2664 qc->flags |= QUIC_FL_CONN_TX_TP_RECEIVED;
William Lallemand70a6e632022-09-07 11:21:34 +02002665 }
2666#endif /* USE_QUIC */
2667
Emeric Brunfc0421f2012-09-07 17:30:07 +02002668 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002669 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002670#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002671 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002672 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002673#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002674 if (s->strict_sni)
2675 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002676 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002677 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002678 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002679 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002680 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002681
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002682 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002683 if (!servername[i])
2684 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002685 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002686 if (!wildp && (trash.area[i] == '.'))
2687 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002688 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002689 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002690
William Lallemand150bfa82019-09-19 17:12:49 +02002691 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002692 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002693 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002694 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2695 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002696 if (!container_of(n, struct sni_ctx, name)->neg) {
2697 node = n;
2698 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002699 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002700 }
2701 if (!node && wildp) {
2702 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002703 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2704 /* lookup a not neg filter */
2705 if (!container_of(n, struct sni_ctx, name)->neg) {
2706 node = n;
2707 break;
2708 }
2709 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002710 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002711 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002712#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002713 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(servername, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002714 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002715 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002716 return SSL_TLSEXT_ERR_OK;
2717 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002718#endif
William Lallemand21724f02019-11-04 17:56:13 +01002719 if (s->strict_sni) {
2720 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002721 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002722 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002723 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002724 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002725 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002726 }
2727
2728 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002729 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002730 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002731 return SSL_TLSEXT_ERR_OK;
2732}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002733#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002734#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2735
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002736#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002737
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002738static inline HASSL_DH *ssl_new_dh_fromdata(BIGNUM *p, BIGNUM *g)
2739{
2740#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2741 OSSL_PARAM_BLD *tmpl = NULL;
2742 OSSL_PARAM *params = NULL;
2743 EVP_PKEY_CTX *ctx = NULL;
2744 EVP_PKEY *pkey = NULL;
2745
2746 if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
2747 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
2748 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)
2749 || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
2750 goto end;
2751 }
2752 ctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2753 if (ctx == NULL
2754 || !EVP_PKEY_fromdata_init(ctx)
2755 || !EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params)) {
2756 goto end;
2757 }
2758
2759end:
2760 EVP_PKEY_CTX_free(ctx);
2761 OSSL_PARAM_free(params);
2762 OSSL_PARAM_BLD_free(tmpl);
Remi Tricot-Le Bretona2c21db2022-11-03 15:16:47 +01002763 BN_free(p);
2764 BN_free(g);
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002765 return pkey;
2766#else
2767
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002768 HASSL_DH *dh = DH_new();
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002769
2770 if (!dh)
2771 return NULL;
2772
2773 DH_set0_pqg(dh, p, NULL, g);
2774
2775 return dh;
2776#endif
2777}
2778
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02002779#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002780static inline HASSL_DH *ssl_get_dh_by_nid(int nid)
2781{
2782#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2783 OSSL_PARAM params[2];
2784 EVP_PKEY *pkey = NULL;
2785 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2786 const char *named_group = NULL;
2787
2788 if (!pctx)
2789 goto end;
2790
2791 named_group = OBJ_nid2ln(nid);
2792
2793 if (!named_group)
2794 goto end;
2795
2796 params[0] = OSSL_PARAM_construct_utf8_string("group", (char*)named_group, 0);
2797 params[1] = OSSL_PARAM_construct_end();
2798
2799 if (EVP_PKEY_keygen_init(pctx) && EVP_PKEY_CTX_set_params(pctx, params))
2800 EVP_PKEY_generate(pctx, &pkey);
2801
2802end:
2803 EVP_PKEY_CTX_free(pctx);
2804 return pkey;
2805#else
2806
2807 HASSL_DH *dh = NULL;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002808 dh = DH_new_by_nid(nid);
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002809 return dh;
2810#endif
2811}
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02002812#endif
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002813
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002814
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002815static HASSL_DH * ssl_get_dh_1024(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002816{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002817 static unsigned char dh1024_p[]={
2818 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2819 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2820 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2821 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2822 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2823 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2824 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2825 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2826 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2827 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2828 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2829 };
2830 static unsigned char dh1024_g[]={
2831 0x02,
2832 };
2833
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002834 BIGNUM *p;
2835 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002836
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002837 HASSL_DH *dh = NULL;
2838
2839 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2840 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
2841
2842 if (p && g)
2843 dh = ssl_new_dh_fromdata(p, g);
2844
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002845 return dh;
2846}
2847
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002848static HASSL_DH *ssl_get_dh_2048(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002849{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002850#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02002851 static unsigned char dh2048_p[]={
2852 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2853 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2854 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2855 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2856 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2857 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2858 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2859 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2860 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2861 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2862 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2863 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2864 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2865 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2866 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2867 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2868 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2869 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2870 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2871 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2872 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2873 0xB7,0x1F,0x77,0xF3,
2874 };
2875 static unsigned char dh2048_g[]={
2876 0x02,
2877 };
2878
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002879 BIGNUM *p;
2880 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002881
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002882 HASSL_DH *dh = NULL;
2883
2884 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2885 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
2886
2887 if (p && g)
2888 dh = ssl_new_dh_fromdata(p, g);
2889
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002890 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002891#else
2892 return ssl_get_dh_by_nid(NID_ffdhe2048);
2893#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002894}
2895
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002896static HASSL_DH *ssl_get_dh_4096(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002897{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002898#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02002899 static unsigned char dh4096_p[]={
2900 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2901 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2902 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2903 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2904 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2905 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2906 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2907 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2908 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2909 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2910 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2911 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2912 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2913 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2914 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2915 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2916 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2917 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2918 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2919 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2920 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2921 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2922 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2923 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2924 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2925 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2926 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2927 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2928 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2929 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2930 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2931 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2932 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2933 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2934 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2935 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2936 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2937 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2938 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2939 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2940 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2941 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2942 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002943 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002944 static unsigned char dh4096_g[]={
2945 0x02,
2946 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002947
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002948 BIGNUM *p;
2949 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002950
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002951 HASSL_DH *dh = NULL;
2952
2953 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2954 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
2955
2956 if (p && g)
2957 dh = ssl_new_dh_fromdata(p, g);
2958
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002959 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002960#else
2961 return ssl_get_dh_by_nid(NID_ffdhe4096);
2962#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002963}
2964
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002965static HASSL_DH *ssl_get_tmp_dh(EVP_PKEY *pkey)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002966{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002967 HASSL_DH *dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002968 int type;
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002969 int keylen = 0;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002970
2971 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002972
Ilya Shipitsin52f2ff52022-07-23 23:55:19 +05002973 if (type == EVP_PKEY_EC) {
2974 keylen = global_ssl.default_dh_param;
2975 }
2976
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002977 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2978 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2979 */
2980 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2981 keylen = EVP_PKEY_bits(pkey);
2982 }
2983
Willy Tarreauef934602016-12-22 23:12:01 +01002984 if (keylen > global_ssl.default_dh_param) {
2985 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002986 }
2987
Remi Gacogned3a341a2015-05-29 16:26:17 +02002988 if (keylen >= 4096) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01002989 if (!local_dh_4096)
2990 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02002991 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002992 }
2993 else if (keylen >= 2048) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01002994 if (!local_dh_2048)
2995 local_dh_2048 = ssl_get_dh_2048();
Remi Gacogne8de54152014-07-15 11:36:40 +02002996 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002997 }
2998 else {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01002999 if (!local_dh_1024)
3000 local_dh_1024 = ssl_get_dh_1024();
Remi Gacogne8de54152014-07-15 11:36:40 +02003001 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003002 }
3003
3004 return dh;
3005}
3006
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003007#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003008/* Returns Diffie-Hellman parameters matching the private key length
3009 but not exceeding global_ssl.default_dh_param */
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003010static HASSL_DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003011{
3012 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
3013
3014 return ssl_get_tmp_dh(pkey);
3015}
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003016#endif
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003017
Remi Tricot-Le Breton846eda92022-02-11 12:04:50 +01003018static int ssl_sock_set_tmp_dh(SSL_CTX *ctx, HASSL_DH *dh)
3019{
3020#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
3021 return SSL_CTX_set_tmp_dh(ctx, dh);
3022#else
3023 int retval = 0;
3024 HASSL_DH_up_ref(dh);
3025
3026 retval = SSL_CTX_set0_tmp_dh_pkey(ctx, dh);
3027
3028 if (!retval)
3029 HASSL_DH_free(dh);
3030
3031 return retval;
3032#endif
3033}
3034
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003035#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3036static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey)
3037{
3038 HASSL_DH *dh = NULL;
3039 if (pkey && (dh = ssl_get_tmp_dh(pkey))) {
3040 HASSL_DH_up_ref(dh);
3041 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dh))
3042 HASSL_DH_free(dh);
3043 }
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003044}
3045#endif
3046
Remi Tricot-Le Breton09ebb332022-02-11 12:04:48 +01003047HASSL_DH *ssl_sock_get_dh_from_bio(BIO *bio)
3048{
3049#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3050 HASSL_DH *dh = NULL;
3051 OSSL_DECODER_CTX *dctx = NULL;
3052 const char *format = "PEM";
3053 const char *keytype = "DH";
3054
3055 dctx = OSSL_DECODER_CTX_new_for_pkey(&dh, format, NULL, keytype,
3056 OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
3057 NULL, NULL);
3058
3059 if (dctx == NULL || OSSL_DECODER_CTX_get_num_decoders(dctx) == 0)
3060 goto end;
3061
3062 /* The DH parameters might not be the first section found in the PEM
3063 * file so we need to iterate over all of them until we find the right
3064 * one.
3065 */
3066 while (!BIO_eof(bio) && !dh)
3067 OSSL_DECODER_from_bio(dctx, bio);
3068
3069end:
3070 OSSL_DECODER_CTX_free(dctx);
3071 return dh;
3072#else
3073 HASSL_DH *dh = NULL;
3074
3075 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3076
3077 return dh;
3078#endif
3079}
3080
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003081static HASSL_DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003082{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003083 HASSL_DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02003084 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003085
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003086 if (in == NULL)
3087 goto end;
3088
Remi Gacogne47783ef2015-05-29 15:53:22 +02003089 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003090 goto end;
3091
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003092 dh = ssl_sock_get_dh_from_bio(in);
Remi Gacogne47783ef2015-05-29 15:53:22 +02003093
3094end:
3095 if (in)
3096 BIO_free(in);
3097
Emeric Brune1b4ed42018-08-16 15:14:12 +02003098 ERR_clear_error();
3099
Remi Gacogne47783ef2015-05-29 15:53:22 +02003100 return dh;
3101}
3102
3103int ssl_sock_load_global_dh_param_from_file(const char *filename)
3104{
3105 global_dh = ssl_sock_get_dh_from_file(filename);
3106
3107 if (global_dh) {
3108 return 0;
3109 }
3110
3111 return -1;
3112}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003113#endif
3114
William Lallemand9117de92019-10-04 00:29:42 +02003115/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02003116static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02003117 struct bind_conf *s, struct ssl_bind_conf *conf,
3118 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003119{
3120 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003121 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003122
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003123 if (*name == '!') {
3124 neg = 1;
3125 name++;
3126 }
3127 if (*name == '*') {
3128 wild = 1;
3129 name++;
3130 }
3131 /* !* filter is a nop */
3132 if (neg && wild)
3133 return order;
3134 if (*name) {
3135 int j, len;
3136 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003137 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02003138 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003139 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02003140 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003141 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003142
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003143 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02003144 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02003145 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003146 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02003147 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003148 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003149 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003150 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003151 sc->order = order++;
3152 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02003153 sc->wild = wild;
3154 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01003155 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02003156 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003157 }
3158 return order;
3159}
3160
William Lallemand6af03992019-07-23 15:00:54 +02003161/*
William Lallemand1d29c742019-10-04 00:53:29 +02003162 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
3163 * This function can't return an error.
3164 *
3165 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
3166 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003167void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02003168{
3169
3170 struct sni_ctx *sc0, *sc0b, *sc1;
3171 struct ebmb_node *node;
3172
3173 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
3174
3175 /* ignore if sc0 was already inserted in a tree */
3176 if (sc0->name.node.leaf_p)
3177 continue;
3178
3179 /* Check for duplicates. */
3180 if (sc0->wild)
3181 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
3182 else
3183 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
3184
3185 for (; node; node = ebmb_next_dup(node)) {
3186 sc1 = ebmb_entry(node, struct sni_ctx, name);
3187 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
3188 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
3189 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02003190 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02003191 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003192 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02003193 break;
William Lallemand1d29c742019-10-04 00:53:29 +02003194 }
3195 }
3196
3197 /* if duplicate, ignore the insertion */
3198 if (!sc0)
3199 continue;
3200
3201 if (sc0->wild)
3202 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
3203 else
3204 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003205 }
William Lallemand21724f02019-11-04 17:56:13 +01003206
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003207 /* replace the default_ctx if required with the instance's ctx. */
3208 if (ckch_inst->is_default) {
3209 SSL_CTX_free(bind_conf->default_ctx);
3210 SSL_CTX_up_ref(ckch_inst->ctx);
3211 bind_conf->default_ctx = ckch_inst->ctx;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003212 bind_conf->default_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02003213 }
3214}
3215
3216/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003217 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02003218 */
William Lallemande3af8fb2019-10-08 11:36:53 +02003219struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02003220
William Lallemand2954c472020-03-06 21:54:13 +01003221/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02003222struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02003223
Emeric Brun7a883362019-10-17 13:27:40 +02003224/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003225 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02003226 * DH parameter is loaded into the SSL_CTX and if there is no
3227 * DH parameter available in ckchs nor in global, the default
3228 * DH parameters are applied on the SSL_CTX.
3229 * Returns a bitfield containing the flags:
3230 * ERR_FATAL in any fatal error case
3231 * ERR_ALERT if a reason of the error is availabine in err
3232 * ERR_WARN if a warning is available into err
3233 * The value 0 means there is no error nor warning and
3234 * the operation succeed.
3235 */
William Lallemandfa892222019-07-23 16:06:08 +02003236#ifndef OPENSSL_NO_DH
William Lallemand52ddd992022-11-22 11:51:53 +01003237static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct ckch_data *data,
Emeric Brun7a883362019-10-17 13:27:40 +02003238 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02003239{
Emeric Brun7a883362019-10-17 13:27:40 +02003240 int ret = 0;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003241 HASSL_DH *dh = NULL;
William Lallemandfa892222019-07-23 16:06:08 +02003242
William Lallemand52ddd992022-11-22 11:51:53 +01003243 if (data && data->dh) {
3244 dh = data->dh;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003245 if (!ssl_sock_set_tmp_dh(ctx, dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003246 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
3247 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003248 memprintf(err, "%s, DH ciphers won't be available.\n",
3249 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003250 ret |= ERR_WARN;
3251 goto end;
3252 }
William Lallemandfa892222019-07-23 16:06:08 +02003253
3254 if (ssl_dh_ptr_index >= 0) {
3255 /* store a pointer to the DH params to avoid complaining about
3256 ssl-default-dh-param not being set for this SSL_CTX */
3257 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
3258 }
3259 }
3260 else if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003261 if (!ssl_sock_set_tmp_dh(ctx, global_dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003262 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
3263 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003264 memprintf(err, "%s, DH ciphers won't be available.\n",
3265 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003266 ret |= ERR_WARN;
3267 goto end;
3268 }
William Lallemandfa892222019-07-23 16:06:08 +02003269 }
3270 else {
3271 /* Clear openssl global errors stack */
3272 ERR_clear_error();
3273
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003274 /* We do not want DHE ciphers to be added to the cipher list
3275 * unless there is an explicit global dh option in the conf.
3276 */
3277 if (global_ssl.default_dh_param) {
3278 if (global_ssl.default_dh_param <= 1024) {
3279 /* we are limited to DH parameter of 1024 bits anyway */
3280 if (local_dh_1024 == NULL)
3281 local_dh_1024 = ssl_get_dh_1024();
William Lallemandfa892222019-07-23 16:06:08 +02003282
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003283 if (local_dh_1024 == NULL) {
3284 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3285 err && *err ? *err : "", path);
3286 ret |= ERR_ALERT | ERR_FATAL;
3287 goto end;
3288 }
William Lallemandfa892222019-07-23 16:06:08 +02003289
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003290 if (!ssl_sock_set_tmp_dh(ctx, local_dh_1024)) {
3291 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3292 err && *err ? *err : "", path);
3293 memprintf(err, "%s, DH ciphers won't be available.\n",
3294 err && *err ? *err : "");
3295 ret |= ERR_WARN;
3296 goto end;
3297 }
Emeric Bruna9363eb2019-10-17 14:53:03 +02003298 }
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003299 else {
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003300#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003301 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003302#else
William Lallemand52ddd992022-11-22 11:51:53 +01003303 ssl_sock_set_tmp_dh_from_pkey(ctx, data ? data->key : NULL);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003304#endif
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003305 }
William Lallemandfa892222019-07-23 16:06:08 +02003306 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003307 }
3308
William Lallemandf9568fc2019-10-16 18:27:58 +02003309end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003310 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003311 return ret;
3312}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003313#endif
William Lallemandfa892222019-07-23 16:06:08 +02003314
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003315
3316/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003317 * Returns a bitfield containing the flags:
3318 * ERR_FATAL in any fatal error case
3319 * ERR_ALERT if the reason of the error is available in err
3320 * ERR_WARN if a warning is available into err
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003321 * The caller is responsible of freeing the newly built or newly refcounted
3322 * find_chain element.
Emeric Bruna96b5822019-10-17 13:25:14 +02003323 * The value 0 means there is no error nor warning and
3324 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003325 */
William Lallemand52ddd992022-11-22 11:51:53 +01003326static int ssl_sock_load_cert_chain(const char *path, const struct ckch_data *data,
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003327 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003328{
Emeric Bruna96b5822019-10-17 13:25:14 +02003329 int errcode = 0;
William Lallemand45fed2c2022-11-15 16:56:03 +01003330 int ret;
3331
3332 ERR_clear_error();
Emeric Bruna96b5822019-10-17 13:25:14 +02003333
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003334 if (find_chain == NULL) {
3335 errcode |= ERR_FATAL;
3336 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003337 }
3338
William Lallemand52ddd992022-11-22 11:51:53 +01003339 if (!SSL_CTX_use_certificate(ctx, data->cert)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003340 ret = ERR_get_error();
3341 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s': %s.\n",
3342 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Emeric Bruna96b5822019-10-17 13:25:14 +02003343 errcode |= ERR_ALERT | ERR_FATAL;
3344 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003345 }
3346
William Lallemand52ddd992022-11-22 11:51:53 +01003347 if (data->chain) {
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003348 *find_chain = X509_chain_up_ref(data->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003349 } else {
3350 /* Find Certificate Chain in global */
3351 struct issuer_chain *issuer;
William Lallemand52ddd992022-11-22 11:51:53 +01003352 issuer = ssl_get0_issuer_chain(data->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003353 if (issuer)
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003354 *find_chain = X509_chain_up_ref(issuer->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003355 }
William Lallemand85888572020-02-27 14:48:35 +01003356
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003357 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003358 /* always put a null chain stack in the SSL_CTX so it does not
3359 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003360 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003361 }
3362
William Lallemand52ddd992022-11-22 11:51:53 +01003363 /* Load all certs in the data into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003364#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003365 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003366 ret = ERR_get_error();
3367 memprintf(err, "%sunable to load chain certificate into SSL Context '%s': %s. Make sure you are linking against Openssl >= 1.0.2.\n",
3368 err && *err ? *err : "", path, ERR_reason_error_string(ret));
William Lallemand935d8292020-08-12 20:02:10 +02003369 errcode |= ERR_ALERT | ERR_FATAL;
3370 goto end;
3371 }
William Lallemandf187ce62020-06-02 18:27:20 +02003372#else
3373 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003374 X509 *ca;
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003375 while ((ca = sk_X509_shift(*find_chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003376 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003377 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3378 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003379 X509_free(ca);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003380 errcode |= ERR_ALERT | ERR_FATAL;
3381 goto end;
3382 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003383 }
William Lallemandf187ce62020-06-02 18:27:20 +02003384#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003385
William Lallemand9a1d8392020-08-10 17:28:23 +02003386#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003387 /* remove the Root CA from the SSL_CTX if the option is activated */
3388 if (global_ssl.skip_self_issued_ca) {
3389 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3390 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3391 err && *err ? *err : "", path);
3392 errcode |= ERR_ALERT | ERR_FATAL;
3393 goto end;
3394 }
3395 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003396#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003397
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003398end:
3399 return errcode;
3400}
3401
3402
3403/* Loads the info in ckch into ctx
3404 * Returns a bitfield containing the flags:
3405 * ERR_FATAL in any fatal error case
3406 * ERR_ALERT if the reason of the error is available in err
3407 * ERR_WARN if a warning is available into err
3408 * The value 0 means there is no error nor warning and
3409 * the operation succeed.
3410 */
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01003411static 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 +01003412{
3413 int errcode = 0;
3414 STACK_OF(X509) *find_chain = NULL;
3415
William Lallemand5de49512022-10-27 14:41:07 +02003416 ERR_clear_error();
3417
William Lallemand52ddd992022-11-22 11:51:53 +01003418 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
William Lallemand5de49512022-10-27 14:41:07 +02003419 int ret;
3420
3421 ret = ERR_get_error();
3422 memprintf(err, "%sunable to load SSL private key into SSL Context '%s': %s.\n",
3423 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003424 errcode |= ERR_ALERT | ERR_FATAL;
3425 return errcode;
3426 }
3427
3428 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01003429 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003430 if (errcode & ERR_CODE)
3431 goto end;
3432
William Lallemandfa892222019-07-23 16:06:08 +02003433#ifndef OPENSSL_NO_DH
3434 /* store a NULL pointer to indicate we have not yet loaded
3435 a custom DH param file */
3436 if (ssl_dh_ptr_index >= 0) {
3437 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3438 }
3439
William Lallemand52ddd992022-11-22 11:51:53 +01003440 errcode |= ssl_sock_load_dh_params(ctx, data, path, err);
Emeric Brun7a883362019-10-17 13:27:40 +02003441 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003442 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3443 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003444 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003445 }
3446#endif
3447
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003448#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemand52ddd992022-11-22 11:51:53 +01003449 if (sctl_ex_index >= 0 && data->sctl) {
3450 if (ssl_sock_load_sctl(ctx, data->sctl) < 0) {
William Lallemanda17f4112019-10-10 15:16:44 +02003451 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003452 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003453 errcode |= ERR_ALERT | ERR_FATAL;
3454 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003455 }
3456 }
3457#endif
3458
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003459#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 +01003460 /* Load OCSP Info into context
3461 * If OCSP update mode is set to 'on', an entry will be created in the
3462 * ocsp tree even if no ocsp_response was known during init, unless the
3463 * frontend's conf disables ocsp update explicitely.
3464 */
3465 if (ssl_sock_load_ocsp(ctx, data, find_chain) < 0) {
3466 if (data->ocsp_response)
Tim Duesterhus93128532019-11-23 23:45:10 +01003467 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 +01003468 err && *err ? *err : "", path);
3469 else
3470 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",
3471 err && *err ? *err : "", path);
3472 errcode |= ERR_ALERT | ERR_FATAL;
3473 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003474 }
William Lallemand246c0242019-10-11 08:59:13 +02003475#endif
3476
Emeric Bruna96b5822019-10-17 13:25:14 +02003477 end:
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003478 sk_X509_pop_free(find_chain, X509_free);
Emeric Bruna96b5822019-10-17 13:25:14 +02003479 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003480}
3481
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003482
3483/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
3484 * Returns a bitfield containing the flags:
3485 * ERR_FATAL in any fatal error case
3486 * ERR_ALERT if the reason of the error is available in err
3487 * ERR_WARN if a warning is available into err
3488 * The value 0 means there is no error nor warning and
3489 * the operation succeed.
3490 */
William Lallemand52ddd992022-11-22 11:51:53 +01003491static 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 +01003492 SSL_CTX *ctx, char **err)
3493{
3494 int errcode = 0;
3495 STACK_OF(X509) *find_chain = NULL;
3496
3497 /* Load the private key */
William Lallemand52ddd992022-11-22 11:51:53 +01003498 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003499 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3500 err && *err ? *err : "", path);
3501 errcode |= ERR_ALERT | ERR_FATAL;
3502 }
3503
3504 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01003505 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003506 if (errcode & ERR_CODE)
3507 goto end;
3508
3509 if (SSL_CTX_check_private_key(ctx) <= 0) {
3510 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3511 err && *err ? *err : "", path);
3512 errcode |= ERR_ALERT | ERR_FATAL;
3513 }
3514
3515end:
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003516 sk_X509_pop_free(find_chain, X509_free);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003517 return errcode;
3518}
3519
3520
William Lallemand614ca0d2019-10-07 13:52:11 +02003521/*
3522 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003523 *
3524 * Returns a bitfield containing the flags:
3525 * ERR_FATAL in any fatal error case
3526 * ERR_ALERT if the reason of the error is available in err
3527 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003528 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003529int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003530 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003531{
William Lallemandc9402072019-05-15 15:33:54 +02003532 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003533 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003534 int order = 0;
3535 X509_NAME *xname;
3536 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003537 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003538 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003539#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3540 STACK_OF(GENERAL_NAME) *names;
3541#endif
William Lallemand52ddd992022-11-22 11:51:53 +01003542 struct ckch_data *data;
William Lallemand614ca0d2019-10-07 13:52:11 +02003543 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003544 int errcode = 0;
3545
3546 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003547
William Lallemand52ddd992022-11-22 11:51:53 +01003548 if (!ckchs || !ckchs->data)
Emeric Brun054563d2019-10-17 13:16:58 +02003549 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003550
William Lallemand52ddd992022-11-22 11:51:53 +01003551 data = ckchs->data;
William Lallemand36b84632019-07-18 19:28:17 +02003552
William Lallemandc9402072019-05-15 15:33:54 +02003553 ctx = SSL_CTX_new(SSLv23_server_method());
3554 if (!ctx) {
3555 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3556 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003557 errcode |= ERR_ALERT | ERR_FATAL;
3558 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003559 }
3560
William Lallemand52ddd992022-11-22 11:51:53 +01003561 errcode |= ssl_sock_put_ckch_into_ctx(path, data, ctx, err);
Emeric Bruna96b5822019-10-17 13:25:14 +02003562 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003563 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003564
3565 ckch_inst = ckch_inst_new();
3566 if (!ckch_inst) {
3567 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3568 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003569 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003570 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003571 }
3572
William Lallemand52ddd992022-11-22 11:51:53 +01003573 pkey = X509_get_pubkey(data->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003574 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003575 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003576 switch(EVP_PKEY_base_id(pkey)) {
3577 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003578 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003579 break;
3580 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003581 kinfo.sig = TLSEXT_signature_ecdsa;
3582 break;
3583 case EVP_PKEY_DSA:
3584 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003585 break;
3586 }
3587 EVP_PKEY_free(pkey);
3588 }
3589
Emeric Brun50bcecc2013-04-22 13:05:23 +02003590 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003591 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003592 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 +02003593 if (order < 0) {
3594 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003595 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003596 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003597 }
3598 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003599 }
3600 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003601#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand52ddd992022-11-22 11:51:53 +01003602 names = X509_get_ext_d2i(data->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003603 if (names) {
3604 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3605 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3606 if (name->type == GEN_DNS) {
3607 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003608 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003609 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003610 if (order < 0) {
3611 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003612 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003613 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003614 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003615 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003616 }
3617 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003618 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003619 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003620#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand52ddd992022-11-22 11:51:53 +01003621 xname = X509_get_subject_name(data->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003622 i = -1;
3623 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3624 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003625 ASN1_STRING *value;
3626
3627 value = X509_NAME_ENTRY_get_data(entry);
3628 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003629 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003630 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003631 if (order < 0) {
3632 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003633 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003634 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003635 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003636 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003637 }
3638 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003639 /* we must not free the SSL_CTX anymore below, since it's already in
3640 * the tree, so it will be discovered and cleaned in time.
3641 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003642
Emeric Brunfc0421f2012-09-07 17:30:07 +02003643#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003644 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003645 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3646 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003647 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003648 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003649 }
3650#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003651 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003652 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003653 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003654 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003655 SSL_CTX_up_ref(ctx);
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003656 bind_conf->default_inst = ckch_inst;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003657 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003658
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003659 /* Always keep a reference to the newly constructed SSL_CTX in the
3660 * instance. This way if the instance has no SNIs, the SSL_CTX will
3661 * still be linked. */
3662 SSL_CTX_up_ref(ctx);
3663 ckch_inst->ctx = ctx;
3664
William Lallemand9117de92019-10-04 00:29:42 +02003665 /* everything succeed, the ckch instance can be used */
3666 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003667 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003668 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003669
William Lallemand02e19a52020-04-08 16:11:26 +02003670 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3671
Emeric Brun054563d2019-10-17 13:16:58 +02003672 *ckchi = ckch_inst;
3673 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003674
3675error:
3676 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003677 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003678 if (ckch_inst->is_default)
3679 SSL_CTX_free(ctx);
3680
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003681 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003682 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003683 }
William Lallemandd9199372019-10-04 15:37:05 +02003684 SSL_CTX_free(ctx);
3685
Emeric Brun054563d2019-10-17 13:16:58 +02003686 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003687}
3688
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003689
3690/*
3691 * This function allocate a ckch_inst that will be used on the backend side
3692 * (server line)
3693 *
3694 * Returns a bitfield containing the flags:
3695 * ERR_FATAL in any fatal error case
3696 * ERR_ALERT if the reason of the error is available in err
3697 * ERR_WARN if a warning is available into err
3698 */
3699int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01003700 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003701{
3702 SSL_CTX *ctx;
William Lallemand52ddd992022-11-22 11:51:53 +01003703 struct ckch_data *data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003704 struct ckch_inst *ckch_inst = NULL;
3705 int errcode = 0;
3706
3707 *ckchi = NULL;
3708
William Lallemand52ddd992022-11-22 11:51:53 +01003709 if (!ckchs || !ckchs->data)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003710 return ERR_FATAL;
3711
William Lallemand52ddd992022-11-22 11:51:53 +01003712 data = ckchs->data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003713
3714 ctx = SSL_CTX_new(SSLv23_client_method());
3715 if (!ctx) {
3716 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3717 err && *err ? *err : "", path);
3718 errcode |= ERR_ALERT | ERR_FATAL;
3719 goto error;
3720 }
3721
William Lallemand52ddd992022-11-22 11:51:53 +01003722 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, data, ctx, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003723 if (errcode & ERR_CODE)
3724 goto error;
3725
3726 ckch_inst = ckch_inst_new();
3727 if (!ckch_inst) {
3728 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3729 err && *err ? *err : "", path);
3730 errcode |= ERR_ALERT | ERR_FATAL;
3731 goto error;
3732 }
3733
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003734 /* everything succeed, the ckch instance can be used */
3735 ckch_inst->bind_conf = NULL;
3736 ckch_inst->ssl_conf = NULL;
3737 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01003738 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003739 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003740
3741 *ckchi = ckch_inst;
3742 return errcode;
3743
3744error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003745 SSL_CTX_free(ctx);
3746
3747 return errcode;
3748}
3749
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003750/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003751static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3752 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003753 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003754{
Emeric Brun054563d2019-10-17 13:16:58 +02003755 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003756
3757 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003758 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 +02003759
Emeric Brun054563d2019-10-17 13:16:58 +02003760 if (errcode & ERR_CODE)
3761 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003762
William Lallemand24bde432020-03-09 16:48:43 +01003763 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003764
3765 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003766 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003767 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003768}
3769
William Lallemanddb26e2b2021-01-26 12:01:46 +01003770/* This function generates a <struct ckch_inst *> for a <struct server *>, and
3771 * fill the SSL_CTX of the server.
3772 *
3773 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003774static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01003775 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003776{
3777 int errcode = 0;
3778
3779 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01003780 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003781
3782 if (errcode & ERR_CODE)
3783 return errcode;
3784
William Lallemanddb26e2b2021-01-26 12:01:46 +01003785 (*ckch_inst)->server = server;
3786 /* Keep the reference to the SSL_CTX in the server. */
3787 SSL_CTX_up_ref((*ckch_inst)->ctx);
3788 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003789 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003790 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003791 return errcode;
3792}
3793
William Lallemand6be66ec2020-03-06 22:26:32 +01003794
William Lallemand4c68bba2020-03-30 18:45:10 +02003795
3796
3797/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3798 * done once. Zero is returned if the operation fails. No error is returned
3799 * if the random is said as not implemented, because we expect that openssl
3800 * will use another method once needed.
3801 */
Amaury Denoyellec593bcd2021-05-19 15:35:29 +02003802int ssl_initialize_random(void)
William Lallemand4c68bba2020-03-30 18:45:10 +02003803{
3804 unsigned char random;
3805 static int random_initialized = 0;
3806
3807 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3808 random_initialized = 1;
3809
3810 return random_initialized;
3811}
3812
William Lallemand2954c472020-03-06 21:54:13 +01003813/* Load a crt-list file, this is done in 2 parts:
3814 * - store the content of the file in a crtlist structure with crtlist_entry structures
3815 * - generate the instances by iterating on entries in the crtlist struct
3816 *
3817 * Nothing is locked there, this function is used in the configuration parser.
3818 *
3819 * Returns a set of ERR_* flags possibly with an error in <err>.
3820 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003821int 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 +01003822{
3823 struct crtlist *crtlist = NULL;
3824 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003825 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003826 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003827 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003828 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003829
William Lallemand79d31ec2020-03-25 15:10:49 +01003830 bind_conf_node = malloc(sizeof(*bind_conf_node));
3831 if (!bind_conf_node) {
3832 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3833 cfgerr |= ERR_FATAL | ERR_ALERT;
3834 goto error;
3835 }
3836 bind_conf_node->next = NULL;
3837 bind_conf_node->bind_conf = bind_conf;
3838
William Lallemand41ca9302020-04-08 13:15:18 +02003839 /* strip trailing slashes, including first one */
3840 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3841 *end = 0;
3842
William Lallemand2954c472020-03-06 21:54:13 +01003843 /* look for an existing crtlist or create one */
3844 eb = ebst_lookup(&crtlists_tree, file);
3845 if (eb) {
3846 crtlist = ebmb_entry(eb, struct crtlist, node);
3847 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003848 /* load a crt-list OR a directory */
3849 if (dir)
3850 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3851 else
3852 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3853
William Lallemand2954c472020-03-06 21:54:13 +01003854 if (!(cfgerr & ERR_CODE))
3855 ebst_insert(&crtlists_tree, &crtlist->node);
3856 }
3857
3858 if (cfgerr & ERR_CODE) {
3859 cfgerr |= ERR_FATAL | ERR_ALERT;
3860 goto error;
3861 }
3862
3863 /* generates ckch instance from the crtlist_entry */
3864 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3865 struct ckch_store *store;
3866 struct ckch_inst *ckch_inst = NULL;
3867
3868 store = entry->node.key;
3869 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3870 if (cfgerr & ERR_CODE) {
3871 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3872 goto error;
3873 }
Willy Tarreau2b718102021-04-21 07:32:39 +02003874 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003875 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003876 }
William Lallemand2954c472020-03-06 21:54:13 +01003877
William Lallemand79d31ec2020-03-25 15:10:49 +01003878 /* add the bind_conf to the list */
3879 bind_conf_node->next = crtlist->bind_conf;
3880 crtlist->bind_conf = bind_conf_node;
3881
William Lallemand2954c472020-03-06 21:54:13 +01003882 return cfgerr;
3883error:
3884 {
William Lallemand49398312020-03-30 17:01:33 +02003885 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003886 struct ckch_inst *inst, *s_inst;
3887
William Lallemand49398312020-03-30 17:01:33 +02003888 lastentry = entry; /* which entry we tried to generate last */
3889 if (lastentry) {
3890 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3891 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3892 break;
3893
3894 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003895
William Lallemand49398312020-03-30 17:01:33 +02003896 /* this was not generated for this bind_conf, skip */
3897 if (inst->bind_conf != bind_conf)
3898 continue;
3899
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003900 /* free the sni_ctx and instance */
3901 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003902 }
William Lallemand2954c472020-03-06 21:54:13 +01003903 }
William Lallemand2954c472020-03-06 21:54:13 +01003904 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003905 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003906 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003907 return cfgerr;
3908}
3909
William Lallemand06b22a82020-03-16 14:45:55 +01003910/* Returns a set of ERR_* flags possibly with an error in <err>. */
3911int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3912{
3913 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01003914 int cfgerr = 0;
3915 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003916 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01003917 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01003918
3919 if ((ckchs = ckchs_lookup(path))) {
3920 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01003921 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3922 found++;
3923 } else if (stat(path, &buf) == 0) {
3924 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01003925 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003926 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003927 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003928 cfgerr |= ERR_ALERT | ERR_FATAL;
3929 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003930 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01003931 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003932 }
3933 } else {
3934 /* stat failed, could be a bundle */
3935 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02003936 char fp[MAXPATHLEN+1] = {0};
3937 int n = 0;
3938
3939 /* Load all possible certs and keys in separate ckch_store */
3940 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3941 struct stat buf;
3942 int ret;
3943
3944 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3945 if (ret > sizeof(fp))
3946 continue;
3947
3948 if ((ckchs = ckchs_lookup(fp))) {
3949 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01003950 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02003951 } else {
3952 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01003953 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003954 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02003955 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003956 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02003957 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3958 }
3959 }
3960 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01003961#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
3962 if (found) {
3963 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
3964 err && *err ? *err : "", path);
3965 cfgerr |= ERR_ALERT | ERR_FATAL;
3966 }
3967#endif
William Lallemand06b22a82020-03-16 14:45:55 +01003968 }
3969 }
William Lallemand06ce84a2020-11-20 15:36:13 +01003970 if (!found) {
3971 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3972 err && *err ? *err : "", path, strerror(errno));
3973 cfgerr |= ERR_ALERT | ERR_FATAL;
3974 }
William Lallemand06b22a82020-03-16 14:45:55 +01003975
3976 return cfgerr;
3977}
3978
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003979
3980/* Create a full ssl context and ckch instance that will be used for a specific
3981 * backend server (server configuration line).
3982 * Returns a set of ERR_* flags possibly with an error in <err>.
3983 */
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02003984int 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 +01003985{
3986 struct stat buf;
3987 int cfgerr = 0;
3988 struct ckch_store *ckchs;
3989 int found = 0; /* did we found a file to load ? */
3990
3991 if ((ckchs = ckchs_lookup(path))) {
3992 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01003993 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003994 found++;
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02003995 } else {
3996 if (!create_if_none) {
3997 memprintf(err, "%sunable to stat SSL certificate '%s'.\n",
3998 err && *err ? *err : "", path);
3999 cfgerr |= ERR_ALERT | ERR_FATAL;
4000 goto out;
4001 }
4002
4003 if (stat(path, &buf) == 0) {
4004 /* We do not manage directories on backend side. */
4005 if (S_ISDIR(buf.st_mode) == 0) {
4006 ++found;
4007 ckchs = ckchs_load_cert_file(path, err);
4008 if (!ckchs)
4009 cfgerr |= ERR_ALERT | ERR_FATAL;
4010 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
4011 }
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004012 }
4013 }
4014 if (!found) {
4015 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
4016 err && *err ? *err : "", path, strerror(errno));
4017 cfgerr |= ERR_ALERT | ERR_FATAL;
4018 }
4019
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004020out:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004021 return cfgerr;
4022}
4023
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004024/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004025static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004026ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004027{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004028 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004029 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004030 SSL_OP_ALL | /* all known workarounds for bugs */
4031 SSL_OP_NO_SSLv2 |
4032 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02004033 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02004034 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004035 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02004036 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004037 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004038 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004039 SSL_MODE_ENABLE_PARTIAL_WRITE |
4040 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004041 SSL_MODE_RELEASE_BUFFERS |
4042 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004043 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004044 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004045 int flags = MC_SSL_O_ALL;
4046 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02004047 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004048
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004049 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004050 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004051
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004052 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004053 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
4054 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4055 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004056 else
4057 flags = conf_ssl_methods->flags;
4058
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004059 min = conf_ssl_methods->min;
4060 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02004061
4062 /* default minimum is TLSV12, */
4063 if (!min) {
4064 if (!max || (max >= default_min_ver)) {
4065 min = default_min_ver;
4066 } else {
4067 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). "
4068 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
4069 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
4070 min = max;
4071 }
4072 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004073 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004074 if (min)
4075 flags |= (methodVersions[min].flag - 1);
4076 if (max)
4077 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004078 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004079 min = max = CONF_TLSV_NONE;
4080 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004081 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004082 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004083 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004084 if (min) {
4085 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004086 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
4087 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4088 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
4089 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004090 hole = 0;
4091 }
4092 max = i;
4093 }
4094 else {
4095 min = max = i;
4096 }
4097 }
4098 else {
4099 if (min)
4100 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004101 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004102 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004103 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4104 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004105 cfgerr += 1;
4106 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004107 /* save real min/max in bind_conf */
4108 conf_ssl_methods->min = min;
4109 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004110
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004111#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004112 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004113 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004114 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004115 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004116 else
William Lallemandd0712f32020-06-11 17:34:00 +02004117 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
4118 /* clear every version flags in case SSL_CTX_new()
4119 * returns an SSL_CTX with disabled versions */
4120 SSL_CTX_clear_options(ctx, methodVersions[i].option);
4121
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004122 if (flags & methodVersions[i].flag)
4123 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02004124
4125 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004126#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004127 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004128 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4129 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02004130#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004131
4132 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
4133 options |= SSL_OP_NO_TICKET;
4134 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
4135 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08004136
4137#ifdef SSL_OP_NO_RENEGOTIATION
4138 options |= SSL_OP_NO_RENEGOTIATION;
4139#endif
4140
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004141 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004142
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004143#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004144 if (global_ssl.async)
4145 mode |= SSL_MODE_ASYNC;
4146#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004147 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004148 if (global_ssl.life_time)
4149 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004150
4151#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand4b7938d2022-09-07 10:54:17 +02004152# ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004153 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
4154 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004155# elif defined(HAVE_SSL_CLIENT_HELLO_CB)
4156# if defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01004157 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01004158 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
William Lallemand4b7938d2022-09-07 10:54:17 +02004159# endif /* ! SSL_OP_NO_ANTI_REPLAY */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02004160 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
4161 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004162# else /* ! OPENSSL_IS_BORINGSSL && ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004163 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004164# endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02004165 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
William Lallemand4b7938d2022-09-07 10:54:17 +02004166#endif /* ! SSL_CTRL_SET_TLSEXT_HOSTNAME */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004167 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004168}
4169
William Lallemand4f45bb92017-10-30 20:08:51 +01004170
4171static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
4172{
4173 if (first == block) {
4174 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4175 if (first->len > 0)
4176 sh_ssl_sess_tree_delete(sh_ssl_sess);
4177 }
4178}
4179
4180/* return first block from sh_ssl_sess */
4181static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
4182{
4183 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
4184
4185}
4186
4187/* store a session into the cache
4188 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
4189 * data: asn1 encoded session
4190 * data_len: asn1 encoded session length
4191 * Returns 1 id session was stored (else 0)
4192 */
4193static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
4194{
4195 struct shared_block *first;
4196 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
4197
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004198 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01004199 if (!first) {
4200 /* Could not retrieve enough free blocks to store that session */
4201 return 0;
4202 }
4203
4204 /* STORE the key in the first elem */
4205 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4206 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
4207 first->len = sizeof(struct sh_ssl_sess_hdr);
4208
4209 /* it returns the already existing node
4210 or current node if none, never returns null */
4211 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
4212 if (oldsh_ssl_sess != sh_ssl_sess) {
4213 /* NOTE: Row couldn't be in use because we lock read & write function */
4214 /* release the reserved row */
William Lallemand222e5a22023-01-31 14:12:28 +01004215 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 +01004216 shctx_row_dec_hot(ssl_shctx, first);
4217 /* replace the previous session already in the tree */
4218 sh_ssl_sess = oldsh_ssl_sess;
4219 /* ignore the previous session data, only use the header */
4220 first = sh_ssl_sess_first_block(sh_ssl_sess);
4221 shctx_row_inc_hot(ssl_shctx, first);
4222 first->len = sizeof(struct sh_ssl_sess_hdr);
4223 }
4224
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004225 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01004226 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004227 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01004228 }
4229
4230 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004231
4232 return 1;
4233}
William Lallemanded0b5ad2017-10-30 19:36:36 +01004234
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004235/* SSL callback used when a new session is created while connecting to a server */
4236static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4237{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004238 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004239 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004240
Willy Tarreau07d94e42018-09-20 10:57:52 +02004241 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004242
William Lallemand3ce6eed2021-02-08 10:43:44 +01004243 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4244 * one cache per thread, it only prevents to flush it from the CLI in
4245 * another thread */
4246
Olivier Houcharde6060c52017-11-16 17:42:52 +01004247 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4248 int len;
4249 unsigned char *ptr;
William Lallemande18d4e82021-11-17 02:59:21 +01004250 const char *sni;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004251
Olivier Houcharde6060c52017-11-16 17:42:52 +01004252 len = i2d_SSL_SESSION(sess, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01004253 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004254 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004255 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4256 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4257 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004258 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
4259 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004260 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4261 }
4262 if (s->ssl_ctx.reused_sess[tid].ptr) {
4263 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4264 &ptr);
4265 }
William Lallemande18d4e82021-11-17 02:59:21 +01004266
4267 if (s->ssl_ctx.reused_sess[tid].sni) {
4268 /* if the new sni is empty or isn' t the same as the old one */
4269 if ((!sni) || strcmp(s->ssl_ctx.reused_sess[tid].sni, sni) != 0) {
4270 ha_free(&s->ssl_ctx.reused_sess[tid].sni);
4271 if (sni)
4272 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4273 }
4274 } else if (sni) {
4275 /* if there wasn't an old sni but there is a new one */
4276 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4277 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004278 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004279 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004280 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004281 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004282 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004283 }
4284
4285 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004286}
4287
Olivier Houcharde6060c52017-11-16 17:42:52 +01004288
William Lallemanded0b5ad2017-10-30 19:36:36 +01004289/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004290int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004291{
4292 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4293 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4294 unsigned char *p;
4295 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004296 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004297 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004298
4299 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004300 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004301 * note: SSL_SESSION_set1_id is using
4302 * a memcpy so we need to use a different pointer
4303 * than sid_data or sid_ctx_data to avoid valgrind
4304 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004305 */
4306
4307 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004308
4309 /* copy value in an other buffer */
4310 memcpy(encid, sid_data, sid_length);
4311
4312 /* pad with 0 */
4313 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4314 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4315
4316 /* force length to zero to avoid ASN1 encoding */
4317 SSL_SESSION_set1_id(sess, encid, 0);
4318
4319 /* force length to zero to avoid ASN1 encoding */
4320 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004321
4322 /* check if buffer is large enough for the ASN1 encoded session */
4323 data_len = i2d_SSL_SESSION(sess, NULL);
4324 if (data_len > SHSESS_MAX_DATA_LEN)
4325 goto err;
4326
4327 p = encsess;
4328
4329 /* process ASN1 session encoding before the lock */
4330 i2d_SSL_SESSION(sess, &p);
4331
William Lallemanded0b5ad2017-10-30 19:36:36 +01004332
William Lallemanda3c77cf2017-10-30 23:44:40 +01004333 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004334 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004335 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004336 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004337err:
4338 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004339 SSL_SESSION_set1_id(sess, encid, sid_length);
4340 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004341
4342 return 0; /* do not increment session reference count */
4343}
4344
4345/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004346SSL_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 +01004347{
William Lallemand4f45bb92017-10-30 20:08:51 +01004348 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004349 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4350 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004351 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004352 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004353
Willy Tarreau4c19e992021-06-15 16:39:22 +02004354 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004355
4356 /* allow the session to be freed automatically by openssl */
4357 *do_copy = 0;
4358
4359 /* tree key is zeros padded sessionid */
4360 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4361 memcpy(tmpkey, key, key_len);
4362 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4363 key = tmpkey;
4364 }
4365
4366 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004367 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004368
4369 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004370 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4371 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004372 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004373 shctx_unlock(ssl_shctx);
Willy Tarreau4c19e992021-06-15 16:39:22 +02004374 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004375 return NULL;
4376 }
4377
William Lallemand4f45bb92017-10-30 20:08:51 +01004378 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4379 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004380
William Lallemand4f45bb92017-10-30 20:08:51 +01004381 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 +01004382
William Lallemanda3c77cf2017-10-30 23:44:40 +01004383 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004384
4385 /* decode ASN1 session */
4386 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004387 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004388 /* Reset session id and session id contenxt */
4389 if (sess) {
4390 SSL_SESSION_set1_id(sess, key, key_len);
4391 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4392 }
4393
4394 return sess;
4395}
4396
William Lallemand4f45bb92017-10-30 20:08:51 +01004397
William Lallemanded0b5ad2017-10-30 19:36:36 +01004398/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004399void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004400{
William Lallemand4f45bb92017-10-30 20:08:51 +01004401 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004402 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4403 unsigned int sid_length;
4404 const unsigned char *sid_data;
4405 (void)ctx;
4406
4407 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4408 /* tree key is zeros padded sessionid */
4409 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4410 memcpy(tmpkey, sid_data, sid_length);
4411 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4412 sid_data = tmpkey;
4413 }
4414
William Lallemanda3c77cf2017-10-30 23:44:40 +01004415 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004416
4417 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004418 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4419 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004420 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004421 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004422 }
4423
4424 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004425 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004426}
4427
4428/* Set session cache mode to server and disable openssl internal cache.
4429 * Set shared cache callbacks on an ssl context.
4430 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004431void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004432{
4433 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4434
4435 if (!ssl_shctx) {
4436 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4437 return;
4438 }
4439
4440 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4441 SSL_SESS_CACHE_NO_INTERNAL |
4442 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4443
4444 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004445 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4446 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4447 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004448}
William Lallemand7d42ef52020-07-06 11:41:30 +02004449
4450/*
4451 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4452 *
4453 * The format is:
4454 * * <Label> <space> <ClientRandom> <space> <Secret>
4455 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4456 */
4457
William Lallemand722180a2021-06-09 16:46:12 +02004458#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004459void SSL_CTX_keylog(const SSL *ssl, const char *line)
4460{
4461 struct ssl_keylog *keylog;
4462 char *lastarg = NULL;
4463 char *dst = NULL;
4464
4465 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4466 if (!keylog)
4467 return;
4468
4469 lastarg = strrchr(line, ' ');
4470 if (lastarg == NULL || ++lastarg == NULL)
4471 return;
4472
4473 dst = pool_alloc(pool_head_ssl_keylog_str);
4474 if (!dst)
4475 return;
4476
4477 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4478 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4479
4480 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4481 if (keylog->client_random)
4482 goto error;
4483 keylog->client_random = dst;
4484
4485 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4486 if (keylog->client_early_traffic_secret)
4487 goto error;
4488 keylog->client_early_traffic_secret = dst;
4489
4490 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4491 if(keylog->client_handshake_traffic_secret)
4492 goto error;
4493 keylog->client_handshake_traffic_secret = dst;
4494
4495 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4496 if (keylog->server_handshake_traffic_secret)
4497 goto error;
4498 keylog->server_handshake_traffic_secret = dst;
4499
4500 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4501 if (keylog->client_traffic_secret_0)
4502 goto error;
4503 keylog->client_traffic_secret_0 = dst;
4504
4505 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4506 if (keylog->server_traffic_secret_0)
4507 goto error;
4508 keylog->server_traffic_secret_0 = dst;
4509
4510 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4511 if (keylog->early_exporter_secret)
4512 goto error;
4513 keylog->early_exporter_secret = dst;
4514
4515 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4516 if (keylog->exporter_secret)
4517 goto error;
4518 keylog->exporter_secret = dst;
4519 } else {
4520 goto error;
4521 }
4522
4523 return;
4524
4525error:
4526 pool_free(pool_head_ssl_keylog_str, dst);
4527
4528 return;
4529}
4530#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004531
William Lallemand8b453912019-11-21 15:48:10 +01004532/*
4533 * This function applies the SSL configuration on a SSL_CTX
4534 * It returns an error code and fills the <err> buffer
4535 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004536static 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 +01004537{
4538 struct proxy *curproxy = bind_conf->frontend;
4539 int cfgerr = 0;
4540 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004541 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004542 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004543#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004544 const char *conf_ciphersuites;
4545#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004546 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004547
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004548 if (ssl_conf) {
4549 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4550 int i, min, max;
4551 int flags = MC_SSL_O_ALL;
4552
4553 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004554 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4555 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004556 if (min)
4557 flags |= (methodVersions[min].flag - 1);
4558 if (max)
4559 flags |= ~((methodVersions[max].flag << 1) - 1);
4560 min = max = CONF_TLSV_NONE;
4561 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4562 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4563 if (min)
4564 max = i;
4565 else
4566 min = max = i;
4567 }
4568 /* save real min/max */
4569 conf_ssl_methods->min = min;
4570 conf_ssl_methods->max = max;
4571 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004572 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4573 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004574 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004575 }
4576 }
4577
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004578 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004579 case SSL_SOCK_VERIFY_NONE:
4580 verify = SSL_VERIFY_NONE;
4581 break;
4582 case SSL_SOCK_VERIFY_OPTIONAL:
4583 verify = SSL_VERIFY_PEER;
4584 break;
4585 case SSL_SOCK_VERIFY_REQUIRED:
4586 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4587 break;
4588 }
4589 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4590 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004591 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 +01004592 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 +01004593 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 +01004594 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004595 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004596 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004597 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004598 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004599 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004600 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004601 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4602 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4603 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4604 cfgerr |= ERR_ALERT | ERR_FATAL;
4605 }
4606 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004607 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004608 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 +02004609 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004610 }
Emeric Brun850efd52014-01-29 12:24:34 +01004611 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004612 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4613 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004614 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004615 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004616#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004617 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004618 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4619
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004620 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004621 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4622 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004623 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004624 }
Emeric Brun561e5742012-10-02 15:20:55 +02004625 else {
4626 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4627 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004628 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004629#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004630 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004631 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004632#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004633 if(bind_conf->keys_ref) {
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +01004634 if (!SSL_CTX_set_tlsext_ticket_key_evp_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004635 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4636 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004637 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004638 }
4639 }
4640#endif
4641
William Lallemand4f45bb92017-10-30 20:08:51 +01004642 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004643 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4644 if (conf_ciphers &&
4645 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004646 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4647 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004648 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004649 }
4650
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004651#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004652 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4653 if (conf_ciphersuites &&
4654 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004655 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4656 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004657 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004658 }
4659#endif
4660
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004661#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02004662 if (!local_dh_1024)
4663 local_dh_1024 = ssl_get_dh_1024();
4664 if (!local_dh_2048)
4665 local_dh_2048 = ssl_get_dh_2048();
4666 if (!local_dh_4096)
4667 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02004668#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004669
Emeric Brunfc0421f2012-09-07 17:30:07 +02004670 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004671#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004672 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004673#endif
William Lallemand722180a2021-06-09 16:46:12 +02004674#ifdef HAVE_SSL_KEYLOG
William Lallemandb60a77b2022-11-18 15:00:15 +01004675 /* only activate the keylog callback if it was required to prevent performance loss */
4676 if (global_ssl.keylog > 0)
4677 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02004678#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004679
Bernard Spil13c53f82018-02-15 13:34:58 +01004680#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004681 ssl_conf_cur = NULL;
4682 if (ssl_conf && ssl_conf->npn_str)
4683 ssl_conf_cur = ssl_conf;
4684 else if (bind_conf->ssl_conf.npn_str)
4685 ssl_conf_cur = &bind_conf->ssl_conf;
4686 if (ssl_conf_cur)
4687 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004688#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004689#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004690 ssl_conf_cur = NULL;
4691 if (ssl_conf && ssl_conf->alpn_str)
4692 ssl_conf_cur = ssl_conf;
4693 else if (bind_conf->ssl_conf.alpn_str)
4694 ssl_conf_cur = &bind_conf->ssl_conf;
4695 if (ssl_conf_cur)
4696 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004697#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004698#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004699 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4700 if (conf_curves) {
4701 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004702 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4703 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004704 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004705 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004706 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004707 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004708#endif /* defined(SSL_CTX_set1_curves_list) */
4709
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004710 if (!conf_curves) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004711#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004712#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004713 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004714 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4715 NULL);
4716
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004717 if (ecdhe && SSL_CTX_set1_curves_list(ctx, ecdhe) == 0) {
4718 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4719 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
4720 cfgerr |= ERR_ALERT | ERR_FATAL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02004721 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004722#endif /* defined(SSL_CTX_set1_curves_list) */
Olivier Houchardc2aae742017-09-22 18:26:28 +02004723#else
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004724#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
4725 int i;
4726 EC_KEY *ecdh;
4727
Olivier Houchardc2aae742017-09-22 18:26:28 +02004728 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4729 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4730 ECDHE_DEFAULT_CURVE);
Emeric Brun2b58d042012-09-20 17:10:03 +02004731
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004732 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004733 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004734 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 +01004735 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004736 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004737 }
4738 else {
4739 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4740 EC_KEY_free(ecdh);
4741 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004742#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
4743#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Emeric Brun2b58d042012-09-20 17:10:03 +02004744 }
Emeric Brun2b58d042012-09-20 17:10:03 +02004745
Emeric Brunfc0421f2012-09-07 17:30:07 +02004746 return cfgerr;
4747}
4748
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004749
4750/*
4751 * Prepare the SSL_CTX based on the bind line configuration.
4752 * Since the CA file loading is made depending on the verify option of the bind
4753 * line, the link between the SSL_CTX and the CA file tree entry is made here.
4754 * If we want to create a link between the CA file entry and the corresponding
4755 * ckch instance (for CA file hot update), it needs to be done after
4756 * ssl_sock_prepare_ctx.
4757 * Returns 0 in case of success.
4758 */
4759int ssl_sock_prep_ctx_and_inst(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
4760 SSL_CTX *ctx, struct ckch_inst *ckch_inst, char **err)
4761{
4762 int errcode = 0;
4763
4764 errcode |= ssl_sock_prepare_ctx(bind_conf, ssl_conf, ctx, err);
4765 if (!errcode && ckch_inst)
4766 ckch_inst_add_cafile_link(ckch_inst, bind_conf, ssl_conf, NULL);
4767
4768 return errcode;
4769}
4770
Evan Broderbe554312013-06-27 00:05:25 -07004771static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4772{
4773 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4774 size_t prefixlen, suffixlen;
4775
4776 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004777 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004778 return 1;
4779
Evan Broderbe554312013-06-27 00:05:25 -07004780 /* The rest of this logic is based on RFC 6125, section 6.4.3
4781 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4782
Emeric Bruna848dae2013-10-08 11:27:28 +02004783 pattern_wildcard = NULL;
4784 pattern_left_label_end = pattern;
4785 while (*pattern_left_label_end != '.') {
4786 switch (*pattern_left_label_end) {
4787 case 0:
4788 /* End of label not found */
4789 return 0;
4790 case '*':
4791 /* If there is more than one wildcards */
4792 if (pattern_wildcard)
4793 return 0;
4794 pattern_wildcard = pattern_left_label_end;
4795 break;
4796 }
4797 pattern_left_label_end++;
4798 }
4799
4800 /* If it's not trivial and there is no wildcard, it can't
4801 * match */
4802 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004803 return 0;
4804
4805 /* Make sure all labels match except the leftmost */
4806 hostname_left_label_end = strchr(hostname, '.');
4807 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004808 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004809 return 0;
4810
4811 /* Make sure the leftmost label of the hostname is long enough
4812 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004813 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004814 return 0;
4815
4816 /* Finally compare the string on either side of the
4817 * wildcard */
4818 prefixlen = pattern_wildcard - pattern;
4819 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004820 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4821 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004822 return 0;
4823
4824 return 1;
4825}
4826
4827static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4828{
4829 SSL *ssl;
4830 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004831 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004832 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004833 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004834
4835 int depth;
4836 X509 *cert;
4837 STACK_OF(GENERAL_NAME) *alt_names;
4838 int i;
4839 X509_NAME *cert_subject;
4840 char *str;
4841
4842 if (ok == 0)
4843 return ok;
4844
4845 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004846 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02004847 ssl_ctx = __conn_get_ssl_sock_ctx(conn);
Evan Broderbe554312013-06-27 00:05:25 -07004848
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004849 /* We're checking if the provided hostnames match the desired one. The
4850 * desired hostname comes from the SNI we presented if any, or if not
4851 * provided then it may have been explicitly stated using a "verifyhost"
4852 * directive. If neither is set, we don't care about the name so the
4853 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004854 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004855 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004856 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004857 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004858 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004859 if (!servername)
4860 return ok;
4861 }
Evan Broderbe554312013-06-27 00:05:25 -07004862
4863 /* We only need to verify the CN on the actual server cert,
4864 * not the indirect CAs */
4865 depth = X509_STORE_CTX_get_error_depth(ctx);
4866 if (depth != 0)
4867 return ok;
4868
4869 /* At this point, the cert is *not* OK unless we can find a
4870 * hostname match */
4871 ok = 0;
4872
4873 cert = X509_STORE_CTX_get_current_cert(ctx);
4874 /* It seems like this might happen if verify peer isn't set */
4875 if (!cert)
4876 return ok;
4877
4878 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4879 if (alt_names) {
4880 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4881 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4882 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004883#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004884 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4885#else
Evan Broderbe554312013-06-27 00:05:25 -07004886 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004887#endif
Evan Broderbe554312013-06-27 00:05:25 -07004888 ok = ssl_sock_srv_hostcheck(str, servername);
4889 OPENSSL_free(str);
4890 }
4891 }
4892 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004893 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004894 }
4895
4896 cert_subject = X509_get_subject_name(cert);
4897 i = -1;
4898 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4899 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004900 ASN1_STRING *value;
4901 value = X509_NAME_ENTRY_get_data(entry);
4902 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004903 ok = ssl_sock_srv_hostcheck(str, servername);
4904 OPENSSL_free(str);
4905 }
4906 }
4907
Willy Tarreau71d058c2017-07-26 20:09:56 +02004908 /* report the mismatch and indicate if SNI was used or not */
4909 if (!ok && !conn->err_code)
4910 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004911 return ok;
4912}
4913
Emeric Brun94324a42012-10-11 14:00:19 +02004914/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004915int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004916{
4917 int cfgerr = 0;
William Lallemand2c776f12021-12-28 18:47:17 +01004918 SSL_CTX *ctx;
William Lallemand0adafb32022-12-13 18:17:44 +01004919 /* Automatic memory computations need to know we use SSL there
4920 * If this is an internal proxy, don't use it for the computation */
William Lallemand04007cb2022-12-14 10:34:36 +01004921 if (!(srv->proxy->cap & PR_CAP_INT))
William Lallemand0adafb32022-12-13 18:17:44 +01004922 global.ssl_used_backend = 1;
Willy Tarreaufce03112015-01-15 21:32:40 +01004923
4924 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004925 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004926 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004927 ha_alert("out of memory.\n");
Emeric Brun821bb9b2017-06-15 16:37:39 +02004928 cfgerr++;
4929 return cfgerr;
4930 }
4931 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004932 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004933 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004934
William Lallemand2c776f12021-12-28 18:47:17 +01004935 if (srv->ssl_ctx.client_crt) {
4936 const int create_if_none = srv->flags & SRV_F_DYNAMIC ? 0 : 1;
4937 char *err = NULL;
4938 int err_code = 0;
4939
4940 /* If there is a crt keyword there, the SSL_CTX will be created here. */
4941 err_code = ssl_sock_load_srv_cert(srv->ssl_ctx.client_crt, srv, create_if_none, &err);
4942 if (err_code != ERR_NONE) {
4943 if ((err_code & ERR_WARN) && !(err_code & ERR_ALERT))
4944 ha_warning("%s", err);
4945 else
4946 ha_alert("%s", err);
4947
4948 if (err_code & (ERR_FATAL|ERR_ABORT))
4949 cfgerr++;
4950 }
4951 ha_free(&err);
4952 }
4953
4954 ctx = srv->ssl_ctx.ctx;
4955
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004956 /* The context will be uninitialized if there wasn't any "cert" option
4957 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004958 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004959 ctx = SSL_CTX_new(SSLv23_client_method());
4960 if (!ctx) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004961 ha_alert("unable to allocate ssl context.\n");
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004962 cfgerr++;
4963 return cfgerr;
4964 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004965
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004966 srv->ssl_ctx.ctx = ctx;
4967 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004968
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004969 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 +01004970
4971 return cfgerr;
4972}
4973
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004974/* Initialize an SSL context that will be used on the backend side.
4975 * Returns an error count.
4976 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004977static int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004978{
4979 struct proxy *curproxy = srv->proxy;
4980 int cfgerr = 0;
4981 long options =
4982 SSL_OP_ALL | /* all known workarounds for bugs */
4983 SSL_OP_NO_SSLv2 |
4984 SSL_OP_NO_COMPRESSION;
4985 long mode =
4986 SSL_MODE_ENABLE_PARTIAL_WRITE |
4987 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
4988 SSL_MODE_RELEASE_BUFFERS |
4989 SSL_MODE_SMALL_BUFFERS;
4990 int verify = SSL_VERIFY_NONE;
4991 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
4992 int i, min, max, hole;
4993 int flags = MC_SSL_O_ALL;
4994
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004995 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004996 ha_warning("no-sslv3/no-tlsv1x are ignored for this server. "
4997 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n");
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004998 else
4999 flags = conf_ssl_methods->flags;
5000
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005001 /* Real min and max should be determinate with configuration and openssl's capabilities */
5002 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005003 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005004 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005005 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005006
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005007 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005008 min = max = CONF_TLSV_NONE;
5009 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005010 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005011 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005012 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005013 if (min) {
5014 if (hole) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005015 ha_warning("%s '%s': SSL/TLS versions range not contiguous for server '%s'. "
Christopher Faulet767a84b2017-11-24 16:50:31 +01005016 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
5017 proxy_type_str(curproxy), curproxy->id, srv->id,
5018 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005019 hole = 0;
5020 }
5021 max = i;
5022 }
5023 else {
5024 min = max = i;
5025 }
5026 }
5027 else {
5028 if (min)
5029 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005030 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005031 if (!min) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005032 ha_alert("%s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01005033 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005034 cfgerr += 1;
5035 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005036
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005037#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005038 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08005039 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005040 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005041 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005042 else
5043 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
5044 if (flags & methodVersions[i].flag)
5045 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005046#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005047 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005048 methodVersions[min].ctx_set_version(ctx, SET_MIN);
5049 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005050#endif
5051
5052 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
5053 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005054 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005055
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005056#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005057 if (global_ssl.async)
5058 mode |= SSL_MODE_ASYNC;
5059#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005060 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005061
Emeric Brun850efd52014-01-29 12:24:34 +01005062 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
5063 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01005064 switch (srv->ssl_ctx.verify) {
5065 case SSL_SOCK_VERIFY_NONE:
5066 verify = SSL_VERIFY_NONE;
5067 break;
5068 case SSL_SOCK_VERIFY_REQUIRED:
5069 verify = SSL_VERIFY_PEER;
5070 break;
5071 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005072 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02005073 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01005074 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02005075 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02005076 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005077 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005078 ha_alert("unable to set CA file '%s'.\n",
5079 srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005080 cfgerr++;
5081 }
5082 }
Emeric Brun850efd52014-01-29 12:24:34 +01005083 else {
5084 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005085 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 +01005086 else
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005087 ha_alert("verify is enabled but no CA file specified.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01005088 cfgerr++;
5089 }
Emeric Brunef42d922012-10-11 16:11:36 +02005090#ifdef X509_V_FLAG_CRL_CHECK
5091 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005092 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02005093
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01005094 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005095 ha_alert("unable to configure CRL file '%s'.\n",
5096 srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005097 cfgerr++;
5098 }
5099 else {
5100 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5101 }
5102 }
5103#endif
5104 }
5105
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005106 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5107 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02005108 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005109 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005110 ha_alert("unable to set SSL cipher list to '%s'.\n",
5111 srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02005112 cfgerr++;
5113 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005114
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05005115#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005116 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005117 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005118 ha_alert("unable to set TLS 1.3 cipher suites to '%s'.\n",
5119 srv->ssl_ctx.ciphersuites);
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005120 cfgerr++;
5121 }
5122#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01005123#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
5124 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005125 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01005126#endif
5127#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5128 if (srv->ssl_ctx.alpn_str)
5129 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
5130#endif
5131
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005132
5133 return cfgerr;
5134}
5135
5136/*
5137 * Prepare the frontend's SSL_CTX based on the server line configuration.
5138 * Since the CA file loading is made depending on the verify option of the
5139 * server line, the link between the SSL_CTX and the CA file tree entry is
5140 * made here.
5141 * If we want to create a link between the CA file entry and the corresponding
5142 * ckch instance (for CA file hot update), it needs to be done after
5143 * ssl_sock_prepare_srv_ssl_ctx.
5144 * Returns an error count.
5145 */
5146int ssl_sock_prep_srv_ctx_and_inst(const struct server *srv, SSL_CTX *ctx,
5147 struct ckch_inst *ckch_inst)
5148{
5149 int cfgerr = 0;
5150
5151 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, ctx);
5152 if (!cfgerr && ckch_inst)
5153 ckch_inst_add_cafile_link(ckch_inst, NULL, NULL, srv);
Emeric Brun94324a42012-10-11 14:00:19 +02005154
5155 return cfgerr;
5156}
5157
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005158
Frédéric Lécailleec216522020-11-23 14:33:30 +01005159/*
5160 * Create an initial CTX used to start the SSL connections.
5161 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
5162 * Returns 0 if succeeded, or something >0 if not.
5163 */
5164#ifdef USE_QUIC
5165static int ssl_initial_ctx(struct bind_conf *bind_conf)
5166{
5167 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
5168 return ssl_quic_initial_ctx(bind_conf);
5169 else
5170 return ssl_sock_initial_ctx(bind_conf);
5171}
5172#else
5173static int ssl_initial_ctx(struct bind_conf *bind_conf)
5174{
5175 return ssl_sock_initial_ctx(bind_conf);
5176}
5177#endif
5178
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005179/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005180 * be NULL, in which case nothing is done. Returns the number of errors
5181 * encountered.
5182 */
Willy Tarreau03209342016-12-22 17:08:28 +01005183int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005184{
5185 struct ebmb_node *node;
5186 struct sni_ctx *sni;
5187 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01005188 int errcode = 0;
5189 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02005190
Willy Tarreaufce03112015-01-15 21:32:40 +01005191 /* Automatic memory computations need to know we use SSL there */
5192 global.ssl_used_frontend = 1;
5193
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005194 /* Create initial_ctx used to start the ssl connection before do switchctx */
5195 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01005196 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005197 /* It should not be necessary to call this function, but it's
5198 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01005199 to initial_ctx in ssl_initial_ctx. */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005200 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, NULL, bind_conf->initial_ctx, NULL, &errmsg);
5201 }
5202 if (bind_conf->default_ctx) {
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005203 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 +01005204 }
Emeric Brun0bed9942014-10-30 19:25:24 +01005205
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005206 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005207 while (node) {
5208 sni = ebmb_entry(node, struct sni_ctx, name);
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005209 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005210 /* only initialize the CTX on its first occurrence and
5211 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005212 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
5213 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005214 node = ebmb_next(node);
5215 }
5216
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005217 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005218 while (node) {
5219 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01005220 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005221 /* only initialize the CTX on its first occurrence and
5222 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005223 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005224 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005225 node = ebmb_next(node);
5226 }
William Lallemand8b453912019-11-21 15:48:10 +01005227
5228 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005229 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005230 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005231 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005232 err++;
5233 }
5234
5235 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005236 return err;
5237}
5238
Willy Tarreau55d37912016-12-21 23:38:39 +01005239/* Prepares all the contexts for a bind_conf and allocates the shared SSL
5240 * context if needed. Returns < 0 on error, 0 on success. The warnings and
5241 * alerts are directly emitted since the rest of the stack does it below.
5242 */
5243int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
5244{
5245 struct proxy *px = bind_conf->frontend;
5246 int alloc_ctx;
5247 int err;
5248
Willy Tarreau11ba4042022-05-20 15:56:32 +02005249 if (!(bind_conf->options & BC_O_USE_SSL)) {
Willy Tarreau55d37912016-12-21 23:38:39 +01005250 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005251 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
5252 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01005253 }
5254 return 0;
5255 }
5256 if (!bind_conf->default_ctx) {
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005257 if (bind_conf->strict_sni && !(bind_conf->options & BC_O_GENERATE_CERTS)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005258 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5259 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005260 }
5261 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005262 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5263 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005264 return -1;
5265 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005266 }
William Lallemandc61c0b32017-12-04 18:46:39 +01005267 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005268 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02005269 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
Willy Tarreau91358592021-06-15 08:08:04 +02005270 sizeof(*sh_ssl_sess_tree), (global.nbthread > 1));
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02005271 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005272 if (alloc_ctx == SHCTX_E_INIT_LOCK)
5273 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");
5274 else
5275 ha_alert("Unable to allocate SSL session cache.\n");
5276 return -1;
5277 }
5278 /* free block callback */
5279 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5280 /* init the root tree within the extra space */
5281 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5282 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01005283 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005284 err = 0;
5285 /* initialize all certificate contexts */
5286 err += ssl_sock_prepare_all_ctx(bind_conf);
5287
5288 /* initialize CA variables if the certificates generation is enabled */
5289 err += ssl_sock_load_ca(bind_conf);
5290
5291 return -err;
5292}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005293
William Lallemand231610a2021-12-30 11:25:43 +01005294/* release ssl context allocated for servers. Most of the field free here
5295 * must also be allocated in srv_ssl_settings_cpy() */
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005296void ssl_sock_free_srv_ctx(struct server *srv)
5297{
Olivier Houchardc7566002018-11-20 23:33:50 +01005298#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
William Lallemand231610a2021-12-30 11:25:43 +01005299 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005300#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005301#ifdef OPENSSL_NPN_NEGOTIATED
William Lallemand231610a2021-12-30 11:25:43 +01005302 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005303#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005304 if (srv->ssl_ctx.reused_sess) {
5305 int i;
5306
William Lallemande18d4e82021-11-17 02:59:21 +01005307 for (i = 0; i < global.nbthread; i++) {
Willy Tarreaue709e822021-02-26 21:06:32 +01005308 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
William Lallemande18d4e82021-11-17 02:59:21 +01005309 ha_free(&srv->ssl_ctx.reused_sess[i].sni);
5310 }
Willy Tarreaue709e822021-02-26 21:06:32 +01005311 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005312 }
5313
Willy Tarreaue709e822021-02-26 21:06:32 +01005314 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005315 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005316 srv->ssl_ctx.ctx = NULL;
5317 }
William Lallemand231610a2021-12-30 11:25:43 +01005318
5319 ha_free(&srv->ssl_ctx.ca_file);
5320 ha_free(&srv->ssl_ctx.crl_file);
5321 ha_free(&srv->ssl_ctx.client_crt);
5322 ha_free(&srv->ssl_ctx.verify_host);
5323#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5324 ha_free(&srv->sni_expr);
William Lallemand43c2ce42022-03-16 17:48:19 +01005325 release_sample_expr(srv->ssl_ctx.sni);
5326 srv->ssl_ctx.sni = NULL;
William Lallemand231610a2021-12-30 11:25:43 +01005327#endif
5328 ha_free(&srv->ssl_ctx.ciphers);
5329#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
5330 ha_free(&srv->ssl_ctx.ciphersuites);
5331#endif
William Lallemande69563f2021-12-30 14:45:19 +01005332 /* If there is a certificate we must unlink the ckch instance */
5333 ckch_inst_free(srv->ssl_ctx.inst);
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005334}
5335
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005336/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005337 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5338 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005339void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005340{
5341 struct ebmb_node *node, *back;
5342 struct sni_ctx *sni;
5343
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005344 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005345 while (node) {
5346 sni = ebmb_entry(node, struct sni_ctx, name);
5347 back = ebmb_next(node);
5348 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005349 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005350 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005351 free(sni);
5352 node = back;
5353 }
5354
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005355 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005356 while (node) {
5357 sni = ebmb_entry(node, struct sni_ctx, name);
5358 back = ebmb_next(node);
5359 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005360 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005361 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005362 free(sni);
5363 node = back;
5364 }
William Lallemandb2408692020-06-24 09:54:29 +02005365
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005366 SSL_CTX_free(bind_conf->initial_ctx);
5367 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005368 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005369 bind_conf->default_ctx = NULL;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005370 bind_conf->default_inst = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005371 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005372}
William Lallemandb2408692020-06-24 09:54:29 +02005373
5374
5375void ssl_sock_deinit()
5376{
5377 crtlist_deinit(); /* must be free'd before the ckchs */
5378 ckch_deinit();
5379}
5380REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005381
Willy Tarreau795cdab2016-12-22 17:30:54 +01005382/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5383void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5384{
5385 ssl_sock_free_ca(bind_conf);
5386 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005387 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005388 free(bind_conf->ca_sign_file);
5389 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005390 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005391 free(bind_conf->keys_ref->filename);
5392 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005393 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005394 free(bind_conf->keys_ref);
5395 }
5396 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005397 bind_conf->ca_sign_pass = NULL;
5398 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005399}
5400
Christopher Faulet31af49d2015-06-09 17:29:50 +02005401/* Load CA cert file and private key used to generate certificates */
5402int
Willy Tarreau03209342016-12-22 17:08:28 +01005403ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005404{
Willy Tarreau03209342016-12-22 17:08:28 +01005405 struct proxy *px = bind_conf->frontend;
William Lallemand52ddd992022-11-22 11:51:53 +01005406 struct ckch_data *data = NULL;
Shimi Gersner5846c492020-08-23 13:58:12 +03005407 int ret = 0;
5408 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005409
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005410 if (!(bind_conf->options & BC_O_GENERATE_CERTS))
Shimi Gersner5846c492020-08-23 13:58:12 +03005411 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005412
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005413#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005414 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005415 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005416 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005417 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005418 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005419#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005420
Christopher Faulet31af49d2015-06-09 17:29:50 +02005421 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005422 ha_alert("Proxy '%s': cannot enable certificate generation, "
5423 "no CA certificate File configured at [%s:%d].\n",
5424 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005425 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005426 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005427
Shimi Gersner5846c492020-08-23 13:58:12 +03005428 /* Allocate cert structure */
William Lallemand52ddd992022-11-22 11:51:53 +01005429 data = calloc(1, sizeof(*data));
5430 if (!data) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005431 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5432 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5433 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005434 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005435
5436 /* Try to parse file */
William Lallemand52ddd992022-11-22 11:51:53 +01005437 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, data, &err)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005438 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5439 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005440 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005441 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005442 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005443
5444 /* Fail if missing cert or pkey */
William Lallemand52ddd992022-11-22 11:51:53 +01005445 if ((!data->cert) || (!data->key)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005446 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5447 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5448 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005449 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005450
Shimi Gersner5846c492020-08-23 13:58:12 +03005451 /* Final assignment to bind */
William Lallemand52ddd992022-11-22 11:51:53 +01005452 bind_conf->ca_sign_ckch = data;
Shimi Gersner5846c492020-08-23 13:58:12 +03005453 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005454
Shimi Gersner5846c492020-08-23 13:58:12 +03005455 failed:
William Lallemand52ddd992022-11-22 11:51:53 +01005456 if (data) {
5457 ssl_sock_free_cert_key_and_chain_contents(data);
5458 free(data);
Shimi Gersner5846c492020-08-23 13:58:12 +03005459 }
5460
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005461 bind_conf->options &= ~BC_O_GENERATE_CERTS;
Shimi Gersner5846c492020-08-23 13:58:12 +03005462 ret++;
5463 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005464}
5465
5466/* Release CA cert and private key used to generate certificated */
5467void
5468ssl_sock_free_ca(struct bind_conf *bind_conf)
5469{
Shimi Gersner5846c492020-08-23 13:58:12 +03005470 if (bind_conf->ca_sign_ckch) {
5471 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005472 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005473 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005474}
5475
Emeric Brun46591952012-05-18 15:47:34 +02005476/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005477 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5478 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5479 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5480 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005481 * 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 +01005482 * as parameters to this function.
5483 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5484 * CO_ER_SSL_NO_MEM.
5485 */
5486int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5487 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5488{
5489 int retry = 1;
5490
5491 retry:
5492 /* Alloc a new SSL session. */
5493 *ssl = SSL_new(ssl_ctx);
5494 if (!*ssl) {
5495 if (!retry--)
5496 goto err;
5497
5498 pool_gc(NULL);
5499 goto retry;
5500 }
5501
5502 *bio = BIO_new(bio_meth);
5503 if (!*bio) {
5504 SSL_free(*ssl);
5505 *ssl = NULL;
5506 if (!retry--)
5507 goto err;
5508
5509 pool_gc(NULL);
5510 goto retry;
5511 }
5512
5513 BIO_set_data(*bio, ctx);
5514 SSL_set_bio(*ssl, *bio, *bio);
5515
5516 /* set connection pointer. */
5517 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5518 SSL_free(*ssl);
5519 *ssl = NULL;
5520 if (!retry--)
5521 goto err;
5522
5523 pool_gc(NULL);
5524 goto retry;
5525 }
5526
5527 return 0;
5528
5529 err:
5530 conn->err_code = CO_ER_SSL_NO_MEM;
5531 return -1;
5532}
5533
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005534/* This function is called when all the XPRT have been initialized. We can
5535 * now attempt to start the SSL handshake.
5536 */
5537static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5538{
5539 struct ssl_sock_ctx *ctx = xprt_ctx;
5540
5541 if (ctx->xprt->start) {
5542 int ret;
5543
5544 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5545 if (ret < 0)
5546 return ret;
5547 }
5548 tasklet_wakeup(ctx->wait_event.tasklet);
5549
5550 return 0;
5551}
5552
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005553/*
Emeric Brun46591952012-05-18 15:47:34 +02005554 * This function is called if SSL * context is not yet allocated. The function
5555 * is designed to be called before any other data-layer operation and sets the
5556 * handshake flag on the connection. It is safe to call it multiple times.
5557 * It returns 0 on success and -1 in error case.
5558 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005559static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005560{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005561 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005562 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005563 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005564 return 0;
5565
Olivier Houchard66ab4982019-02-26 18:37:15 +01005566 ctx = pool_alloc(ssl_sock_ctx_pool);
5567 if (!ctx) {
5568 conn->err_code = CO_ER_SSL_NO_MEM;
5569 return -1;
5570 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005571 ctx->wait_event.tasklet = tasklet_new();
5572 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005573 conn->err_code = CO_ER_SSL_NO_MEM;
5574 pool_free(ssl_sock_ctx_pool, ctx);
5575 return -1;
5576 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005577 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5578 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005579 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005580 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005581 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005582 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005583 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005584 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005585 ctx->xprt_st = 0;
5586 ctx->xprt_ctx = NULL;
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005587 ctx->error_code = 0;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005588
5589 /* Only work with sockets for now, this should be adapted when we'll
5590 * add QUIC support.
5591 */
5592 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005593 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005594 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5595 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005596 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005597
Willy Tarreau82531f62021-10-06 12:15:18 +02005598 if (global.maxsslconn && global.sslconns >= global.maxsslconn) {
Willy Tarreau20879a02012-12-03 16:32:10 +01005599 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005600 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005601 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005602
Emeric Brun46591952012-05-18 15:47:34 +02005603 /* If it is in client mode initiate SSL session
5604 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005605 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005606 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5607 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005608 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005609
Olivier Houchard66ab4982019-02-26 18:37:15 +01005610 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005611 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005612 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5613 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5614 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 +01005615 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005616 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005617 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005618 } else if (sess) {
5619 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005620 }
5621 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005622 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005623
Emeric Brun46591952012-05-18 15:47:34 +02005624 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005625 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005626
Willy Tarreau82531f62021-10-06 12:15:18 +02005627 _HA_ATOMIC_INC(&global.sslconns);
5628 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005629 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005630 return 0;
5631 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005632 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005633 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005634
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005635 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5636 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005637 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005638
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005639#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005640 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005641 b_alloc(&ctx->early_buf);
5642 SSL_set_max_early_data(ctx->ssl,
5643 /* Only allow early data if we managed to allocate
5644 * a buffer.
5645 */
5646 (!b_is_null(&ctx->early_buf)) ?
5647 global.tune.bufsize - global.tune.maxrewrite : 0);
5648 }
5649#endif
5650
Olivier Houchard66ab4982019-02-26 18:37:15 +01005651 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005652
Emeric Brun46591952012-05-18 15:47:34 +02005653 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005654 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005655#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005656 if (bc->ssl_conf.early_data)
5657 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005658#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005659
Willy Tarreau82531f62021-10-06 12:15:18 +02005660 _HA_ATOMIC_INC(&global.sslconns);
5661 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005662 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005663 return 0;
5664 }
5665 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005666 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005667err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005668 if (ctx && ctx->wait_event.tasklet)
5669 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005670 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005671 return -1;
5672}
5673
5674
5675/* This is the callback which is used when an SSL handshake is pending. It
5676 * updates the FD status if it wants some polling before being called again.
5677 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5678 * otherwise it returns non-zero and removes itself from the connection's
5679 * flags (the bit is provided in <flag> by the caller).
5680 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005681static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005682{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005683 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Emeric Brun46591952012-05-18 15:47:34 +02005684 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005685 struct ssl_counters *counters = NULL;
5686 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005687 struct listener *li;
5688 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005689 socklen_t lskerr;
5690 int skerr;
5691
Emeric Brun46591952012-05-18 15:47:34 +02005692
Willy Tarreau3c728722014-01-23 13:50:42 +01005693 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005694 return 0;
5695
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005696 /* get counters */
5697 switch (obj_type(conn->target)) {
5698 case OBJ_TYPE_LISTENER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005699 li = __objt_listener(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005700 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5701 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5702 &ssl_stats_module);
5703 break;
5704
5705 case OBJ_TYPE_SERVER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005706 srv = __objt_server(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005707 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5708 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5709 &ssl_stats_module);
5710 break;
5711
5712 default:
5713 break;
5714 }
5715
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005716 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005717 goto out_error;
5718
Willy Tarreau06300382021-02-02 15:42:25 +01005719 /* don't start calculating a handshake on a dead connection */
5720 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5721 goto out_error;
5722
5723 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5724 * status from the lower layers, so let's check the FD directly. Ideally
5725 * the xprt layers should provide some status indicating their knowledge
5726 * of shutdowns or error.
5727 */
Willy Tarreau07ecfc52022-04-11 18:07:03 +02005728 BUG_ON(conn->flags & CO_FL_FDLESS);
5729
Willy Tarreau06300382021-02-02 15:42:25 +01005730 skerr = 0;
5731 lskerr = sizeof(skerr);
5732 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5733 skerr != 0)
5734 goto out_error;
5735
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005736#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005737 /*
5738 * Check if we have early data. If we do, we have to read them
5739 * before SSL_do_handshake() is called, And there's no way to
5740 * detect early data, except to try to read them
5741 */
5742 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005743 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005744
Olivier Houchard54907bb2019-12-19 15:02:39 +01005745 while (1) {
5746 ret = SSL_read_early_data(ctx->ssl,
5747 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5748 &read_data);
5749 if (ret == SSL_READ_EARLY_DATA_ERROR)
5750 goto check_error;
5751 if (read_data > 0) {
5752 conn->flags |= CO_FL_EARLY_DATA;
5753 b_add(&ctx->early_buf, read_data);
5754 }
5755 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5756 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5757 if (!b_data(&ctx->early_buf))
5758 b_free(&ctx->early_buf);
5759 break;
5760 }
5761 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005762 }
5763#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005764 /* If we use SSL_do_handshake to process a reneg initiated by
5765 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5766 * Usually SSL_write and SSL_read are used and process implicitly
5767 * the reneg handshake.
5768 * Here we use SSL_peek as a workaround for reneg.
5769 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005770 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005771 char c;
5772
Olivier Houchard66ab4982019-02-26 18:37:15 +01005773 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005774 if (ret <= 0) {
5775 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005776 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005777
Emeric Brun674b7432012-11-08 19:21:55 +01005778 if (ret == SSL_ERROR_WANT_WRITE) {
5779 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005780 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005781 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005782 return 0;
5783 }
5784 else if (ret == SSL_ERROR_WANT_READ) {
5785 /* handshake may have been completed but we have
5786 * no more data to read.
5787 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005788 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005789 ret = 1;
5790 goto reneg_ok;
5791 }
5792 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005793 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005794 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005795 return 0;
5796 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005797#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005798 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005799 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005800 return 0;
5801 }
5802#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005803 else if (ret == SSL_ERROR_SYSCALL) {
5804 /* if errno is null, then connection was successfully established */
5805 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5806 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005807 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005808#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5809 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005810 conn->err_code = CO_ER_SSL_HANDSHAKE;
5811#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005812 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005813#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005814 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005815 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005816 empty_handshake = state == TLS_ST_BEFORE;
5817#else
Lukas Tribus49799162019-07-08 14:29:15 +02005818 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5819 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005820#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005821 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005822 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005823 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005824 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5825 else
5826 conn->err_code = CO_ER_SSL_EMPTY;
5827 }
5828 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005829 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005830 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5831 else
5832 conn->err_code = CO_ER_SSL_ABORT;
5833 }
5834 }
5835 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005836 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005837 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005838 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005839 conn->err_code = CO_ER_SSL_HANDSHAKE;
5840 }
Lukas Tribus49799162019-07-08 14:29:15 +02005841#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005842 }
Emeric Brun674b7432012-11-08 19:21:55 +01005843 goto out_error;
5844 }
5845 else {
5846 /* Fail on all other handshake errors */
5847 /* Note: OpenSSL may leave unread bytes in the socket's
5848 * buffer, causing an RST to be emitted upon close() on
5849 * TCP sockets. We first try to drain possibly pending
5850 * data to avoid this as much as possible.
5851 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005852 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005853 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005854 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005855 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005856 goto out_error;
5857 }
5858 }
5859 /* read some data: consider handshake completed */
5860 goto reneg_ok;
5861 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005862 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005863check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005864 if (ret != 1) {
5865 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005866 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005867
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005868 if (!ctx->error_code)
5869 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton7c6898e2021-07-29 09:45:51 +02005870
Emeric Brun46591952012-05-18 15:47:34 +02005871 if (ret == SSL_ERROR_WANT_WRITE) {
5872 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005873 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005874 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005875 return 0;
5876 }
5877 else if (ret == SSL_ERROR_WANT_READ) {
5878 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005879 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005880 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5881 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005882 return 0;
5883 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005884#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005885 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005886 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005887 return 0;
5888 }
5889#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005890 else if (ret == SSL_ERROR_SYSCALL) {
5891 /* if errno is null, then connection was successfully established */
5892 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5893 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005894 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005895#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5896 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005897 conn->err_code = CO_ER_SSL_HANDSHAKE;
5898#else
5899 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005900#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005901 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005902 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005903 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005904#else
Lukas Tribus49799162019-07-08 14:29:15 +02005905 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5906 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005907#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005908 if (empty_handshake) {
5909 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005910 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005911 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5912 else
5913 conn->err_code = CO_ER_SSL_EMPTY;
5914 }
5915 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005916 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005917 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5918 else
5919 conn->err_code = CO_ER_SSL_ABORT;
5920 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005921 }
5922 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005923 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005924 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5925 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005926 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005927 }
Lukas Tribus49799162019-07-08 14:29:15 +02005928#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005929 }
Willy Tarreau89230192012-09-28 20:22:13 +02005930 goto out_error;
5931 }
Emeric Brun46591952012-05-18 15:47:34 +02005932 else {
5933 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005934 /* Note: OpenSSL may leave unread bytes in the socket's
5935 * buffer, causing an RST to be emitted upon close() on
5936 * TCP sockets. We first try to drain possibly pending
5937 * data to avoid this as much as possible.
5938 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005939 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005940 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005941 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005942 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005943 goto out_error;
5944 }
5945 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005946#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005947 else {
5948 /*
5949 * If the server refused the early data, we have to send a
5950 * 425 to the client, as we no longer have the data to sent
5951 * them again.
5952 */
5953 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005954 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005955 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5956 goto out_error;
5957 }
5958 }
5959 }
5960#endif
5961
Emeric Brun46591952012-05-18 15:47:34 +02005962
Emeric Brun674b7432012-11-08 19:21:55 +01005963reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005964
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005965#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00005966 /* ASYNC engine API doesn't support moving read/write
5967 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005968 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005969 */
5970 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005971 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005972#endif
Emeric Brun46591952012-05-18 15:47:34 +02005973 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005974 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005975 if (objt_server(conn->target)) {
5976 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5977 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5978 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005979 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005980 else {
5981 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5982 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5983 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5984 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005985
Willy Tarreau42995282020-11-06 13:19:18 +01005986 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01005987 HA_ATOMIC_INC(&counters->sess);
5988 HA_ATOMIC_INC(&counters_px->sess);
Willy Tarreau42995282020-11-06 13:19:18 +01005989 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005990 }
Willy Tarreau42995282020-11-06 13:19:18 +01005991 else if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01005992 HA_ATOMIC_INC(&counters->reused_sess);
5993 HA_ATOMIC_INC(&counters_px->reused_sess);
Emeric Brun46591952012-05-18 15:47:34 +02005994 }
5995
5996 /* The connection is now established at both layers, it's time to leave */
5997 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5998 return 1;
5999
6000 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006001 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006002 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006003 ERR_clear_error();
6004
Emeric Brun9fa89732012-10-04 17:09:56 +02006005 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01006006 if (objt_server(conn->target)) {
6007 struct server *s = __objt_server(conn->target);
6008 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
6009 * one cache per thread, it only prevents to flush it from the CLI in
6010 * another thread */
6011
6012 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01006013 if (s->ssl_ctx.reused_sess[tid].ptr)
6014 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01006015 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02006016 }
6017
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006018 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006019 HA_ATOMIC_INC(&counters->failed_handshake);
6020 HA_ATOMIC_INC(&counters_px->failed_handshake);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006021 }
6022
Emeric Brun46591952012-05-18 15:47:34 +02006023 /* Fail on all other handshake errors */
6024 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01006025 if (!conn->err_code)
6026 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006027 return 0;
6028}
6029
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006030/* Called from the upper layer, to subscribe <es> to events <event_type>. The
6031 * event subscriber <es> is not allowed to change from a previous call as long
6032 * as at least one event is still subscribed. The <event_type> must only be a
6033 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
6034 * unless the transport layer was already released.
6035 */
6036static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006037{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006038 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006039
Olivier Houchard0ff28652019-06-24 18:57:39 +02006040 if (!ctx)
6041 return -1;
6042
Willy Tarreau113d52b2020-01-10 09:20:26 +01006043 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006044 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006045
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006046 ctx->subs = es;
6047 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006048
6049 /* we may have to subscribe to lower layers for new events */
6050 event_type &= ~ctx->wait_event.events;
6051 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
6052 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006053 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006054}
6055
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006056/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
6057 * The <es> pointer is not allowed to differ from the one passed to the
6058 * subscribe() call. It always returns zero.
6059 */
6060static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006061{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006062 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006063
Willy Tarreau113d52b2020-01-10 09:20:26 +01006064 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006065 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006066
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006067 es->events &= ~event_type;
6068 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01006069 ctx->subs = NULL;
6070
6071 /* If we subscribed, and we're not doing the handshake,
6072 * then we subscribed because the upper layer asked for it,
6073 * as the upper layer is no longer interested, we can
6074 * unsubscribe too.
6075 */
6076 event_type &= ctx->wait_event.events;
6077 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
6078 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006079
6080 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006081}
6082
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006083/* The connection has been taken over, so destroy the old tasklet and create
6084 * a new one. The original thread ID must be passed into orig_tid
6085 * It should be called with the takeover lock for the old thread held.
6086 * Returns 0 on success, and -1 on failure
6087 */
6088static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
6089{
6090 struct ssl_sock_ctx *ctx = xprt_ctx;
6091 struct tasklet *tl = tasklet_new();
6092
6093 if (!tl)
6094 return -1;
6095
6096 ctx->wait_event.tasklet->context = NULL;
6097 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
6098 ctx->wait_event.tasklet = tl;
6099 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
6100 ctx->wait_event.tasklet->context = ctx;
6101 return 0;
6102}
6103
Willy Tarreau41491682021-03-02 17:29:56 +01006104/* notify the next xprt that the connection is about to become idle and that it
6105 * may be stolen at any time after the function returns and that any tasklet in
6106 * the chain must be careful before dereferencing its context.
6107 */
6108static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
6109{
6110 struct ssl_sock_ctx *ctx = xprt_ctx;
6111
6112 if (!ctx || !ctx->wait_event.tasklet)
6113 return;
6114
6115 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6116 if (ctx->xprt)
6117 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
6118}
6119
6120/* notify the next xprt that the connection is not idle anymore and that it may
6121 * not be stolen before the next xprt_set_idle().
6122 */
6123static void ssl_set_used(struct connection *conn, void *xprt_ctx)
6124{
6125 struct ssl_sock_ctx *ctx = xprt_ctx;
6126
6127 if (!ctx || !ctx->wait_event.tasklet)
6128 return;
6129
6130 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6131 if (ctx->xprt)
6132 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
6133}
6134
Olivier Houchard2e055482019-05-27 19:50:12 +02006135/* Use the provided XPRT as an underlying XPRT, and provide the old one.
6136 * Returns 0 on success, and non-zero on failure.
6137 */
6138static 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)
6139{
6140 struct ssl_sock_ctx *ctx = xprt_ctx;
6141
6142 if (oldxprt_ops != NULL)
6143 *oldxprt_ops = ctx->xprt;
6144 if (oldxprt_ctx != NULL)
6145 *oldxprt_ctx = ctx->xprt_ctx;
6146 ctx->xprt = toadd_ops;
6147 ctx->xprt_ctx = toadd_ctx;
6148 return 0;
6149}
6150
Olivier Houchard5149b592019-05-23 17:47:36 +02006151/* Remove the specified xprt. If if it our underlying XPRT, remove it and
6152 * return 0, otherwise just call the remove_xprt method from the underlying
6153 * XPRT.
6154 */
6155static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
6156{
6157 struct ssl_sock_ctx *ctx = xprt_ctx;
6158
6159 if (ctx->xprt_ctx == toremove_ctx) {
6160 ctx->xprt_ctx = newctx;
6161 ctx->xprt = newops;
6162 return 0;
6163 }
6164 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
6165}
6166
Willy Tarreau144f84a2021-03-02 16:09:26 +01006167struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02006168{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006169 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006170 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006171 struct connection *conn;
6172 int conn_in_list;
6173 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006174
Willy Tarreau41491682021-03-02 17:29:56 +01006175 if (state & TASK_F_USR1) {
6176 /* the tasklet was idling on an idle connection, it might have
6177 * been stolen, let's be careful!
6178 */
6179 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6180 if (tl->context == NULL) {
6181 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6182 tasklet_free(tl);
6183 return NULL;
6184 }
6185 conn = ctx->conn;
6186 conn_in_list = conn->flags & CO_FL_LIST_MASK;
6187 if (conn_in_list)
6188 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006189 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01006190 } else {
6191 conn = ctx->conn;
6192 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006193 }
Willy Tarreau41491682021-03-02 17:29:56 +01006194
Olivier Houchardea8dd942019-05-20 14:02:16 +02006195 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01006196 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006197 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006198 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
6199 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01006200 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006201 }
6202 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006203 /* If we had an error, or the handshake is done and I/O is available,
6204 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01006205 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02006206 * we can't be sure conn_fd_handler() will be called again.
6207 */
6208 if ((ctx->conn->flags & CO_FL_ERROR) ||
6209 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006210 int woke = 0;
6211
6212 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006213 if (ctx->subs) {
6214 tasklet_wakeup(ctx->subs->tasklet);
6215 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006216 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006217 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006218 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006219
Olivier Houchardea8dd942019-05-20 14:02:16 +02006220 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01006221 * upper layers know. If we have no mux, create it,
6222 * and once we have a mux, call its wake method if we didn't
6223 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02006224 */
6225 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01006226 if (!ctx->conn->mux)
6227 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006228 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006229 ret = ctx->conn->mux->wake(ctx->conn);
6230 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006231 }
6232 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006233#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006234 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006235 else if (b_data(&ctx->early_buf) && ctx->subs &&
6236 ctx->subs->events & SUB_RETRY_RECV) {
6237 tasklet_wakeup(ctx->subs->tasklet);
6238 ctx->subs->events &= ~SUB_RETRY_RECV;
6239 if (!ctx->subs->events)
6240 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01006241 }
6242#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006243leave:
6244 if (!ret && conn_in_list) {
6245 struct server *srv = objt_server(conn->target);
6246
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006247 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006248 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau85223482022-09-29 20:32:43 +02006249 eb64_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006250 else
Willy Tarreau85223482022-09-29 20:32:43 +02006251 eb64_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006252 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006253 }
Willy Tarreau74163142021-03-13 11:30:19 +01006254 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006255}
6256
Emeric Brun46591952012-05-18 15:47:34 +02006257/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01006258 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02006259 * buffer wraps, in which case a second call may be performed. The connection's
6260 * flags are updated with whatever special event is detected (error, read0,
6261 * empty). The caller is responsible for taking care of those events and
6262 * avoiding the call if inappropriate. The function does not call the
6263 * connection's polling update function, so the caller is responsible for this.
6264 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006265static 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 +02006266{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006267 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02006268 ssize_t ret;
6269 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02006270
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006271 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006272 goto out_error;
6273
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006274#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006275 if (b_data(&ctx->early_buf)) {
6276 try = b_contig_space(buf);
6277 if (try > b_data(&ctx->early_buf))
6278 try = b_data(&ctx->early_buf);
6279 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
6280 b_add(buf, try);
6281 b_del(&ctx->early_buf, try);
6282 if (b_data(&ctx->early_buf) == 0)
6283 b_free(&ctx->early_buf);
6284 return try;
6285 }
6286#endif
6287
Willy Tarreau911db9b2020-01-23 16:27:54 +01006288 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006289 /* a handshake was requested */
6290 return 0;
6291
Emeric Brun46591952012-05-18 15:47:34 +02006292 /* read the largest possible block. For this, we perform only one call
6293 * to recv() unless the buffer wraps and we exactly fill the first hunk,
6294 * in which case we accept to do it once again. A new attempt is made on
6295 * EINTR too.
6296 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01006297 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006298
Willy Tarreau591d4452018-06-15 17:21:00 +02006299 try = b_contig_space(buf);
6300 if (!try)
6301 break;
6302
Willy Tarreauabf08d92014-01-14 11:31:27 +01006303 if (try > count)
6304 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02006305
Olivier Houchard66ab4982019-02-26 18:37:15 +01006306 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02006307
Emeric Brune1f38db2012-09-03 20:36:47 +02006308 if (conn->flags & CO_FL_ERROR) {
6309 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006310 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006311 }
Emeric Brun46591952012-05-18 15:47:34 +02006312 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006313 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006314 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006315 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006316 }
Emeric Brun46591952012-05-18 15:47:34 +02006317 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006318 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006319 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006320 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006321 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006322 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006323#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006324 /* Async mode can be re-enabled, because we're leaving data state.*/
6325 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006326 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006327#endif
Emeric Brun46591952012-05-18 15:47:34 +02006328 break;
6329 }
6330 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006331 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006332 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6333 SUB_RETRY_RECV,
6334 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006335 /* handshake is running, and it may need to re-enable read */
6336 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006337#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006338 /* Async mode can be re-enabled, because we're leaving data state.*/
6339 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006340 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006341#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006342 break;
6343 }
Emeric Brun46591952012-05-18 15:47:34 +02006344 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006345 } else if (ret == SSL_ERROR_ZERO_RETURN)
6346 goto read0;
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006347 else if (ret == SSL_ERROR_SSL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006348 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6349 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006350 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006351 conn->err_code = CO_ERR_SSL_FATAL;
6352 }
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006353 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6354 * stack before shutting down the connection for
6355 * reading. */
Willy Tarreauacef5e22022-04-25 20:32:15 +02006356 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN || errno == EWOULDBLOCK))
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006357 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006358 /* otherwise it's a real error */
6359 goto out_error;
6360 }
6361 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006362 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006363 return done;
6364
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006365 clear_ssl_error:
6366 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006367 ssl_sock_dump_errors(conn, NULL);
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006368 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006369 read0:
6370 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006371 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006372
Emeric Brun46591952012-05-18 15:47:34 +02006373 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006374 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006375 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006376 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006377 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006378 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006379}
6380
6381
Willy Tarreau787db9a2018-06-14 18:31:46 +02006382/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6383 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6384 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006385 * Only one call to send() is performed, unless the buffer wraps, in which case
6386 * a second call may be performed. The connection's flags are updated with
6387 * whatever special event is detected (error, empty). The caller is responsible
6388 * for taking care of those events and avoiding the call if inappropriate. The
6389 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006390 * is responsible for this. The buffer's output is not adjusted, it's up to the
6391 * caller to take care of this. It's up to the caller to update the buffer's
6392 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006393 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006394static 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 +02006395{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006396 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006397 ssize_t ret;
6398 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006399
6400 done = 0;
6401
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006402 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006403 goto out_error;
6404
Willy Tarreau911db9b2020-01-23 16:27:54 +01006405 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006406 /* a handshake was requested */
6407 return 0;
6408
6409 /* send the largest possible block. For this we perform only one call
6410 * to send() unless the buffer wraps and we exactly fill the first hunk,
6411 * in which case we accept to do it once again.
6412 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006413 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006414#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006415 size_t written_data;
6416#endif
6417
Willy Tarreau787db9a2018-06-14 18:31:46 +02006418 try = b_contig_data(buf, done);
6419 if (try > count)
6420 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006421
Thomas Prückl10243932022-04-27 13:04:54 +02006422 if (global_ssl.hard_max_record && try > global_ssl.hard_max_record)
6423 try = global_ssl.hard_max_record;
6424
Willy Tarreau7bed9452014-02-02 02:00:24 +01006425 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006426 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006427 global_ssl.max_record && try > global_ssl.max_record) {
6428 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006429 }
6430 else {
6431 /* we need to keep the information about the fact that
6432 * we're not limiting the upcoming send(), because if it
6433 * fails, we'll have to retry with at least as many data.
6434 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006435 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006436 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006437
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006438#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006439 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006440 unsigned int max_early;
6441
Olivier Houchard522eea72017-11-03 16:27:47 +01006442 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006443 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006444 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006445 if (SSL_get0_session(ctx->ssl))
6446 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006447 else
6448 max_early = 0;
6449 }
6450
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006451 if (try + ctx->sent_early_data > max_early) {
6452 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006453 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006454 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006455 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006456 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006457 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006458 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006459 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006460 if (ret == 1) {
6461 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006462 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006463 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006464 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006465 /* Initiate the handshake, now */
6466 tasklet_wakeup(ctx->wait_event.tasklet);
6467 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006468
Olivier Houchardc2aae742017-09-22 18:26:28 +02006469 }
6470
6471 } else
6472#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006473 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006474
Emeric Brune1f38db2012-09-03 20:36:47 +02006475 if (conn->flags & CO_FL_ERROR) {
6476 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006477 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006478 }
Emeric Brun46591952012-05-18 15:47:34 +02006479 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006480 /* A send succeeded, so we can consider ourself connected */
6481 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006482 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006483 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006484 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006485 }
6486 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006487 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006488
Emeric Brun46591952012-05-18 15:47:34 +02006489 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006490 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006491 /* handshake is running, and it may need to re-enable write */
6492 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006493 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006494#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006495 /* Async mode can be re-enabled, because we're leaving data state.*/
6496 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006497 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006498#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006499 break;
6500 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006501
Emeric Brun46591952012-05-18 15:47:34 +02006502 break;
6503 }
6504 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006505 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006506 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006507 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6508 SUB_RETRY_RECV,
6509 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006510#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006511 /* Async mode can be re-enabled, because we're leaving data state.*/
6512 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006513 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006514#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006515 break;
6516 }
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006517 else if (ret == SSL_ERROR_SSL || ret == SSL_ERROR_SYSCALL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006518 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6519
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02006520 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006521 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006522 conn->err_code = CO_ERR_SSL_FATAL;
6523 }
Emeric Brun46591952012-05-18 15:47:34 +02006524 goto out_error;
6525 }
6526 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006527 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006528 return done;
6529
6530 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006531 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006532 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006533 ERR_clear_error();
6534
Emeric Brun46591952012-05-18 15:47:34 +02006535 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006536 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006537}
6538
Willy Tarreau832e2422021-05-13 10:11:03 +02006539void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006540
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006541 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006542
Olivier Houchardea8dd942019-05-20 14:02:16 +02006543
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006544 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006545 if (ctx->wait_event.events != 0)
6546 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6547 ctx->wait_event.events,
6548 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006549 if (ctx->subs) {
6550 ctx->subs->events = 0;
6551 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006552 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006553
Olivier Houchard692c1d02019-05-23 18:41:47 +02006554 if (ctx->xprt->close)
6555 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006556#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006557 if (global_ssl.async) {
6558 OSSL_ASYNC_FD all_fd[32], afd;
6559 size_t num_all_fds = 0;
6560 int i;
6561
Olivier Houchard66ab4982019-02-26 18:37:15 +01006562 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006563 if (num_all_fds > 32) {
6564 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6565 return;
6566 }
6567
Olivier Houchard66ab4982019-02-26 18:37:15 +01006568 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006569
6570 /* If an async job is pending, we must try to
6571 to catch the end using polling before calling
6572 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006573 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006574 for (i=0 ; i < num_all_fds ; i++) {
6575 /* switch on an handler designed to
6576 * handle the SSL_free
6577 */
6578 afd = all_fd[i];
6579 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006580 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006581 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006582 /* To ensure that the fd cache won't be used
6583 * and we'll catch a real RD event.
6584 */
6585 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006586 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006587 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006588 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006589 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006590 return;
6591 }
Emeric Brun3854e012017-05-17 20:42:48 +02006592 /* Else we can remove the fds from the fdtab
6593 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006594 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006595 * because the fd is owned by the engine.
6596 * the engine is responsible to close
6597 */
Emeric Brun7d392a52022-07-01 17:36:50 +02006598 for (i=0 ; i < num_all_fds ; i++) {
6599 /* We want to remove the fd from the fdtab
6600 * but we flag it to disown because the
6601 * close is performed by the engine itself
6602 */
6603 fdtab[all_fd[i]].state |= FD_DISOWN;
6604 fd_delete(all_fd[i]);
6605 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006606 }
6607#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006608 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006609 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006610 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006611 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau82531f62021-10-06 12:15:18 +02006612 _HA_ATOMIC_DEC(&global.sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006613 }
Emeric Brun46591952012-05-18 15:47:34 +02006614}
6615
6616/* This function tries to perform a clean shutdown on an SSL connection, and in
6617 * any case, flags the connection as reusable if no handshake was in progress.
6618 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006619static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006620{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006621 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006622
Willy Tarreau911db9b2020-01-23 16:27:54 +01006623 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006624 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006625 if (!clean)
6626 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006627 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006628 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006629 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006630 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006631 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006632 ERR_clear_error();
6633 }
Emeric Brun46591952012-05-18 15:47:34 +02006634}
6635
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006636
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006637/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006638int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6639{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006640 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemandd4f946c2019-12-05 10:26:40 +01006641 X509 *crt;
6642
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006643 if (!ctx)
William Lallemandd4f946c2019-12-05 10:26:40 +01006644 return 0;
William Lallemandd4f946c2019-12-05 10:26:40 +01006645 crt = SSL_get_certificate(ctx->ssl);
6646 if (!crt)
6647 return 0;
6648
6649 return cert_get_pkey_algo(crt, out);
6650}
6651
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006652/* used for ppv2 cert signature (can be used for logging) */
6653const char *ssl_sock_get_cert_sig(struct connection *conn)
6654{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006655 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006656
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006657 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6658 X509 *crt;
6659
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006660 if (!ctx)
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006661 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006662 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006663 if (!crt)
6664 return NULL;
6665 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6666 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6667}
6668
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006669/* used for ppv2 authority */
6670const char *ssl_sock_get_sni(struct connection *conn)
6671{
6672#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006673 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006674
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006675 if (!ctx)
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006676 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006677 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006678#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006679 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006680#endif
6681}
6682
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006683/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006684const char *ssl_sock_get_cipher_name(struct connection *conn)
6685{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006686 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006687
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006688 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006689 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006690 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006691}
6692
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006693/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006694const char *ssl_sock_get_proto_version(struct connection *conn)
6695{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006696 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006697
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006698 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006699 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006700 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006701}
6702
Olivier Houchardab28a322018-12-21 19:45:40 +01006703void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6704{
6705#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006706 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006707
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006708 if (!ctx)
Olivier Houcharde488ea82019-06-28 14:10:33 +02006709 return;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006710 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006711#endif
6712}
6713
Willy Tarreau119a4082016-12-22 21:58:38 +01006714/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6715 * to disable SNI.
6716 */
Willy Tarreau63076412015-07-10 11:33:32 +02006717void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6718{
6719#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006720 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemande18d4e82021-11-17 02:59:21 +01006721 struct server *s;
Willy Tarreau119a4082016-12-22 21:58:38 +01006722 char *prev_name;
6723
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006724 if (!ctx)
Willy Tarreau63076412015-07-10 11:33:32 +02006725 return;
Willy Tarreau77bfa662021-12-23 11:12:13 +01006726
6727 BUG_ON(!(conn->flags & CO_FL_WAIT_L6_CONN));
6728 BUG_ON(!(conn->flags & CO_FL_SSL_WAIT_HS));
6729
William Lallemande18d4e82021-11-17 02:59:21 +01006730 s = __objt_server(conn->target);
Willy Tarreau63076412015-07-10 11:33:32 +02006731
Willy Tarreau119a4082016-12-22 21:58:38 +01006732 /* if the SNI changes, we must destroy the reusable context so that a
William Lallemande18d4e82021-11-17 02:59:21 +01006733 * new connection will present a new SNI. compare with the SNI
6734 * previously stored in the reused_sess */
6735 /* the RWLOCK is used to ensure that we are not trying to flush the
6736 * cache from the CLI */
6737
6738 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
6739 prev_name = s->ssl_ctx.reused_sess[tid].sni;
Willy Tarreau119a4082016-12-22 21:58:38 +01006740 if ((!prev_name && hostname) ||
6741 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006742 SSL_set_session(ctx->ssl, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01006743 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau119a4082016-12-22 21:58:38 +01006744
Olivier Houchard66ab4982019-02-26 18:37:15 +01006745 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006746#endif
6747}
6748
Emeric Brun0abf8362014-06-24 18:26:41 +02006749/* Extract peer certificate's common name into the chunk dest
6750 * Returns
6751 * the len of the extracted common name
6752 * or 0 if no CN found in DN
6753 * or -1 on error case (i.e. no peer certificate)
6754 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006755int ssl_sock_get_remote_common_name(struct connection *conn,
6756 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006757{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006758 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
David Safb76832014-05-08 23:42:08 -04006759 X509 *crt = NULL;
6760 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006761 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006762 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006763 .area = (char *)&find_cn,
6764 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006765 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006766 int result = -1;
David Safb76832014-05-08 23:42:08 -04006767
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006768 if (!ctx)
Emeric Brun0abf8362014-06-24 18:26:41 +02006769 goto out;
David Safb76832014-05-08 23:42:08 -04006770
6771 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006772 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006773 if (!crt)
6774 goto out;
6775
6776 name = X509_get_subject_name(crt);
6777 if (!name)
6778 goto out;
David Safb76832014-05-08 23:42:08 -04006779
Emeric Brun0abf8362014-06-24 18:26:41 +02006780 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6781out:
David Safb76832014-05-08 23:42:08 -04006782 if (crt)
6783 X509_free(crt);
6784
6785 return result;
6786}
6787
Dave McCowan328fb582014-07-30 10:39:13 -04006788/* returns 1 if client passed a certificate for this session, 0 if not */
6789int ssl_sock_get_cert_used_sess(struct connection *conn)
6790{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006791 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dave McCowan328fb582014-07-30 10:39:13 -04006792 X509 *crt = NULL;
6793
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006794 if (!ctx)
Dave McCowan328fb582014-07-30 10:39:13 -04006795 return 0;
6796
6797 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006798 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006799 if (!crt)
6800 return 0;
6801
6802 X509_free(crt);
6803 return 1;
6804}
6805
6806/* returns 1 if client passed a certificate for this connection, 0 if not */
6807int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006808{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006809 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006810
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006811 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006812 return 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006813 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006814}
6815
6816/* returns result from SSL verify */
6817unsigned int ssl_sock_get_verify_result(struct connection *conn)
6818{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006819 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006820
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006821 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006822 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006823 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006824}
6825
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006826/* Returns the application layer protocol name in <str> and <len> when known.
6827 * Zero is returned if the protocol name was not found, otherwise non-zero is
6828 * returned. The string is allocated in the SSL context and doesn't have to be
6829 * freed by the caller. NPN is also checked if available since older versions
6830 * of openssl (1.0.1) which are more common in field only support this one.
6831 */
Amaury Denoyelle71e588c2021-11-12 11:23:29 +01006832int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006833{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006834#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6835 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006836 struct ssl_sock_ctx *ctx = xprt_ctx;
6837 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006838 return 0;
6839
6840 *str = NULL;
6841
6842#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006843 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006844 if (*str)
6845 return 1;
6846#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006847#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006848 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006849 if (*str)
6850 return 1;
6851#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006852#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006853 return 0;
6854}
6855
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006856/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006857int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006858{
6859 X509 *ca;
6860 X509_NAME *name = NULL;
6861 ASN1_OCTET_STRING *skid = NULL;
6862 STACK_OF(X509) *chain = NULL;
6863 struct issuer_chain *issuer;
6864 struct eb64_node *node;
6865 char *path;
6866 u64 key;
6867 int ret = 0;
6868
6869 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6870 if (chain == NULL) {
6871 chain = sk_X509_new_null();
6872 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6873 name = X509_get_subject_name(ca);
6874 }
6875 if (!sk_X509_push(chain, ca)) {
6876 X509_free(ca);
6877 goto end;
6878 }
6879 }
6880 if (!chain) {
6881 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6882 goto end;
6883 }
6884 if (!skid) {
6885 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6886 goto end;
6887 }
6888 if (!name) {
6889 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6890 goto end;
6891 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01006892 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006893 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006894 issuer = container_of(node, typeof(*issuer), node);
6895 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6896 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6897 goto end;
6898 }
6899 }
6900 issuer = calloc(1, sizeof *issuer);
6901 path = strdup(fp);
6902 if (!issuer || !path) {
6903 free(issuer);
6904 free(path);
6905 goto end;
6906 }
6907 issuer->node.key = key;
6908 issuer->path = path;
6909 issuer->chain = chain;
6910 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006911 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006912 ret = 1;
6913 end:
6914 if (skid)
6915 ASN1_OCTET_STRING_free(skid);
6916 if (chain)
6917 sk_X509_pop_free(chain, X509_free);
6918 return ret;
6919}
6920
William Lallemandda8584c2020-05-14 10:14:37 +02006921 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006922{
6923 AUTHORITY_KEYID *akid;
6924 struct issuer_chain *issuer = NULL;
6925
6926 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01006927 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006928 struct eb64_node *node;
6929 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01006930 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006931 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6932 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6933 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6934 issuer = ti;
6935 break;
6936 }
6937 }
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006938 }
Remi Tricot-Le Breton1621dc12022-11-03 15:16:48 +01006939 AUTHORITY_KEYID_free(akid);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006940 return issuer;
6941}
6942
William Lallemanddad31052020-05-14 17:47:32 +02006943void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006944{
6945 struct eb64_node *node, *back;
6946 struct issuer_chain *issuer;
6947
William Lallemande0f3fd52020-02-25 14:53:06 +01006948 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006949 while (node) {
6950 issuer = container_of(node, typeof(*issuer), node);
6951 back = eb64_next(node);
6952 eb64_delete(node);
6953 free(issuer->path);
6954 sk_X509_pop_free(issuer->chain, X509_free);
6955 free(issuer);
6956 node = back;
6957 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006958}
6959
William Lallemandd7bfbe22022-04-11 18:41:24 +02006960#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006961static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01006962 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006963
Emeric Brun3854e012017-05-17 20:42:48 +02006964 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006965 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006966 err_code = ERR_ABORT;
6967 }
6968 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006969}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006970#endif
6971
Willy Tarreaude5675a2021-01-20 14:41:29 +01006972/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006973 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01006974 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01006975static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01006976{
6977 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006978 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006979
6980 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006981 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006982
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006983 if (sctx->conn != conn) {
6984 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
6985 ret = 1;
6986 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01006987 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
6988
6989 if (sctx->xprt) {
6990 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
6991 if (sctx->xprt_ctx)
6992 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
6993 }
6994
6995 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006996
6997 /* as soon as a shutdown is reported the lower layer unregisters its
6998 * subscriber, so the situations below are transient and rare enough to
6999 * be reported as suspicious. In any case they shouldn't last.
7000 */
7001 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
7002 ret = 1;
7003 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
7004 ret = 1;
7005
Willy Tarreaude5675a2021-01-20 14:41:29 +01007006 chunk_appendf(&trash, " .subs=%p", sctx->subs);
7007 if (sctx->subs) {
7008 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007009 if (sctx->subs->tasklet->calls >= 1000000)
7010 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007011 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
7012 sctx->subs->tasklet->calls,
7013 sctx->subs->tasklet->context);
7014 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
7015 chunk_appendf(&trash, ")");
7016 }
7017 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
7018 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007019 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007020}
7021
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007022#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02007023/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007024 * each reference. The variable <ref> must point to the current node's list
7025 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02007026 */
William Lallemand32af2032016-10-29 18:09:35 +02007027static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007028struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02007029{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007030 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007031 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02007032
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007033 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007034 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007035 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02007036
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007037 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02007038}
7039
7040static inline
7041struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
7042{
7043 int id;
7044 char *error;
7045
7046 /* If the reference starts by a '#', this is numeric id. */
7047 if (reference[0] == '#') {
7048 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
7049 id = strtol(reference + 1, &error, 10);
7050 if (*error != '\0')
7051 return NULL;
7052
7053 /* Perform the unique id lookup. */
7054 return tlskeys_ref_lookupid(id);
7055 }
7056
7057 /* Perform the string lookup. */
7058 return tlskeys_ref_lookup(reference);
7059}
7060#endif
7061
7062
7063#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7064
Willy Tarreaua9380522022-05-05 08:50:17 +02007065/* dumps all tls keys. Relies on the show_keys_ctx context from the appctx. */
Willy Tarreaubd338642022-05-05 08:59:17 +02007066static int cli_io_handler_tlskeys_files(struct appctx *appctx)
7067{
Willy Tarreaua9380522022-05-05 08:50:17 +02007068 struct show_keys_ctx *ctx = appctx->svcctx;
William Lallemand32af2032016-10-29 18:09:35 +02007069
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007070 switch (ctx->state) {
7071 case SHOW_KEYS_INIT:
William Lallemand32af2032016-10-29 18:09:35 +02007072 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08007073 * quit the function with returning 0. The function is called
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007074 * later and restart at the state "SHOW_KEYS_INIT".
William Lallemand32af2032016-10-29 18:09:35 +02007075 */
7076 chunk_reset(&trash);
7077
Willy Tarreaubd338642022-05-05 08:59:17 +02007078 if (ctx->dump_entries)
William Lallemand32af2032016-10-29 18:09:35 +02007079 chunk_appendf(&trash, "# id secret\n");
7080 else
7081 chunk_appendf(&trash, "# id (file)\n");
7082
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007083 if (applet_putchk(appctx, &trash) == -1)
William Lallemand32af2032016-10-29 18:09:35 +02007084 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007085
William Lallemand32af2032016-10-29 18:09:35 +02007086 /* Now, we start the browsing of the references lists.
7087 * Note that the following call to LIST_ELEM return bad pointer. The only
7088 * available field of this pointer is <list>. It is used with the function
7089 * tlskeys_list_get_next() for retruning the first available entry
7090 */
Willy Tarreaua9380522022-05-05 08:50:17 +02007091 if (ctx->next_ref == NULL)
7092 ctx->next_ref = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007093
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007094 ctx->state = SHOW_KEYS_LIST;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007095 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007096
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007097 case SHOW_KEYS_LIST:
Willy Tarreaua9380522022-05-05 08:50:17 +02007098 while (ctx->next_ref) {
7099 struct tls_keys_ref *ref = ctx->next_ref;
William Lallemand32af2032016-10-29 18:09:35 +02007100
7101 chunk_reset(&trash);
Willy Tarreaubd338642022-05-05 08:59:17 +02007102 if (ctx->dump_entries && ctx->next_index == 0)
William Lallemand32af2032016-10-29 18:09:35 +02007103 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007104
Willy Tarreaua9380522022-05-05 08:50:17 +02007105 if (ctx->next_index == 0)
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007106 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
7107
Willy Tarreaubd338642022-05-05 08:59:17 +02007108 if (ctx->dump_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01007109 int head;
7110
7111 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
7112 head = ref->tls_ticket_enc_index;
Willy Tarreaua9380522022-05-05 08:50:17 +02007113 while (ctx->next_index < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02007114 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02007115
7116 chunk_reset(t2);
7117 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01007118 if (ref->key_size_bits == 128) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007119 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007120 sizeof(struct tls_sess_key_128),
7121 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007122 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007123 t2->area);
7124 }
7125 else if (ref->key_size_bits == 256) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007126 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007127 sizeof(struct tls_sess_key_256),
7128 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007129 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007130 t2->area);
7131 }
7132 else {
7133 /* This case should never happen */
Willy Tarreaua9380522022-05-05 08:50:17 +02007134 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, ctx->next_index);
Emeric Brun9e754772019-01-10 17:51:55 +01007135 }
William Lallemand32af2032016-10-29 18:09:35 +02007136
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007137 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007138 /* let's try again later from this stream. We add ourselves into
7139 * this stream's users so that it can remove us upon termination.
7140 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01007141 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
William Lallemand32af2032016-10-29 18:09:35 +02007142 return 0;
7143 }
Willy Tarreaua9380522022-05-05 08:50:17 +02007144 ctx->next_index++;
William Lallemand32af2032016-10-29 18:09:35 +02007145 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01007146 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaua9380522022-05-05 08:50:17 +02007147 ctx->next_index = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007148 }
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007149 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007150 /* let's try again later from this stream. We add ourselves into
7151 * this stream's users so that it can remove us upon termination.
7152 */
William Lallemand32af2032016-10-29 18:09:35 +02007153 return 0;
7154 }
7155
Willy Tarreaua9380522022-05-05 08:50:17 +02007156 if (ctx->names_only == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02007157 break;
7158
7159 /* get next list entry and check the end of the list */
Willy Tarreaua9380522022-05-05 08:50:17 +02007160 ctx->next_ref = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007161 }
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007162 ctx->state = SHOW_KEYS_DONE;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007163 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007164
7165 default:
William Lallemand32af2032016-10-29 18:09:35 +02007166 return 1;
7167 }
7168 return 0;
7169}
7170
Willy Tarreaua9380522022-05-05 08:50:17 +02007171/* Prepares a "show_keys_ctx" and sets the appropriate io_handler if needed */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007172static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007173{
Willy Tarreaua9380522022-05-05 08:50:17 +02007174 struct show_keys_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
7175
William Lallemand32af2032016-10-29 18:09:35 +02007176 /* no parameter, shows only file list */
7177 if (!*args[2]) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007178 ctx->names_only = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007179 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007180 }
7181
7182 if (args[2][0] == '*') {
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007183 /* list every TLS ticket keys */
7184 ctx->names_only = 1;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007185 } else {
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007186 ctx->next_ref = tlskeys_ref_lookup_ref(args[2]);
7187 if (!ctx->next_ref)
7188 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007189 }
7190
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007191 ctx->dump_entries = 1;
7192 return 0;
7193}
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007194
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007195static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
7196{
7197 struct tls_keys_ref *ref;
7198 int ret;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007199
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007200 /* Expect two parameters: the filename and the new new TLS key in encoding */
7201 if (!*args[3] || !*args[4])
7202 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 +02007203
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007204 ref = tlskeys_ref_lookup_ref(args[3]);
7205 if (!ref)
7206 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007207
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007208 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
7209 if (ret < 0)
7210 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007211
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007212 trash.data = ret;
7213 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
7214 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007215
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007216 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007217}
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007218#endif
7219
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007220
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007221#ifdef HAVE_SSL_PROVIDERS
7222struct provider_name {
7223 const char *name;
7224 struct list list;
7225};
7226
7227
7228static int ssl_provider_get_name_cb(OSSL_PROVIDER *provider, void *cbdata)
7229{
7230 struct list *provider_names = cbdata;
7231 struct provider_name *item = NULL;
7232 const char *name = OSSL_PROVIDER_get0_name(provider);
7233
7234 if (!provider_names)
7235 return 0;
7236
7237 item = calloc(1, sizeof(*item));
7238
7239 if (!item)
7240 return 0;
7241
7242 item->name = name;
7243 LIST_APPEND(provider_names, &item->list);
7244
7245 return 1;
7246}
7247
7248static void ssl_provider_get_name_list(struct list *provider_names)
7249{
7250 if (!provider_names)
7251 return;
7252
7253 OSSL_PROVIDER_do_all(NULL, ssl_provider_get_name_cb, provider_names);
7254}
7255
7256static void ssl_provider_clear_name_list(struct list *provider_names)
7257{
7258 struct provider_name *item = NULL, *item_s = NULL;
7259
7260 if (provider_names) {
7261 list_for_each_entry_safe(item, item_s, provider_names, list) {
7262 LIST_DELETE(&item->list);
7263 free(item);
7264 }
7265 }
7266}
7267
7268static int cli_io_handler_show_providers(struct appctx *appctx)
7269{
7270 struct buffer *trash = get_trash_chunk();
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007271 struct list provider_names;
7272 struct provider_name *name;
7273
7274 LIST_INIT(&provider_names);
7275
7276 chunk_appendf(trash, "Loaded providers : \n");
7277
7278 ssl_provider_get_name_list(&provider_names);
7279
7280 list_for_each_entry(name, &provider_names, list) {
7281 chunk_appendf(trash, "\t- %s\n", name->name);
7282 }
7283
7284 ssl_provider_clear_name_list(&provider_names);
7285
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007286 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007287 goto yield;
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007288
7289 return 1;
7290
7291yield:
7292 return 0;
7293}
7294#endif
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01007295
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007296
William Lallemand32af2032016-10-29 18:09:35 +02007297/* register cli keywords */
7298static struct cli_kw_list cli_kws = {{ },{
7299#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01007300 { { "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 },
7301 { { "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 +02007302#endif
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007303#ifdef HAVE_SSL_PROVIDERS
7304 { { "show", "ssl", "providers", NULL }, "show ssl providers : show loaded SSL providers", NULL, cli_io_handler_show_providers },
7305#endif
William Lallemand32af2032016-10-29 18:09:35 +02007306 { { NULL }, NULL, NULL, NULL }
7307}};
7308
Willy Tarreau0108d902018-11-25 19:14:37 +01007309INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02007310
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02007311/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02007312struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02007313 .snd_buf = ssl_sock_from_buf,
7314 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01007315 .subscribe = ssl_subscribe,
7316 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02007317 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02007318 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02007319 .rcv_pipe = NULL,
7320 .snd_pipe = NULL,
7321 .shutr = NULL,
7322 .shutw = ssl_sock_shutw,
7323 .close = ssl_sock_close,
7324 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01007325 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01007326 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01007327 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01007328 .prepare_srv = ssl_sock_prepare_srv_ctx,
7329 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007330 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02007331 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01007332 .set_idle = ssl_set_idle,
7333 .set_used = ssl_set_used,
Willy Tarreaude827952022-04-11 10:43:28 +02007334 .get_ssl_sock_ctx = ssl_sock_get_ctx,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01007335 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01007336 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02007337};
7338
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007339enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
7340 struct session *sess, struct stream *s, int flags)
7341{
7342 struct connection *conn;
7343
7344 conn = objt_conn(sess->origin);
7345
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007346 if (conn) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007347 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007348 sc_ep_set(s->scf, SE_FL_WAIT_FOR_HS);
Christopher Faulet6e1bbc42022-12-12 08:08:15 +01007349 s->req.flags |= CF_READ_EVENT;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007350 return ACT_RET_YIELD;
7351 }
7352 }
7353 return (ACT_RET_CONT);
7354}
7355
7356static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
7357{
7358 rule->action_ptr = ssl_action_wait_for_hs;
7359
7360 return ACT_RET_PRS_OK;
7361}
7362
7363static struct action_kw_list http_req_actions = {ILH, {
7364 { "wait-for-handshake", ssl_parse_wait_for_hs },
7365 { /* END */ }
7366}};
7367
Willy Tarreau0108d902018-11-25 19:14:37 +01007368INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
7369
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007370#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007371
7372static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7373{
7374 if (ptr) {
7375 chunk_destroy(ptr);
7376 free(ptr);
7377 }
7378}
7379
7380#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007381
William Lallemand76b4a122020-08-04 17:41:39 +02007382
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007383static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7384{
Willy Tarreaubafbe012017-11-24 17:34:44 +01007385 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007386}
William Lallemand7d42ef52020-07-06 11:41:30 +02007387
William Lallemand722180a2021-06-09 16:46:12 +02007388#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007389static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7390{
7391 struct ssl_keylog *keylog;
7392
7393 if (!ptr)
7394 return;
7395
7396 keylog = ptr;
7397
7398 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7399 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7400 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7401 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7402 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7403 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7404 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7405 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7406
7407 pool_free(pool_head_ssl_keylog, ptr);
7408}
7409#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007410
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007411static void ssl_sock_clt_crt_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7412{
7413 if (!ptr)
7414 return;
7415
7416 X509_free((X509*)ptr);
7417}
7418
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01007419static void ssl_sock_clt_sni_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7420{
7421 pool_free(ssl_sock_client_sni_pool, ptr);
7422}
7423
Willy Tarreau92faadf2012-10-10 23:04:25 +02007424static void __ssl_sock_init(void)
7425{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007426#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007427 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007428 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007429#endif
Emeric Brun46591952012-05-18 15:47:34 +02007430
Willy Tarreauef934602016-12-22 23:12:01 +01007431 if (global_ssl.listen_default_ciphers)
7432 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7433 if (global_ssl.connect_default_ciphers)
7434 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007435#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007436 if (global_ssl.listen_default_ciphersuites)
7437 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7438 if (global_ssl.connect_default_ciphersuites)
7439 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7440#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007441
Willy Tarreau13e14102016-12-22 20:25:26 +01007442 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007443#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007444 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007445#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007446#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007447 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007448 n = sk_SSL_COMP_num(cm);
7449 while (n--) {
7450 (void) sk_SSL_COMP_pop(cm);
7451 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007452#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007453
Willy Tarreau5db847a2019-05-09 14:13:35 +02007454#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007455 ssl_locking_init();
7456#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007457#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007458 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
7459#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007460
7461#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7462 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
7463#endif
7464
Thierry FOURNIER28962c92018-06-17 21:37:05 +02007465 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02007466 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 +01007467#ifdef USE_QUIC
7468 ssl_qc_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7469#endif /* USE_QUIC */
William Lallemand722180a2021-06-09 16:46:12 +02007470#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007471 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
7472#endif
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007473 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 +01007474 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 +02007475#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00007476 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007477 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007478#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01007479#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7480 hap_register_post_check(tlskeys_finalize_config);
7481#endif
Willy Tarreau80713382018-11-26 10:19:54 +01007482
7483 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
7484 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
7485
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007486 hap_register_post_deinit(ssl_free_global_issuers);
7487
Willy Tarreau80713382018-11-26 10:19:54 +01007488#ifndef OPENSSL_NO_DH
7489 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7490 hap_register_post_deinit(ssl_free_dh);
7491#endif
William Lallemandd7bfbe22022-04-11 18:41:24 +02007492#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Willy Tarreau80713382018-11-26 10:19:54 +01007493 hap_register_post_deinit(ssl_free_engines);
7494#endif
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02007495#ifdef HAVE_SSL_PROVIDERS
7496 hap_register_post_deinit(ssl_unload_providers);
7497#endif
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01007498#if HA_OPENSSL_VERSION_NUMBER < 0x3000000fL
Willy Tarreau80713382018-11-26 10:19:54 +01007499 /* Load SSL string for the verbose & debug mode. */
7500 ERR_load_SSL_strings();
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01007501#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007502 ha_meth = BIO_meth_new(0x666, "ha methods");
7503 BIO_meth_set_write(ha_meth, ha_ssl_write);
7504 BIO_meth_set_read(ha_meth, ha_ssl_read);
7505 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
7506 BIO_meth_set_create(ha_meth, ha_ssl_new);
7507 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
7508 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
7509 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02007510
7511 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007512
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01007513 HA_SPIN_INIT(&ocsp_tree_lock);
7514
Dragan Dosen9ac98092020-05-11 15:51:45 +02007515 /* Try to register dedicated SSL/TLS protocol message callbacks for
7516 * heartbleed attack (CVE-2014-0160) and clienthello.
7517 */
7518 hap_register_post_check(ssl_sock_register_msg_callbacks);
7519
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007520 /* Try to free all callbacks that were registered by using
7521 * ssl_sock_register_msg_callback().
7522 */
7523 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01007524}
Willy Tarreau79367f92022-04-25 19:18:24 +02007525INITCALL0(STG_REGISTER, __ssl_sock_init);
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01007526
Willy Tarreau80713382018-11-26 10:19:54 +01007527/* Compute and register the version string */
7528static void ssl_register_build_options()
7529{
7530 char *ptr = NULL;
7531 int i;
7532
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007533 memprintf(&ptr, "Built with OpenSSL version : "
7534#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007535 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007536#else /* OPENSSL_IS_BORINGSSL */
7537 OPENSSL_VERSION_TEXT
7538 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08007539 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02007540 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007541#endif
7542 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007543#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007544 "no (library version too old)"
7545#elif defined(OPENSSL_NO_TLSEXT)
7546 "no (disabled via OPENSSL_NO_TLSEXT)"
7547#else
7548 "yes"
7549#endif
7550 "", ptr);
7551
7552 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
7553#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
7554 "yes"
7555#else
7556#ifdef OPENSSL_NO_TLSEXT
7557 "no (because of OPENSSL_NO_TLSEXT)"
7558#else
7559 "no (version might be too old, 0.9.8f min needed)"
7560#endif
7561#endif
7562 "", ptr);
7563
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02007564 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
7565 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
7566 if (methodVersions[i].option)
7567 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007568
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007569#ifdef HAVE_SSL_PROVIDERS
7570 {
7571 struct list provider_names;
7572 struct provider_name *name;
7573 LIST_INIT(&provider_names);
7574 ssl_provider_get_name_list(&provider_names);
7575
7576 memprintf(&ptr, "%s\nOpenSSL providers loaded :", ptr);
7577
7578 list_for_each_entry(name, &provider_names, list) {
7579 memprintf(&ptr, "%s %s", ptr, name->name);
7580 }
7581
7582 ssl_provider_clear_name_list(&provider_names);
7583 }
7584#endif
7585
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007586 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01007587}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007588
Willy Tarreau80713382018-11-26 10:19:54 +01007589INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02007590
William Lallemandd7bfbe22022-04-11 18:41:24 +02007591#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00007592void ssl_free_engines(void) {
7593 struct ssl_engine_list *wl, *wlb;
7594 /* free up engine list */
7595 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
7596 ENGINE_finish(wl->e);
7597 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02007598 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00007599 free(wl);
7600 }
7601}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007602#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02007603
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02007604#ifdef HAVE_SSL_PROVIDERS
7605void ssl_unload_providers(void) {
7606 struct ssl_provider_list *prov, *provb;
7607 list_for_each_entry_safe(prov, provb, &openssl_providers, list) {
7608 OSSL_PROVIDER_unload(prov->provider);
7609 LIST_DELETE(&prov->list);
7610 free(prov);
7611 }
7612}
7613#endif
7614
Remi Gacogned3a23c32015-05-28 16:39:47 +02007615#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00007616void ssl_free_dh(void) {
7617 if (local_dh_1024) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007618 HASSL_DH_free(local_dh_1024);
Grant Zhang872f9c22017-01-21 01:10:18 +00007619 local_dh_1024 = NULL;
7620 }
7621 if (local_dh_2048) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007622 HASSL_DH_free(local_dh_2048);
Grant Zhang872f9c22017-01-21 01:10:18 +00007623 local_dh_2048 = NULL;
7624 }
7625 if (local_dh_4096) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007626 HASSL_DH_free(local_dh_4096);
Grant Zhang872f9c22017-01-21 01:10:18 +00007627 local_dh_4096 = NULL;
7628 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02007629 if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007630 HASSL_DH_free(global_dh);
Remi Gacogne47783ef2015-05-29 15:53:22 +02007631 global_dh = NULL;
7632 }
Grant Zhang872f9c22017-01-21 01:10:18 +00007633}
7634#endif
7635
Grant Zhang872f9c22017-01-21 01:10:18 +00007636static void __ssl_sock_deinit(void)
7637{
7638#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007639 if (ssl_ctx_lru_tree) {
7640 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007641 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02007642 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02007643#endif
7644
Willy Tarreau5db847a2019-05-09 14:13:35 +02007645#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007646 ERR_remove_state(0);
7647 ERR_free_strings();
7648
7649 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08007650#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007651
Willy Tarreau5db847a2019-05-09 14:13:35 +02007652#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007653 CRYPTO_cleanup_all_ex_data();
7654#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007655 BIO_meth_free(ha_meth);
Remi Tricot-Le Breton6477bbd2022-12-20 11:11:13 +01007656
7657#if !defined OPENSSL_NO_OCSP
7658 ssl_destroy_ocsp_update_task();
7659#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007660}
Willy Tarreau79367f92022-04-25 19:18:24 +02007661REGISTER_POST_DEINIT(__ssl_sock_deinit);
Remi Gacogned3a23c32015-05-28 16:39:47 +02007662
William Dauchyf6370442020-11-14 19:25:33 +01007663
Emeric Brun46591952012-05-18 15:47:34 +02007664/*
7665 * Local variables:
7666 * c-indent-level: 8
7667 * c-basic-offset: 8
7668 * End:
7669 */