blob: 5ebc72f67e0a3c6fbcc8422da06dbf4dcb631eb7 [file] [log] [blame]
yanbzhu08ce6ab2015-12-02 13:01:29 -05001
Emeric Brun46591952012-05-18 15:47:34 +02002/*
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02003 * SSL/TLS transport layer over SOCK_STREAM sockets
Emeric Brun46591952012-05-18 15:47:34 +02004 *
5 * Copyright (C) 2012 EXCELIANCE, Emeric Brun <ebrun@exceliance.fr>
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version
10 * 2 of the License, or (at your option) any later version.
11 *
Willy Tarreau69845df2012-09-10 09:43:09 +020012 * Acknowledgement:
13 * We'd like to specially thank the Stud project authors for a very clean
14 * and well documented code which helped us understand how the OpenSSL API
15 * ought to be used in non-blocking mode. This is one difficult part which
16 * is not easy to get from the OpenSSL doc, and reading the Stud code made
17 * it much more obvious than the examples in the OpenSSL package. Keep up
18 * the good works, guys !
19 *
20 * Stud is an extremely efficient and scalable SSL/TLS proxy which combines
21 * particularly well with haproxy. For more info about this project, visit :
22 * https://github.com/bumptech/stud
23 *
Emeric Brun46591952012-05-18 15:47:34 +020024 */
25
Willy Tarreau8d164dc2019-05-10 09:35:00 +020026/* Note: do NOT include openssl/xxx.h here, do it in openssl-compat.h */
Emeric Brun46591952012-05-18 15:47:34 +020027#define _GNU_SOURCE
Emeric Brunfc0421f2012-09-07 17:30:07 +020028#include <ctype.h>
29#include <dirent.h>
Emeric Brun46591952012-05-18 15:47:34 +020030#include <errno.h>
Emeric Brun46591952012-05-18 15:47:34 +020031#include <stdio.h>
32#include <stdlib.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020033#include <string.h>
34#include <unistd.h>
Emeric Brun46591952012-05-18 15:47:34 +020035
36#include <sys/socket.h>
37#include <sys/stat.h>
38#include <sys/types.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020039#include <netdb.h>
Emeric Brun46591952012-05-18 15:47:34 +020040#include <netinet/tcp.h>
41
Willy Tarreaub2551052020-06-09 09:07:15 +020042#include <import/ebpttree.h>
43#include <import/ebsttree.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020044#include <import/lru.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020045
Willy Tarreaub2551052020-06-09 09:07:15 +020046#include <haproxy/api.h>
Willy Tarreaua9380522022-05-05 08:50:17 +020047#include <haproxy/applet.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020048#include <haproxy/arg.h>
49#include <haproxy/base64.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020050#include <haproxy/channel.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020051#include <haproxy/chunk.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020052#include <haproxy/cli.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020053#include <haproxy/connection.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020054#include <haproxy/dynbuf.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020055#include <haproxy/errors.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020056#include <haproxy/fd.h>
57#include <haproxy/freq_ctr.h>
Willy Tarreau762d7a52020-06-04 11:23:07 +020058#include <haproxy/frontend.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020059#include <haproxy/global.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020060#include <haproxy/http_rules.h>
Willy Tarreauaeed4a82020-06-04 22:01:04 +020061#include <haproxy/log.h>
Willy Tarreau6019fab2020-05-27 16:26:00 +020062#include <haproxy/openssl-compat.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020063#include <haproxy/pattern-t.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020064#include <haproxy/proto_tcp.h>
Willy Tarreaua264d962020-06-04 22:29:18 +020065#include <haproxy/proxy.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020066#include <haproxy/sample.h>
67#include <haproxy/sc_strm.h>
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020068#include <haproxy/quic_conn.h>
Frédéric Lécaille748ece62022-05-21 23:58:40 +020069#include <haproxy/quic_tp.h>
Willy Tarreau1e56f922020-06-04 23:20:13 +020070#include <haproxy/server.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020071#include <haproxy/shctx.h>
Willy Tarreau47d7f902020-06-04 14:25:47 +020072#include <haproxy/ssl_ckch.h>
Willy Tarreau52d88722020-06-04 14:29:23 +020073#include <haproxy/ssl_crtlist.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020074#include <haproxy/ssl_sock.h>
Willy Tarreaub2bd8652020-06-04 14:21:22 +020075#include <haproxy/ssl_utils.h>
Amaury Denoyelle9963fa72020-11-03 17:10:00 +010076#include <haproxy/stats.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020077#include <haproxy/stconn.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020078#include <haproxy/stream-t.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020079#include <haproxy/task.h>
Willy Tarreauc2f7c582020-06-02 18:15:32 +020080#include <haproxy/ticks.h>
Willy Tarreau92b4f132020-06-01 11:05:15 +020081#include <haproxy/time.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020082#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020083#include <haproxy/vars.h>
Tim Duesterhusd5fc8fc2021-09-11 17:51:13 +020084#include <haproxy/xxhash.h>
Remi Tricot-Le Breton2e7d1eb2022-01-11 10:11:10 +010085#include <haproxy/istbuf.h>
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +010086#include <haproxy/ssl_ocsp.h>
Emeric Brun46591952012-05-18 15:47:34 +020087
Emeric Brun46591952012-05-18 15:47:34 +020088
Willy Tarreau9356dac2019-05-10 09:22:53 +020089/* ***** READ THIS before adding code here! *****
90 *
91 * Due to API incompatibilities between multiple OpenSSL versions and their
92 * derivatives, it's often tempting to add macros to (re-)define certain
93 * symbols. Please do not do this here, and do it in common/openssl-compat.h
94 * exclusively so that the whole code consistently uses the same macros.
95 *
96 * Whenever possible if a macro is missing in certain versions, it's better
97 * to conditionally define it in openssl-compat.h than using lots of ifdefs.
98 */
99
Emeric Brunece0c332017-12-06 13:51:49 +0100100int nb_engines = 0;
Emeric Brune1f38db2012-09-03 20:36:47 +0200101
William Lallemande0f3fd52020-02-25 14:53:06 +0100102static struct eb_root cert_issuer_tree = EB_ROOT; /* issuers tree from "issuers-chain-path" */
103
William Lallemand7fd8b452020-05-07 15:20:43 +0200104struct global_ssl global_ssl = {
Willy Tarreauef934602016-12-22 23:12:01 +0100105#ifdef LISTEN_DEFAULT_CIPHERS
106 .listen_default_ciphers = LISTEN_DEFAULT_CIPHERS,
107#endif
108#ifdef CONNECT_DEFAULT_CIPHERS
109 .connect_default_ciphers = CONNECT_DEFAULT_CIPHERS,
110#endif
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +0500111#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200112 .listen_default_ciphersuites = LISTEN_DEFAULT_CIPHERSUITES,
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200113 .connect_default_ciphersuites = CONNECT_DEFAULT_CIPHERSUITES,
114#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100115 .listen_default_ssloptions = BC_SSL_O_NONE,
116 .connect_default_ssloptions = SRV_SSL_O_NONE,
117
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +0200118 .listen_default_sslmethods.flags = MC_SSL_O_ALL,
119 .listen_default_sslmethods.min = CONF_TLSV_NONE,
120 .listen_default_sslmethods.max = CONF_TLSV_NONE,
121 .connect_default_sslmethods.flags = MC_SSL_O_ALL,
122 .connect_default_sslmethods.min = CONF_TLSV_NONE,
123 .connect_default_sslmethods.max = CONF_TLSV_NONE,
124
Willy Tarreauef934602016-12-22 23:12:01 +0100125#ifdef DEFAULT_SSL_MAX_RECORD
126 .max_record = DEFAULT_SSL_MAX_RECORD,
127#endif
Thomas Prückl10243932022-04-27 13:04:54 +0200128 .hard_max_record = 0,
Willy Tarreauef934602016-12-22 23:12:01 +0100129 .default_dh_param = SSL_DEFAULT_DH_PARAM,
130 .ctx_cache = DEFAULT_SSL_CTX_CACHE,
Marcin Deranek310a2602021-07-13 19:04:24 +0200131 .capture_buffer_size = 0,
William Lallemand3af48e72020-02-03 17:15:52 +0100132 .extra_files = SSL_GF_ALL,
William Lallemand8e8581e2020-10-20 17:36:46 +0200133 .extra_files_noext = 0,
William Lallemand722180a2021-06-09 16:46:12 +0200134#ifdef HAVE_SSL_KEYLOG
Remi Tricot-Le Breton58432372023-02-28 17:46:29 +0100135 .keylog = 0,
136#endif
137#ifndef OPENSSL_NO_OCSP
138 .ocsp_update.delay_max = SSL_OCSP_UPDATE_DELAY_MAX,
139 .ocsp_update.delay_min = SSL_OCSP_UPDATE_DELAY_MIN,
William Lallemand7d42ef52020-07-06 11:41:30 +0200140#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100141};
142
Olivier Houcharda8955d52019-04-07 22:00:38 +0200143static BIO_METHOD *ha_meth;
144
Willy Tarreaub8dec4a2022-06-23 11:02:08 +0200145DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx", sizeof(struct ssl_sock_ctx));
Olivier Houchard66ab4982019-02-26 18:37:15 +0100146
Willy Tarreaub8dec4a2022-06-23 11:02:08 +0200147DECLARE_STATIC_POOL(ssl_sock_client_sni_pool, "ssl_sock_client_sni", TLSEXT_MAXLEN_host_name + 1);
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100148
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100149/* ssl stats module */
150enum {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100151 SSL_ST_SESS,
152 SSL_ST_REUSED_SESS,
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100153 SSL_ST_FAILED_HANDSHAKE,
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100154
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100155 SSL_ST_STATS_COUNT /* must be the last member of the enum */
156};
157
158static struct name_desc ssl_stats[] = {
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100159 [SSL_ST_SESS] = { .name = "ssl_sess",
160 .desc = "Total number of ssl sessions established" },
161 [SSL_ST_REUSED_SESS] = { .name = "ssl_reused_sess",
162 .desc = "Total number of ssl sessions reused" },
163 [SSL_ST_FAILED_HANDSHAKE] = { .name = "ssl_failed_handshake",
164 .desc = "Total number of failed handshake" },
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100165};
166
167static struct ssl_counters {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100168 long long sess;
169 long long reused_sess;
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100170 long long failed_handshake;
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100171} ssl_counters;
172
173static void ssl_fill_stats(void *data, struct field *stats)
174{
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100175 struct ssl_counters *counters = data;
176
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100177 stats[SSL_ST_SESS] = mkf_u64(FN_COUNTER, counters->sess);
178 stats[SSL_ST_REUSED_SESS] = mkf_u64(FN_COUNTER, counters->reused_sess);
179 stats[SSL_ST_FAILED_HANDSHAKE] = mkf_u64(FN_COUNTER, counters->failed_handshake);
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100180}
181
182static struct stats_module ssl_stats_module = {
183 .name = "ssl",
184 .fill_stats = ssl_fill_stats,
185 .stats = ssl_stats,
186 .stats_count = SSL_ST_STATS_COUNT,
187 .counters = &ssl_counters,
188 .counters_size = sizeof(ssl_counters),
189 .domain_flags = MK_STATS_PROXY_DOMAIN(STATS_PX_CAP_FE|STATS_PX_CAP_LI|STATS_PX_CAP_BE|STATS_PX_CAP_SRV),
190 .clearable = 1,
191};
192
193INITCALL1(STG_REGISTER, stats_register_module, &ssl_stats_module);
194
Willy Tarreaua9380522022-05-05 08:50:17 +0200195/* CLI context for "show tls-keys" */
196struct show_keys_ctx {
197 struct tls_keys_ref *next_ref; /* next reference to be dumped */
198 int names_only; /* non-zero = only show file names */
199 int next_index; /* next index to be dumped */
Willy Tarreaubd338642022-05-05 08:59:17 +0200200 int dump_entries; /* dump entries also */
Willy Tarreau9c5a38c2022-05-05 09:03:44 +0200201 enum {
202 SHOW_KEYS_INIT = 0,
203 SHOW_KEYS_LIST,
204 SHOW_KEYS_DONE,
205 } state; /* phase of the current dump */
Willy Tarreaua9380522022-05-05 08:50:17 +0200206};
207
Willy Tarreau691d5032021-01-20 14:55:01 +0100208/* ssl_sock_io_cb is exported to see it resolved in "show fd" */
Willy Tarreau144f84a2021-03-02 16:09:26 +0100209struct task *ssl_sock_io_cb(struct task *, void *, unsigned int);
Olivier Houchard000694c2019-05-23 14:45:12 +0200210static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
Olivier Houchardea8dd942019-05-20 14:02:16 +0200211
Olivier Houcharda8955d52019-04-07 22:00:38 +0200212/* Methods to implement OpenSSL BIO */
213static int ha_ssl_write(BIO *h, const char *buf, int num)
214{
215 struct buffer tmpbuf;
216 struct ssl_sock_ctx *ctx;
217 int ret;
218
219 ctx = BIO_get_data(h);
220 tmpbuf.size = num;
221 tmpbuf.area = (void *)(uintptr_t)buf;
222 tmpbuf.data = num;
223 tmpbuf.head = 0;
224 ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200225 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200226 BIO_set_retry_write(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200227 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200228 } else if (ret == 0)
229 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200230 return ret;
231}
232
233static int ha_ssl_gets(BIO *h, char *buf, int size)
234{
235
236 return 0;
237}
238
239static int ha_ssl_puts(BIO *h, const char *str)
240{
241
242 return ha_ssl_write(h, str, strlen(str));
243}
244
245static int ha_ssl_read(BIO *h, char *buf, int size)
246{
247 struct buffer tmpbuf;
248 struct ssl_sock_ctx *ctx;
249 int ret;
250
251 ctx = BIO_get_data(h);
252 tmpbuf.size = size;
253 tmpbuf.area = buf;
254 tmpbuf.data = 0;
255 tmpbuf.head = 0;
256 ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200257 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200258 BIO_set_retry_read(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200259 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200260 } else if (ret == 0)
261 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200262
263 return ret;
264}
265
266static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
267{
268 int ret = 0;
269 switch (cmd) {
270 case BIO_CTRL_DUP:
271 case BIO_CTRL_FLUSH:
272 ret = 1;
273 break;
274 }
275 return ret;
276}
277
278static int ha_ssl_new(BIO *h)
279{
280 BIO_set_init(h, 1);
281 BIO_set_data(h, NULL);
282 BIO_clear_flags(h, ~0);
283 return 1;
284}
285
286static int ha_ssl_free(BIO *data)
287{
288
289 return 1;
290}
291
292
Willy Tarreau5db847a2019-05-09 14:13:35 +0200293#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100294
Emeric Brun821bb9b2017-06-15 16:37:39 +0200295static HA_RWLOCK_T *ssl_rwlocks;
296
297
298unsigned long ssl_id_function(void)
299{
300 return (unsigned long)tid;
301}
302
303void ssl_locking_function(int mode, int n, const char * file, int line)
304{
305 if (mode & CRYPTO_LOCK) {
306 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100307 HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200308 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100309 HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200310 }
311 else {
312 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100313 HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200314 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100315 HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200316 }
317}
318
319static int ssl_locking_init(void)
320{
321 int i;
322
323 ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
324 if (!ssl_rwlocks)
325 return -1;
326
327 for (i = 0 ; i < CRYPTO_num_locks() ; i++)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100328 HA_RWLOCK_INIT(&ssl_rwlocks[i]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200329
330 CRYPTO_set_id_callback(ssl_id_function);
331 CRYPTO_set_locking_callback(ssl_locking_function);
332
333 return 0;
334}
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100335
Emeric Brun821bb9b2017-06-15 16:37:39 +0200336#endif
337
Willy Tarreauaf613e82020-06-05 08:40:51 +0200338__decl_thread(HA_SPINLOCK_T ckch_lock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200339
William Lallemandbc6ca7c2019-10-29 23:48:19 +0100340
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200341
342/* mimic what X509_STORE_load_locations do with store_ctx */
343static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
344{
Remi Tricot-Le Bretond75b99e2021-05-17 11:45:55 +0200345 X509_STORE *store = NULL;
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +0100346 struct cafile_entry *ca_e = ssl_store_get_cafile_entry(path, 0);
347 if (ca_e)
348 store = ca_e->ca_store;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200349 if (store_ctx && store) {
350 int i;
351 X509_OBJECT *obj;
352 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
353 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
354 obj = sk_X509_OBJECT_value(objs, i);
355 switch (X509_OBJECT_get_type(obj)) {
356 case X509_LU_X509:
357 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
358 break;
359 case X509_LU_CRL:
360 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
361 break;
362 default:
363 break;
364 }
365 }
366 return 1;
367 }
368 return 0;
369}
370
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500371/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200372static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
373{
374 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
375 return ssl_set_cert_crl_file(store_ctx, path);
376}
377
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200378/*
379 Extract CA_list from CA_file already in tree.
380 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
381 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
382*/
383static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
384{
385 struct ebmb_node *eb;
386 struct cafile_entry *ca_e;
387
388 eb = ebst_lookup(&cafile_tree, path);
389 if (!eb)
390 return NULL;
391 ca_e = ebmb_entry(eb, struct cafile_entry, node);
392
393 if (ca_e->ca_list == NULL) {
394 int i;
395 unsigned long key;
396 struct eb_root ca_name_tree = EB_ROOT;
397 struct eb64_node *node, *back;
398 struct {
399 struct eb64_node node;
400 X509_NAME *xname;
401 } *ca_name;
402 STACK_OF(X509_OBJECT) *objs;
403 STACK_OF(X509_NAME) *skn;
404 X509 *x;
405 X509_NAME *xn;
406
407 skn = sk_X509_NAME_new_null();
408 /* take x509 from cafile_tree */
409 objs = X509_STORE_get0_objects(ca_e->ca_store);
410 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
411 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
412 if (!x)
413 continue;
414 xn = X509_get_subject_name(x);
415 if (!xn)
416 continue;
417 /* Check for duplicates. */
418 key = X509_NAME_hash(xn);
419 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
420 node && ca_name == NULL;
421 node = eb64_next(node)) {
422 ca_name = container_of(node, typeof(*ca_name), node);
423 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
424 ca_name = NULL;
425 }
426 /* find a duplicate */
427 if (ca_name)
428 continue;
429 ca_name = calloc(1, sizeof *ca_name);
430 xn = X509_NAME_dup(xn);
431 if (!ca_name ||
432 !xn ||
433 !sk_X509_NAME_push(skn, xn)) {
434 free(ca_name);
435 X509_NAME_free(xn);
436 sk_X509_NAME_pop_free(skn, X509_NAME_free);
437 sk_X509_NAME_free(skn);
438 skn = NULL;
439 break;
440 }
441 ca_name->node.key = key;
442 ca_name->xname = xn;
443 eb64_insert(&ca_name_tree, &ca_name->node);
444 }
445 ca_e->ca_list = skn;
446 /* remove temporary ca_name tree */
447 node = eb64_first(&ca_name_tree);
448 while (node) {
449 ca_name = container_of(node, typeof(*ca_name), node);
450 back = eb64_next(node);
451 eb64_delete(node);
452 free(ca_name);
453 node = back;
454 }
455 }
456 return ca_e->ca_list;
457}
458
Willy Tarreauff882702021-04-10 17:23:00 +0200459struct pool_head *pool_head_ssl_capture __read_mostly = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200460int ssl_capture_ptr_index = -1;
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +0100461int ssl_app_data_index = -1;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +0100462#ifdef USE_QUIC
463int ssl_qc_app_data_index = -1;
464#endif /* USE_QUIC */
Willy Tarreauef934602016-12-22 23:12:01 +0100465
William Lallemand722180a2021-06-09 16:46:12 +0200466#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200467int ssl_keylog_index = -1;
Willy Tarreauff882702021-04-10 17:23:00 +0200468struct pool_head *pool_head_ssl_keylog __read_mostly = NULL;
469struct pool_head *pool_head_ssl_keylog_str __read_mostly = NULL;
William Lallemand7d42ef52020-07-06 11:41:30 +0200470#endif
471
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +0200472int ssl_client_crt_ref_index = -1;
473
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100474/* Used to store the client's SNI in case of ClientHello callback error */
475int ssl_client_sni_index = -1;
476
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200477#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
478struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
479#endif
480
William Lallemandd7bfbe22022-04-11 18:41:24 +0200481#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200482unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000483struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
484struct ssl_engine_list {
485 struct list list;
486 ENGINE *e;
487};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200488#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000489
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +0200490#ifdef HAVE_SSL_PROVIDERS
491struct list openssl_providers = LIST_HEAD_INIT(openssl_providers);
492struct ssl_provider_list {
493 struct list list;
494 OSSL_PROVIDER *provider;
495};
496#endif
497
Remi Gacogne8de54152014-07-15 11:36:40 +0200498#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200499static int ssl_dh_ptr_index = -1;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +0100500static HASSL_DH *global_dh = NULL;
501static HASSL_DH *local_dh_1024 = NULL;
502static HASSL_DH *local_dh_2048 = NULL;
503static HASSL_DH *local_dh_4096 = NULL;
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100504#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +0100505static DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100506#else
507static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey);
508#endif
Remi Gacogne8de54152014-07-15 11:36:40 +0200509#endif /* OPENSSL_NO_DH */
510
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100511#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200512/* X509V3 Extensions that will be added on generated certificates */
513#define X509V3_EXT_SIZE 5
514static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
515 "basicConstraints",
516 "nsComment",
517 "subjectKeyIdentifier",
518 "authorityKeyIdentifier",
519 "keyUsage",
520};
521static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
522 "CA:FALSE",
523 "\"OpenSSL Generated Certificate\"",
524 "hash",
525 "keyid,issuer:always",
526 "nonRepudiation,digitalSignature,keyEncipherment"
527};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200528/* LRU cache to store generated certificate */
529static struct lru64_head *ssl_ctx_lru_tree = NULL;
530static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200531static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100532__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200533
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200534#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
535
yanbzhube2774d2015-12-10 15:07:30 -0500536/* The order here matters for picking a default context,
537 * keep the most common keytype at the bottom of the list
538 */
539const char *SSL_SOCK_KEYTYPE_NAMES[] = {
540 "dsa",
541 "ecdsa",
542 "rsa"
543};
yanbzhube2774d2015-12-10 15:07:30 -0500544
William Lallemandc3cd35f2017-11-28 11:04:43 +0100545static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100546static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
547
Dragan Dosen9ac98092020-05-11 15:51:45 +0200548/* Dedicated callback functions for heartbeat and clienthello.
549 */
550#ifdef TLS1_RT_HEARTBEAT
551static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
552 int content_type, const void *buf, size_t len,
553 SSL *ssl);
554#endif
555static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
556 int content_type, const void *buf, size_t len,
557 SSL *ssl);
558
William Lallemand722180a2021-06-09 16:46:12 +0200559#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200560static void ssl_init_keylog(struct connection *conn, int write_p, int version,
561 int content_type, const void *buf, size_t len,
562 SSL *ssl);
563#endif
564
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200565/* List head of all registered SSL/TLS protocol message callbacks. */
566struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
567
568/* Registers the function <func> in order to be called on SSL/TLS protocol
569 * message processing. It will return 0 if the function <func> is not set
570 * or if it fails to allocate memory.
571 */
572int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
573{
574 struct ssl_sock_msg_callback *cbk;
575
576 if (!func)
577 return 0;
578
579 cbk = calloc(1, sizeof(*cbk));
580 if (!cbk) {
581 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
582 return 0;
583 }
584
585 cbk->func = func;
586
Willy Tarreau2b718102021-04-21 07:32:39 +0200587 LIST_APPEND(&ssl_sock_msg_callbacks, &cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200588
589 return 1;
590}
591
Dragan Dosen9ac98092020-05-11 15:51:45 +0200592/* Used to register dedicated SSL/TLS protocol message callbacks.
593 */
594static int ssl_sock_register_msg_callbacks(void)
595{
596#ifdef TLS1_RT_HEARTBEAT
597 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
598 return ERR_ABORT;
599#endif
Marcin Deranek310a2602021-07-13 19:04:24 +0200600 if (global_ssl.capture_buffer_size > 0) {
Dragan Dosen9ac98092020-05-11 15:51:45 +0200601 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
602 return ERR_ABORT;
603 }
William Lallemand722180a2021-06-09 16:46:12 +0200604#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200605 if (global_ssl.keylog > 0) {
606 if (!ssl_sock_register_msg_callback(ssl_init_keylog))
607 return ERR_ABORT;
608 }
609#endif
610
Christopher Fauletfc633b62020-11-06 15:24:23 +0100611 return ERR_NONE;
Dragan Dosen9ac98092020-05-11 15:51:45 +0200612}
613
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200614/* Used to free all SSL/TLS protocol message callbacks that were
615 * registered by using ssl_sock_register_msg_callback().
616 */
617static void ssl_sock_unregister_msg_callbacks(void)
618{
619 struct ssl_sock_msg_callback *cbk, *cbkback;
620
621 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +0200622 LIST_DELETE(&cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200623 free(cbk);
624 }
625}
626
Willy Tarreaude827952022-04-11 10:43:28 +0200627static struct ssl_sock_ctx *ssl_sock_get_ctx(struct connection *conn)
628{
629 if (!conn || conn->xprt != xprt_get(XPRT_SSL) || !conn->xprt_ctx)
630 return NULL;
631
632 return (struct ssl_sock_ctx *)conn->xprt_ctx;
633}
634
Dragan Doseneb607fe2020-05-11 17:17:06 +0200635SSL *ssl_sock_get_ssl_object(struct connection *conn)
636{
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200637 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dragan Doseneb607fe2020-05-11 17:17:06 +0200638
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200639 return ctx ? ctx->ssl : NULL;
Dragan Doseneb607fe2020-05-11 17:17:06 +0200640}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100641/*
642 * This function gives the detail of the SSL error. It is used only
643 * if the debug mode and the verbose mode are activated. It dump all
644 * the SSL error until the stack was empty.
645 */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +0200646static forceinline void ssl_sock_dump_errors(struct connection *conn,
647 struct quic_conn *qc)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100648{
649 unsigned long ret;
650
651 if (unlikely(global.mode & MODE_DEBUG)) {
652 while(1) {
Remi Tricot-Le Breton1effd9a2022-02-11 12:04:44 +0100653 const char *func = NULL;
654 ERR_peek_error_func(&func);
655
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100656 ret = ERR_get_error();
657 if (ret == 0)
658 return;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +0200659 if (conn) {
660 fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
661 conn_fd(conn), ret,
662 func, ERR_reason_error_string(ret));
663 }
664#ifdef USE_QUIC
665 else {
666 /* TODO: we are not sure <conn> is always initialized for QUIC connections */
667 fprintf(stderr, "qc @%p OpenSSL error[0x%lx] %s: %s\n", qc, ret,
668 func, ERR_reason_error_string(ret));
669 }
670#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100671 }
672 }
673}
674
yanbzhube2774d2015-12-10 15:07:30 -0500675
William Lallemandd7bfbe22022-04-11 18:41:24 +0200676#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200677int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000678{
679 int err_code = ERR_ABORT;
680 ENGINE *engine;
681 struct ssl_engine_list *el;
682
683 /* grab the structural reference to the engine */
684 engine = ENGINE_by_id(engine_id);
685 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100686 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000687 goto fail_get;
688 }
689
690 if (!ENGINE_init(engine)) {
691 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100692 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000693 goto fail_init;
694 }
695
696 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100697 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000698 goto fail_set_method;
699 }
700
701 el = calloc(1, sizeof(*el));
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200702 if (!el)
703 goto fail_alloc;
Grant Zhang872f9c22017-01-21 01:10:18 +0000704 el->e = engine;
Willy Tarreau2b718102021-04-21 07:32:39 +0200705 LIST_INSERT(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100706 nb_engines++;
707 if (global_ssl.async)
708 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000709 return 0;
710
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200711fail_alloc:
Grant Zhang872f9c22017-01-21 01:10:18 +0000712fail_set_method:
713 /* release the functional reference from ENGINE_init() */
714 ENGINE_finish(engine);
715
716fail_init:
717 /* release the structural reference from ENGINE_by_id() */
718 ENGINE_free(engine);
719
720fail_get:
721 return err_code;
722}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200723#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000724
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +0200725#ifdef HAVE_SSL_PROVIDERS
726int ssl_init_provider(const char *provider_name)
727{
728 int err_code = ERR_ABORT;
729 struct ssl_provider_list *prov = NULL;
730
731 prov = calloc(1, sizeof(*prov));
732 if (!prov) {
733 ha_alert("ssl-provider %s: memory allocation failure\n", provider_name);
734 goto error;
735 }
736
737 if ((prov->provider = OSSL_PROVIDER_load(NULL, provider_name)) == NULL) {
738 ha_alert("ssl-provider %s: unknown provider\n", provider_name);
739 goto error;
740 }
741
742 LIST_INSERT(&openssl_providers, &prov->list);
743
744 return 0;
745
746error:
747 ha_free(&prov);
748 return err_code;
749}
750#endif /* HAVE_SSL_PROVIDERS */
751
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +0500752#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +0200753/*
754 * openssl async fd handler
755 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200756void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000757{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200758 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000759
Emeric Brun3854e012017-05-17 20:42:48 +0200760 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000761 * to poll this fd until it is requested
762 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000763 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000764 fd_cant_recv(fd);
765
766 /* crypto engine is available, let's notify the associated
767 * connection that it can pursue its processing.
768 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200769 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000770}
771
Emeric Brun3854e012017-05-17 20:42:48 +0200772/*
773 * openssl async delayed SSL_free handler
774 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200775void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000776{
777 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200778 OSSL_ASYNC_FD all_fd[32];
779 size_t num_all_fds = 0;
780 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000781
Emeric Brun3854e012017-05-17 20:42:48 +0200782 /* We suppose that the async job for a same SSL *
783 * are serialized. So if we are awake it is
784 * because the running job has just finished
785 * and we can remove all async fds safely
786 */
787 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
788 if (num_all_fds > 32) {
789 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
790 return;
791 }
792
793 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
Emeric Brun7d392a52022-07-01 17:36:50 +0200794 for (i=0 ; i < num_all_fds ; i++) {
795 /* We want to remove the fd from the fdtab
796 * but we flag it to disown because the
797 * close is performed by the engine itself
798 */
799 fdtab[all_fd[i]].state |= FD_DISOWN;
800 fd_delete(all_fd[i]);
801 }
Emeric Brun3854e012017-05-17 20:42:48 +0200802
803 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000804 SSL_free(ssl);
Willy Tarreau82531f62021-10-06 12:15:18 +0200805 _HA_ATOMIC_DEC(&global.sslconns);
Willy Tarreau4781b152021-04-06 13:53:36 +0200806 _HA_ATOMIC_DEC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000807}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000808/*
Emeric Brun3854e012017-05-17 20:42:48 +0200809 * function used to manage a returned SSL_ERROR_WANT_ASYNC
810 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000811 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200812static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000813{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100814 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200815 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200816 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000817 size_t num_add_fds = 0;
818 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200819 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000820
821 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
822 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200823 if (num_add_fds > 32 || num_del_fds > 32) {
824 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 +0000825 return;
826 }
827
Emeric Brun3854e012017-05-17 20:42:48 +0200828 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000829
Emeric Brun3854e012017-05-17 20:42:48 +0200830 /* We remove unused fds from the fdtab */
Emeric Brun7d392a52022-07-01 17:36:50 +0200831 for (i=0 ; i < num_del_fds ; i++) {
832 /* We want to remove the fd from the fdtab
833 * but we flag it to disown because the
834 * close is performed by the engine itself
835 */
836 fdtab[del_fd[i]].state |= FD_DISOWN;
837 fd_delete(del_fd[i]);
838 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000839
Emeric Brun3854e012017-05-17 20:42:48 +0200840 /* We add new fds to the fdtab */
841 for (i=0 ; i < num_add_fds ; i++) {
Willy Tarreau27a32452022-07-07 08:29:00 +0200842 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tgid, ti->ltid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000843 }
844
Emeric Brun3854e012017-05-17 20:42:48 +0200845 num_add_fds = 0;
846 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
847 if (num_add_fds > 32) {
848 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
849 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000850 }
Emeric Brun3854e012017-05-17 20:42:48 +0200851
852 /* We activate the polling for all known async fds */
853 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000854 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200855 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000856 /* To ensure that the fd cache won't be used
857 * We'll prefer to catch a real RD event
858 * because handling an EAGAIN on this fd will
859 * result in a context switch and also
860 * some engines uses a fd in blocking mode.
861 */
862 fd_cant_recv(add_fd[i]);
863 }
Emeric Brun3854e012017-05-17 20:42:48 +0200864
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000865}
866#endif
867
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100868
869/*
870 * Initialize an HMAC context <hctx> using the <key> and <md> parameters.
871 * Returns -1 in case of error, 1 otherwise.
872 */
873static int ssl_hmac_init(MAC_CTX *hctx, unsigned char *key, int key_len, const EVP_MD *md)
874{
875#ifdef HAVE_OSSL_PARAM
876 OSSL_PARAM params[3];
877
878 params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, key, key_len);
879 params[1] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, (char*)EVP_MD_name(md), 0);
880 params[2] = OSSL_PARAM_construct_end();
881 if (EVP_MAC_CTX_set_params(hctx, params) == 0)
882 return -1; /* error in mac initialisation */
883
884#else
885 HMAC_Init_ex(hctx, key, key_len, md, NULL);
886#endif
887 return 1;
888}
889
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100890#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +0100891
892static 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 +0100893{
Frédéric Lécaille6aec1f32022-09-06 17:04:55 +0200894 struct tls_keys_ref *ref = NULL;
Emeric Brun9e754772019-01-10 17:51:55 +0100895 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100896 int head;
897 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +0100898 int ret = -1; /* error by default */
Frédéric Lécaille6aec1f32022-09-06 17:04:55 +0200899 struct connection *conn = SSL_get_ex_data(s, ssl_app_data_index);
900#ifdef USE_QUIC
901 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
902#endif
903
904 if (conn)
905 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
906#ifdef USE_QUIC
907 else if (qc)
908 ref = qc->li->bind_conf->keys_ref;
909#endif
910
911 if (!ref) {
912 /* must never happen */
913 ABORT_NOW();
914 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100915
Christopher Faulet16f45c82018-02-16 11:23:49 +0100916 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
917
918 keys = ref->tlskeys;
919 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100920
921 if (enc) {
922 memcpy(key_name, keys[head].name, 16);
923
924 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +0100925 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100926
Emeric Brun9e754772019-01-10 17:51:55 +0100927 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100928
Emeric Brun9e754772019-01-10 17:51:55 +0100929 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
930 goto end;
931
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100932 if (ssl_hmac_init(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
933 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100934 ret = 1;
935 }
936 else if (ref->key_size_bits == 256 ) {
937
938 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
939 goto end;
940
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100941 if (ssl_hmac_init(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
942 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100943 ret = 1;
944 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100945 } else {
946 for (i = 0; i < TLS_TICKETS_NO; i++) {
947 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
948 goto found;
949 }
Christopher Faulet16f45c82018-02-16 11:23:49 +0100950 ret = 0;
951 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100952
Christopher Faulet16f45c82018-02-16 11:23:49 +0100953 found:
Emeric Brun9e754772019-01-10 17:51:55 +0100954 if (ref->key_size_bits == 128) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100955 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
956 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100957 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
958 goto end;
959 /* 2 for key renewal, 1 if current key is still valid */
960 ret = i ? 2 : 1;
961 }
962 else if (ref->key_size_bits == 256) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100963 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
964 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100965 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
966 goto end;
967 /* 2 for key renewal, 1 if current key is still valid */
968 ret = i ? 2 : 1;
969 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100970 }
Emeric Brun9e754772019-01-10 17:51:55 +0100971
Christopher Faulet16f45c82018-02-16 11:23:49 +0100972 end:
973 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
974 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200975}
976
977struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
978{
979 struct tls_keys_ref *ref;
980
981 list_for_each_entry(ref, &tlskeys_reference, list)
982 if (ref->filename && strcmp(filename, ref->filename) == 0)
983 return ref;
984 return NULL;
985}
986
987struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
988{
989 struct tls_keys_ref *ref;
990
991 list_for_each_entry(ref, &tlskeys_reference, list)
992 if (ref->unique_id == unique_id)
993 return ref;
994 return NULL;
995}
996
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500997/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +0100998 * match existing ones, this function returns -1
999 * else it returns 0 on success.
1000 */
1001int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001002 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001003{
Emeric Brun9e754772019-01-10 17:51:55 +01001004 if (ref->key_size_bits == 128) {
1005 if (tlskey->data != sizeof(struct tls_sess_key_128))
1006 return -1;
1007 }
1008 else if (ref->key_size_bits == 256) {
1009 if (tlskey->data != sizeof(struct tls_sess_key_256))
1010 return -1;
1011 }
1012 else
1013 return -1;
1014
Christopher Faulet16f45c82018-02-16 11:23:49 +01001015 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001016 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1017 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001018 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1019 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001020
1021 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001022}
1023
Willy Tarreau83061a82018-07-13 11:56:34 +02001024int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001025{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001026 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1027
1028 if(!ref) {
1029 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1030 return 1;
1031 }
Emeric Brun9e754772019-01-10 17:51:55 +01001032 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1033 memprintf(err, "Invalid key size");
1034 return 1;
1035 }
1036
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001037 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001038}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001039
1040/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001041 * automatic ids. It's called just after the basic checks. It returns
1042 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001043 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001044static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001045{
1046 int i = 0;
1047 struct tls_keys_ref *ref, *ref2, *ref3;
1048 struct list tkr = LIST_HEAD_INIT(tkr);
1049
1050 list_for_each_entry(ref, &tlskeys_reference, list) {
1051 if (ref->unique_id == -1) {
1052 /* Look for the first free id. */
1053 while (1) {
1054 list_for_each_entry(ref2, &tlskeys_reference, list) {
1055 if (ref2->unique_id == i) {
1056 i++;
1057 break;
1058 }
1059 }
1060 if (&ref2->list == &tlskeys_reference)
1061 break;
1062 }
1063
1064 /* Uses the unique id and increment it for the next entry. */
1065 ref->unique_id = i;
1066 i++;
1067 }
1068 }
1069
1070 /* This sort the reference list by id. */
1071 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001072 LIST_DELETE(&ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001073 list_for_each_entry(ref3, &tkr, list) {
1074 if (ref->unique_id < ref3->unique_id) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001075 LIST_APPEND(&ref3->list, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001076 break;
1077 }
1078 }
1079 if (&ref3->list == &tkr)
Willy Tarreau2b718102021-04-21 07:32:39 +02001080 LIST_APPEND(&tkr, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001081 }
1082
1083 /* swap root */
Willy Tarreau2b718102021-04-21 07:32:39 +02001084 LIST_INSERT(&tkr, &tlskeys_reference);
1085 LIST_DELETE(&tkr);
Christopher Fauletfc633b62020-11-06 15:24:23 +01001086 return ERR_NONE;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001087}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001088#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1089
William Lallemand4a660132019-10-14 14:51:41 +02001090
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001091#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001092/*
1093 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001094 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1095 * status extension, the issuer's certificate is mandatory. It should be
1096 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001097 *
William Lallemand246c0242019-10-11 08:59:13 +02001098 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1099 * OCSP response. If file is empty or content is not a valid OCSP response,
1100 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1101 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001102 *
1103 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001104 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001105 */
Remi Tricot-Le Breton0c96ee42023-03-01 16:11:50 +01001106static int ssl_sock_load_ocsp(const char *path, SSL_CTX *ctx, struct ckch_data *data, STACK_OF(X509) *chain)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001107{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001108 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001109 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001110 struct certificate_ocsp *ocsp = NULL, *iocsp;
1111 char *warn = NULL;
1112 unsigned char *p;
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01001113#ifndef USE_OPENSSL_WOLFSSL
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001114 void (*callback) (void);
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01001115#else
1116 tlsextStatusCb callback;
1117#endif
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001118 struct buffer *ocsp_uri = get_trash_chunk();
Emeric Brun4147b2e2014-06-16 18:36:30 +02001119
Emeric Brun4147b2e2014-06-16 18:36:30 +02001120
William Lallemand52ddd992022-11-22 11:51:53 +01001121 x = data->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001122 if (!x)
1123 goto out;
1124
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001125 if (data->ocsp_update_mode == SSL_SOCK_OCSP_UPDATE_ON) {
1126 ssl_ocsp_get_uri_from_cert(x, ocsp_uri, NULL);
1127 /* We should have an "OCSP URI" field in order for auto update to work. */
1128 if (b_data(ocsp_uri) == 0)
1129 goto out;
1130 }
1131
1132 /* In case of ocsp update mode set to 'on', this function might be
1133 * called with no known ocsp response. If no ocsp uri can be found in
1134 * the certificate, nothing needs to be done here. */
1135 if (!data->ocsp_response) {
1136 if (data->ocsp_update_mode != SSL_SOCK_OCSP_UPDATE_ON || b_data(ocsp_uri) == 0) {
1137 ret = 0;
1138 goto out;
1139 }
1140 }
1141
William Lallemand52ddd992022-11-22 11:51:53 +01001142 issuer = data->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001143 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1144 if (chain) {
1145 /* check if one of the certificate of the chain is the issuer */
1146 for (i = 0; i < sk_X509_num(chain); i++) {
1147 X509 *ti = sk_X509_value(chain, i);
1148 if (X509_check_issued(ti, x) == X509_V_OK) {
1149 issuer = ti;
1150 break;
1151 }
1152 }
1153 }
William Lallemand246c0242019-10-11 08:59:13 +02001154 if (!issuer)
1155 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001156
Remi Tricot-Le Breton2d1daa82023-01-09 12:02:47 +01001157 if (!data->ocsp_cid)
1158 data->ocsp_cid = OCSP_cert_to_id(0, x, issuer);
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001159 if (!data->ocsp_cid)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001160 goto out;
1161
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001162 i = i2d_OCSP_CERTID(data->ocsp_cid, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001163 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1164 goto out;
1165
Remi Tricot-Le Breton0c96ee42023-03-01 16:11:50 +01001166 ocsp = calloc(1, sizeof(*ocsp)+strlen(path)+1);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001167 if (!ocsp)
1168 goto out;
1169
1170 p = ocsp->key_data;
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001171 ocsp->key_length = i2d_OCSP_CERTID(data->ocsp_cid, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001172
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001173 HA_SPIN_LOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001174 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1175 if (iocsp == ocsp)
1176 ocsp = NULL;
1177
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001178#ifndef SSL_CTX_get_tlsext_status_cb
1179# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1180 *cb = (void (*) (void))ctx->tlsext_status_cb;
1181#endif
1182 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1183
1184 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001185 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001186 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001187
William Lallemanda560c062020-07-31 11:43:20 +02001188 cb_arg = calloc(1, sizeof(*cb_arg));
1189 if (!cb_arg)
1190 goto out;
1191
yanbzhube2774d2015-12-10 15:07:30 -05001192 cb_arg->is_single = 1;
1193 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001194 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001195
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001196 pkey = X509_get_pubkey(x);
1197 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1198 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001199
1200 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001201 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 */
1202
yanbzhube2774d2015-12-10 15:07:30 -05001203 } else {
1204 /*
1205 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1206 * Update that cb_arg with the new cert's staple
1207 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001208 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001209 struct certificate_ocsp *tmp_ocsp;
1210 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001211 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001212 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001213
William Lallemand76b4a122020-08-04 17:41:39 +02001214 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001215
1216 /*
1217 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1218 * the order of operations below matter, take care when changing it
1219 */
1220 tmp_ocsp = cb_arg->s_ocsp;
1221 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1222 cb_arg->s_ocsp = NULL;
1223 cb_arg->m_ocsp[index] = tmp_ocsp;
1224 cb_arg->is_single = 0;
1225 cb_arg->single_kt = 0;
1226
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001227 pkey = X509_get_pubkey(x);
1228 key_type = EVP_PKEY_base_id(pkey);
1229 EVP_PKEY_free(pkey);
1230
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001231 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001232 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001233 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001234 iocsp->refcount++;
1235 }
yanbzhube2774d2015-12-10 15:07:30 -05001236 }
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001237 HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001238
1239 ret = 0;
1240
1241 warn = NULL;
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001242 if (data->ocsp_response && ssl_sock_load_ocsp_response(data->ocsp_response, iocsp, data->ocsp_cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001243 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001244 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001245 }
1246
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001247 if (data->ocsp_update_mode == SSL_SOCK_OCSP_UPDATE_ON) {
1248
1249 /* Do not insert the same certificate_ocsp structure in the
1250 * update tree more than once. */
1251 if (!ocsp) {
Remi Tricot-Le Breton112b16a2023-01-09 12:02:44 +01001252 /* Issuer certificate is not included in the certificate
1253 * chain, it will have to be treated separately during
1254 * ocsp response validation. */
1255 if (issuer == data->ocsp_issuer) {
1256 iocsp->issuer = issuer;
1257 X509_up_ref(issuer);
1258 }
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001259 if (data->chain)
1260 iocsp->chain = X509_chain_up_ref(data->chain);
1261
Remi Tricot-Le Breton648c83e2023-01-09 12:02:48 +01001262 iocsp->uri = calloc(1, sizeof(*iocsp->uri));
1263 if (!chunk_dup(iocsp->uri, ocsp_uri)) {
1264 ha_free(&iocsp->uri);
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001265 goto out;
Remi Tricot-Le Breton648c83e2023-01-09 12:02:48 +01001266 }
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001267
Remi Tricot-Le Breton0c96ee42023-03-01 16:11:50 +01001268 strcpy(iocsp->path, path);
1269
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001270 ssl_ocsp_update_insert(iocsp);
Remi Tricot-Le Breton86d1e0b2023-03-02 15:49:53 +01001271 /* If we are during init the update task is not
1272 * scheduled yet so a wakeup won't do anything.
1273 * Otherwise, if the OCSP was added through the CLI, we
1274 * wake the task up to manage the case of a new entry
1275 * that needs to be updated before the previous first
1276 * entry.
1277 */
1278 if (ocsp_update_task)
1279 task_wakeup(ocsp_update_task, TASK_WOKEN_MSG);
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001280 }
1281 }
1282
Emeric Brun4147b2e2014-06-16 18:36:30 +02001283out:
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001284 if (ret && data->ocsp_cid)
1285 OCSP_CERTID_free(data->ocsp_cid);
1286
1287 if (!ret && data->ocsp_response) {
1288 ha_free(&data->ocsp_response->area);
1289 ha_free(&data->ocsp_response);
1290 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001291
1292 if (ocsp)
Remi Tricot-Le Bretonaa529f72022-11-03 15:16:49 +01001293 ssl_sock_free_ocsp(ocsp);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001294
1295 if (warn)
1296 free(warn);
1297
Emeric Brun4147b2e2014-06-16 18:36:30 +02001298 return ret;
1299}
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01001300
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001301#endif
1302
1303#ifdef OPENSSL_IS_BORINGSSL
Remi Tricot-Le Breton0c96ee42023-03-01 16:11:50 +01001304static int ssl_sock_load_ocsp(const char *path, SSL_CTX *ctx, struct ckch_data *data, STACK_OF(X509) *chain)
Emmanuel Hocdet2c32d8f2017-05-22 14:58:00 +02001305{
William Lallemand4a660132019-10-14 14:51:41 +02001306 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 +02001307}
1308#endif
1309
William Lallemand4a660132019-10-14 14:51:41 +02001310
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001311#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001312
1313#define CT_EXTENSION_TYPE 18
1314
William Lallemand03c331c2020-05-13 10:10:01 +02001315int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001316
1317int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1318{
Willy Tarreau83061a82018-07-13 11:56:34 +02001319 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001320
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001321 *out = (unsigned char *) sctl->area;
1322 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001323
1324 return 1;
1325}
1326
1327int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1328{
1329 return 1;
1330}
1331
William Lallemanda17f4112019-10-10 15:16:44 +02001332static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001333{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001334 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001335
William Lallemanda17f4112019-10-10 15:16:44 +02001336 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 +01001337 goto out;
1338
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001339 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1340
1341 ret = 0;
1342
1343out:
1344 return ret;
1345}
1346
1347#endif
1348
Emeric Brune1f38db2012-09-03 20:36:47 +02001349void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1350{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001351 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001352#ifdef USE_QUIC
1353 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1354#endif /* USE_QUIC */
1355 struct ssl_sock_ctx *ctx = NULL;
1356
Emeric Brund8b2bb52014-01-28 15:43:53 +01001357 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001358 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001359
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001360 if (conn)
Willy Tarreau939b0bf2022-04-11 11:29:11 +02001361 ctx = conn_get_ssl_sock_ctx(conn);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001362#ifdef USE_QUIC
1363 else if (qc)
1364 ctx = qc->xprt_ctx;
1365#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01001366
1367 if (!ctx) {
1368 /* must never happen */
1369 ABORT_NOW();
1370 return;
1371 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001372
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001373#ifndef SSL_OP_NO_RENEGOTIATION
1374 /* Please note that BoringSSL defines this macro to zero so don't
1375 * change this to #if and do not assign a default value to this macro!
1376 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001377 if (where & SSL_CB_HANDSHAKE_START) {
1378 /* Disable renegotiation (CVE-2009-3555) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001379 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 +02001380 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001381 conn->err_code = CO_ER_SSL_RENEG;
1382 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001383 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001384#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001385
1386 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001387 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001388 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001389 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001390 consider that the buffering was activated,
1391 so we rise the output buffer size from 4k
1392 to 16k */
1393 write_bio = SSL_get_wbio(ssl);
1394 if (write_bio != SSL_get_rbio(ssl)) {
1395 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001396 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001397 }
1398 }
1399 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001400}
1401
Emeric Brune64aef12012-09-21 13:15:06 +02001402/* Callback is called for each certificate of the chain during a verify
1403 ok is set to 1 if preverify detect no error on current certificate.
1404 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001405int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001406{
1407 SSL *ssl;
1408 struct connection *conn;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001409 struct ssl_sock_ctx *ctx = NULL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001410 int err, depth;
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001411 X509 *client_crt;
1412 STACK_OF(X509) *certs;
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001413 struct bind_conf *bind_conf = NULL;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001414 struct quic_conn *qc = NULL;
Emeric Brune64aef12012-09-21 13:15:06 +02001415
1416 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001417 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001418 client_crt = SSL_get_ex_data(ssl, ssl_client_crt_ref_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001419
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001420 if (conn) {
1421 bind_conf = __objt_listener(conn->target)->bind_conf;
1422 ctx = __conn_get_ssl_sock_ctx(conn);
1423 }
1424#ifdef USE_QUIC
1425 else {
1426 qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
Amaury Denoyelleba303de2022-10-17 18:46:49 +02001427 BUG_ON(!qc); /* Must never happen */
1428 bind_conf = qc->li->bind_conf;
1429 ctx = qc->xprt_ctx;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001430 }
1431#endif
1432
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001433 BUG_ON(!ctx || !bind_conf);
Christopher Faulet881cce92022-11-23 09:27:13 +01001434 ALREADY_CHECKED(ctx);
1435 ALREADY_CHECKED(bind_conf);
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001436
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001437 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001438
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001439 depth = X509_STORE_CTX_get_error_depth(x_store);
1440 err = X509_STORE_CTX_get_error(x_store);
1441
Emeric Brun81c00f02012-09-21 14:31:21 +02001442 if (ok) /* no errors */
1443 return ok;
1444
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001445 /* Keep a reference to the client's certificate in order to be able to
1446 * dump some fetches values in a log even when the verification process
1447 * fails. */
1448 if (depth == 0) {
1449 X509_free(client_crt);
1450 client_crt = X509_STORE_CTX_get0_cert(x_store);
1451 if (client_crt) {
1452 X509_up_ref(client_crt);
1453 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
1454 }
1455 }
1456 else {
1457 /* An error occurred on a CA certificate of the certificate
1458 * chain, we might never call this verify callback on the client
1459 * certificate's depth (which is 0) so we try to store the
1460 * reference right now. */
Remi Tricot-Le Bretonf95c2952021-08-20 09:51:23 +02001461 certs = X509_STORE_CTX_get1_chain(x_store);
1462 if (certs) {
1463 client_crt = sk_X509_value(certs, 0);
1464 if (client_crt) {
1465 X509_up_ref(client_crt);
1466 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001467 }
1468 sk_X509_pop_free(certs, X509_free);
1469 }
1470 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001471
1472 /* check if CA error needs to be ignored */
1473 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001474 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1475 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1476 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001477 }
1478
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01001479 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01001480 cert_ignerr_bitfield_get(bind_conf->ca_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001481 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02001482
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001483 /* TODO: for QUIC connection, this error code is lost */
1484 if (conn)
1485 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001486 return 0;
1487 }
1488
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001489 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1490 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001491
Emeric Brun81c00f02012-09-21 14:31:21 +02001492 /* check if certificate error needs to be ignored */
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01001493 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01001494 cert_ignerr_bitfield_get(bind_conf->crt_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001495 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02001496
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001497 /* TODO: for QUIC connection, this error code is lost */
1498 if (conn)
1499 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001500 return 0;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001501
1502 err_ignored:
1503 ssl_sock_dump_errors(conn, qc);
1504 ERR_clear_error();
1505 return 1;
Emeric Brune64aef12012-09-21 13:15:06 +02001506}
1507
Dragan Dosen9ac98092020-05-11 15:51:45 +02001508#ifdef TLS1_RT_HEARTBEAT
1509static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1510 int content_type, const void *buf, size_t len,
1511 SSL *ssl)
1512{
1513 /* test heartbeat received (write_p is set to 0
1514 for a received record) */
1515 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02001516 struct ssl_sock_ctx *ctx = __conn_get_ssl_sock_ctx(conn);
Dragan Dosen9ac98092020-05-11 15:51:45 +02001517 const unsigned char *p = buf;
1518 unsigned int payload;
1519
1520 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1521
1522 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1523 if (*p != TLS1_HB_REQUEST)
1524 return;
1525
1526 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1527 goto kill_it;
1528
1529 payload = (p[1] * 256) + p[2];
1530 if (3 + payload + 16 <= len)
1531 return; /* OK no problem */
1532 kill_it:
1533 /* We have a clear heartbleed attack (CVE-2014-0160), the
1534 * advertised payload is larger than the advertised packet
1535 * length, so we have garbage in the buffer between the
1536 * payload and the end of the buffer (p+len). We can't know
1537 * if the SSL stack is patched, and we don't know if we can
1538 * safely wipe out the area between p+3+len and payload.
1539 * So instead, we prevent the response from being sent by
1540 * setting the max_send_fragment to 0 and we report an SSL
1541 * error, which will kill this connection. It will be reported
1542 * above as SSL_ERROR_SSL while an other handshake failure with
1543 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1544 */
1545 ssl->max_send_fragment = 0;
1546 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1547 }
1548}
1549#endif
1550
1551static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1552 int content_type, const void *buf, size_t len,
1553 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001554{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001555 struct ssl_capture *capture;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001556 uchar *msg;
1557 uchar *end;
1558 uchar *extensions_end;
1559 uchar *ec_start = NULL;
1560 uchar *ec_formats_start = NULL;
1561 uchar *list_end;
1562 ushort protocol_version;
1563 ushort extension_id;
1564 ushort ec_len = 0;
1565 uchar ec_formats_len = 0;
1566 int offset = 0;
1567 int rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001568
1569 /* This function is called for "from client" and "to server"
1570 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001571 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001572 */
1573
1574 /* "write_p" is set to 0 is the bytes are received messages,
1575 * otherwise it is set to 1.
1576 */
1577 if (write_p != 0)
1578 return;
1579
1580 /* content_type contains the type of message received or sent
1581 * according with the SSL/TLS protocol spec. This message is
1582 * encoded with one byte. The value 256 (two bytes) is used
1583 * for designing the SSL/TLS record layer. According with the
1584 * rfc6101, the expected message (other than 256) are:
1585 * - change_cipher_spec(20)
1586 * - alert(21)
1587 * - handshake(22)
1588 * - application_data(23)
1589 * - (255)
1590 * We are interessed by the handshake and specially the client
1591 * hello.
1592 */
1593 if (content_type != 22)
1594 return;
1595
1596 /* The message length is at least 4 bytes, containing the
1597 * message type and the message length.
1598 */
1599 if (len < 4)
1600 return;
1601
1602 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001603 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001604 * - hello_request(0)
1605 * - client_hello(1)
1606 * - server_hello(2)
1607 * - certificate(11)
1608 * - server_key_exchange (12)
1609 * - certificate_request(13)
1610 * - server_hello_done(14)
1611 * We are interested by the client hello.
1612 */
1613 msg = (unsigned char *)buf;
1614 if (msg[0] != 1)
1615 return;
1616
1617 /* Next three bytes are the length of the message. The total length
1618 * must be this decoded length + 4. If the length given as argument
1619 * is not the same, we abort the protocol dissector.
1620 */
1621 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1622 if (len < rec_len + 4)
1623 return;
1624 msg += 4;
1625 end = msg + rec_len;
1626 if (end < msg)
1627 return;
1628
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001629 /* Expect 2 bytes for protocol version
1630 * (1 byte for major and 1 byte for minor)
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001631 */
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001632 if (msg + 2 > end)
1633 return;
1634 protocol_version = (msg[0] << 8) + msg[1];
1635 msg += 2;
1636
1637 /* Expect the random, composed by 4 bytes for the unix time and
1638 * 28 bytes for unix payload. So we jump 4 + 28.
1639 */
1640 msg += 4 + 28;
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001641 if (msg > end)
1642 return;
1643
1644 /* Next, is session id:
1645 * if present, we have to jump by length + 1 for the size information
1646 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001647 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001648 if (msg[0] > 0)
1649 msg += msg[0];
1650 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001651 if (msg > end)
1652 return;
1653
1654 /* Next two bytes are the ciphersuite length. */
1655 if (msg + 2 > end)
1656 return;
1657 rec_len = (msg[0] << 8) + msg[1];
1658 msg += 2;
1659 if (msg + rec_len > end || msg + rec_len < msg)
1660 return;
1661
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001662 capture = pool_zalloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001663 if (!capture)
1664 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001665 /* Compute the xxh64 of the ciphersuite. */
1666 capture->xxh64 = XXH64(msg, rec_len, 0);
1667
1668 /* Capture the ciphersuite. */
Marcin Deranek310a2602021-07-13 19:04:24 +02001669 capture->ciphersuite_len = MIN(global_ssl.capture_buffer_size, rec_len);
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001670 capture->ciphersuite_offset = 0;
1671 memcpy(capture->data, msg, capture->ciphersuite_len);
1672 msg += rec_len;
1673 offset += capture->ciphersuite_len;
1674
1675 /* Initialize other data */
1676 capture->protocol_version = protocol_version;
1677
1678 /* Next, compression methods:
1679 * if present, we have to jump by length + 1 for the size information
1680 * if not present, we have to jump by 1 only
1681 */
1682 if (msg[0] > 0)
1683 msg += msg[0];
1684 msg += 1;
1685 if (msg > end)
1686 goto store_capture;
1687
1688 /* We reached extensions */
1689 if (msg + 2 > end)
1690 goto store_capture;
1691 rec_len = (msg[0] << 8) + msg[1];
1692 msg += 2;
1693 if (msg + rec_len > end || msg + rec_len < msg)
1694 goto store_capture;
1695 extensions_end = msg + rec_len;
1696 capture->extensions_offset = offset;
1697
1698 /* Parse each extension */
1699 while (msg + 4 < extensions_end) {
1700 /* Add 2 bytes of extension_id */
Marcin Deranek310a2602021-07-13 19:04:24 +02001701 if (global_ssl.capture_buffer_size >= offset + 2) {
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001702 capture->data[offset++] = msg[0];
1703 capture->data[offset++] = msg[1];
1704 capture->extensions_len += 2;
1705 }
1706 else
1707 break;
1708 extension_id = (msg[0] << 8) + msg[1];
1709 /* Length of the extension */
1710 rec_len = (msg[2] << 8) + msg[3];
1711
1712 /* Expect 2 bytes extension id + 2 bytes extension size */
1713 msg += 2 + 2;
1714 if (msg + rec_len > extensions_end || msg + rec_len < msg)
1715 goto store_capture;
1716 /* TLS Extensions
1717 * https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml */
1718 if (extension_id == 0x000a) {
1719 /* Elliptic Curves:
1720 * https://www.rfc-editor.org/rfc/rfc8422.html
1721 * https://www.rfc-editor.org/rfc/rfc7919.html */
1722 list_end = msg + rec_len;
1723 if (msg + 2 > list_end)
1724 goto store_capture;
1725 rec_len = (msg[0] << 8) + msg[1];
1726 msg += 2;
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_start = msg;
1732 ec_len = rec_len;
1733 }
1734 else if (extension_id == 0x000b) {
1735 /* Elliptic Curves Point Formats:
1736 * https://www.rfc-editor.org/rfc/rfc8422.html */
1737 list_end = msg + rec_len;
1738 if (msg + 1 > list_end)
1739 goto store_capture;
1740 rec_len = msg[0];
1741 msg += 1;
1742
1743 if (msg + rec_len > list_end || msg + rec_len < msg)
1744 goto store_capture;
1745 /* Store location/size of the list */
1746 ec_formats_start = msg;
1747 ec_formats_len = rec_len;
1748 }
1749 msg += rec_len;
1750 }
1751
1752 if (ec_start) {
1753 rec_len = ec_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001754 if (offset + rec_len > global_ssl.capture_buffer_size)
1755 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001756 memcpy(capture->data + offset, ec_start, rec_len);
1757 capture->ec_offset = offset;
1758 capture->ec_len = rec_len;
1759 offset += rec_len;
1760 }
1761 if (ec_formats_start) {
1762 rec_len = ec_formats_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001763 if (offset + rec_len > global_ssl.capture_buffer_size)
1764 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001765 memcpy(capture->data + offset, ec_formats_start, rec_len);
1766 capture->ec_formats_offset = offset;
1767 capture->ec_formats_len = rec_len;
1768 offset += rec_len;
1769 }
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001770
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001771 store_capture:
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001772 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001773}
William Lallemand7d42ef52020-07-06 11:41:30 +02001774
1775
William Lallemand722180a2021-06-09 16:46:12 +02001776#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001777static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1778 int content_type, const void *buf, size_t len,
1779 SSL *ssl)
1780{
1781 struct ssl_keylog *keylog;
1782
1783 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1784 return;
1785
Willy Tarreauf208ac02021-03-22 21:10:12 +01001786 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02001787 if (!keylog)
1788 return;
1789
William Lallemand7d42ef52020-07-06 11:41:30 +02001790 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
1791 pool_free(pool_head_ssl_keylog, keylog);
1792 return;
1793 }
1794}
1795#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001796
Emeric Brun29f037d2014-04-25 19:05:36 +02001797/* Callback is called for ssl protocol analyse */
1798void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1799{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001800 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1801 struct ssl_sock_msg_callback *cbk;
1802
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001803 /* Try to call all callback functions that were registered by using
1804 * ssl_sock_register_msg_callback().
1805 */
1806 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1807 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1808 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001809}
1810
Bernard Spil13c53f82018-02-15 13:34:58 +01001811#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001812static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1813 const unsigned char *in, unsigned int inlen,
1814 void *arg)
1815{
1816 struct server *srv = arg;
1817
1818 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1819 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1820 return SSL_TLSEXT_ERR_OK;
1821 return SSL_TLSEXT_ERR_NOACK;
1822}
1823#endif
1824
1825#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001826/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001827 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001828 */
1829static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1830 unsigned int *len, void *arg)
1831{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001832 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001833
1834 *data = (const unsigned char *)conf->npn_str;
1835 *len = conf->npn_len;
1836 return SSL_TLSEXT_ERR_OK;
1837}
1838#endif
1839
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001840#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001841/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001842 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001843 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001844static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1845 unsigned char *outlen,
1846 const unsigned char *server,
1847 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001848{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001849 struct ssl_bind_conf *conf = arg;
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001850#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001851 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001852#endif
Willy Tarreauab861d32013-04-02 02:30:41 +02001853
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001854 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1855 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01001856#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001857 if (qc)
1858 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01001859#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001860 return SSL_TLSEXT_ERR_NOACK;
1861 }
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001862
1863#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001864 if (qc && !quic_set_app_ops(qc, *out, *outlen)) {
1865 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001866 return SSL_TLSEXT_ERR_NOACK;
1867 }
1868#endif
1869
Willy Tarreauab861d32013-04-02 02:30:41 +02001870 return SSL_TLSEXT_ERR_OK;
1871}
1872#endif
1873
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001874#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001875#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001876
cui flitera94bedc2022-08-29 14:42:57 +08001877/* Configure a DNS SAN extension on a certificate. */
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001878int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
1879 int failure = 0;
1880 X509_EXTENSION *san_ext = NULL;
1881 CONF *conf = NULL;
1882 struct buffer *san_name = get_trash_chunk();
1883
1884 conf = NCONF_new(NULL);
1885 if (!conf) {
1886 failure = 1;
1887 goto cleanup;
1888 }
1889
1890 /* Build an extension based on the DNS entry above */
1891 chunk_appendf(san_name, "DNS:%s", servername);
1892 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
1893 if (!san_ext) {
1894 failure = 1;
1895 goto cleanup;
1896 }
1897
1898 /* Add the extension */
1899 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
1900 failure = 1;
1901 goto cleanup;
1902 }
1903
1904 /* Success */
1905 failure = 0;
1906
1907cleanup:
1908 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
1909 if (NULL != conf) NCONF_free(conf);
1910
1911 return failure;
1912}
1913
Christopher Faulet30548802015-06-11 13:39:32 +02001914/* Create a X509 certificate with the specified servername and serial. This
1915 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001916static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001917ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001918{
Shimi Gersner5846c492020-08-23 13:58:12 +03001919 X509 *cacert = bind_conf->ca_sign_ckch->cert;
1920 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001921 SSL_CTX *ssl_ctx = NULL;
1922 X509 *newcrt = NULL;
1923 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001924 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001925 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001926 X509_NAME *name;
1927 const EVP_MD *digest;
1928 X509V3_CTX ctx;
1929 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001930 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001931
Christopher Faulet48a83322017-07-28 16:56:09 +02001932 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05001933#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001934 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1935#else
1936 tmp_ssl = SSL_new(bind_conf->default_ctx);
1937 if (tmp_ssl)
1938 pkey = SSL_get_privatekey(tmp_ssl);
1939#endif
1940 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001941 goto mkcert_error;
1942
1943 /* Create the certificate */
1944 if (!(newcrt = X509_new()))
1945 goto mkcert_error;
1946
1947 /* Set version number for the certificate (X509v3) and the serial
1948 * number */
1949 if (X509_set_version(newcrt, 2L) != 1)
1950 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02001951 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001952
1953 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001954 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1955 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001956 goto mkcert_error;
1957
1958 /* set public key in the certificate */
1959 if (X509_set_pubkey(newcrt, pkey) != 1)
1960 goto mkcert_error;
1961
1962 /* Set issuer name from the CA */
1963 if (!(name = X509_get_subject_name(cacert)))
1964 goto mkcert_error;
1965 if (X509_set_issuer_name(newcrt, name) != 1)
1966 goto mkcert_error;
1967
1968 /* Set the subject name using the same, but the CN */
1969 name = X509_NAME_dup(name);
1970 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1971 (const unsigned char *)servername,
1972 -1, -1, 0) != 1) {
1973 X509_NAME_free(name);
1974 goto mkcert_error;
1975 }
1976 if (X509_set_subject_name(newcrt, name) != 1) {
1977 X509_NAME_free(name);
1978 goto mkcert_error;
1979 }
1980 X509_NAME_free(name);
1981
1982 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001983 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001984 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1985 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1986 X509_EXTENSION *ext;
1987
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001988 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001989 goto mkcert_error;
1990 if (!X509_add_ext(newcrt, ext, -1)) {
1991 X509_EXTENSION_free(ext);
1992 goto mkcert_error;
1993 }
1994 X509_EXTENSION_free(ext);
1995 }
1996
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001997 /* Add SAN extension */
1998 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
1999 goto mkcert_error;
2000 }
2001
Christopher Faulet31af49d2015-06-09 17:29:50 +02002002 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002003
2004 key_type = EVP_PKEY_base_id(capkey);
2005
2006 if (key_type == EVP_PKEY_DSA)
2007 digest = EVP_sha1();
2008 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002009 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002010 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02002011 digest = EVP_sha256();
2012 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05002013#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02002014 int nid;
2015
2016 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
2017 goto mkcert_error;
2018 if (!(digest = EVP_get_digestbynid(nid)))
2019 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02002020#else
2021 goto mkcert_error;
2022#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02002023 }
2024
Christopher Faulet31af49d2015-06-09 17:29:50 +02002025 if (!(X509_sign(newcrt, capkey, digest)))
2026 goto mkcert_error;
2027
2028 /* Create and set the new SSL_CTX */
2029 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
2030 goto mkcert_error;
2031 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
2032 goto mkcert_error;
2033 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
2034 goto mkcert_error;
2035 if (!SSL_CTX_check_private_key(ssl_ctx))
2036 goto mkcert_error;
2037
Shimi Gersner5846c492020-08-23 13:58:12 +03002038 /* Build chaining the CA cert and the rest of the chain, keep these order */
2039#if defined(SSL_CTX_add1_chain_cert)
2040 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
2041 goto mkcert_error;
2042 }
2043
2044 if (bind_conf->ca_sign_ckch->chain) {
2045 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2046 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2047 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2048 goto mkcert_error;
2049 }
2050 }
2051 }
2052#endif
2053
Christopher Faulet31af49d2015-06-09 17:29:50 +02002054 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002055
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002056#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002057#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002058 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002059#else
2060 ssl_sock_set_tmp_dh_from_pkey(ssl_ctx, pkey);
2061#endif
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002062#endif
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002063
2064#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
2065#if defined(SSL_CTX_set1_curves_list)
2066 {
2067 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
2068 if (!SSL_CTX_set1_curves_list(ssl_ctx, ecdhe))
2069 goto end;
2070 }
2071#endif
2072#else
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002073#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2074 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002075 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002076 EC_KEY *ecc;
2077 int nid;
2078
2079 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2080 goto end;
2081 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2082 goto end;
2083 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2084 EC_KEY_free(ecc);
2085 }
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002086#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
2087#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002088 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002089 return ssl_ctx;
2090
2091 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002092 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002093 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002094 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2095 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002096 return NULL;
2097}
2098
Christopher Faulet7969a332015-10-09 11:15:03 +02002099
Christopher Faulet30548802015-06-11 13:39:32 +02002100/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002101 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002102SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002103ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002104{
2105 struct lru64 *lru = NULL;
2106
2107 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002108 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002109 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002110 if (lru && lru->domain) {
2111 if (ssl)
2112 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002113 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002114 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002115 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002116 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002117 }
2118 return NULL;
2119}
2120
Emeric Brun821bb9b2017-06-15 16:37:39 +02002121/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2122 * function is not thread-safe, it should only be used to check if a certificate
2123 * exists in the lru cache (with no warranty it will not be removed by another
2124 * thread). It is kept for backward compatibility. */
2125SSL_CTX *
2126ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2127{
2128 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2129}
2130
Christopher Fauletd2cab922015-07-28 16:03:47 +02002131/* Set a certificate int the LRU cache used to store generated
2132 * certificate. Return 0 on success, otherwise -1 */
2133int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002134ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002135{
2136 struct lru64 *lru = NULL;
2137
2138 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002139 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002140 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002141 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002142 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002143 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002144 }
Christopher Faulet30548802015-06-11 13:39:32 +02002145 if (lru->domain && lru->data)
2146 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002147 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002148 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002149 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002150 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002151 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002152}
2153
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002154/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002155unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002156ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002157{
2158 return XXH32(data, len, ssl_ctx_lru_seed);
2159}
2160
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002161/* Generate a cert and immediately assign it to the SSL session so that the cert's
2162 * refcount is maintained regardless of the cert's presence in the LRU cache.
2163 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002164static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002165ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002166{
Shimi Gersner5846c492020-08-23 13:58:12 +03002167 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002168 SSL_CTX *ssl_ctx = NULL;
2169 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002170 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002171
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002172 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002173 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002174 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002175 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002176 if (lru && lru->domain)
2177 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002178 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002179 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002180 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002181 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002182 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002183 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002184 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002185 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002186 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002187 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002188 SSL_set_SSL_CTX(ssl, ssl_ctx);
2189 /* No LRU cache, this CTX will be released as soon as the session dies */
2190 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002191 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002192 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002193 return 0;
2194}
2195static int
2196ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2197{
2198 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002199 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002200
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002201 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002202 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002203 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002204 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002205 }
2206 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002207}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002208#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002209
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002210#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002211
2212static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002213{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002214#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002215 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002216 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2217#endif
2218}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002219static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2220 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002221 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2222}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002223static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002224#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002225 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002226 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2227#endif
2228}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002229static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002230#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002231 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002232 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2233#endif
2234}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002235/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002236static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2237/* Unusable in this context. */
2238static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2239static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2240static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2241static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2242static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002243#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002244
2245static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2246 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002247 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2248}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002249static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2250 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2251 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2252}
2253static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2254 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002255 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2256}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002257static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2258 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2259 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2260}
2261static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2262 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002263 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2264}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002265static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2266 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2267 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2268}
2269static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2270 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002271 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2272}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002273static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2274 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2275 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2276}
2277static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002278#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002279 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002280 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2281#endif
2282}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002283static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002284#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002285 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2286 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002287#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002288}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002289#endif
2290static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2291static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002292
William Lallemand7fd8b452020-05-07 15:20:43 +02002293struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002294 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2295 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2296 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2297 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2298 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2299 {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 +02002300};
2301
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002302static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2303{
2304 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2305 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2306 SSL_set_SSL_CTX(ssl, ctx);
2307}
2308
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002309#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002310
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002311int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002312{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002313 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002314 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002315
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002316 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || (s->options & BC_O_GENERATE_CERTS))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002317 return SSL_TLSEXT_ERR_OK;
2318 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002319}
2320
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002321#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002322int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002323{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002324 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002325#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002326int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002327{
2328#endif
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002329 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2330#ifdef USE_QUIC
2331 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2332#endif /* USE_QUIC */
2333 struct bind_conf *s = NULL;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002334 const uint8_t *extension_data;
2335 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002336 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002337
2338 char *wildp = NULL;
2339 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002340 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002341 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002342 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002343 int i;
2344
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002345 if (conn)
2346 s = __objt_listener(conn->target)->bind_conf;
2347#ifdef USE_QUIC
2348 else if (qc)
2349 s = qc->li->bind_conf;
2350#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01002351
2352 if (!s) {
2353 /* must never happen */
2354 ABORT_NOW();
2355 return 0;
2356 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002357
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002358#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002359 if (qc) {
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002360 /* Look for the QUIC transport parameters. */
2361#ifdef OPENSSL_IS_BORINGSSL
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002362 if (!SSL_early_callback_ctx_extension_get(ctx, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002363 &extension_data, &extension_len))
2364#else
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002365 if (!SSL_client_hello_get0_ext(ssl, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002366 &extension_data, &extension_len))
2367#endif
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002368 {
2369 /* This is not redundant. It we only return 0 without setting
2370 * <*al>, this has as side effect to generate another TLS alert
2371 * which would be set after calling quic_set_tls_alert().
2372 */
2373 *al = SSL_AD_MISSING_EXTENSION;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002374 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002375 return 0;
2376 }
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002377
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002378 if (!quic_transport_params_store(qc, 0, extension_data,
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002379 extension_data + extension_len))
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002380 goto abort;
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002381
2382 qc->flags |= QUIC_FL_CONN_TX_TP_RECEIVED;
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002383 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002384#endif /* USE_QUIC */
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002385
Olivier Houchard9679ac92017-10-27 14:58:08 +02002386 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002387 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002388#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002389 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2390 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002391#else
2392 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2393#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002394 /*
2395 * The server_name extension was given too much extensibility when it
2396 * was written, so parsing the normal case is a bit complex.
2397 */
2398 size_t len;
2399 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002400 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002401 /* Extract the length of the supplied list of names. */
2402 len = (*extension_data++) << 8;
2403 len |= *extension_data++;
2404 if (len + 2 != extension_len)
2405 goto abort;
2406 /*
2407 * The list in practice only has a single element, so we only consider
2408 * the first one.
2409 */
2410 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2411 goto abort;
2412 extension_len = len - 1;
2413 /* Now we can finally pull out the byte array with the actual hostname. */
2414 if (extension_len <= 2)
2415 goto abort;
2416 len = (*extension_data++) << 8;
2417 len |= *extension_data++;
2418 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2419 || memchr(extension_data, 0, len) != NULL)
2420 goto abort;
2421 servername = extension_data;
2422 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002423 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002424#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002425 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002426 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002427 }
2428#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002429 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002430 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002431 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002432 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002433 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002434 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002435 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002436 goto abort;
2437 }
2438
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002439 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002440#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002441 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002442#else
2443 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2444#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002445 uint8_t sign;
2446 size_t len;
2447 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002448 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002449 len = (*extension_data++) << 8;
2450 len |= *extension_data++;
2451 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002452 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002453 if (len % 2 != 0)
2454 goto abort;
2455 for (; len > 0; len -= 2) {
2456 extension_data++; /* hash */
2457 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002458 switch (sign) {
2459 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002460 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002461 break;
2462 case TLSEXT_signature_ecdsa:
2463 has_ecdsa_sig = 1;
2464 break;
2465 default:
2466 continue;
2467 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002468 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002469 break;
2470 }
2471 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002472 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002473 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002474 }
2475 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002476 const SSL_CIPHER *cipher;
2477 size_t len;
2478 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002479 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002480#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002481 len = ctx->cipher_suites_len;
2482 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002483#else
2484 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2485#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002486 if (len % 2 != 0)
2487 goto abort;
2488 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002489#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002490 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002491 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002492#else
2493 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2494#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002495 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002496 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002497 break;
2498 }
2499 }
2500 }
2501
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002502 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002503 trash.area[i] = tolower(servername[i]);
2504 if (!wildp && (trash.area[i] == '.'))
2505 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002506 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002507 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002508
William Lallemand150bfa82019-09-19 17:12:49 +02002509 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002510
William Lallemand94bd3192020-08-14 14:43:35 +02002511 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2512 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002513 for (i = 0; i < 2; i++) {
2514 if (i == 0) /* lookup in full qualified names */
2515 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002516 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002517 node = ebst_lookup(&s->sni_w_ctx, wildp);
2518 else
2519 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002520
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002521 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002522
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002523 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002524 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002525 struct sni_ctx *sni, *sni_tmp;
2526 int skip = 0;
2527
2528 if (i == 1 && wildp) { /* wildcard */
2529 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2530 sni = container_of(n, struct sni_ctx, name);
2531 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002532 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002533 skip = 1;
2534 break;
2535 }
2536 }
2537 if (skip)
2538 continue;
2539 }
2540
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002541 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002542 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002543 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002544 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002545 break;
2546 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002547 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002548 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002549 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002550 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002551 if (!node_anonymous)
2552 node_anonymous = n;
2553 break;
2554 }
2555 }
2556 }
William Lallemand94bd3192020-08-14 14:43:35 +02002557 }
2558 /* Once the certificates are found, select them depending on what is
2559 * supported in the client and by key_signature priority order: EDSA >
2560 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002561 if (has_ecdsa_sig && node_ecdsa)
2562 node = node_ecdsa;
2563 else if (has_rsa_sig && node_rsa)
2564 node = node_rsa;
2565 else if (node_anonymous)
2566 node = node_anonymous;
2567 else if (node_ecdsa)
2568 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2569 else
2570 node = node_rsa; /* no rsa signature case (far far away) */
2571
William Lallemand94bd3192020-08-14 14:43:35 +02002572 if (node) {
2573 /* switch ctx */
2574 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2575 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2576 if (conf) {
2577 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2578 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2579 if (conf->early_data)
2580 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002581 }
William Lallemand94bd3192020-08-14 14:43:35 +02002582 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2583 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002584 }
William Lallemand150bfa82019-09-19 17:12:49 +02002585
William Lallemand02010472019-10-18 11:02:19 +02002586 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002587#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002588 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002589 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002590 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002591 }
2592#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002593 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002594 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002595 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002596 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002597 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
William Lallemand7980dff2021-11-18 17:46:26 +01002598 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002599 }
William Lallemand7980dff2021-11-18 17:46:26 +01002600
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01002601 /* We are about to raise an handshake error so the servername extension
2602 * callback will never be called and the SNI will never be stored in the
2603 * SSL context. In order for the ssl_fc_sni sample fetch to still work
2604 * in such a case, we store the SNI ourselves as an ex_data information
2605 * in the SSL context.
2606 */
2607 {
2608 char *client_sni = pool_alloc(ssl_sock_client_sni_pool);
2609 if (client_sni) {
2610 strncpy(client_sni, trash.area, TLSEXT_MAXLEN_host_name);
2611 client_sni[TLSEXT_MAXLEN_host_name] = '\0';
2612 SSL_set_ex_data(ssl, ssl_client_sni_index, client_sni);
2613 }
2614 }
2615
William Lallemand7980dff2021-11-18 17:46:26 +01002616 /* other cases fallback on abort, if strict-sni is set but no node was found */
2617
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002618 abort:
2619 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002620 if (conn)
2621 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002622#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002623 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002624#else
2625 *al = SSL_AD_UNRECOGNIZED_NAME;
2626 return 0;
2627#endif
William Lallemand7980dff2021-11-18 17:46:26 +01002628
2629allow_early:
2630#ifdef OPENSSL_IS_BORINGSSL
2631 if (allow_early)
2632 SSL_set_early_data_enabled(ssl, 1);
2633#else
2634 if (!allow_early)
2635 SSL_set_max_early_data(ssl, 0);
2636#endif
2637 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002638}
2639
William Lallemand002e2062021-11-18 15:25:16 +01002640#else /* ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002641
Emeric Brunfc0421f2012-09-07 17:30:07 +02002642/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2643 * warning when no match is found, which implies the default (first) cert
2644 * will keep being used.
2645 */
William Lallemand844009d2022-09-02 15:27:32 +02002646int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002647{
2648 const char *servername;
2649 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002650 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002651 struct bind_conf *s = priv;
William Lallemand70a6e632022-09-07 11:21:34 +02002652#ifdef USE_QUIC
2653 const uint8_t *extension_data;
2654 size_t extension_len;
2655 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2656#endif /* USE_QUIC */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002657 int i;
2658 (void)al; /* shut gcc stupid warning */
2659
William Lallemand70a6e632022-09-07 11:21:34 +02002660#ifdef USE_QUIC
2661 if (qc) {
2662
2663 /* Look for the QUIC transport parameters. */
2664 SSL_get_peer_quic_transport_params(ssl, &extension_data, &extension_len);
2665 if (extension_len == 0) {
2666 /* This is not redundant. It we only return 0 without setting
2667 * <*al>, this has as side effect to generate another TLS alert
2668 * which would be set after calling quic_set_tls_alert().
2669 */
2670 *al = SSL_AD_MISSING_EXTENSION;
2671 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
2672 return SSL_TLSEXT_ERR_NOACK;
2673 }
2674
2675 if (!quic_transport_params_store(qc, 0, extension_data,
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002676 extension_data + extension_len))
William Lallemand70a6e632022-09-07 11:21:34 +02002677 return SSL_TLSEXT_ERR_NOACK;
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002678
2679 qc->flags |= QUIC_FL_CONN_TX_TP_RECEIVED;
William Lallemand70a6e632022-09-07 11:21:34 +02002680 }
2681#endif /* USE_QUIC */
2682
Emeric Brunfc0421f2012-09-07 17:30:07 +02002683 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002684 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002685#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002686 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002687 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002688#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002689 if (s->strict_sni)
2690 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002691 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002692 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002693 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002694 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002695 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002696
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002697 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002698 if (!servername[i])
2699 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002700 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002701 if (!wildp && (trash.area[i] == '.'))
2702 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002703 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002704 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002705
William Lallemand150bfa82019-09-19 17:12:49 +02002706 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002707 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002708 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002709 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2710 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002711 if (!container_of(n, struct sni_ctx, name)->neg) {
2712 node = n;
2713 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002714 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002715 }
2716 if (!node && wildp) {
2717 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002718 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2719 /* lookup a not neg filter */
2720 if (!container_of(n, struct sni_ctx, name)->neg) {
2721 node = n;
2722 break;
2723 }
2724 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002725 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002726 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002727#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002728 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(servername, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002729 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002730 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002731 return SSL_TLSEXT_ERR_OK;
2732 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002733#endif
William Lallemand21724f02019-11-04 17:56:13 +01002734 if (s->strict_sni) {
2735 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002736 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002737 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002738 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002739 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002740 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002741 }
2742
2743 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002744 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002745 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002746 return SSL_TLSEXT_ERR_OK;
2747}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002748#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002749#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2750
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002751#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002752
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002753static inline HASSL_DH *ssl_new_dh_fromdata(BIGNUM *p, BIGNUM *g)
2754{
2755#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2756 OSSL_PARAM_BLD *tmpl = NULL;
2757 OSSL_PARAM *params = NULL;
2758 EVP_PKEY_CTX *ctx = NULL;
2759 EVP_PKEY *pkey = NULL;
2760
2761 if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
2762 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
2763 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)
2764 || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
2765 goto end;
2766 }
2767 ctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2768 if (ctx == NULL
2769 || !EVP_PKEY_fromdata_init(ctx)
2770 || !EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params)) {
2771 goto end;
2772 }
2773
2774end:
2775 EVP_PKEY_CTX_free(ctx);
2776 OSSL_PARAM_free(params);
2777 OSSL_PARAM_BLD_free(tmpl);
Remi Tricot-Le Bretona2c21db2022-11-03 15:16:47 +01002778 BN_free(p);
2779 BN_free(g);
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002780 return pkey;
2781#else
2782
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002783 HASSL_DH *dh = DH_new();
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002784
2785 if (!dh)
2786 return NULL;
2787
2788 DH_set0_pqg(dh, p, NULL, g);
2789
2790 return dh;
2791#endif
2792}
2793
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02002794#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002795static inline HASSL_DH *ssl_get_dh_by_nid(int nid)
2796{
2797#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2798 OSSL_PARAM params[2];
2799 EVP_PKEY *pkey = NULL;
2800 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2801 const char *named_group = NULL;
2802
2803 if (!pctx)
2804 goto end;
2805
2806 named_group = OBJ_nid2ln(nid);
2807
2808 if (!named_group)
2809 goto end;
2810
2811 params[0] = OSSL_PARAM_construct_utf8_string("group", (char*)named_group, 0);
2812 params[1] = OSSL_PARAM_construct_end();
2813
2814 if (EVP_PKEY_keygen_init(pctx) && EVP_PKEY_CTX_set_params(pctx, params))
2815 EVP_PKEY_generate(pctx, &pkey);
2816
2817end:
2818 EVP_PKEY_CTX_free(pctx);
2819 return pkey;
2820#else
2821
2822 HASSL_DH *dh = NULL;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002823 dh = DH_new_by_nid(nid);
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002824 return dh;
2825#endif
2826}
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02002827#endif
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002828
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002829
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002830static HASSL_DH * ssl_get_dh_1024(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002831{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002832 static unsigned char dh1024_p[]={
2833 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2834 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2835 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2836 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2837 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2838 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2839 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2840 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2841 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2842 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2843 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2844 };
2845 static unsigned char dh1024_g[]={
2846 0x02,
2847 };
2848
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002849 BIGNUM *p;
2850 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002851
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002852 HASSL_DH *dh = NULL;
2853
2854 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2855 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
2856
2857 if (p && g)
2858 dh = ssl_new_dh_fromdata(p, g);
2859
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002860 return dh;
2861}
2862
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002863static HASSL_DH *ssl_get_dh_2048(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002864{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002865#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02002866 static unsigned char dh2048_p[]={
2867 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2868 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2869 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2870 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2871 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2872 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2873 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2874 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2875 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2876 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2877 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2878 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2879 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2880 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2881 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2882 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2883 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2884 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2885 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2886 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2887 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2888 0xB7,0x1F,0x77,0xF3,
2889 };
2890 static unsigned char dh2048_g[]={
2891 0x02,
2892 };
2893
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002894 BIGNUM *p;
2895 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002896
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002897 HASSL_DH *dh = NULL;
2898
2899 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2900 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
2901
2902 if (p && g)
2903 dh = ssl_new_dh_fromdata(p, g);
2904
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002905 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002906#else
2907 return ssl_get_dh_by_nid(NID_ffdhe2048);
2908#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002909}
2910
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002911static HASSL_DH *ssl_get_dh_4096(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002912{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002913#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02002914 static unsigned char dh4096_p[]={
2915 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2916 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2917 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2918 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2919 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2920 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2921 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2922 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2923 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2924 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2925 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2926 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2927 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2928 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2929 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2930 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2931 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2932 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2933 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2934 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2935 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2936 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2937 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2938 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2939 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2940 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2941 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2942 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2943 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2944 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2945 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2946 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2947 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2948 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2949 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2950 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2951 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2952 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2953 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2954 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2955 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2956 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2957 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002958 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002959 static unsigned char dh4096_g[]={
2960 0x02,
2961 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002962
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002963 BIGNUM *p;
2964 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002965
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002966 HASSL_DH *dh = NULL;
2967
2968 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2969 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
2970
2971 if (p && g)
2972 dh = ssl_new_dh_fromdata(p, g);
2973
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002974 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002975#else
2976 return ssl_get_dh_by_nid(NID_ffdhe4096);
2977#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002978}
2979
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002980static HASSL_DH *ssl_get_tmp_dh(EVP_PKEY *pkey)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002981{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002982 HASSL_DH *dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002983 int type;
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002984 int keylen = 0;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002985
2986 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002987
Ilya Shipitsin52f2ff52022-07-23 23:55:19 +05002988 if (type == EVP_PKEY_EC) {
2989 keylen = global_ssl.default_dh_param;
2990 }
2991
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002992 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2993 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2994 */
2995 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2996 keylen = EVP_PKEY_bits(pkey);
2997 }
2998
Willy Tarreauef934602016-12-22 23:12:01 +01002999 if (keylen > global_ssl.default_dh_param) {
3000 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003001 }
3002
Remi Gacogned3a341a2015-05-29 16:26:17 +02003003 if (keylen >= 4096) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003004 if (!local_dh_4096)
3005 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02003006 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003007 }
3008 else if (keylen >= 2048) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003009 if (!local_dh_2048)
3010 local_dh_2048 = ssl_get_dh_2048();
Remi Gacogne8de54152014-07-15 11:36:40 +02003011 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003012 }
3013 else {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003014 if (!local_dh_1024)
3015 local_dh_1024 = ssl_get_dh_1024();
Remi Gacogne8de54152014-07-15 11:36:40 +02003016 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003017 }
3018
3019 return dh;
3020}
3021
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003022#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003023/* Returns Diffie-Hellman parameters matching the private key length
3024 but not exceeding global_ssl.default_dh_param */
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003025static HASSL_DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003026{
3027 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
3028
3029 return ssl_get_tmp_dh(pkey);
3030}
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003031#endif
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003032
Remi Tricot-Le Breton846eda92022-02-11 12:04:50 +01003033static int ssl_sock_set_tmp_dh(SSL_CTX *ctx, HASSL_DH *dh)
3034{
3035#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
3036 return SSL_CTX_set_tmp_dh(ctx, dh);
3037#else
3038 int retval = 0;
3039 HASSL_DH_up_ref(dh);
3040
3041 retval = SSL_CTX_set0_tmp_dh_pkey(ctx, dh);
3042
3043 if (!retval)
3044 HASSL_DH_free(dh);
3045
3046 return retval;
3047#endif
3048}
3049
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003050#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3051static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey)
3052{
3053 HASSL_DH *dh = NULL;
3054 if (pkey && (dh = ssl_get_tmp_dh(pkey))) {
3055 HASSL_DH_up_ref(dh);
3056 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dh))
3057 HASSL_DH_free(dh);
3058 }
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003059}
3060#endif
3061
Remi Tricot-Le Breton09ebb332022-02-11 12:04:48 +01003062HASSL_DH *ssl_sock_get_dh_from_bio(BIO *bio)
3063{
3064#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3065 HASSL_DH *dh = NULL;
3066 OSSL_DECODER_CTX *dctx = NULL;
3067 const char *format = "PEM";
3068 const char *keytype = "DH";
3069
3070 dctx = OSSL_DECODER_CTX_new_for_pkey(&dh, format, NULL, keytype,
3071 OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
3072 NULL, NULL);
3073
3074 if (dctx == NULL || OSSL_DECODER_CTX_get_num_decoders(dctx) == 0)
3075 goto end;
3076
3077 /* The DH parameters might not be the first section found in the PEM
3078 * file so we need to iterate over all of them until we find the right
3079 * one.
3080 */
3081 while (!BIO_eof(bio) && !dh)
3082 OSSL_DECODER_from_bio(dctx, bio);
3083
3084end:
3085 OSSL_DECODER_CTX_free(dctx);
3086 return dh;
3087#else
3088 HASSL_DH *dh = NULL;
3089
3090 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3091
3092 return dh;
3093#endif
3094}
3095
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003096static HASSL_DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003097{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003098 HASSL_DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02003099 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003100
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003101 if (in == NULL)
3102 goto end;
3103
Remi Gacogne47783ef2015-05-29 15:53:22 +02003104 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003105 goto end;
3106
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003107 dh = ssl_sock_get_dh_from_bio(in);
Remi Gacogne47783ef2015-05-29 15:53:22 +02003108
3109end:
3110 if (in)
3111 BIO_free(in);
3112
Emeric Brune1b4ed42018-08-16 15:14:12 +02003113 ERR_clear_error();
3114
Remi Gacogne47783ef2015-05-29 15:53:22 +02003115 return dh;
3116}
3117
3118int ssl_sock_load_global_dh_param_from_file(const char *filename)
3119{
3120 global_dh = ssl_sock_get_dh_from_file(filename);
3121
3122 if (global_dh) {
3123 return 0;
3124 }
3125
3126 return -1;
3127}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003128#endif
3129
William Lallemand9117de92019-10-04 00:29:42 +02003130/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02003131static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02003132 struct bind_conf *s, struct ssl_bind_conf *conf,
3133 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003134{
3135 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003136 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003137
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003138 if (*name == '!') {
3139 neg = 1;
3140 name++;
3141 }
3142 if (*name == '*') {
3143 wild = 1;
3144 name++;
3145 }
3146 /* !* filter is a nop */
3147 if (neg && wild)
3148 return order;
3149 if (*name) {
3150 int j, len;
3151 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003152 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02003153 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003154 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02003155 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003156 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003157
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003158 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02003159 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02003160 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003161 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02003162 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003163 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003164 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003165 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003166 sc->order = order++;
3167 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02003168 sc->wild = wild;
3169 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01003170 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02003171 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003172 }
3173 return order;
3174}
3175
William Lallemand6af03992019-07-23 15:00:54 +02003176/*
William Lallemand1d29c742019-10-04 00:53:29 +02003177 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
3178 * This function can't return an error.
3179 *
3180 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
3181 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003182void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02003183{
3184
3185 struct sni_ctx *sc0, *sc0b, *sc1;
3186 struct ebmb_node *node;
3187
3188 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
3189
3190 /* ignore if sc0 was already inserted in a tree */
3191 if (sc0->name.node.leaf_p)
3192 continue;
3193
3194 /* Check for duplicates. */
3195 if (sc0->wild)
3196 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
3197 else
3198 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
3199
3200 for (; node; node = ebmb_next_dup(node)) {
3201 sc1 = ebmb_entry(node, struct sni_ctx, name);
3202 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
3203 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
3204 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02003205 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02003206 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003207 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02003208 break;
William Lallemand1d29c742019-10-04 00:53:29 +02003209 }
3210 }
3211
3212 /* if duplicate, ignore the insertion */
3213 if (!sc0)
3214 continue;
3215
3216 if (sc0->wild)
3217 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
3218 else
3219 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003220 }
William Lallemand21724f02019-11-04 17:56:13 +01003221
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003222 /* replace the default_ctx if required with the instance's ctx. */
3223 if (ckch_inst->is_default) {
3224 SSL_CTX_free(bind_conf->default_ctx);
3225 SSL_CTX_up_ref(ckch_inst->ctx);
3226 bind_conf->default_ctx = ckch_inst->ctx;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003227 bind_conf->default_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02003228 }
3229}
3230
3231/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003232 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02003233 */
William Lallemande3af8fb2019-10-08 11:36:53 +02003234struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02003235
William Lallemand2954c472020-03-06 21:54:13 +01003236/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02003237struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02003238
Emeric Brun7a883362019-10-17 13:27:40 +02003239/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003240 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02003241 * DH parameter is loaded into the SSL_CTX and if there is no
3242 * DH parameter available in ckchs nor in global, the default
3243 * DH parameters are applied on the SSL_CTX.
3244 * Returns a bitfield containing the flags:
3245 * ERR_FATAL in any fatal error case
3246 * ERR_ALERT if a reason of the error is availabine in err
3247 * ERR_WARN if a warning is available into err
3248 * The value 0 means there is no error nor warning and
3249 * the operation succeed.
3250 */
William Lallemandfa892222019-07-23 16:06:08 +02003251#ifndef OPENSSL_NO_DH
William Lallemand52ddd992022-11-22 11:51:53 +01003252static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct ckch_data *data,
Emeric Brun7a883362019-10-17 13:27:40 +02003253 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02003254{
Emeric Brun7a883362019-10-17 13:27:40 +02003255 int ret = 0;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003256 HASSL_DH *dh = NULL;
William Lallemandfa892222019-07-23 16:06:08 +02003257
William Lallemand52ddd992022-11-22 11:51:53 +01003258 if (data && data->dh) {
3259 dh = data->dh;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003260 if (!ssl_sock_set_tmp_dh(ctx, dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003261 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
3262 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003263 memprintf(err, "%s, DH ciphers won't be available.\n",
3264 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003265 ret |= ERR_WARN;
3266 goto end;
3267 }
William Lallemandfa892222019-07-23 16:06:08 +02003268
3269 if (ssl_dh_ptr_index >= 0) {
3270 /* store a pointer to the DH params to avoid complaining about
3271 ssl-default-dh-param not being set for this SSL_CTX */
3272 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
3273 }
3274 }
3275 else if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003276 if (!ssl_sock_set_tmp_dh(ctx, global_dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003277 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
3278 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003279 memprintf(err, "%s, DH ciphers won't be available.\n",
3280 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003281 ret |= ERR_WARN;
3282 goto end;
3283 }
William Lallemandfa892222019-07-23 16:06:08 +02003284 }
3285 else {
3286 /* Clear openssl global errors stack */
3287 ERR_clear_error();
3288
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003289 /* We do not want DHE ciphers to be added to the cipher list
3290 * unless there is an explicit global dh option in the conf.
3291 */
3292 if (global_ssl.default_dh_param) {
3293 if (global_ssl.default_dh_param <= 1024) {
3294 /* we are limited to DH parameter of 1024 bits anyway */
3295 if (local_dh_1024 == NULL)
3296 local_dh_1024 = ssl_get_dh_1024();
William Lallemandfa892222019-07-23 16:06:08 +02003297
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003298 if (local_dh_1024 == NULL) {
3299 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3300 err && *err ? *err : "", path);
3301 ret |= ERR_ALERT | ERR_FATAL;
3302 goto end;
3303 }
William Lallemandfa892222019-07-23 16:06:08 +02003304
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003305 if (!ssl_sock_set_tmp_dh(ctx, local_dh_1024)) {
3306 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3307 err && *err ? *err : "", path);
3308 memprintf(err, "%s, DH ciphers won't be available.\n",
3309 err && *err ? *err : "");
3310 ret |= ERR_WARN;
3311 goto end;
3312 }
Emeric Bruna9363eb2019-10-17 14:53:03 +02003313 }
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003314 else {
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003315#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003316 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003317#else
William Lallemand52ddd992022-11-22 11:51:53 +01003318 ssl_sock_set_tmp_dh_from_pkey(ctx, data ? data->key : NULL);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003319#endif
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003320 }
William Lallemandfa892222019-07-23 16:06:08 +02003321 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003322 }
3323
William Lallemandf9568fc2019-10-16 18:27:58 +02003324end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003325 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003326 return ret;
3327}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003328#endif
William Lallemandfa892222019-07-23 16:06:08 +02003329
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003330
3331/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003332 * Returns a bitfield containing the flags:
3333 * ERR_FATAL in any fatal error case
3334 * ERR_ALERT if the reason of the error is available in err
3335 * ERR_WARN if a warning is available into err
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003336 * The caller is responsible of freeing the newly built or newly refcounted
3337 * find_chain element.
Emeric Bruna96b5822019-10-17 13:25:14 +02003338 * The value 0 means there is no error nor warning and
3339 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003340 */
William Lallemand52ddd992022-11-22 11:51:53 +01003341static int ssl_sock_load_cert_chain(const char *path, const struct ckch_data *data,
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003342 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003343{
Emeric Bruna96b5822019-10-17 13:25:14 +02003344 int errcode = 0;
William Lallemand45fed2c2022-11-15 16:56:03 +01003345 int ret;
3346
3347 ERR_clear_error();
Emeric Bruna96b5822019-10-17 13:25:14 +02003348
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003349 if (find_chain == NULL) {
3350 errcode |= ERR_FATAL;
3351 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003352 }
3353
William Lallemand52ddd992022-11-22 11:51:53 +01003354 if (!SSL_CTX_use_certificate(ctx, data->cert)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003355 ret = ERR_get_error();
3356 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s': %s.\n",
3357 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Emeric Bruna96b5822019-10-17 13:25:14 +02003358 errcode |= ERR_ALERT | ERR_FATAL;
3359 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003360 }
3361
William Lallemand52ddd992022-11-22 11:51:53 +01003362 if (data->chain) {
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003363 *find_chain = X509_chain_up_ref(data->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003364 } else {
3365 /* Find Certificate Chain in global */
3366 struct issuer_chain *issuer;
William Lallemand52ddd992022-11-22 11:51:53 +01003367 issuer = ssl_get0_issuer_chain(data->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003368 if (issuer)
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003369 *find_chain = X509_chain_up_ref(issuer->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003370 }
William Lallemand85888572020-02-27 14:48:35 +01003371
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003372 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003373 /* always put a null chain stack in the SSL_CTX so it does not
3374 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003375 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003376 }
3377
William Lallemand52ddd992022-11-22 11:51:53 +01003378 /* Load all certs in the data into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003379#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003380 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003381 ret = ERR_get_error();
3382 memprintf(err, "%sunable to load chain certificate into SSL Context '%s': %s. Make sure you are linking against Openssl >= 1.0.2.\n",
3383 err && *err ? *err : "", path, ERR_reason_error_string(ret));
William Lallemand935d8292020-08-12 20:02:10 +02003384 errcode |= ERR_ALERT | ERR_FATAL;
3385 goto end;
3386 }
William Lallemandf187ce62020-06-02 18:27:20 +02003387#else
3388 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003389 X509 *ca;
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003390 while ((ca = sk_X509_shift(*find_chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003391 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003392 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3393 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003394 X509_free(ca);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003395 errcode |= ERR_ALERT | ERR_FATAL;
3396 goto end;
3397 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003398 }
William Lallemandf187ce62020-06-02 18:27:20 +02003399#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003400
William Lallemand9a1d8392020-08-10 17:28:23 +02003401#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003402 /* remove the Root CA from the SSL_CTX if the option is activated */
3403 if (global_ssl.skip_self_issued_ca) {
3404 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3405 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3406 err && *err ? *err : "", path);
3407 errcode |= ERR_ALERT | ERR_FATAL;
3408 goto end;
3409 }
3410 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003411#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003412
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003413end:
3414 return errcode;
3415}
3416
3417
3418/* Loads the info in ckch into ctx
3419 * Returns a bitfield containing the flags:
3420 * ERR_FATAL in any fatal error case
3421 * ERR_ALERT if the reason of the error is available in err
3422 * ERR_WARN if a warning is available into err
3423 * The value 0 means there is no error nor warning and
3424 * the operation succeed.
3425 */
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01003426static 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 +01003427{
3428 int errcode = 0;
3429 STACK_OF(X509) *find_chain = NULL;
3430
William Lallemand5de49512022-10-27 14:41:07 +02003431 ERR_clear_error();
3432
William Lallemand52ddd992022-11-22 11:51:53 +01003433 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
William Lallemand5de49512022-10-27 14:41:07 +02003434 int ret;
3435
3436 ret = ERR_get_error();
3437 memprintf(err, "%sunable to load SSL private key into SSL Context '%s': %s.\n",
3438 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003439 errcode |= ERR_ALERT | ERR_FATAL;
3440 return errcode;
3441 }
3442
3443 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01003444 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003445 if (errcode & ERR_CODE)
3446 goto end;
3447
William Lallemandfa892222019-07-23 16:06:08 +02003448#ifndef OPENSSL_NO_DH
3449 /* store a NULL pointer to indicate we have not yet loaded
3450 a custom DH param file */
3451 if (ssl_dh_ptr_index >= 0) {
3452 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3453 }
3454
William Lallemand52ddd992022-11-22 11:51:53 +01003455 errcode |= ssl_sock_load_dh_params(ctx, data, path, err);
Emeric Brun7a883362019-10-17 13:27:40 +02003456 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003457 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3458 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003459 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003460 }
3461#endif
3462
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003463#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemand52ddd992022-11-22 11:51:53 +01003464 if (sctl_ex_index >= 0 && data->sctl) {
3465 if (ssl_sock_load_sctl(ctx, data->sctl) < 0) {
William Lallemanda17f4112019-10-10 15:16:44 +02003466 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003467 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003468 errcode |= ERR_ALERT | ERR_FATAL;
3469 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003470 }
3471 }
3472#endif
3473
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003474#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 +01003475 /* Load OCSP Info into context
3476 * If OCSP update mode is set to 'on', an entry will be created in the
3477 * ocsp tree even if no ocsp_response was known during init, unless the
3478 * frontend's conf disables ocsp update explicitely.
3479 */
Remi Tricot-Le Breton0c96ee42023-03-01 16:11:50 +01003480 if (ssl_sock_load_ocsp(path, ctx, data, find_chain) < 0) {
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01003481 if (data->ocsp_response)
Tim Duesterhus93128532019-11-23 23:45:10 +01003482 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 +01003483 err && *err ? *err : "", path);
3484 else
3485 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",
3486 err && *err ? *err : "", path);
3487 errcode |= ERR_ALERT | ERR_FATAL;
3488 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003489 }
William Lallemand246c0242019-10-11 08:59:13 +02003490#endif
3491
Emeric Bruna96b5822019-10-17 13:25:14 +02003492 end:
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003493 sk_X509_pop_free(find_chain, X509_free);
Emeric Bruna96b5822019-10-17 13:25:14 +02003494 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003495}
3496
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003497
3498/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
3499 * Returns a bitfield containing the flags:
3500 * ERR_FATAL in any fatal error case
3501 * ERR_ALERT if the reason of the error is available in err
3502 * ERR_WARN if a warning is available into err
3503 * The value 0 means there is no error nor warning and
3504 * the operation succeed.
3505 */
William Lallemand52ddd992022-11-22 11:51:53 +01003506static 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 +01003507 SSL_CTX *ctx, char **err)
3508{
3509 int errcode = 0;
3510 STACK_OF(X509) *find_chain = NULL;
3511
3512 /* Load the private key */
William Lallemand52ddd992022-11-22 11:51:53 +01003513 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003514 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3515 err && *err ? *err : "", path);
3516 errcode |= ERR_ALERT | ERR_FATAL;
3517 }
3518
3519 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01003520 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003521 if (errcode & ERR_CODE)
3522 goto end;
3523
3524 if (SSL_CTX_check_private_key(ctx) <= 0) {
3525 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3526 err && *err ? *err : "", path);
3527 errcode |= ERR_ALERT | ERR_FATAL;
3528 }
3529
3530end:
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003531 sk_X509_pop_free(find_chain, X509_free);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003532 return errcode;
3533}
3534
3535
William Lallemand614ca0d2019-10-07 13:52:11 +02003536/*
3537 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003538 *
3539 * Returns a bitfield containing the flags:
3540 * ERR_FATAL in any fatal error case
3541 * ERR_ALERT if the reason of the error is available in err
3542 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003543 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003544int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003545 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003546{
William Lallemandc9402072019-05-15 15:33:54 +02003547 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003548 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003549 int order = 0;
3550 X509_NAME *xname;
3551 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003552 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003553 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003554#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3555 STACK_OF(GENERAL_NAME) *names;
3556#endif
William Lallemand52ddd992022-11-22 11:51:53 +01003557 struct ckch_data *data;
William Lallemand614ca0d2019-10-07 13:52:11 +02003558 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003559 int errcode = 0;
3560
3561 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003562
William Lallemand52ddd992022-11-22 11:51:53 +01003563 if (!ckchs || !ckchs->data)
Emeric Brun054563d2019-10-17 13:16:58 +02003564 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003565
William Lallemand52ddd992022-11-22 11:51:53 +01003566 data = ckchs->data;
William Lallemand36b84632019-07-18 19:28:17 +02003567
William Lallemandc9402072019-05-15 15:33:54 +02003568 ctx = SSL_CTX_new(SSLv23_server_method());
3569 if (!ctx) {
3570 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3571 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003572 errcode |= ERR_ALERT | ERR_FATAL;
3573 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003574 }
3575
William Lallemand52ddd992022-11-22 11:51:53 +01003576 errcode |= ssl_sock_put_ckch_into_ctx(path, data, ctx, err);
Emeric Bruna96b5822019-10-17 13:25:14 +02003577 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003578 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003579
3580 ckch_inst = ckch_inst_new();
3581 if (!ckch_inst) {
3582 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3583 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003584 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003585 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003586 }
3587
William Lallemand52ddd992022-11-22 11:51:53 +01003588 pkey = X509_get_pubkey(data->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003589 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003590 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003591 switch(EVP_PKEY_base_id(pkey)) {
3592 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003593 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003594 break;
3595 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003596 kinfo.sig = TLSEXT_signature_ecdsa;
3597 break;
3598 case EVP_PKEY_DSA:
3599 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003600 break;
3601 }
3602 EVP_PKEY_free(pkey);
3603 }
3604
Emeric Brun50bcecc2013-04-22 13:05:23 +02003605 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003606 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003607 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 +02003608 if (order < 0) {
3609 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003610 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003611 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003612 }
3613 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003614 }
3615 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003616#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand52ddd992022-11-22 11:51:53 +01003617 names = X509_get_ext_d2i(data->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003618 if (names) {
3619 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3620 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3621 if (name->type == GEN_DNS) {
3622 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003623 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003624 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003625 if (order < 0) {
3626 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003627 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003628 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003629 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003630 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003631 }
3632 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003633 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003634 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003635#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand52ddd992022-11-22 11:51:53 +01003636 xname = X509_get_subject_name(data->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003637 i = -1;
3638 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3639 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003640 ASN1_STRING *value;
3641
3642 value = X509_NAME_ENTRY_get_data(entry);
3643 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003644 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003645 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003646 if (order < 0) {
3647 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003648 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003649 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003650 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003651 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003652 }
3653 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003654 /* we must not free the SSL_CTX anymore below, since it's already in
3655 * the tree, so it will be discovered and cleaned in time.
3656 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003657
Emeric Brunfc0421f2012-09-07 17:30:07 +02003658#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003659 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003660 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3661 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003662 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003663 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003664 }
3665#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003666 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003667 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003668 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003669 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003670 SSL_CTX_up_ref(ctx);
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003671 bind_conf->default_inst = ckch_inst;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003672 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003673
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003674 /* Always keep a reference to the newly constructed SSL_CTX in the
3675 * instance. This way if the instance has no SNIs, the SSL_CTX will
3676 * still be linked. */
3677 SSL_CTX_up_ref(ctx);
3678 ckch_inst->ctx = ctx;
3679
William Lallemand9117de92019-10-04 00:29:42 +02003680 /* everything succeed, the ckch instance can be used */
3681 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003682 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003683 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003684
William Lallemand02e19a52020-04-08 16:11:26 +02003685 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3686
Emeric Brun054563d2019-10-17 13:16:58 +02003687 *ckchi = ckch_inst;
3688 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003689
3690error:
3691 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003692 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003693 if (ckch_inst->is_default)
3694 SSL_CTX_free(ctx);
3695
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003696 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003697 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003698 }
William Lallemandd9199372019-10-04 15:37:05 +02003699 SSL_CTX_free(ctx);
3700
Emeric Brun054563d2019-10-17 13:16:58 +02003701 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003702}
3703
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003704
3705/*
3706 * This function allocate a ckch_inst that will be used on the backend side
3707 * (server line)
3708 *
3709 * Returns a bitfield containing the flags:
3710 * ERR_FATAL in any fatal error case
3711 * ERR_ALERT if the reason of the error is available in err
3712 * ERR_WARN if a warning is available into err
3713 */
3714int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01003715 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003716{
3717 SSL_CTX *ctx;
William Lallemand52ddd992022-11-22 11:51:53 +01003718 struct ckch_data *data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003719 struct ckch_inst *ckch_inst = NULL;
3720 int errcode = 0;
3721
3722 *ckchi = NULL;
3723
William Lallemand52ddd992022-11-22 11:51:53 +01003724 if (!ckchs || !ckchs->data)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003725 return ERR_FATAL;
3726
William Lallemand52ddd992022-11-22 11:51:53 +01003727 data = ckchs->data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003728
3729 ctx = SSL_CTX_new(SSLv23_client_method());
3730 if (!ctx) {
3731 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3732 err && *err ? *err : "", path);
3733 errcode |= ERR_ALERT | ERR_FATAL;
3734 goto error;
3735 }
3736
William Lallemand52ddd992022-11-22 11:51:53 +01003737 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, data, ctx, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003738 if (errcode & ERR_CODE)
3739 goto error;
3740
3741 ckch_inst = ckch_inst_new();
3742 if (!ckch_inst) {
3743 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3744 err && *err ? *err : "", path);
3745 errcode |= ERR_ALERT | ERR_FATAL;
3746 goto error;
3747 }
3748
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003749 /* everything succeed, the ckch instance can be used */
3750 ckch_inst->bind_conf = NULL;
3751 ckch_inst->ssl_conf = NULL;
3752 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01003753 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003754 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003755
3756 *ckchi = ckch_inst;
3757 return errcode;
3758
3759error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003760 SSL_CTX_free(ctx);
3761
3762 return errcode;
3763}
3764
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003765/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003766static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3767 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003768 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003769{
Emeric Brun054563d2019-10-17 13:16:58 +02003770 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003771
3772 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003773 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 +02003774
Emeric Brun054563d2019-10-17 13:16:58 +02003775 if (errcode & ERR_CODE)
3776 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003777
William Lallemand24bde432020-03-09 16:48:43 +01003778 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003779
3780 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003781 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003782 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003783}
3784
William Lallemanddb26e2b2021-01-26 12:01:46 +01003785/* This function generates a <struct ckch_inst *> for a <struct server *>, and
3786 * fill the SSL_CTX of the server.
3787 *
3788 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003789static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01003790 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003791{
3792 int errcode = 0;
3793
3794 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01003795 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003796
3797 if (errcode & ERR_CODE)
3798 return errcode;
3799
William Lallemanddb26e2b2021-01-26 12:01:46 +01003800 (*ckch_inst)->server = server;
3801 /* Keep the reference to the SSL_CTX in the server. */
3802 SSL_CTX_up_ref((*ckch_inst)->ctx);
3803 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003804 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003805 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003806 return errcode;
3807}
3808
William Lallemand6be66ec2020-03-06 22:26:32 +01003809
William Lallemand4c68bba2020-03-30 18:45:10 +02003810
3811
3812/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3813 * done once. Zero is returned if the operation fails. No error is returned
3814 * if the random is said as not implemented, because we expect that openssl
3815 * will use another method once needed.
3816 */
Amaury Denoyellec593bcd2021-05-19 15:35:29 +02003817int ssl_initialize_random(void)
William Lallemand4c68bba2020-03-30 18:45:10 +02003818{
3819 unsigned char random;
3820 static int random_initialized = 0;
3821
3822 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3823 random_initialized = 1;
3824
3825 return random_initialized;
3826}
3827
William Lallemand2954c472020-03-06 21:54:13 +01003828/* Load a crt-list file, this is done in 2 parts:
3829 * - store the content of the file in a crtlist structure with crtlist_entry structures
3830 * - generate the instances by iterating on entries in the crtlist struct
3831 *
3832 * Nothing is locked there, this function is used in the configuration parser.
3833 *
3834 * Returns a set of ERR_* flags possibly with an error in <err>.
3835 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003836int 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 +01003837{
3838 struct crtlist *crtlist = NULL;
3839 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003840 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003841 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003842 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003843 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003844
William Lallemand79d31ec2020-03-25 15:10:49 +01003845 bind_conf_node = malloc(sizeof(*bind_conf_node));
3846 if (!bind_conf_node) {
3847 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3848 cfgerr |= ERR_FATAL | ERR_ALERT;
3849 goto error;
3850 }
3851 bind_conf_node->next = NULL;
3852 bind_conf_node->bind_conf = bind_conf;
3853
William Lallemand41ca9302020-04-08 13:15:18 +02003854 /* strip trailing slashes, including first one */
3855 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3856 *end = 0;
3857
William Lallemand2954c472020-03-06 21:54:13 +01003858 /* look for an existing crtlist or create one */
3859 eb = ebst_lookup(&crtlists_tree, file);
3860 if (eb) {
3861 crtlist = ebmb_entry(eb, struct crtlist, node);
3862 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003863 /* load a crt-list OR a directory */
3864 if (dir)
3865 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3866 else
3867 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3868
William Lallemand2954c472020-03-06 21:54:13 +01003869 if (!(cfgerr & ERR_CODE))
3870 ebst_insert(&crtlists_tree, &crtlist->node);
3871 }
3872
3873 if (cfgerr & ERR_CODE) {
3874 cfgerr |= ERR_FATAL | ERR_ALERT;
3875 goto error;
3876 }
3877
3878 /* generates ckch instance from the crtlist_entry */
3879 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3880 struct ckch_store *store;
3881 struct ckch_inst *ckch_inst = NULL;
3882
3883 store = entry->node.key;
3884 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3885 if (cfgerr & ERR_CODE) {
3886 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3887 goto error;
3888 }
Willy Tarreau2b718102021-04-21 07:32:39 +02003889 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003890 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003891 }
William Lallemand2954c472020-03-06 21:54:13 +01003892
William Lallemand79d31ec2020-03-25 15:10:49 +01003893 /* add the bind_conf to the list */
3894 bind_conf_node->next = crtlist->bind_conf;
3895 crtlist->bind_conf = bind_conf_node;
3896
William Lallemand2954c472020-03-06 21:54:13 +01003897 return cfgerr;
3898error:
3899 {
William Lallemand49398312020-03-30 17:01:33 +02003900 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003901 struct ckch_inst *inst, *s_inst;
3902
William Lallemand49398312020-03-30 17:01:33 +02003903 lastentry = entry; /* which entry we tried to generate last */
3904 if (lastentry) {
3905 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3906 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3907 break;
3908
3909 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003910
William Lallemand49398312020-03-30 17:01:33 +02003911 /* this was not generated for this bind_conf, skip */
3912 if (inst->bind_conf != bind_conf)
3913 continue;
3914
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003915 /* free the sni_ctx and instance */
3916 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003917 }
William Lallemand2954c472020-03-06 21:54:13 +01003918 }
William Lallemand2954c472020-03-06 21:54:13 +01003919 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003920 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003921 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003922 return cfgerr;
3923}
3924
William Lallemand06b22a82020-03-16 14:45:55 +01003925/* Returns a set of ERR_* flags possibly with an error in <err>. */
3926int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3927{
3928 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01003929 int cfgerr = 0;
3930 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003931 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01003932 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01003933
3934 if ((ckchs = ckchs_lookup(path))) {
3935 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01003936 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3937 found++;
3938 } else if (stat(path, &buf) == 0) {
3939 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01003940 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003941 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003942 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003943 cfgerr |= ERR_ALERT | ERR_FATAL;
3944 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003945 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01003946 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003947 }
3948 } else {
3949 /* stat failed, could be a bundle */
3950 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02003951 char fp[MAXPATHLEN+1] = {0};
3952 int n = 0;
3953
3954 /* Load all possible certs and keys in separate ckch_store */
3955 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3956 struct stat buf;
3957 int ret;
3958
3959 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3960 if (ret > sizeof(fp))
3961 continue;
3962
3963 if ((ckchs = ckchs_lookup(fp))) {
3964 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01003965 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02003966 } else {
3967 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01003968 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003969 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02003970 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003971 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02003972 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3973 }
3974 }
3975 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01003976#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
3977 if (found) {
3978 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
3979 err && *err ? *err : "", path);
3980 cfgerr |= ERR_ALERT | ERR_FATAL;
3981 }
3982#endif
William Lallemand06b22a82020-03-16 14:45:55 +01003983 }
3984 }
William Lallemand06ce84a2020-11-20 15:36:13 +01003985 if (!found) {
3986 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3987 err && *err ? *err : "", path, strerror(errno));
3988 cfgerr |= ERR_ALERT | ERR_FATAL;
3989 }
William Lallemand06b22a82020-03-16 14:45:55 +01003990
3991 return cfgerr;
3992}
3993
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003994
3995/* Create a full ssl context and ckch instance that will be used for a specific
3996 * backend server (server configuration line).
3997 * Returns a set of ERR_* flags possibly with an error in <err>.
3998 */
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02003999int 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 +01004000{
4001 struct stat buf;
4002 int cfgerr = 0;
4003 struct ckch_store *ckchs;
4004 int found = 0; /* did we found a file to load ? */
4005
4006 if ((ckchs = ckchs_lookup(path))) {
4007 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01004008 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004009 found++;
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004010 } else {
4011 if (!create_if_none) {
4012 memprintf(err, "%sunable to stat SSL certificate '%s'.\n",
4013 err && *err ? *err : "", path);
4014 cfgerr |= ERR_ALERT | ERR_FATAL;
4015 goto out;
4016 }
4017
4018 if (stat(path, &buf) == 0) {
4019 /* We do not manage directories on backend side. */
4020 if (S_ISDIR(buf.st_mode) == 0) {
4021 ++found;
4022 ckchs = ckchs_load_cert_file(path, err);
4023 if (!ckchs)
4024 cfgerr |= ERR_ALERT | ERR_FATAL;
4025 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
4026 }
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004027 }
4028 }
4029 if (!found) {
4030 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
4031 err && *err ? *err : "", path, strerror(errno));
4032 cfgerr |= ERR_ALERT | ERR_FATAL;
4033 }
4034
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004035out:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004036 return cfgerr;
4037}
4038
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004039/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004040static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004041ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004042{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004043 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004044 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004045 SSL_OP_ALL | /* all known workarounds for bugs */
4046 SSL_OP_NO_SSLv2 |
4047 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02004048 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02004049 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004050 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02004051 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004052 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004053 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004054 SSL_MODE_ENABLE_PARTIAL_WRITE |
4055 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004056 SSL_MODE_RELEASE_BUFFERS |
4057 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004058 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004059 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004060 int flags = MC_SSL_O_ALL;
4061 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02004062 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004063
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004064 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004065 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004066
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004067 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004068 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
4069 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4070 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004071 else
4072 flags = conf_ssl_methods->flags;
4073
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004074 min = conf_ssl_methods->min;
4075 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02004076
4077 /* default minimum is TLSV12, */
4078 if (!min) {
4079 if (!max || (max >= default_min_ver)) {
4080 min = default_min_ver;
4081 } else {
4082 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). "
4083 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
4084 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
4085 min = max;
4086 }
4087 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004088 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004089 if (min)
4090 flags |= (methodVersions[min].flag - 1);
4091 if (max)
4092 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004093 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004094 min = max = CONF_TLSV_NONE;
4095 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004096 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004097 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004098 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004099 if (min) {
4100 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004101 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
4102 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4103 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
4104 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004105 hole = 0;
4106 }
4107 max = i;
4108 }
4109 else {
4110 min = max = i;
4111 }
4112 }
4113 else {
4114 if (min)
4115 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004116 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004117 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004118 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4119 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004120 cfgerr += 1;
4121 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004122 /* save real min/max in bind_conf */
4123 conf_ssl_methods->min = min;
4124 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004125
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004126#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004127 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004128 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004129 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004130 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004131 else
William Lallemandd0712f32020-06-11 17:34:00 +02004132 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
4133 /* clear every version flags in case SSL_CTX_new()
4134 * returns an SSL_CTX with disabled versions */
4135 SSL_CTX_clear_options(ctx, methodVersions[i].option);
4136
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004137 if (flags & methodVersions[i].flag)
4138 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02004139
4140 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004141#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004142 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004143 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4144 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02004145#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004146
4147 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
4148 options |= SSL_OP_NO_TICKET;
4149 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
4150 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08004151
4152#ifdef SSL_OP_NO_RENEGOTIATION
4153 options |= SSL_OP_NO_RENEGOTIATION;
4154#endif
4155
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004156 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004157
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004158#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004159 if (global_ssl.async)
4160 mode |= SSL_MODE_ASYNC;
4161#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004162 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004163 if (global_ssl.life_time)
4164 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004165
4166#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand4b7938d2022-09-07 10:54:17 +02004167# ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004168 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
4169 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004170# elif defined(HAVE_SSL_CLIENT_HELLO_CB)
4171# if defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01004172 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01004173 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
William Lallemand4b7938d2022-09-07 10:54:17 +02004174# endif /* ! SSL_OP_NO_ANTI_REPLAY */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02004175 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
4176 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004177# else /* ! OPENSSL_IS_BORINGSSL && ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004178 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004179# endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02004180 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
William Lallemand4b7938d2022-09-07 10:54:17 +02004181#endif /* ! SSL_CTRL_SET_TLSEXT_HOSTNAME */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004182 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004183}
4184
William Lallemand4f45bb92017-10-30 20:08:51 +01004185
4186static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
4187{
4188 if (first == block) {
4189 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4190 if (first->len > 0)
4191 sh_ssl_sess_tree_delete(sh_ssl_sess);
4192 }
4193}
4194
4195/* return first block from sh_ssl_sess */
4196static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
4197{
4198 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
4199
4200}
4201
4202/* store a session into the cache
4203 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
4204 * data: asn1 encoded session
4205 * data_len: asn1 encoded session length
4206 * Returns 1 id session was stored (else 0)
4207 */
4208static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
4209{
4210 struct shared_block *first;
4211 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
4212
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004213 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01004214 if (!first) {
4215 /* Could not retrieve enough free blocks to store that session */
4216 return 0;
4217 }
4218
4219 /* STORE the key in the first elem */
4220 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4221 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
4222 first->len = sizeof(struct sh_ssl_sess_hdr);
4223
4224 /* it returns the already existing node
4225 or current node if none, never returns null */
4226 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
4227 if (oldsh_ssl_sess != sh_ssl_sess) {
4228 /* NOTE: Row couldn't be in use because we lock read & write function */
4229 /* release the reserved row */
William Lallemand222e5a22023-01-31 14:12:28 +01004230 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 +01004231 shctx_row_dec_hot(ssl_shctx, first);
4232 /* replace the previous session already in the tree */
4233 sh_ssl_sess = oldsh_ssl_sess;
4234 /* ignore the previous session data, only use the header */
4235 first = sh_ssl_sess_first_block(sh_ssl_sess);
4236 shctx_row_inc_hot(ssl_shctx, first);
4237 first->len = sizeof(struct sh_ssl_sess_hdr);
4238 }
4239
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004240 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01004241 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004242 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01004243 }
4244
4245 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004246
4247 return 1;
4248}
William Lallemanded0b5ad2017-10-30 19:36:36 +01004249
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004250/* SSL callback used when a new session is created while connecting to a server */
4251static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4252{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004253 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004254 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004255
Willy Tarreau07d94e42018-09-20 10:57:52 +02004256 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004257
William Lallemand3ce6eed2021-02-08 10:43:44 +01004258 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4259 * one cache per thread, it only prevents to flush it from the CLI in
4260 * another thread */
4261
Olivier Houcharde6060c52017-11-16 17:42:52 +01004262 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4263 int len;
4264 unsigned char *ptr;
William Lallemande18d4e82021-11-17 02:59:21 +01004265 const char *sni;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004266
Olivier Houcharde6060c52017-11-16 17:42:52 +01004267 len = i2d_SSL_SESSION(sess, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01004268 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004269 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004270 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4271 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4272 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004273 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
4274 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004275 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4276 }
4277 if (s->ssl_ctx.reused_sess[tid].ptr) {
4278 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4279 &ptr);
4280 }
William Lallemande18d4e82021-11-17 02:59:21 +01004281
4282 if (s->ssl_ctx.reused_sess[tid].sni) {
4283 /* if the new sni is empty or isn' t the same as the old one */
4284 if ((!sni) || strcmp(s->ssl_ctx.reused_sess[tid].sni, sni) != 0) {
4285 ha_free(&s->ssl_ctx.reused_sess[tid].sni);
4286 if (sni)
4287 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4288 }
4289 } else if (sni) {
4290 /* if there wasn't an old sni but there is a new one */
4291 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4292 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004293 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004294 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004295 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004296 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004297 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004298 }
4299
4300 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004301}
4302
Olivier Houcharde6060c52017-11-16 17:42:52 +01004303
William Lallemanded0b5ad2017-10-30 19:36:36 +01004304/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004305int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004306{
4307 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4308 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4309 unsigned char *p;
4310 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004311 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004312 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004313
4314 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004315 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004316 * note: SSL_SESSION_set1_id is using
4317 * a memcpy so we need to use a different pointer
4318 * than sid_data or sid_ctx_data to avoid valgrind
4319 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004320 */
4321
4322 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004323
4324 /* copy value in an other buffer */
4325 memcpy(encid, sid_data, sid_length);
4326
4327 /* pad with 0 */
4328 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4329 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4330
4331 /* force length to zero to avoid ASN1 encoding */
4332 SSL_SESSION_set1_id(sess, encid, 0);
4333
4334 /* force length to zero to avoid ASN1 encoding */
4335 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004336
4337 /* check if buffer is large enough for the ASN1 encoded session */
4338 data_len = i2d_SSL_SESSION(sess, NULL);
4339 if (data_len > SHSESS_MAX_DATA_LEN)
4340 goto err;
4341
4342 p = encsess;
4343
4344 /* process ASN1 session encoding before the lock */
4345 i2d_SSL_SESSION(sess, &p);
4346
William Lallemanded0b5ad2017-10-30 19:36:36 +01004347
William Lallemanda3c77cf2017-10-30 23:44:40 +01004348 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004349 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004350 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004351 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004352err:
4353 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004354 SSL_SESSION_set1_id(sess, encid, sid_length);
4355 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004356
4357 return 0; /* do not increment session reference count */
4358}
4359
4360/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004361SSL_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 +01004362{
William Lallemand4f45bb92017-10-30 20:08:51 +01004363 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004364 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4365 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004366 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004367 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004368
Willy Tarreau4c19e992021-06-15 16:39:22 +02004369 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004370
4371 /* allow the session to be freed automatically by openssl */
4372 *do_copy = 0;
4373
4374 /* tree key is zeros padded sessionid */
4375 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4376 memcpy(tmpkey, key, key_len);
4377 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4378 key = tmpkey;
4379 }
4380
4381 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004382 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004383
4384 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004385 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4386 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004387 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004388 shctx_unlock(ssl_shctx);
Willy Tarreau4c19e992021-06-15 16:39:22 +02004389 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004390 return NULL;
4391 }
4392
William Lallemand4f45bb92017-10-30 20:08:51 +01004393 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4394 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004395
William Lallemand4f45bb92017-10-30 20:08:51 +01004396 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 +01004397
William Lallemanda3c77cf2017-10-30 23:44:40 +01004398 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004399
4400 /* decode ASN1 session */
4401 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004402 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004403 /* Reset session id and session id contenxt */
4404 if (sess) {
4405 SSL_SESSION_set1_id(sess, key, key_len);
4406 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4407 }
4408
4409 return sess;
4410}
4411
William Lallemand4f45bb92017-10-30 20:08:51 +01004412
William Lallemanded0b5ad2017-10-30 19:36:36 +01004413/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004414void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004415{
William Lallemand4f45bb92017-10-30 20:08:51 +01004416 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004417 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4418 unsigned int sid_length;
4419 const unsigned char *sid_data;
4420 (void)ctx;
4421
4422 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4423 /* tree key is zeros padded sessionid */
4424 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4425 memcpy(tmpkey, sid_data, sid_length);
4426 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4427 sid_data = tmpkey;
4428 }
4429
William Lallemanda3c77cf2017-10-30 23:44:40 +01004430 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004431
4432 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004433 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4434 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004435 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004436 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004437 }
4438
4439 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004440 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004441}
4442
4443/* Set session cache mode to server and disable openssl internal cache.
4444 * Set shared cache callbacks on an ssl context.
4445 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004446void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004447{
4448 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4449
4450 if (!ssl_shctx) {
4451 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4452 return;
4453 }
4454
4455 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4456 SSL_SESS_CACHE_NO_INTERNAL |
4457 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4458
4459 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004460 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4461 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4462 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004463}
William Lallemand7d42ef52020-07-06 11:41:30 +02004464
4465/*
4466 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4467 *
4468 * The format is:
4469 * * <Label> <space> <ClientRandom> <space> <Secret>
4470 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4471 */
4472
William Lallemand722180a2021-06-09 16:46:12 +02004473#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004474void SSL_CTX_keylog(const SSL *ssl, const char *line)
4475{
4476 struct ssl_keylog *keylog;
4477 char *lastarg = NULL;
4478 char *dst = NULL;
4479
4480 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4481 if (!keylog)
4482 return;
4483
4484 lastarg = strrchr(line, ' ');
4485 if (lastarg == NULL || ++lastarg == NULL)
4486 return;
4487
4488 dst = pool_alloc(pool_head_ssl_keylog_str);
4489 if (!dst)
4490 return;
4491
4492 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4493 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4494
4495 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4496 if (keylog->client_random)
4497 goto error;
4498 keylog->client_random = dst;
4499
4500 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4501 if (keylog->client_early_traffic_secret)
4502 goto error;
4503 keylog->client_early_traffic_secret = dst;
4504
4505 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4506 if(keylog->client_handshake_traffic_secret)
4507 goto error;
4508 keylog->client_handshake_traffic_secret = dst;
4509
4510 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4511 if (keylog->server_handshake_traffic_secret)
4512 goto error;
4513 keylog->server_handshake_traffic_secret = dst;
4514
4515 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4516 if (keylog->client_traffic_secret_0)
4517 goto error;
4518 keylog->client_traffic_secret_0 = dst;
4519
4520 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4521 if (keylog->server_traffic_secret_0)
4522 goto error;
4523 keylog->server_traffic_secret_0 = dst;
4524
4525 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4526 if (keylog->early_exporter_secret)
4527 goto error;
4528 keylog->early_exporter_secret = dst;
4529
4530 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4531 if (keylog->exporter_secret)
4532 goto error;
4533 keylog->exporter_secret = dst;
4534 } else {
4535 goto error;
4536 }
4537
4538 return;
4539
4540error:
4541 pool_free(pool_head_ssl_keylog_str, dst);
4542
4543 return;
4544}
4545#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004546
William Lallemand8b453912019-11-21 15:48:10 +01004547/*
4548 * This function applies the SSL configuration on a SSL_CTX
4549 * It returns an error code and fills the <err> buffer
4550 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004551static 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 +01004552{
4553 struct proxy *curproxy = bind_conf->frontend;
4554 int cfgerr = 0;
4555 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004556 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004557 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004558#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004559 const char *conf_ciphersuites;
4560#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004561 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004562
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004563 if (ssl_conf) {
4564 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4565 int i, min, max;
4566 int flags = MC_SSL_O_ALL;
4567
4568 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004569 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4570 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004571 if (min)
4572 flags |= (methodVersions[min].flag - 1);
4573 if (max)
4574 flags |= ~((methodVersions[max].flag << 1) - 1);
4575 min = max = CONF_TLSV_NONE;
4576 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4577 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4578 if (min)
4579 max = i;
4580 else
4581 min = max = i;
4582 }
4583 /* save real min/max */
4584 conf_ssl_methods->min = min;
4585 conf_ssl_methods->max = max;
4586 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004587 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4588 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004589 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004590 }
4591 }
4592
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004593 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004594 case SSL_SOCK_VERIFY_NONE:
4595 verify = SSL_VERIFY_NONE;
4596 break;
4597 case SSL_SOCK_VERIFY_OPTIONAL:
4598 verify = SSL_VERIFY_PEER;
4599 break;
4600 case SSL_SOCK_VERIFY_REQUIRED:
4601 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4602 break;
4603 }
4604 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4605 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004606 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 +01004607 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 +01004608 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 +01004609 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004610 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004611 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004612 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004613 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004614 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004615 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004616 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4617 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4618 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4619 cfgerr |= ERR_ALERT | ERR_FATAL;
4620 }
4621 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004622 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004623 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 +02004624 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004625 }
Emeric Brun850efd52014-01-29 12:24:34 +01004626 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004627 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4628 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004629 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004630 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004631#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004632 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004633 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4634
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004635 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004636 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4637 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004638 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004639 }
Emeric Brun561e5742012-10-02 15:20:55 +02004640 else {
4641 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4642 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004643 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004644#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004645 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004646 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004647#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004648 if(bind_conf->keys_ref) {
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +01004649 if (!SSL_CTX_set_tlsext_ticket_key_evp_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004650 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4651 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004652 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004653 }
4654 }
4655#endif
4656
William Lallemand4f45bb92017-10-30 20:08:51 +01004657 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004658 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4659 if (conf_ciphers &&
4660 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004661 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4662 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004663 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004664 }
4665
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004666#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004667 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4668 if (conf_ciphersuites &&
4669 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004670 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4671 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004672 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004673 }
4674#endif
4675
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004676#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02004677 if (!local_dh_1024)
4678 local_dh_1024 = ssl_get_dh_1024();
4679 if (!local_dh_2048)
4680 local_dh_2048 = ssl_get_dh_2048();
4681 if (!local_dh_4096)
4682 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02004683#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004684
Emeric Brunfc0421f2012-09-07 17:30:07 +02004685 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004686#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004687 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004688#endif
William Lallemand722180a2021-06-09 16:46:12 +02004689#ifdef HAVE_SSL_KEYLOG
William Lallemandb60a77b2022-11-18 15:00:15 +01004690 /* only activate the keylog callback if it was required to prevent performance loss */
4691 if (global_ssl.keylog > 0)
4692 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02004693#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004694
Bernard Spil13c53f82018-02-15 13:34:58 +01004695#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004696 ssl_conf_cur = NULL;
4697 if (ssl_conf && ssl_conf->npn_str)
4698 ssl_conf_cur = ssl_conf;
4699 else if (bind_conf->ssl_conf.npn_str)
4700 ssl_conf_cur = &bind_conf->ssl_conf;
4701 if (ssl_conf_cur)
4702 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004703#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004704#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004705 ssl_conf_cur = NULL;
4706 if (ssl_conf && ssl_conf->alpn_str)
4707 ssl_conf_cur = ssl_conf;
4708 else if (bind_conf->ssl_conf.alpn_str)
4709 ssl_conf_cur = &bind_conf->ssl_conf;
4710 if (ssl_conf_cur)
4711 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004712#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004713#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004714 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4715 if (conf_curves) {
4716 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004717 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4718 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004719 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004720 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004721 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004722 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004723#endif /* defined(SSL_CTX_set1_curves_list) */
4724
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004725 if (!conf_curves) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004726#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004727#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004728 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004729 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4730 NULL);
4731
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004732 if (ecdhe && SSL_CTX_set1_curves_list(ctx, ecdhe) == 0) {
4733 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4734 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
4735 cfgerr |= ERR_ALERT | ERR_FATAL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02004736 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004737#endif /* defined(SSL_CTX_set1_curves_list) */
Olivier Houchardc2aae742017-09-22 18:26:28 +02004738#else
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004739#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
4740 int i;
4741 EC_KEY *ecdh;
4742
Olivier Houchardc2aae742017-09-22 18:26:28 +02004743 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4744 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4745 ECDHE_DEFAULT_CURVE);
Emeric Brun2b58d042012-09-20 17:10:03 +02004746
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004747 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004748 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004749 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 +01004750 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004751 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004752 }
4753 else {
4754 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4755 EC_KEY_free(ecdh);
4756 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004757#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
4758#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Emeric Brun2b58d042012-09-20 17:10:03 +02004759 }
Emeric Brun2b58d042012-09-20 17:10:03 +02004760
Emeric Brunfc0421f2012-09-07 17:30:07 +02004761 return cfgerr;
4762}
4763
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004764
4765/*
4766 * Prepare the SSL_CTX based on the bind line configuration.
4767 * Since the CA file loading is made depending on the verify option of the bind
4768 * line, the link between the SSL_CTX and the CA file tree entry is made here.
4769 * If we want to create a link between the CA file entry and the corresponding
4770 * ckch instance (for CA file hot update), it needs to be done after
4771 * ssl_sock_prepare_ctx.
4772 * Returns 0 in case of success.
4773 */
4774int ssl_sock_prep_ctx_and_inst(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
4775 SSL_CTX *ctx, struct ckch_inst *ckch_inst, char **err)
4776{
4777 int errcode = 0;
4778
4779 errcode |= ssl_sock_prepare_ctx(bind_conf, ssl_conf, ctx, err);
4780 if (!errcode && ckch_inst)
4781 ckch_inst_add_cafile_link(ckch_inst, bind_conf, ssl_conf, NULL);
4782
4783 return errcode;
4784}
4785
Evan Broderbe554312013-06-27 00:05:25 -07004786static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4787{
4788 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4789 size_t prefixlen, suffixlen;
4790
4791 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004792 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004793 return 1;
4794
Evan Broderbe554312013-06-27 00:05:25 -07004795 /* The rest of this logic is based on RFC 6125, section 6.4.3
4796 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4797
Emeric Bruna848dae2013-10-08 11:27:28 +02004798 pattern_wildcard = NULL;
4799 pattern_left_label_end = pattern;
4800 while (*pattern_left_label_end != '.') {
4801 switch (*pattern_left_label_end) {
4802 case 0:
4803 /* End of label not found */
4804 return 0;
4805 case '*':
4806 /* If there is more than one wildcards */
4807 if (pattern_wildcard)
4808 return 0;
4809 pattern_wildcard = pattern_left_label_end;
4810 break;
4811 }
4812 pattern_left_label_end++;
4813 }
4814
4815 /* If it's not trivial and there is no wildcard, it can't
4816 * match */
4817 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004818 return 0;
4819
4820 /* Make sure all labels match except the leftmost */
4821 hostname_left_label_end = strchr(hostname, '.');
4822 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004823 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004824 return 0;
4825
4826 /* Make sure the leftmost label of the hostname is long enough
4827 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004828 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004829 return 0;
4830
4831 /* Finally compare the string on either side of the
4832 * wildcard */
4833 prefixlen = pattern_wildcard - pattern;
4834 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004835 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4836 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004837 return 0;
4838
4839 return 1;
4840}
4841
4842static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4843{
4844 SSL *ssl;
4845 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004846 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004847 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004848 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004849
4850 int depth;
4851 X509 *cert;
4852 STACK_OF(GENERAL_NAME) *alt_names;
4853 int i;
4854 X509_NAME *cert_subject;
4855 char *str;
4856
4857 if (ok == 0)
4858 return ok;
4859
4860 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004861 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02004862 ssl_ctx = __conn_get_ssl_sock_ctx(conn);
Evan Broderbe554312013-06-27 00:05:25 -07004863
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004864 /* We're checking if the provided hostnames match the desired one. The
4865 * desired hostname comes from the SNI we presented if any, or if not
4866 * provided then it may have been explicitly stated using a "verifyhost"
4867 * directive. If neither is set, we don't care about the name so the
4868 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004869 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004870 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004871 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004872 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004873 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004874 if (!servername)
4875 return ok;
4876 }
Evan Broderbe554312013-06-27 00:05:25 -07004877
4878 /* We only need to verify the CN on the actual server cert,
4879 * not the indirect CAs */
4880 depth = X509_STORE_CTX_get_error_depth(ctx);
4881 if (depth != 0)
4882 return ok;
4883
4884 /* At this point, the cert is *not* OK unless we can find a
4885 * hostname match */
4886 ok = 0;
4887
4888 cert = X509_STORE_CTX_get_current_cert(ctx);
4889 /* It seems like this might happen if verify peer isn't set */
4890 if (!cert)
4891 return ok;
4892
4893 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4894 if (alt_names) {
4895 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4896 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4897 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004898#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004899 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4900#else
Evan Broderbe554312013-06-27 00:05:25 -07004901 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004902#endif
Evan Broderbe554312013-06-27 00:05:25 -07004903 ok = ssl_sock_srv_hostcheck(str, servername);
4904 OPENSSL_free(str);
4905 }
4906 }
4907 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004908 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004909 }
4910
4911 cert_subject = X509_get_subject_name(cert);
4912 i = -1;
4913 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4914 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004915 ASN1_STRING *value;
4916 value = X509_NAME_ENTRY_get_data(entry);
4917 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004918 ok = ssl_sock_srv_hostcheck(str, servername);
4919 OPENSSL_free(str);
4920 }
4921 }
4922
Willy Tarreau71d058c2017-07-26 20:09:56 +02004923 /* report the mismatch and indicate if SNI was used or not */
4924 if (!ok && !conn->err_code)
4925 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004926 return ok;
4927}
4928
Emeric Brun94324a42012-10-11 14:00:19 +02004929/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004930int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004931{
4932 int cfgerr = 0;
William Lallemand2c776f12021-12-28 18:47:17 +01004933 SSL_CTX *ctx;
William Lallemand0adafb32022-12-13 18:17:44 +01004934 /* Automatic memory computations need to know we use SSL there
4935 * If this is an internal proxy, don't use it for the computation */
William Lallemand04007cb2022-12-14 10:34:36 +01004936 if (!(srv->proxy->cap & PR_CAP_INT))
William Lallemand0adafb32022-12-13 18:17:44 +01004937 global.ssl_used_backend = 1;
Willy Tarreaufce03112015-01-15 21:32:40 +01004938
4939 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004940 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004941 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004942 ha_alert("out of memory.\n");
Emeric Brun821bb9b2017-06-15 16:37:39 +02004943 cfgerr++;
4944 return cfgerr;
4945 }
4946 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004947 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004948 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004949
William Lallemand2c776f12021-12-28 18:47:17 +01004950 if (srv->ssl_ctx.client_crt) {
4951 const int create_if_none = srv->flags & SRV_F_DYNAMIC ? 0 : 1;
4952 char *err = NULL;
4953 int err_code = 0;
4954
4955 /* If there is a crt keyword there, the SSL_CTX will be created here. */
4956 err_code = ssl_sock_load_srv_cert(srv->ssl_ctx.client_crt, srv, create_if_none, &err);
4957 if (err_code != ERR_NONE) {
4958 if ((err_code & ERR_WARN) && !(err_code & ERR_ALERT))
4959 ha_warning("%s", err);
4960 else
4961 ha_alert("%s", err);
4962
4963 if (err_code & (ERR_FATAL|ERR_ABORT))
4964 cfgerr++;
4965 }
4966 ha_free(&err);
4967 }
4968
4969 ctx = srv->ssl_ctx.ctx;
4970
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004971 /* The context will be uninitialized if there wasn't any "cert" option
4972 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004973 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004974 ctx = SSL_CTX_new(SSLv23_client_method());
4975 if (!ctx) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004976 ha_alert("unable to allocate ssl context.\n");
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004977 cfgerr++;
4978 return cfgerr;
4979 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004980
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004981 srv->ssl_ctx.ctx = ctx;
4982 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004983
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004984 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 +01004985
4986 return cfgerr;
4987}
4988
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004989/* Initialize an SSL context that will be used on the backend side.
4990 * Returns an error count.
4991 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004992static int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004993{
4994 struct proxy *curproxy = srv->proxy;
4995 int cfgerr = 0;
4996 long options =
4997 SSL_OP_ALL | /* all known workarounds for bugs */
4998 SSL_OP_NO_SSLv2 |
4999 SSL_OP_NO_COMPRESSION;
5000 long mode =
5001 SSL_MODE_ENABLE_PARTIAL_WRITE |
5002 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
5003 SSL_MODE_RELEASE_BUFFERS |
5004 SSL_MODE_SMALL_BUFFERS;
5005 int verify = SSL_VERIFY_NONE;
5006 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
5007 int i, min, max, hole;
5008 int flags = MC_SSL_O_ALL;
5009
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005010 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005011 ha_warning("no-sslv3/no-tlsv1x are ignored for this server. "
5012 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n");
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005013 else
5014 flags = conf_ssl_methods->flags;
5015
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005016 /* Real min and max should be determinate with configuration and openssl's capabilities */
5017 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005018 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005019 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005020 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005021
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005022 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005023 min = max = CONF_TLSV_NONE;
5024 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005025 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005026 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005027 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005028 if (min) {
5029 if (hole) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005030 ha_warning("%s '%s': SSL/TLS versions range not contiguous for server '%s'. "
Christopher Faulet767a84b2017-11-24 16:50:31 +01005031 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
5032 proxy_type_str(curproxy), curproxy->id, srv->id,
5033 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005034 hole = 0;
5035 }
5036 max = i;
5037 }
5038 else {
5039 min = max = i;
5040 }
5041 }
5042 else {
5043 if (min)
5044 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005045 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005046 if (!min) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005047 ha_alert("%s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01005048 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005049 cfgerr += 1;
5050 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005051
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005052#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005053 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08005054 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005055 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005056 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005057 else
5058 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
5059 if (flags & methodVersions[i].flag)
5060 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005061#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005062 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005063 methodVersions[min].ctx_set_version(ctx, SET_MIN);
5064 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005065#endif
5066
5067 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
5068 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005069 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005070
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005071#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005072 if (global_ssl.async)
5073 mode |= SSL_MODE_ASYNC;
5074#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005075 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005076
Emeric Brun850efd52014-01-29 12:24:34 +01005077 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
5078 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01005079 switch (srv->ssl_ctx.verify) {
5080 case SSL_SOCK_VERIFY_NONE:
5081 verify = SSL_VERIFY_NONE;
5082 break;
5083 case SSL_SOCK_VERIFY_REQUIRED:
5084 verify = SSL_VERIFY_PEER;
5085 break;
5086 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005087 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02005088 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01005089 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02005090 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02005091 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005092 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005093 ha_alert("unable to set CA file '%s'.\n",
5094 srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005095 cfgerr++;
5096 }
5097 }
Emeric Brun850efd52014-01-29 12:24:34 +01005098 else {
5099 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005100 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 +01005101 else
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005102 ha_alert("verify is enabled but no CA file specified.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01005103 cfgerr++;
5104 }
Emeric Brunef42d922012-10-11 16:11:36 +02005105#ifdef X509_V_FLAG_CRL_CHECK
5106 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005107 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02005108
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01005109 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005110 ha_alert("unable to configure CRL file '%s'.\n",
5111 srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005112 cfgerr++;
5113 }
5114 else {
5115 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5116 }
5117 }
5118#endif
5119 }
5120
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005121 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5122 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02005123 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005124 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005125 ha_alert("unable to set SSL cipher list to '%s'.\n",
5126 srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02005127 cfgerr++;
5128 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005129
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05005130#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005131 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005132 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005133 ha_alert("unable to set TLS 1.3 cipher suites to '%s'.\n",
5134 srv->ssl_ctx.ciphersuites);
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005135 cfgerr++;
5136 }
5137#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01005138#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
5139 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005140 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01005141#endif
5142#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5143 if (srv->ssl_ctx.alpn_str)
5144 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
5145#endif
5146
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005147
5148 return cfgerr;
5149}
5150
5151/*
5152 * Prepare the frontend's SSL_CTX based on the server line configuration.
5153 * Since the CA file loading is made depending on the verify option of the
5154 * server line, the link between the SSL_CTX and the CA file tree entry is
5155 * made here.
5156 * If we want to create a link between the CA file entry and the corresponding
5157 * ckch instance (for CA file hot update), it needs to be done after
5158 * ssl_sock_prepare_srv_ssl_ctx.
5159 * Returns an error count.
5160 */
5161int ssl_sock_prep_srv_ctx_and_inst(const struct server *srv, SSL_CTX *ctx,
5162 struct ckch_inst *ckch_inst)
5163{
5164 int cfgerr = 0;
5165
5166 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, ctx);
5167 if (!cfgerr && ckch_inst)
5168 ckch_inst_add_cafile_link(ckch_inst, NULL, NULL, srv);
Emeric Brun94324a42012-10-11 14:00:19 +02005169
5170 return cfgerr;
5171}
5172
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005173
Frédéric Lécailleec216522020-11-23 14:33:30 +01005174/*
5175 * Create an initial CTX used to start the SSL connections.
5176 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
5177 * Returns 0 if succeeded, or something >0 if not.
5178 */
5179#ifdef USE_QUIC
5180static int ssl_initial_ctx(struct bind_conf *bind_conf)
5181{
5182 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
5183 return ssl_quic_initial_ctx(bind_conf);
5184 else
5185 return ssl_sock_initial_ctx(bind_conf);
5186}
5187#else
5188static int ssl_initial_ctx(struct bind_conf *bind_conf)
5189{
5190 return ssl_sock_initial_ctx(bind_conf);
5191}
5192#endif
5193
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005194/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005195 * be NULL, in which case nothing is done. Returns the number of errors
5196 * encountered.
5197 */
Willy Tarreau03209342016-12-22 17:08:28 +01005198int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005199{
5200 struct ebmb_node *node;
5201 struct sni_ctx *sni;
5202 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01005203 int errcode = 0;
5204 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02005205
Willy Tarreaufce03112015-01-15 21:32:40 +01005206 /* Automatic memory computations need to know we use SSL there */
5207 global.ssl_used_frontend = 1;
5208
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005209 /* Create initial_ctx used to start the ssl connection before do switchctx */
5210 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01005211 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005212 /* It should not be necessary to call this function, but it's
5213 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01005214 to initial_ctx in ssl_initial_ctx. */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005215 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, NULL, bind_conf->initial_ctx, NULL, &errmsg);
5216 }
5217 if (bind_conf->default_ctx) {
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005218 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 +01005219 }
Emeric Brun0bed9942014-10-30 19:25:24 +01005220
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005221 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005222 while (node) {
5223 sni = ebmb_entry(node, struct sni_ctx, name);
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005224 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005225 /* only initialize the CTX on its first occurrence and
5226 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005227 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
5228 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005229 node = ebmb_next(node);
5230 }
5231
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005232 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005233 while (node) {
5234 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01005235 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005236 /* only initialize the CTX on its first occurrence and
5237 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005238 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005239 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005240 node = ebmb_next(node);
5241 }
William Lallemand8b453912019-11-21 15:48:10 +01005242
5243 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005244 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005245 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005246 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005247 err++;
5248 }
5249
5250 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005251 return err;
5252}
5253
Willy Tarreau55d37912016-12-21 23:38:39 +01005254/* Prepares all the contexts for a bind_conf and allocates the shared SSL
5255 * context if needed. Returns < 0 on error, 0 on success. The warnings and
5256 * alerts are directly emitted since the rest of the stack does it below.
5257 */
5258int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
5259{
5260 struct proxy *px = bind_conf->frontend;
5261 int alloc_ctx;
5262 int err;
5263
Willy Tarreau11ba4042022-05-20 15:56:32 +02005264 if (!(bind_conf->options & BC_O_USE_SSL)) {
Willy Tarreau55d37912016-12-21 23:38:39 +01005265 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005266 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
5267 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01005268 }
5269 return 0;
5270 }
5271 if (!bind_conf->default_ctx) {
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005272 if (bind_conf->strict_sni && !(bind_conf->options & BC_O_GENERATE_CERTS)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005273 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5274 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005275 }
5276 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005277 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5278 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005279 return -1;
5280 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005281 }
William Lallemandc61c0b32017-12-04 18:46:39 +01005282 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005283 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02005284 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
Willy Tarreau91358592021-06-15 08:08:04 +02005285 sizeof(*sh_ssl_sess_tree), (global.nbthread > 1));
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02005286 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005287 if (alloc_ctx == SHCTX_E_INIT_LOCK)
5288 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");
5289 else
5290 ha_alert("Unable to allocate SSL session cache.\n");
5291 return -1;
5292 }
5293 /* free block callback */
5294 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5295 /* init the root tree within the extra space */
5296 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5297 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01005298 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005299 err = 0;
5300 /* initialize all certificate contexts */
5301 err += ssl_sock_prepare_all_ctx(bind_conf);
5302
5303 /* initialize CA variables if the certificates generation is enabled */
5304 err += ssl_sock_load_ca(bind_conf);
5305
5306 return -err;
5307}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005308
William Lallemand231610a2021-12-30 11:25:43 +01005309/* release ssl context allocated for servers. Most of the field free here
5310 * must also be allocated in srv_ssl_settings_cpy() */
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005311void ssl_sock_free_srv_ctx(struct server *srv)
5312{
Olivier Houchardc7566002018-11-20 23:33:50 +01005313#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
William Lallemand231610a2021-12-30 11:25:43 +01005314 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005315#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005316#ifdef OPENSSL_NPN_NEGOTIATED
William Lallemand231610a2021-12-30 11:25:43 +01005317 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005318#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005319 if (srv->ssl_ctx.reused_sess) {
5320 int i;
5321
William Lallemande18d4e82021-11-17 02:59:21 +01005322 for (i = 0; i < global.nbthread; i++) {
Willy Tarreaue709e822021-02-26 21:06:32 +01005323 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
William Lallemande18d4e82021-11-17 02:59:21 +01005324 ha_free(&srv->ssl_ctx.reused_sess[i].sni);
5325 }
Willy Tarreaue709e822021-02-26 21:06:32 +01005326 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005327 }
5328
Willy Tarreaue709e822021-02-26 21:06:32 +01005329 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005330 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005331 srv->ssl_ctx.ctx = NULL;
5332 }
William Lallemand231610a2021-12-30 11:25:43 +01005333
5334 ha_free(&srv->ssl_ctx.ca_file);
5335 ha_free(&srv->ssl_ctx.crl_file);
5336 ha_free(&srv->ssl_ctx.client_crt);
5337 ha_free(&srv->ssl_ctx.verify_host);
5338#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5339 ha_free(&srv->sni_expr);
William Lallemand43c2ce42022-03-16 17:48:19 +01005340 release_sample_expr(srv->ssl_ctx.sni);
5341 srv->ssl_ctx.sni = NULL;
William Lallemand231610a2021-12-30 11:25:43 +01005342#endif
5343 ha_free(&srv->ssl_ctx.ciphers);
5344#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
5345 ha_free(&srv->ssl_ctx.ciphersuites);
5346#endif
William Lallemande69563f2021-12-30 14:45:19 +01005347 /* If there is a certificate we must unlink the ckch instance */
5348 ckch_inst_free(srv->ssl_ctx.inst);
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005349}
5350
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005351/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005352 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5353 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005354void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005355{
5356 struct ebmb_node *node, *back;
5357 struct sni_ctx *sni;
5358
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005359 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005360 while (node) {
5361 sni = ebmb_entry(node, struct sni_ctx, name);
5362 back = ebmb_next(node);
5363 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005364 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005365 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005366 free(sni);
5367 node = back;
5368 }
5369
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005370 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005371 while (node) {
5372 sni = ebmb_entry(node, struct sni_ctx, name);
5373 back = ebmb_next(node);
5374 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005375 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005376 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005377 free(sni);
5378 node = back;
5379 }
William Lallemandb2408692020-06-24 09:54:29 +02005380
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005381 SSL_CTX_free(bind_conf->initial_ctx);
5382 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005383 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005384 bind_conf->default_ctx = NULL;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005385 bind_conf->default_inst = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005386 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005387}
William Lallemandb2408692020-06-24 09:54:29 +02005388
5389
5390void ssl_sock_deinit()
5391{
5392 crtlist_deinit(); /* must be free'd before the ckchs */
5393 ckch_deinit();
5394}
5395REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005396
Willy Tarreau795cdab2016-12-22 17:30:54 +01005397/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5398void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5399{
5400 ssl_sock_free_ca(bind_conf);
5401 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005402 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005403 free(bind_conf->ca_sign_file);
5404 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005405 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005406 free(bind_conf->keys_ref->filename);
5407 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005408 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005409 free(bind_conf->keys_ref);
5410 }
5411 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005412 bind_conf->ca_sign_pass = NULL;
5413 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005414}
5415
Christopher Faulet31af49d2015-06-09 17:29:50 +02005416/* Load CA cert file and private key used to generate certificates */
5417int
Willy Tarreau03209342016-12-22 17:08:28 +01005418ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005419{
Willy Tarreau03209342016-12-22 17:08:28 +01005420 struct proxy *px = bind_conf->frontend;
William Lallemand52ddd992022-11-22 11:51:53 +01005421 struct ckch_data *data = NULL;
Shimi Gersner5846c492020-08-23 13:58:12 +03005422 int ret = 0;
5423 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005424
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005425 if (!(bind_conf->options & BC_O_GENERATE_CERTS))
Shimi Gersner5846c492020-08-23 13:58:12 +03005426 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005427
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005428#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005429 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005430 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005431 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005432 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005433 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005434#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005435
Christopher Faulet31af49d2015-06-09 17:29:50 +02005436 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005437 ha_alert("Proxy '%s': cannot enable certificate generation, "
5438 "no CA certificate File configured at [%s:%d].\n",
5439 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005440 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005441 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005442
Shimi Gersner5846c492020-08-23 13:58:12 +03005443 /* Allocate cert structure */
William Lallemand52ddd992022-11-22 11:51:53 +01005444 data = calloc(1, sizeof(*data));
5445 if (!data) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005446 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\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 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005450
5451 /* Try to parse file */
William Lallemand52ddd992022-11-22 11:51:53 +01005452 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, data, &err)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005453 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5454 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005455 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005456 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005457 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005458
5459 /* Fail if missing cert or pkey */
William Lallemand52ddd992022-11-22 11:51:53 +01005460 if ((!data->cert) || (!data->key)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005461 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5462 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5463 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005464 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005465
Shimi Gersner5846c492020-08-23 13:58:12 +03005466 /* Final assignment to bind */
William Lallemand52ddd992022-11-22 11:51:53 +01005467 bind_conf->ca_sign_ckch = data;
Shimi Gersner5846c492020-08-23 13:58:12 +03005468 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005469
Shimi Gersner5846c492020-08-23 13:58:12 +03005470 failed:
William Lallemand52ddd992022-11-22 11:51:53 +01005471 if (data) {
5472 ssl_sock_free_cert_key_and_chain_contents(data);
5473 free(data);
Shimi Gersner5846c492020-08-23 13:58:12 +03005474 }
5475
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005476 bind_conf->options &= ~BC_O_GENERATE_CERTS;
Shimi Gersner5846c492020-08-23 13:58:12 +03005477 ret++;
5478 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005479}
5480
5481/* Release CA cert and private key used to generate certificated */
5482void
5483ssl_sock_free_ca(struct bind_conf *bind_conf)
5484{
Shimi Gersner5846c492020-08-23 13:58:12 +03005485 if (bind_conf->ca_sign_ckch) {
5486 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005487 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005488 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005489}
5490
Emeric Brun46591952012-05-18 15:47:34 +02005491/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005492 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5493 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5494 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5495 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005496 * 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 +01005497 * as parameters to this function.
5498 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5499 * CO_ER_SSL_NO_MEM.
5500 */
5501int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5502 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5503{
5504 int retry = 1;
5505
5506 retry:
5507 /* Alloc a new SSL session. */
5508 *ssl = SSL_new(ssl_ctx);
5509 if (!*ssl) {
5510 if (!retry--)
5511 goto err;
5512
5513 pool_gc(NULL);
5514 goto retry;
5515 }
5516
5517 *bio = BIO_new(bio_meth);
5518 if (!*bio) {
5519 SSL_free(*ssl);
5520 *ssl = NULL;
5521 if (!retry--)
5522 goto err;
5523
5524 pool_gc(NULL);
5525 goto retry;
5526 }
5527
5528 BIO_set_data(*bio, ctx);
5529 SSL_set_bio(*ssl, *bio, *bio);
5530
5531 /* set connection pointer. */
5532 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5533 SSL_free(*ssl);
5534 *ssl = NULL;
5535 if (!retry--)
5536 goto err;
5537
5538 pool_gc(NULL);
5539 goto retry;
5540 }
5541
5542 return 0;
5543
5544 err:
5545 conn->err_code = CO_ER_SSL_NO_MEM;
5546 return -1;
5547}
5548
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005549/* This function is called when all the XPRT have been initialized. We can
5550 * now attempt to start the SSL handshake.
5551 */
5552static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5553{
5554 struct ssl_sock_ctx *ctx = xprt_ctx;
5555
5556 if (ctx->xprt->start) {
5557 int ret;
5558
5559 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5560 if (ret < 0)
5561 return ret;
5562 }
5563 tasklet_wakeup(ctx->wait_event.tasklet);
5564
5565 return 0;
5566}
5567
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005568/*
Emeric Brun46591952012-05-18 15:47:34 +02005569 * This function is called if SSL * context is not yet allocated. The function
5570 * is designed to be called before any other data-layer operation and sets the
5571 * handshake flag on the connection. It is safe to call it multiple times.
5572 * It returns 0 on success and -1 in error case.
5573 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005574static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005575{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005576 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005577 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005578 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005579 return 0;
5580
Olivier Houchard66ab4982019-02-26 18:37:15 +01005581 ctx = pool_alloc(ssl_sock_ctx_pool);
5582 if (!ctx) {
5583 conn->err_code = CO_ER_SSL_NO_MEM;
5584 return -1;
5585 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005586 ctx->wait_event.tasklet = tasklet_new();
5587 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005588 conn->err_code = CO_ER_SSL_NO_MEM;
5589 pool_free(ssl_sock_ctx_pool, ctx);
5590 return -1;
5591 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005592 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5593 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005594 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005595 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005596 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005597 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005598 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005599 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005600 ctx->xprt_st = 0;
5601 ctx->xprt_ctx = NULL;
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005602 ctx->error_code = 0;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005603
5604 /* Only work with sockets for now, this should be adapted when we'll
5605 * add QUIC support.
5606 */
5607 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005608 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005609 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5610 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005611 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005612
Willy Tarreau82531f62021-10-06 12:15:18 +02005613 if (global.maxsslconn && global.sslconns >= global.maxsslconn) {
Willy Tarreau20879a02012-12-03 16:32:10 +01005614 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005615 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005616 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005617
Emeric Brun46591952012-05-18 15:47:34 +02005618 /* If it is in client mode initiate SSL session
5619 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005620 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005621 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5622 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005623 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005624
Olivier Houchard66ab4982019-02-26 18:37:15 +01005625 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005626 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005627 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5628 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5629 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 +01005630 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005631 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005632 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005633 } else if (sess) {
5634 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005635 }
5636 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005637 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005638
Emeric Brun46591952012-05-18 15:47:34 +02005639 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005640 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005641
Willy Tarreau82531f62021-10-06 12:15:18 +02005642 _HA_ATOMIC_INC(&global.sslconns);
5643 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005644 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005645 return 0;
5646 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005647 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005648 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005649
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005650 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5651 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005652 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005653
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005654#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005655 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005656 b_alloc(&ctx->early_buf);
5657 SSL_set_max_early_data(ctx->ssl,
5658 /* Only allow early data if we managed to allocate
5659 * a buffer.
5660 */
5661 (!b_is_null(&ctx->early_buf)) ?
5662 global.tune.bufsize - global.tune.maxrewrite : 0);
5663 }
5664#endif
5665
Olivier Houchard66ab4982019-02-26 18:37:15 +01005666 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005667
Emeric Brun46591952012-05-18 15:47:34 +02005668 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005669 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005670#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005671 if (bc->ssl_conf.early_data)
5672 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005673#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005674
Willy Tarreau82531f62021-10-06 12:15:18 +02005675 _HA_ATOMIC_INC(&global.sslconns);
5676 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005677 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005678 return 0;
5679 }
5680 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005681 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005682err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005683 if (ctx && ctx->wait_event.tasklet)
5684 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005685 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005686 return -1;
5687}
5688
5689
5690/* This is the callback which is used when an SSL handshake is pending. It
5691 * updates the FD status if it wants some polling before being called again.
5692 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5693 * otherwise it returns non-zero and removes itself from the connection's
5694 * flags (the bit is provided in <flag> by the caller).
5695 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005696static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005697{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005698 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Emeric Brun46591952012-05-18 15:47:34 +02005699 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005700 struct ssl_counters *counters = NULL;
5701 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005702 struct listener *li;
5703 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005704 socklen_t lskerr;
5705 int skerr;
5706
Emeric Brun46591952012-05-18 15:47:34 +02005707
Willy Tarreau3c728722014-01-23 13:50:42 +01005708 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005709 return 0;
5710
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005711 /* get counters */
5712 switch (obj_type(conn->target)) {
5713 case OBJ_TYPE_LISTENER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005714 li = __objt_listener(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005715 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5716 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5717 &ssl_stats_module);
5718 break;
5719
5720 case OBJ_TYPE_SERVER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005721 srv = __objt_server(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005722 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5723 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5724 &ssl_stats_module);
5725 break;
5726
5727 default:
5728 break;
5729 }
5730
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005731 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005732 goto out_error;
5733
Willy Tarreau06300382021-02-02 15:42:25 +01005734 /* don't start calculating a handshake on a dead connection */
5735 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5736 goto out_error;
5737
5738 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5739 * status from the lower layers, so let's check the FD directly. Ideally
5740 * the xprt layers should provide some status indicating their knowledge
5741 * of shutdowns or error.
5742 */
Willy Tarreau07ecfc52022-04-11 18:07:03 +02005743 BUG_ON(conn->flags & CO_FL_FDLESS);
5744
Willy Tarreau06300382021-02-02 15:42:25 +01005745 skerr = 0;
5746 lskerr = sizeof(skerr);
5747 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5748 skerr != 0)
5749 goto out_error;
5750
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005751#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005752 /*
5753 * Check if we have early data. If we do, we have to read them
5754 * before SSL_do_handshake() is called, And there's no way to
5755 * detect early data, except to try to read them
5756 */
5757 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005758 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005759
Olivier Houchard54907bb2019-12-19 15:02:39 +01005760 while (1) {
5761 ret = SSL_read_early_data(ctx->ssl,
5762 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5763 &read_data);
5764 if (ret == SSL_READ_EARLY_DATA_ERROR)
5765 goto check_error;
5766 if (read_data > 0) {
5767 conn->flags |= CO_FL_EARLY_DATA;
5768 b_add(&ctx->early_buf, read_data);
5769 }
5770 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5771 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5772 if (!b_data(&ctx->early_buf))
5773 b_free(&ctx->early_buf);
5774 break;
5775 }
5776 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005777 }
5778#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005779 /* If we use SSL_do_handshake to process a reneg initiated by
5780 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5781 * Usually SSL_write and SSL_read are used and process implicitly
5782 * the reneg handshake.
5783 * Here we use SSL_peek as a workaround for reneg.
5784 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005785 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005786 char c;
5787
Olivier Houchard66ab4982019-02-26 18:37:15 +01005788 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005789 if (ret <= 0) {
5790 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005791 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005792
Emeric Brun674b7432012-11-08 19:21:55 +01005793 if (ret == SSL_ERROR_WANT_WRITE) {
5794 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005795 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005796 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005797 return 0;
5798 }
5799 else if (ret == SSL_ERROR_WANT_READ) {
5800 /* handshake may have been completed but we have
5801 * no more data to read.
5802 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005803 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005804 ret = 1;
5805 goto reneg_ok;
5806 }
5807 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005808 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005809 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005810 return 0;
5811 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005812#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005813 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005814 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005815 return 0;
5816 }
5817#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005818 else if (ret == SSL_ERROR_SYSCALL) {
5819 /* if errno is null, then connection was successfully established */
5820 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5821 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005822 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005823#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5824 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005825 conn->err_code = CO_ER_SSL_HANDSHAKE;
5826#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005827 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005828#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005829 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005830 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005831 empty_handshake = state == TLS_ST_BEFORE;
5832#else
Lukas Tribus49799162019-07-08 14:29:15 +02005833 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5834 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005835#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005836 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005837 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005838 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005839 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5840 else
5841 conn->err_code = CO_ER_SSL_EMPTY;
5842 }
5843 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005844 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005845 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5846 else
5847 conn->err_code = CO_ER_SSL_ABORT;
5848 }
5849 }
5850 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005851 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005852 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005853 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005854 conn->err_code = CO_ER_SSL_HANDSHAKE;
5855 }
Lukas Tribus49799162019-07-08 14:29:15 +02005856#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005857 }
Emeric Brun674b7432012-11-08 19:21:55 +01005858 goto out_error;
5859 }
5860 else {
5861 /* Fail on all other handshake errors */
5862 /* Note: OpenSSL may leave unread bytes in the socket's
5863 * buffer, causing an RST to be emitted upon close() on
5864 * TCP sockets. We first try to drain possibly pending
5865 * data to avoid this as much as possible.
5866 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005867 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005868 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005869 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005870 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005871 goto out_error;
5872 }
5873 }
5874 /* read some data: consider handshake completed */
5875 goto reneg_ok;
5876 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005877 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005878check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005879 if (ret != 1) {
5880 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005881 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005882
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005883 if (!ctx->error_code)
5884 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton7c6898e2021-07-29 09:45:51 +02005885
Emeric Brun46591952012-05-18 15:47:34 +02005886 if (ret == SSL_ERROR_WANT_WRITE) {
5887 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005888 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005889 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005890 return 0;
5891 }
5892 else if (ret == SSL_ERROR_WANT_READ) {
5893 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005894 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005895 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5896 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005897 return 0;
5898 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005899#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005900 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005901 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005902 return 0;
5903 }
5904#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005905 else if (ret == SSL_ERROR_SYSCALL) {
5906 /* if errno is null, then connection was successfully established */
5907 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5908 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005909 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005910#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5911 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005912 conn->err_code = CO_ER_SSL_HANDSHAKE;
5913#else
5914 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005915#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005916 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005917 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005918 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005919#else
Lukas Tribus49799162019-07-08 14:29:15 +02005920 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5921 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005922#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005923 if (empty_handshake) {
5924 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005925 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005926 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5927 else
5928 conn->err_code = CO_ER_SSL_EMPTY;
5929 }
5930 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005931 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005932 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5933 else
5934 conn->err_code = CO_ER_SSL_ABORT;
5935 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005936 }
5937 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005938 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005939 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5940 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005941 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005942 }
Lukas Tribus49799162019-07-08 14:29:15 +02005943#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005944 }
Willy Tarreau89230192012-09-28 20:22:13 +02005945 goto out_error;
5946 }
Emeric Brun46591952012-05-18 15:47:34 +02005947 else {
5948 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005949 /* Note: OpenSSL may leave unread bytes in the socket's
5950 * buffer, causing an RST to be emitted upon close() on
5951 * TCP sockets. We first try to drain possibly pending
5952 * data to avoid this as much as possible.
5953 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005954 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005955 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005956 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005957 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005958 goto out_error;
5959 }
5960 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005961#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005962 else {
5963 /*
5964 * If the server refused the early data, we have to send a
5965 * 425 to the client, as we no longer have the data to sent
5966 * them again.
5967 */
5968 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005969 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005970 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5971 goto out_error;
5972 }
5973 }
5974 }
5975#endif
5976
Emeric Brun46591952012-05-18 15:47:34 +02005977
Emeric Brun674b7432012-11-08 19:21:55 +01005978reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005979
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005980#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00005981 /* ASYNC engine API doesn't support moving read/write
5982 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005983 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005984 */
5985 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005986 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005987#endif
Emeric Brun46591952012-05-18 15:47:34 +02005988 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005989 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005990 if (objt_server(conn->target)) {
5991 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5992 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5993 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005994 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005995 else {
5996 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5997 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5998 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5999 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006000
Willy Tarreau42995282020-11-06 13:19:18 +01006001 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006002 HA_ATOMIC_INC(&counters->sess);
6003 HA_ATOMIC_INC(&counters_px->sess);
Willy Tarreau42995282020-11-06 13:19:18 +01006004 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006005 }
Willy Tarreau42995282020-11-06 13:19:18 +01006006 else if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006007 HA_ATOMIC_INC(&counters->reused_sess);
6008 HA_ATOMIC_INC(&counters_px->reused_sess);
Emeric Brun46591952012-05-18 15:47:34 +02006009 }
6010
6011 /* The connection is now established at both layers, it's time to leave */
6012 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
6013 return 1;
6014
6015 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006016 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006017 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006018 ERR_clear_error();
6019
Emeric Brun9fa89732012-10-04 17:09:56 +02006020 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01006021 if (objt_server(conn->target)) {
6022 struct server *s = __objt_server(conn->target);
6023 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
6024 * one cache per thread, it only prevents to flush it from the CLI in
6025 * another thread */
6026
6027 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01006028 if (s->ssl_ctx.reused_sess[tid].ptr)
6029 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01006030 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02006031 }
6032
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006033 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006034 HA_ATOMIC_INC(&counters->failed_handshake);
6035 HA_ATOMIC_INC(&counters_px->failed_handshake);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006036 }
6037
Emeric Brun46591952012-05-18 15:47:34 +02006038 /* Fail on all other handshake errors */
6039 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01006040 if (!conn->err_code)
6041 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006042 return 0;
6043}
6044
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006045/* Called from the upper layer, to subscribe <es> to events <event_type>. The
6046 * event subscriber <es> is not allowed to change from a previous call as long
6047 * as at least one event is still subscribed. The <event_type> must only be a
6048 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
6049 * unless the transport layer was already released.
6050 */
6051static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006052{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006053 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006054
Olivier Houchard0ff28652019-06-24 18:57:39 +02006055 if (!ctx)
6056 return -1;
6057
Willy Tarreau113d52b2020-01-10 09:20:26 +01006058 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006059 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006060
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006061 ctx->subs = es;
6062 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006063
6064 /* we may have to subscribe to lower layers for new events */
6065 event_type &= ~ctx->wait_event.events;
6066 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
6067 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006068 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006069}
6070
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006071/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
6072 * The <es> pointer is not allowed to differ from the one passed to the
6073 * subscribe() call. It always returns zero.
6074 */
6075static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006076{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006077 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006078
Willy Tarreau113d52b2020-01-10 09:20:26 +01006079 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006080 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006081
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006082 es->events &= ~event_type;
6083 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01006084 ctx->subs = NULL;
6085
6086 /* If we subscribed, and we're not doing the handshake,
6087 * then we subscribed because the upper layer asked for it,
6088 * as the upper layer is no longer interested, we can
6089 * unsubscribe too.
6090 */
6091 event_type &= ctx->wait_event.events;
6092 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
6093 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006094
6095 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006096}
6097
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006098/* The connection has been taken over, so destroy the old tasklet and create
6099 * a new one. The original thread ID must be passed into orig_tid
6100 * It should be called with the takeover lock for the old thread held.
6101 * Returns 0 on success, and -1 on failure
6102 */
6103static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
6104{
6105 struct ssl_sock_ctx *ctx = xprt_ctx;
6106 struct tasklet *tl = tasklet_new();
6107
6108 if (!tl)
6109 return -1;
6110
6111 ctx->wait_event.tasklet->context = NULL;
6112 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
6113 ctx->wait_event.tasklet = tl;
6114 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
6115 ctx->wait_event.tasklet->context = ctx;
6116 return 0;
6117}
6118
Willy Tarreau41491682021-03-02 17:29:56 +01006119/* notify the next xprt that the connection is about to become idle and that it
6120 * may be stolen at any time after the function returns and that any tasklet in
6121 * the chain must be careful before dereferencing its context.
6122 */
6123static void ssl_set_idle(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_idle(conn, ctx->xprt, ctx->xprt_ctx);
6133}
6134
6135/* notify the next xprt that the connection is not idle anymore and that it may
6136 * not be stolen before the next xprt_set_idle().
6137 */
6138static void ssl_set_used(struct connection *conn, void *xprt_ctx)
6139{
6140 struct ssl_sock_ctx *ctx = xprt_ctx;
6141
6142 if (!ctx || !ctx->wait_event.tasklet)
6143 return;
6144
6145 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6146 if (ctx->xprt)
6147 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
6148}
6149
Olivier Houchard2e055482019-05-27 19:50:12 +02006150/* Use the provided XPRT as an underlying XPRT, and provide the old one.
6151 * Returns 0 on success, and non-zero on failure.
6152 */
6153static 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)
6154{
6155 struct ssl_sock_ctx *ctx = xprt_ctx;
6156
6157 if (oldxprt_ops != NULL)
6158 *oldxprt_ops = ctx->xprt;
6159 if (oldxprt_ctx != NULL)
6160 *oldxprt_ctx = ctx->xprt_ctx;
6161 ctx->xprt = toadd_ops;
6162 ctx->xprt_ctx = toadd_ctx;
6163 return 0;
6164}
6165
Olivier Houchard5149b592019-05-23 17:47:36 +02006166/* Remove the specified xprt. If if it our underlying XPRT, remove it and
6167 * return 0, otherwise just call the remove_xprt method from the underlying
6168 * XPRT.
6169 */
6170static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
6171{
6172 struct ssl_sock_ctx *ctx = xprt_ctx;
6173
6174 if (ctx->xprt_ctx == toremove_ctx) {
6175 ctx->xprt_ctx = newctx;
6176 ctx->xprt = newops;
6177 return 0;
6178 }
6179 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
6180}
6181
Willy Tarreau144f84a2021-03-02 16:09:26 +01006182struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02006183{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006184 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006185 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006186 struct connection *conn;
6187 int conn_in_list;
6188 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006189
Willy Tarreau41491682021-03-02 17:29:56 +01006190 if (state & TASK_F_USR1) {
6191 /* the tasklet was idling on an idle connection, it might have
6192 * been stolen, let's be careful!
6193 */
6194 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6195 if (tl->context == NULL) {
6196 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6197 tasklet_free(tl);
6198 return NULL;
6199 }
6200 conn = ctx->conn;
6201 conn_in_list = conn->flags & CO_FL_LIST_MASK;
6202 if (conn_in_list)
6203 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006204 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01006205 } else {
6206 conn = ctx->conn;
6207 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006208 }
Willy Tarreau41491682021-03-02 17:29:56 +01006209
Olivier Houchardea8dd942019-05-20 14:02:16 +02006210 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01006211 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006212 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006213 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
6214 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01006215 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006216 }
6217 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006218 /* If we had an error, or the handshake is done and I/O is available,
6219 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01006220 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02006221 * we can't be sure conn_fd_handler() will be called again.
6222 */
6223 if ((ctx->conn->flags & CO_FL_ERROR) ||
6224 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006225 int woke = 0;
6226
6227 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006228 if (ctx->subs) {
6229 tasklet_wakeup(ctx->subs->tasklet);
6230 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006231 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006232 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006233 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006234
Olivier Houchardea8dd942019-05-20 14:02:16 +02006235 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01006236 * upper layers know. If we have no mux, create it,
6237 * and once we have a mux, call its wake method if we didn't
6238 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02006239 */
6240 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01006241 if (!ctx->conn->mux)
6242 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006243 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006244 ret = ctx->conn->mux->wake(ctx->conn);
6245 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006246 }
6247 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006248#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006249 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006250 else if (b_data(&ctx->early_buf) && ctx->subs &&
6251 ctx->subs->events & SUB_RETRY_RECV) {
6252 tasklet_wakeup(ctx->subs->tasklet);
6253 ctx->subs->events &= ~SUB_RETRY_RECV;
6254 if (!ctx->subs->events)
6255 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01006256 }
6257#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006258leave:
6259 if (!ret && conn_in_list) {
6260 struct server *srv = objt_server(conn->target);
6261
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006262 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006263 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau85223482022-09-29 20:32:43 +02006264 eb64_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006265 else
Willy Tarreau85223482022-09-29 20:32:43 +02006266 eb64_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006267 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006268 }
Willy Tarreau74163142021-03-13 11:30:19 +01006269 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006270}
6271
Emeric Brun46591952012-05-18 15:47:34 +02006272/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01006273 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02006274 * buffer wraps, in which case a second call may be performed. The connection's
6275 * flags are updated with whatever special event is detected (error, read0,
6276 * empty). The caller is responsible for taking care of those events and
6277 * avoiding the call if inappropriate. The function does not call the
6278 * connection's polling update function, so the caller is responsible for this.
6279 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006280static 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 +02006281{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006282 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02006283 ssize_t ret;
6284 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02006285
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006286 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006287 goto out_error;
6288
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006289#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006290 if (b_data(&ctx->early_buf)) {
6291 try = b_contig_space(buf);
6292 if (try > b_data(&ctx->early_buf))
6293 try = b_data(&ctx->early_buf);
6294 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
6295 b_add(buf, try);
6296 b_del(&ctx->early_buf, try);
6297 if (b_data(&ctx->early_buf) == 0)
6298 b_free(&ctx->early_buf);
6299 return try;
6300 }
6301#endif
6302
Willy Tarreau911db9b2020-01-23 16:27:54 +01006303 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006304 /* a handshake was requested */
6305 return 0;
6306
Emeric Brun46591952012-05-18 15:47:34 +02006307 /* read the largest possible block. For this, we perform only one call
6308 * to recv() unless the buffer wraps and we exactly fill the first hunk,
6309 * in which case we accept to do it once again. A new attempt is made on
6310 * EINTR too.
6311 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01006312 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006313
Willy Tarreau591d4452018-06-15 17:21:00 +02006314 try = b_contig_space(buf);
6315 if (!try)
6316 break;
6317
Willy Tarreauabf08d92014-01-14 11:31:27 +01006318 if (try > count)
6319 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02006320
Olivier Houchard66ab4982019-02-26 18:37:15 +01006321 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02006322
Emeric Brune1f38db2012-09-03 20:36:47 +02006323 if (conn->flags & CO_FL_ERROR) {
6324 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006325 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006326 }
Emeric Brun46591952012-05-18 15:47:34 +02006327 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006328 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006329 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006330 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006331 }
Emeric Brun46591952012-05-18 15:47:34 +02006332 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006333 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006334 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006335 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006336 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006337 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006338#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006339 /* Async mode can be re-enabled, because we're leaving data state.*/
6340 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006341 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006342#endif
Emeric Brun46591952012-05-18 15:47:34 +02006343 break;
6344 }
6345 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006346 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006347 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6348 SUB_RETRY_RECV,
6349 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006350 /* handshake is running, and it may need to re-enable read */
6351 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006352#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006353 /* Async mode can be re-enabled, because we're leaving data state.*/
6354 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006355 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006356#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006357 break;
6358 }
Emeric Brun46591952012-05-18 15:47:34 +02006359 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006360 } else if (ret == SSL_ERROR_ZERO_RETURN)
6361 goto read0;
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006362 else if (ret == SSL_ERROR_SSL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006363 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6364 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006365 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006366 conn->err_code = CO_ERR_SSL_FATAL;
6367 }
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006368 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6369 * stack before shutting down the connection for
6370 * reading. */
Willy Tarreauacef5e22022-04-25 20:32:15 +02006371 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN || errno == EWOULDBLOCK))
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006372 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006373 /* otherwise it's a real error */
6374 goto out_error;
6375 }
6376 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006377 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006378 return done;
6379
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006380 clear_ssl_error:
6381 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006382 ssl_sock_dump_errors(conn, NULL);
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006383 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006384 read0:
6385 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006386 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006387
Emeric Brun46591952012-05-18 15:47:34 +02006388 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006389 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006390 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006391 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006392 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006393 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006394}
6395
6396
Willy Tarreau787db9a2018-06-14 18:31:46 +02006397/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6398 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6399 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006400 * Only one call to send() is performed, unless the buffer wraps, in which case
6401 * a second call may be performed. The connection's flags are updated with
6402 * whatever special event is detected (error, empty). The caller is responsible
6403 * for taking care of those events and avoiding the call if inappropriate. The
6404 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006405 * is responsible for this. The buffer's output is not adjusted, it's up to the
6406 * caller to take care of this. It's up to the caller to update the buffer's
6407 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006408 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006409static 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 +02006410{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006411 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006412 ssize_t ret;
6413 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006414
6415 done = 0;
6416
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006417 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006418 goto out_error;
6419
Willy Tarreau911db9b2020-01-23 16:27:54 +01006420 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006421 /* a handshake was requested */
6422 return 0;
6423
6424 /* send the largest possible block. For this we perform only one call
6425 * to send() unless the buffer wraps and we exactly fill the first hunk,
6426 * in which case we accept to do it once again.
6427 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006428 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006429#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006430 size_t written_data;
6431#endif
6432
Willy Tarreau787db9a2018-06-14 18:31:46 +02006433 try = b_contig_data(buf, done);
6434 if (try > count)
6435 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006436
Thomas Prückl10243932022-04-27 13:04:54 +02006437 if (global_ssl.hard_max_record && try > global_ssl.hard_max_record)
6438 try = global_ssl.hard_max_record;
6439
Willy Tarreau7bed9452014-02-02 02:00:24 +01006440 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006441 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006442 global_ssl.max_record && try > global_ssl.max_record) {
6443 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006444 }
6445 else {
6446 /* we need to keep the information about the fact that
6447 * we're not limiting the upcoming send(), because if it
6448 * fails, we'll have to retry with at least as many data.
6449 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006450 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006451 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006452
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006453#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006454 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006455 unsigned int max_early;
6456
Olivier Houchard522eea72017-11-03 16:27:47 +01006457 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006458 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006459 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006460 if (SSL_get0_session(ctx->ssl))
6461 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006462 else
6463 max_early = 0;
6464 }
6465
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006466 if (try + ctx->sent_early_data > max_early) {
6467 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006468 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006469 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006470 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006471 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006472 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006473 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006474 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006475 if (ret == 1) {
6476 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006477 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006478 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006479 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006480 /* Initiate the handshake, now */
6481 tasklet_wakeup(ctx->wait_event.tasklet);
6482 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006483
Olivier Houchardc2aae742017-09-22 18:26:28 +02006484 }
6485
6486 } else
6487#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006488 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006489
Emeric Brune1f38db2012-09-03 20:36:47 +02006490 if (conn->flags & CO_FL_ERROR) {
6491 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006492 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006493 }
Emeric Brun46591952012-05-18 15:47:34 +02006494 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006495 /* A send succeeded, so we can consider ourself connected */
6496 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006497 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006498 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006499 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006500 }
6501 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006502 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006503
Emeric Brun46591952012-05-18 15:47:34 +02006504 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006505 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006506 /* handshake is running, and it may need to re-enable write */
6507 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006508 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006509#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006510 /* Async mode can be re-enabled, because we're leaving data state.*/
6511 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006512 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006513#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006514 break;
6515 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006516
Emeric Brun46591952012-05-18 15:47:34 +02006517 break;
6518 }
6519 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006520 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006521 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006522 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6523 SUB_RETRY_RECV,
6524 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006525#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006526 /* Async mode can be re-enabled, because we're leaving data state.*/
6527 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006528 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006529#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006530 break;
6531 }
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006532 else if (ret == SSL_ERROR_SSL || ret == SSL_ERROR_SYSCALL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006533 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6534
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02006535 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006536 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006537 conn->err_code = CO_ERR_SSL_FATAL;
6538 }
Emeric Brun46591952012-05-18 15:47:34 +02006539 goto out_error;
6540 }
6541 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006542 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006543 return done;
6544
6545 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006546 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006547 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006548 ERR_clear_error();
6549
Emeric Brun46591952012-05-18 15:47:34 +02006550 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006551 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006552}
6553
Willy Tarreau832e2422021-05-13 10:11:03 +02006554void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006555
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006556 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006557
Olivier Houchardea8dd942019-05-20 14:02:16 +02006558
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006559 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006560 if (ctx->wait_event.events != 0)
6561 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6562 ctx->wait_event.events,
6563 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006564 if (ctx->subs) {
6565 ctx->subs->events = 0;
6566 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006567 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006568
Olivier Houchard692c1d02019-05-23 18:41:47 +02006569 if (ctx->xprt->close)
6570 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006571#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006572 if (global_ssl.async) {
6573 OSSL_ASYNC_FD all_fd[32], afd;
6574 size_t num_all_fds = 0;
6575 int i;
6576
Olivier Houchard66ab4982019-02-26 18:37:15 +01006577 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006578 if (num_all_fds > 32) {
6579 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6580 return;
6581 }
6582
Olivier Houchard66ab4982019-02-26 18:37:15 +01006583 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006584
6585 /* If an async job is pending, we must try to
6586 to catch the end using polling before calling
6587 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006588 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006589 for (i=0 ; i < num_all_fds ; i++) {
6590 /* switch on an handler designed to
6591 * handle the SSL_free
6592 */
6593 afd = all_fd[i];
6594 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006595 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006596 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006597 /* To ensure that the fd cache won't be used
6598 * and we'll catch a real RD event.
6599 */
6600 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006601 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006602 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006603 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006604 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006605 return;
6606 }
Emeric Brun3854e012017-05-17 20:42:48 +02006607 /* Else we can remove the fds from the fdtab
6608 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006609 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006610 * because the fd is owned by the engine.
6611 * the engine is responsible to close
6612 */
Emeric Brun7d392a52022-07-01 17:36:50 +02006613 for (i=0 ; i < num_all_fds ; i++) {
6614 /* We want to remove the fd from the fdtab
6615 * but we flag it to disown because the
6616 * close is performed by the engine itself
6617 */
6618 fdtab[all_fd[i]].state |= FD_DISOWN;
6619 fd_delete(all_fd[i]);
6620 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006621 }
6622#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006623 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006624 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006625 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006626 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau82531f62021-10-06 12:15:18 +02006627 _HA_ATOMIC_DEC(&global.sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006628 }
Emeric Brun46591952012-05-18 15:47:34 +02006629}
6630
6631/* This function tries to perform a clean shutdown on an SSL connection, and in
6632 * any case, flags the connection as reusable if no handshake was in progress.
6633 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006634static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006635{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006636 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006637
Willy Tarreau911db9b2020-01-23 16:27:54 +01006638 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006639 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006640 if (!clean)
6641 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006642 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006643 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006644 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006645 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006646 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006647 ERR_clear_error();
6648 }
Emeric Brun46591952012-05-18 15:47:34 +02006649}
6650
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006651
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006652/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006653int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6654{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006655 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemandd4f946c2019-12-05 10:26:40 +01006656 X509 *crt;
6657
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006658 if (!ctx)
William Lallemandd4f946c2019-12-05 10:26:40 +01006659 return 0;
William Lallemandd4f946c2019-12-05 10:26:40 +01006660 crt = SSL_get_certificate(ctx->ssl);
6661 if (!crt)
6662 return 0;
6663
6664 return cert_get_pkey_algo(crt, out);
6665}
6666
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006667/* used for ppv2 cert signature (can be used for logging) */
6668const char *ssl_sock_get_cert_sig(struct connection *conn)
6669{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006670 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006671
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006672 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6673 X509 *crt;
6674
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006675 if (!ctx)
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006676 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006677 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006678 if (!crt)
6679 return NULL;
6680 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6681 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6682}
6683
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006684/* used for ppv2 authority */
6685const char *ssl_sock_get_sni(struct connection *conn)
6686{
6687#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006688 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006689
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006690 if (!ctx)
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006691 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006692 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006693#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006694 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006695#endif
6696}
6697
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006698/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006699const char *ssl_sock_get_cipher_name(struct connection *conn)
6700{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006701 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006702
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006703 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006704 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006705 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006706}
6707
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006708/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006709const char *ssl_sock_get_proto_version(struct connection *conn)
6710{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006711 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006712
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006713 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006714 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006715 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006716}
6717
Olivier Houchardab28a322018-12-21 19:45:40 +01006718void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6719{
6720#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006721 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006722
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006723 if (!ctx)
Olivier Houcharde488ea82019-06-28 14:10:33 +02006724 return;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006725 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006726#endif
6727}
6728
Willy Tarreau119a4082016-12-22 21:58:38 +01006729/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6730 * to disable SNI.
6731 */
Willy Tarreau63076412015-07-10 11:33:32 +02006732void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6733{
6734#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006735 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemande18d4e82021-11-17 02:59:21 +01006736 struct server *s;
Willy Tarreau119a4082016-12-22 21:58:38 +01006737 char *prev_name;
6738
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006739 if (!ctx)
Willy Tarreau63076412015-07-10 11:33:32 +02006740 return;
Willy Tarreau77bfa662021-12-23 11:12:13 +01006741
6742 BUG_ON(!(conn->flags & CO_FL_WAIT_L6_CONN));
6743 BUG_ON(!(conn->flags & CO_FL_SSL_WAIT_HS));
6744
William Lallemande18d4e82021-11-17 02:59:21 +01006745 s = __objt_server(conn->target);
Willy Tarreau63076412015-07-10 11:33:32 +02006746
Willy Tarreau119a4082016-12-22 21:58:38 +01006747 /* if the SNI changes, we must destroy the reusable context so that a
William Lallemande18d4e82021-11-17 02:59:21 +01006748 * new connection will present a new SNI. compare with the SNI
6749 * previously stored in the reused_sess */
6750 /* the RWLOCK is used to ensure that we are not trying to flush the
6751 * cache from the CLI */
6752
6753 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
6754 prev_name = s->ssl_ctx.reused_sess[tid].sni;
Willy Tarreau119a4082016-12-22 21:58:38 +01006755 if ((!prev_name && hostname) ||
6756 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006757 SSL_set_session(ctx->ssl, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01006758 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau119a4082016-12-22 21:58:38 +01006759
Olivier Houchard66ab4982019-02-26 18:37:15 +01006760 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006761#endif
6762}
6763
Emeric Brun0abf8362014-06-24 18:26:41 +02006764/* Extract peer certificate's common name into the chunk dest
6765 * Returns
6766 * the len of the extracted common name
6767 * or 0 if no CN found in DN
6768 * or -1 on error case (i.e. no peer certificate)
6769 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006770int ssl_sock_get_remote_common_name(struct connection *conn,
6771 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006772{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006773 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
David Safb76832014-05-08 23:42:08 -04006774 X509 *crt = NULL;
6775 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006776 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006777 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006778 .area = (char *)&find_cn,
6779 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006780 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006781 int result = -1;
David Safb76832014-05-08 23:42:08 -04006782
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006783 if (!ctx)
Emeric Brun0abf8362014-06-24 18:26:41 +02006784 goto out;
David Safb76832014-05-08 23:42:08 -04006785
6786 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006787 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006788 if (!crt)
6789 goto out;
6790
6791 name = X509_get_subject_name(crt);
6792 if (!name)
6793 goto out;
David Safb76832014-05-08 23:42:08 -04006794
Emeric Brun0abf8362014-06-24 18:26:41 +02006795 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6796out:
David Safb76832014-05-08 23:42:08 -04006797 if (crt)
6798 X509_free(crt);
6799
6800 return result;
6801}
6802
Dave McCowan328fb582014-07-30 10:39:13 -04006803/* returns 1 if client passed a certificate for this session, 0 if not */
6804int ssl_sock_get_cert_used_sess(struct connection *conn)
6805{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006806 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dave McCowan328fb582014-07-30 10:39:13 -04006807 X509 *crt = NULL;
6808
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006809 if (!ctx)
Dave McCowan328fb582014-07-30 10:39:13 -04006810 return 0;
6811
6812 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006813 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006814 if (!crt)
6815 return 0;
6816
6817 X509_free(crt);
6818 return 1;
6819}
6820
6821/* returns 1 if client passed a certificate for this connection, 0 if not */
6822int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006823{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006824 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006825
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006826 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006827 return 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006828 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006829}
6830
6831/* returns result from SSL verify */
6832unsigned int ssl_sock_get_verify_result(struct connection *conn)
6833{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006834 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006835
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006836 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006837 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006838 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006839}
6840
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006841/* Returns the application layer protocol name in <str> and <len> when known.
6842 * Zero is returned if the protocol name was not found, otherwise non-zero is
6843 * returned. The string is allocated in the SSL context and doesn't have to be
6844 * freed by the caller. NPN is also checked if available since older versions
6845 * of openssl (1.0.1) which are more common in field only support this one.
6846 */
Amaury Denoyelle71e588c2021-11-12 11:23:29 +01006847int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006848{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006849#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6850 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006851 struct ssl_sock_ctx *ctx = xprt_ctx;
6852 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006853 return 0;
6854
6855 *str = NULL;
6856
6857#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006858 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006859 if (*str)
6860 return 1;
6861#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006862#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006863 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006864 if (*str)
6865 return 1;
6866#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006867#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006868 return 0;
6869}
6870
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006871/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006872int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006873{
6874 X509 *ca;
6875 X509_NAME *name = NULL;
6876 ASN1_OCTET_STRING *skid = NULL;
6877 STACK_OF(X509) *chain = NULL;
6878 struct issuer_chain *issuer;
6879 struct eb64_node *node;
6880 char *path;
6881 u64 key;
6882 int ret = 0;
6883
6884 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6885 if (chain == NULL) {
6886 chain = sk_X509_new_null();
6887 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6888 name = X509_get_subject_name(ca);
6889 }
6890 if (!sk_X509_push(chain, ca)) {
6891 X509_free(ca);
6892 goto end;
6893 }
6894 }
6895 if (!chain) {
6896 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6897 goto end;
6898 }
6899 if (!skid) {
6900 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6901 goto end;
6902 }
6903 if (!name) {
6904 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6905 goto end;
6906 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01006907 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006908 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006909 issuer = container_of(node, typeof(*issuer), node);
6910 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6911 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6912 goto end;
6913 }
6914 }
6915 issuer = calloc(1, sizeof *issuer);
6916 path = strdup(fp);
6917 if (!issuer || !path) {
6918 free(issuer);
6919 free(path);
6920 goto end;
6921 }
6922 issuer->node.key = key;
6923 issuer->path = path;
6924 issuer->chain = chain;
6925 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006926 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006927 ret = 1;
6928 end:
6929 if (skid)
6930 ASN1_OCTET_STRING_free(skid);
6931 if (chain)
6932 sk_X509_pop_free(chain, X509_free);
6933 return ret;
6934}
6935
William Lallemandda8584c2020-05-14 10:14:37 +02006936 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006937{
6938 AUTHORITY_KEYID *akid;
6939 struct issuer_chain *issuer = NULL;
6940
6941 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01006942 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006943 struct eb64_node *node;
6944 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01006945 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006946 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6947 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6948 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6949 issuer = ti;
6950 break;
6951 }
6952 }
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006953 }
Remi Tricot-Le Breton1621dc12022-11-03 15:16:48 +01006954 AUTHORITY_KEYID_free(akid);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006955 return issuer;
6956}
6957
William Lallemanddad31052020-05-14 17:47:32 +02006958void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006959{
6960 struct eb64_node *node, *back;
6961 struct issuer_chain *issuer;
6962
William Lallemande0f3fd52020-02-25 14:53:06 +01006963 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006964 while (node) {
6965 issuer = container_of(node, typeof(*issuer), node);
6966 back = eb64_next(node);
6967 eb64_delete(node);
6968 free(issuer->path);
6969 sk_X509_pop_free(issuer->chain, X509_free);
6970 free(issuer);
6971 node = back;
6972 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006973}
6974
William Lallemandd7bfbe22022-04-11 18:41:24 +02006975#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006976static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01006977 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006978
Emeric Brun3854e012017-05-17 20:42:48 +02006979 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006980 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006981 err_code = ERR_ABORT;
6982 }
6983 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006984}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006985#endif
6986
Willy Tarreaude5675a2021-01-20 14:41:29 +01006987/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006988 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01006989 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01006990static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01006991{
6992 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006993 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006994
6995 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006996 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006997
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006998 if (sctx->conn != conn) {
6999 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
7000 ret = 1;
7001 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01007002 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
7003
7004 if (sctx->xprt) {
7005 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
7006 if (sctx->xprt_ctx)
7007 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
7008 }
7009
7010 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007011
7012 /* as soon as a shutdown is reported the lower layer unregisters its
7013 * subscriber, so the situations below are transient and rare enough to
7014 * be reported as suspicious. In any case they shouldn't last.
7015 */
7016 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
7017 ret = 1;
7018 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
7019 ret = 1;
7020
Willy Tarreaude5675a2021-01-20 14:41:29 +01007021 chunk_appendf(&trash, " .subs=%p", sctx->subs);
7022 if (sctx->subs) {
7023 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007024 if (sctx->subs->tasklet->calls >= 1000000)
7025 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007026 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
7027 sctx->subs->tasklet->calls,
7028 sctx->subs->tasklet->context);
7029 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
7030 chunk_appendf(&trash, ")");
7031 }
7032 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
7033 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007034 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007035}
7036
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007037#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02007038/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007039 * each reference. The variable <ref> must point to the current node's list
7040 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02007041 */
William Lallemand32af2032016-10-29 18:09:35 +02007042static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007043struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02007044{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007045 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007046 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02007047
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007048 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007049 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007050 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02007051
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007052 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02007053}
7054
7055static inline
7056struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
7057{
7058 int id;
7059 char *error;
7060
7061 /* If the reference starts by a '#', this is numeric id. */
7062 if (reference[0] == '#') {
7063 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
7064 id = strtol(reference + 1, &error, 10);
7065 if (*error != '\0')
7066 return NULL;
7067
7068 /* Perform the unique id lookup. */
7069 return tlskeys_ref_lookupid(id);
7070 }
7071
7072 /* Perform the string lookup. */
7073 return tlskeys_ref_lookup(reference);
7074}
7075#endif
7076
7077
7078#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7079
Willy Tarreaua9380522022-05-05 08:50:17 +02007080/* dumps all tls keys. Relies on the show_keys_ctx context from the appctx. */
Willy Tarreaubd338642022-05-05 08:59:17 +02007081static int cli_io_handler_tlskeys_files(struct appctx *appctx)
7082{
Willy Tarreaua9380522022-05-05 08:50:17 +02007083 struct show_keys_ctx *ctx = appctx->svcctx;
William Lallemand32af2032016-10-29 18:09:35 +02007084
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007085 switch (ctx->state) {
7086 case SHOW_KEYS_INIT:
William Lallemand32af2032016-10-29 18:09:35 +02007087 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08007088 * quit the function with returning 0. The function is called
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007089 * later and restart at the state "SHOW_KEYS_INIT".
William Lallemand32af2032016-10-29 18:09:35 +02007090 */
7091 chunk_reset(&trash);
7092
Willy Tarreaubd338642022-05-05 08:59:17 +02007093 if (ctx->dump_entries)
William Lallemand32af2032016-10-29 18:09:35 +02007094 chunk_appendf(&trash, "# id secret\n");
7095 else
7096 chunk_appendf(&trash, "# id (file)\n");
7097
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007098 if (applet_putchk(appctx, &trash) == -1)
William Lallemand32af2032016-10-29 18:09:35 +02007099 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007100
William Lallemand32af2032016-10-29 18:09:35 +02007101 /* Now, we start the browsing of the references lists.
7102 * Note that the following call to LIST_ELEM return bad pointer. The only
7103 * available field of this pointer is <list>. It is used with the function
7104 * tlskeys_list_get_next() for retruning the first available entry
7105 */
Willy Tarreaua9380522022-05-05 08:50:17 +02007106 if (ctx->next_ref == NULL)
7107 ctx->next_ref = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007108
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007109 ctx->state = SHOW_KEYS_LIST;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007110 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007111
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007112 case SHOW_KEYS_LIST:
Willy Tarreaua9380522022-05-05 08:50:17 +02007113 while (ctx->next_ref) {
7114 struct tls_keys_ref *ref = ctx->next_ref;
William Lallemand32af2032016-10-29 18:09:35 +02007115
7116 chunk_reset(&trash);
Willy Tarreaubd338642022-05-05 08:59:17 +02007117 if (ctx->dump_entries && ctx->next_index == 0)
William Lallemand32af2032016-10-29 18:09:35 +02007118 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007119
Willy Tarreaua9380522022-05-05 08:50:17 +02007120 if (ctx->next_index == 0)
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007121 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
7122
Willy Tarreaubd338642022-05-05 08:59:17 +02007123 if (ctx->dump_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01007124 int head;
7125
7126 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
7127 head = ref->tls_ticket_enc_index;
Willy Tarreaua9380522022-05-05 08:50:17 +02007128 while (ctx->next_index < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02007129 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02007130
7131 chunk_reset(t2);
7132 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01007133 if (ref->key_size_bits == 128) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007134 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007135 sizeof(struct tls_sess_key_128),
7136 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007137 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007138 t2->area);
7139 }
7140 else if (ref->key_size_bits == 256) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007141 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007142 sizeof(struct tls_sess_key_256),
7143 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007144 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007145 t2->area);
7146 }
7147 else {
7148 /* This case should never happen */
Willy Tarreaua9380522022-05-05 08:50:17 +02007149 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, ctx->next_index);
Emeric Brun9e754772019-01-10 17:51:55 +01007150 }
William Lallemand32af2032016-10-29 18:09:35 +02007151
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007152 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007153 /* let's try again later from this stream. We add ourselves into
7154 * this stream's users so that it can remove us upon termination.
7155 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01007156 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
William Lallemand32af2032016-10-29 18:09:35 +02007157 return 0;
7158 }
Willy Tarreaua9380522022-05-05 08:50:17 +02007159 ctx->next_index++;
William Lallemand32af2032016-10-29 18:09:35 +02007160 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01007161 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaua9380522022-05-05 08:50:17 +02007162 ctx->next_index = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007163 }
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007164 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007165 /* let's try again later from this stream. We add ourselves into
7166 * this stream's users so that it can remove us upon termination.
7167 */
William Lallemand32af2032016-10-29 18:09:35 +02007168 return 0;
7169 }
7170
Willy Tarreaua9380522022-05-05 08:50:17 +02007171 if (ctx->names_only == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02007172 break;
7173
7174 /* get next list entry and check the end of the list */
Willy Tarreaua9380522022-05-05 08:50:17 +02007175 ctx->next_ref = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007176 }
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007177 ctx->state = SHOW_KEYS_DONE;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007178 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007179
7180 default:
William Lallemand32af2032016-10-29 18:09:35 +02007181 return 1;
7182 }
7183 return 0;
7184}
7185
Willy Tarreaua9380522022-05-05 08:50:17 +02007186/* Prepares a "show_keys_ctx" and sets the appropriate io_handler if needed */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007187static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007188{
Willy Tarreaua9380522022-05-05 08:50:17 +02007189 struct show_keys_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
7190
William Lallemand32af2032016-10-29 18:09:35 +02007191 /* no parameter, shows only file list */
7192 if (!*args[2]) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007193 ctx->names_only = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007194 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007195 }
7196
7197 if (args[2][0] == '*') {
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007198 /* list every TLS ticket keys */
7199 ctx->names_only = 1;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007200 } else {
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007201 ctx->next_ref = tlskeys_ref_lookup_ref(args[2]);
7202 if (!ctx->next_ref)
7203 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007204 }
7205
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007206 ctx->dump_entries = 1;
7207 return 0;
7208}
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007209
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007210static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
7211{
7212 struct tls_keys_ref *ref;
7213 int ret;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007214
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007215 /* Expect two parameters: the filename and the new new TLS key in encoding */
7216 if (!*args[3] || !*args[4])
7217 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 +02007218
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007219 ref = tlskeys_ref_lookup_ref(args[3]);
7220 if (!ref)
7221 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007222
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007223 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
7224 if (ret < 0)
7225 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007226
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007227 trash.data = ret;
7228 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
7229 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007230
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007231 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007232}
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007233#endif
7234
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007235
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007236#ifdef HAVE_SSL_PROVIDERS
7237struct provider_name {
7238 const char *name;
7239 struct list list;
7240};
7241
7242
7243static int ssl_provider_get_name_cb(OSSL_PROVIDER *provider, void *cbdata)
7244{
7245 struct list *provider_names = cbdata;
7246 struct provider_name *item = NULL;
7247 const char *name = OSSL_PROVIDER_get0_name(provider);
7248
7249 if (!provider_names)
7250 return 0;
7251
7252 item = calloc(1, sizeof(*item));
7253
7254 if (!item)
7255 return 0;
7256
7257 item->name = name;
7258 LIST_APPEND(provider_names, &item->list);
7259
7260 return 1;
7261}
7262
7263static void ssl_provider_get_name_list(struct list *provider_names)
7264{
7265 if (!provider_names)
7266 return;
7267
7268 OSSL_PROVIDER_do_all(NULL, ssl_provider_get_name_cb, provider_names);
7269}
7270
7271static void ssl_provider_clear_name_list(struct list *provider_names)
7272{
7273 struct provider_name *item = NULL, *item_s = NULL;
7274
7275 if (provider_names) {
7276 list_for_each_entry_safe(item, item_s, provider_names, list) {
7277 LIST_DELETE(&item->list);
7278 free(item);
7279 }
7280 }
7281}
7282
7283static int cli_io_handler_show_providers(struct appctx *appctx)
7284{
7285 struct buffer *trash = get_trash_chunk();
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007286 struct list provider_names;
7287 struct provider_name *name;
7288
7289 LIST_INIT(&provider_names);
7290
7291 chunk_appendf(trash, "Loaded providers : \n");
7292
7293 ssl_provider_get_name_list(&provider_names);
7294
7295 list_for_each_entry(name, &provider_names, list) {
7296 chunk_appendf(trash, "\t- %s\n", name->name);
7297 }
7298
7299 ssl_provider_clear_name_list(&provider_names);
7300
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007301 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007302 goto yield;
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007303
7304 return 1;
7305
7306yield:
7307 return 0;
7308}
7309#endif
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01007310
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007311
William Lallemand32af2032016-10-29 18:09:35 +02007312/* register cli keywords */
7313static struct cli_kw_list cli_kws = {{ },{
7314#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01007315 { { "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 },
7316 { { "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 +02007317#endif
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007318#ifdef HAVE_SSL_PROVIDERS
7319 { { "show", "ssl", "providers", NULL }, "show ssl providers : show loaded SSL providers", NULL, cli_io_handler_show_providers },
7320#endif
William Lallemand32af2032016-10-29 18:09:35 +02007321 { { NULL }, NULL, NULL, NULL }
7322}};
7323
Willy Tarreau0108d902018-11-25 19:14:37 +01007324INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02007325
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02007326/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02007327struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02007328 .snd_buf = ssl_sock_from_buf,
7329 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01007330 .subscribe = ssl_subscribe,
7331 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02007332 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02007333 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02007334 .rcv_pipe = NULL,
7335 .snd_pipe = NULL,
7336 .shutr = NULL,
7337 .shutw = ssl_sock_shutw,
7338 .close = ssl_sock_close,
7339 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01007340 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01007341 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01007342 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01007343 .prepare_srv = ssl_sock_prepare_srv_ctx,
7344 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007345 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02007346 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01007347 .set_idle = ssl_set_idle,
7348 .set_used = ssl_set_used,
Willy Tarreaude827952022-04-11 10:43:28 +02007349 .get_ssl_sock_ctx = ssl_sock_get_ctx,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01007350 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01007351 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02007352};
7353
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007354enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
7355 struct session *sess, struct stream *s, int flags)
7356{
7357 struct connection *conn;
7358
7359 conn = objt_conn(sess->origin);
7360
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007361 if (conn) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007362 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007363 sc_ep_set(s->scf, SE_FL_WAIT_FOR_HS);
Christopher Faulet6e1bbc42022-12-12 08:08:15 +01007364 s->req.flags |= CF_READ_EVENT;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007365 return ACT_RET_YIELD;
7366 }
7367 }
7368 return (ACT_RET_CONT);
7369}
7370
7371static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
7372{
7373 rule->action_ptr = ssl_action_wait_for_hs;
7374
7375 return ACT_RET_PRS_OK;
7376}
7377
7378static struct action_kw_list http_req_actions = {ILH, {
7379 { "wait-for-handshake", ssl_parse_wait_for_hs },
7380 { /* END */ }
7381}};
7382
Willy Tarreau0108d902018-11-25 19:14:37 +01007383INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
7384
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007385#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007386
7387static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7388{
7389 if (ptr) {
7390 chunk_destroy(ptr);
7391 free(ptr);
7392 }
7393}
7394
7395#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007396
William Lallemand76b4a122020-08-04 17:41:39 +02007397
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007398static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7399{
Willy Tarreaubafbe012017-11-24 17:34:44 +01007400 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007401}
William Lallemand7d42ef52020-07-06 11:41:30 +02007402
William Lallemand722180a2021-06-09 16:46:12 +02007403#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007404static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7405{
7406 struct ssl_keylog *keylog;
7407
7408 if (!ptr)
7409 return;
7410
7411 keylog = ptr;
7412
7413 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7414 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7415 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7416 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7417 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7418 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7419 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7420 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7421
7422 pool_free(pool_head_ssl_keylog, ptr);
7423}
7424#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007425
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007426static void ssl_sock_clt_crt_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7427{
7428 if (!ptr)
7429 return;
7430
7431 X509_free((X509*)ptr);
7432}
7433
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01007434static void ssl_sock_clt_sni_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7435{
7436 pool_free(ssl_sock_client_sni_pool, ptr);
7437}
7438
Willy Tarreau92faadf2012-10-10 23:04:25 +02007439static void __ssl_sock_init(void)
7440{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007441#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007442 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007443 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007444#endif
Emeric Brun46591952012-05-18 15:47:34 +02007445
Willy Tarreauef934602016-12-22 23:12:01 +01007446 if (global_ssl.listen_default_ciphers)
7447 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7448 if (global_ssl.connect_default_ciphers)
7449 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007450#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007451 if (global_ssl.listen_default_ciphersuites)
7452 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7453 if (global_ssl.connect_default_ciphersuites)
7454 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7455#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007456
Willy Tarreau13e14102016-12-22 20:25:26 +01007457 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007458#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007459 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007460#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007461#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007462 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007463 n = sk_SSL_COMP_num(cm);
7464 while (n--) {
7465 (void) sk_SSL_COMP_pop(cm);
7466 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007467#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007468
Willy Tarreau5db847a2019-05-09 14:13:35 +02007469#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007470 ssl_locking_init();
7471#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007472#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007473 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
7474#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007475
7476#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7477 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
7478#endif
7479
Thierry FOURNIER28962c92018-06-17 21:37:05 +02007480 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02007481 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 +01007482#ifdef USE_QUIC
7483 ssl_qc_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7484#endif /* USE_QUIC */
William Lallemand722180a2021-06-09 16:46:12 +02007485#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007486 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
7487#endif
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007488 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 +01007489 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 +02007490#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00007491 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007492 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007493#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01007494#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7495 hap_register_post_check(tlskeys_finalize_config);
7496#endif
Willy Tarreau80713382018-11-26 10:19:54 +01007497
7498 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
7499 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
7500
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007501 hap_register_post_deinit(ssl_free_global_issuers);
7502
Willy Tarreau80713382018-11-26 10:19:54 +01007503#ifndef OPENSSL_NO_DH
7504 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7505 hap_register_post_deinit(ssl_free_dh);
7506#endif
William Lallemandd7bfbe22022-04-11 18:41:24 +02007507#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Willy Tarreau80713382018-11-26 10:19:54 +01007508 hap_register_post_deinit(ssl_free_engines);
7509#endif
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02007510#ifdef HAVE_SSL_PROVIDERS
7511 hap_register_post_deinit(ssl_unload_providers);
7512#endif
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01007513#if HA_OPENSSL_VERSION_NUMBER < 0x3000000fL
Willy Tarreau80713382018-11-26 10:19:54 +01007514 /* Load SSL string for the verbose & debug mode. */
7515 ERR_load_SSL_strings();
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01007516#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007517 ha_meth = BIO_meth_new(0x666, "ha methods");
7518 BIO_meth_set_write(ha_meth, ha_ssl_write);
7519 BIO_meth_set_read(ha_meth, ha_ssl_read);
7520 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
7521 BIO_meth_set_create(ha_meth, ha_ssl_new);
7522 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
7523 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
7524 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02007525
7526 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007527
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01007528 HA_SPIN_INIT(&ocsp_tree_lock);
7529
Dragan Dosen9ac98092020-05-11 15:51:45 +02007530 /* Try to register dedicated SSL/TLS protocol message callbacks for
7531 * heartbleed attack (CVE-2014-0160) and clienthello.
7532 */
7533 hap_register_post_check(ssl_sock_register_msg_callbacks);
7534
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007535 /* Try to free all callbacks that were registered by using
7536 * ssl_sock_register_msg_callback().
7537 */
7538 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01007539}
Willy Tarreau79367f92022-04-25 19:18:24 +02007540INITCALL0(STG_REGISTER, __ssl_sock_init);
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01007541
Willy Tarreau80713382018-11-26 10:19:54 +01007542/* Compute and register the version string */
7543static void ssl_register_build_options()
7544{
7545 char *ptr = NULL;
7546 int i;
7547
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007548 memprintf(&ptr, "Built with OpenSSL version : "
7549#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007550 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007551#else /* OPENSSL_IS_BORINGSSL */
7552 OPENSSL_VERSION_TEXT
7553 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08007554 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02007555 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007556#endif
7557 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007558#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007559 "no (library version too old)"
7560#elif defined(OPENSSL_NO_TLSEXT)
7561 "no (disabled via OPENSSL_NO_TLSEXT)"
7562#else
7563 "yes"
7564#endif
7565 "", ptr);
7566
7567 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
7568#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
7569 "yes"
7570#else
7571#ifdef OPENSSL_NO_TLSEXT
7572 "no (because of OPENSSL_NO_TLSEXT)"
7573#else
7574 "no (version might be too old, 0.9.8f min needed)"
7575#endif
7576#endif
7577 "", ptr);
7578
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02007579 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
7580 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
7581 if (methodVersions[i].option)
7582 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007583
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007584#ifdef HAVE_SSL_PROVIDERS
7585 {
7586 struct list provider_names;
7587 struct provider_name *name;
7588 LIST_INIT(&provider_names);
7589 ssl_provider_get_name_list(&provider_names);
7590
7591 memprintf(&ptr, "%s\nOpenSSL providers loaded :", ptr);
7592
7593 list_for_each_entry(name, &provider_names, list) {
7594 memprintf(&ptr, "%s %s", ptr, name->name);
7595 }
7596
7597 ssl_provider_clear_name_list(&provider_names);
7598 }
7599#endif
7600
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007601 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01007602}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007603
Willy Tarreau80713382018-11-26 10:19:54 +01007604INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02007605
William Lallemandd7bfbe22022-04-11 18:41:24 +02007606#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00007607void ssl_free_engines(void) {
7608 struct ssl_engine_list *wl, *wlb;
7609 /* free up engine list */
7610 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
7611 ENGINE_finish(wl->e);
7612 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02007613 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00007614 free(wl);
7615 }
7616}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007617#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02007618
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02007619#ifdef HAVE_SSL_PROVIDERS
7620void ssl_unload_providers(void) {
7621 struct ssl_provider_list *prov, *provb;
7622 list_for_each_entry_safe(prov, provb, &openssl_providers, list) {
7623 OSSL_PROVIDER_unload(prov->provider);
7624 LIST_DELETE(&prov->list);
7625 free(prov);
7626 }
7627}
7628#endif
7629
Remi Gacogned3a23c32015-05-28 16:39:47 +02007630#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00007631void ssl_free_dh(void) {
7632 if (local_dh_1024) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007633 HASSL_DH_free(local_dh_1024);
Grant Zhang872f9c22017-01-21 01:10:18 +00007634 local_dh_1024 = NULL;
7635 }
7636 if (local_dh_2048) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007637 HASSL_DH_free(local_dh_2048);
Grant Zhang872f9c22017-01-21 01:10:18 +00007638 local_dh_2048 = NULL;
7639 }
7640 if (local_dh_4096) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007641 HASSL_DH_free(local_dh_4096);
Grant Zhang872f9c22017-01-21 01:10:18 +00007642 local_dh_4096 = NULL;
7643 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02007644 if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007645 HASSL_DH_free(global_dh);
Remi Gacogne47783ef2015-05-29 15:53:22 +02007646 global_dh = NULL;
7647 }
Grant Zhang872f9c22017-01-21 01:10:18 +00007648}
7649#endif
7650
Grant Zhang872f9c22017-01-21 01:10:18 +00007651static void __ssl_sock_deinit(void)
7652{
7653#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007654 if (ssl_ctx_lru_tree) {
7655 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007656 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02007657 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02007658#endif
7659
Willy Tarreau5db847a2019-05-09 14:13:35 +02007660#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007661 ERR_remove_state(0);
7662 ERR_free_strings();
7663
7664 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08007665#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007666
Willy Tarreau5db847a2019-05-09 14:13:35 +02007667#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007668 CRYPTO_cleanup_all_ex_data();
7669#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007670 BIO_meth_free(ha_meth);
Remi Tricot-Le Breton6477bbd2022-12-20 11:11:13 +01007671
7672#if !defined OPENSSL_NO_OCSP
7673 ssl_destroy_ocsp_update_task();
7674#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007675}
Willy Tarreau79367f92022-04-25 19:18:24 +02007676REGISTER_POST_DEINIT(__ssl_sock_deinit);
Remi Gacogned3a23c32015-05-28 16:39:47 +02007677
William Dauchyf6370442020-11-14 19:25:33 +01007678
Emeric Brun46591952012-05-18 15:47:34 +02007679/*
7680 * Local variables:
7681 * c-indent-level: 8
7682 * c-basic-offset: 8
7683 * End:
7684 */