blob: 97d2c3bb437ae15371d4225f6fb85087f1a6d4dc [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();
Remi Tricot-Le Bretona6c0a592023-03-13 15:56:32 +01001119 char *err = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001120
Emeric Brun4147b2e2014-06-16 18:36:30 +02001121
William Lallemand52ddd992022-11-22 11:51:53 +01001122 x = data->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001123 if (!x)
1124 goto out;
1125
Remi Tricot-Le Bretona6c0a592023-03-13 15:56:32 +01001126 ssl_ocsp_get_uri_from_cert(x, ocsp_uri, &err);
1127 /* We should have an "OCSP URI" field in order for auto update to work. */
1128 if (data->ocsp_update_mode == SSL_SOCK_OCSP_UPDATE_ON && b_data(ocsp_uri) == 0)
1129 goto out;
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001130
1131 /* In case of ocsp update mode set to 'on', this function might be
1132 * called with no known ocsp response. If no ocsp uri can be found in
1133 * the certificate, nothing needs to be done here. */
1134 if (!data->ocsp_response) {
1135 if (data->ocsp_update_mode != SSL_SOCK_OCSP_UPDATE_ON || b_data(ocsp_uri) == 0) {
1136 ret = 0;
1137 goto out;
1138 }
1139 }
1140
William Lallemand52ddd992022-11-22 11:51:53 +01001141 issuer = data->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001142 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1143 if (chain) {
1144 /* check if one of the certificate of the chain is the issuer */
1145 for (i = 0; i < sk_X509_num(chain); i++) {
1146 X509 *ti = sk_X509_value(chain, i);
1147 if (X509_check_issued(ti, x) == X509_V_OK) {
1148 issuer = ti;
1149 break;
1150 }
1151 }
1152 }
William Lallemand246c0242019-10-11 08:59:13 +02001153 if (!issuer)
1154 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001155
Remi Tricot-Le Breton2d1daa82023-01-09 12:02:47 +01001156 if (!data->ocsp_cid)
1157 data->ocsp_cid = OCSP_cert_to_id(0, x, issuer);
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001158 if (!data->ocsp_cid)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001159 goto out;
1160
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001161 i = i2d_OCSP_CERTID(data->ocsp_cid, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001162 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1163 goto out;
1164
Remi Tricot-Le Breton0c96ee42023-03-01 16:11:50 +01001165 ocsp = calloc(1, sizeof(*ocsp)+strlen(path)+1);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001166 if (!ocsp)
1167 goto out;
1168
1169 p = ocsp->key_data;
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001170 ocsp->key_length = i2d_OCSP_CERTID(data->ocsp_cid, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001171
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001172 HA_SPIN_LOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001173 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1174 if (iocsp == ocsp)
1175 ocsp = NULL;
1176
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001177#ifndef SSL_CTX_get_tlsext_status_cb
1178# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1179 *cb = (void (*) (void))ctx->tlsext_status_cb;
1180#endif
1181 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1182
1183 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001184 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001185 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001186
William Lallemanda560c062020-07-31 11:43:20 +02001187 cb_arg = calloc(1, sizeof(*cb_arg));
1188 if (!cb_arg)
1189 goto out;
1190
yanbzhube2774d2015-12-10 15:07:30 -05001191 cb_arg->is_single = 1;
1192 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001193 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001194
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001195 pkey = X509_get_pubkey(x);
1196 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1197 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001198
1199 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001200 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 */
1201
yanbzhube2774d2015-12-10 15:07:30 -05001202 } else {
1203 /*
1204 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1205 * Update that cb_arg with the new cert's staple
1206 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001207 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001208 struct certificate_ocsp *tmp_ocsp;
1209 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001210 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001211 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001212
William Lallemand76b4a122020-08-04 17:41:39 +02001213 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001214
1215 /*
1216 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1217 * the order of operations below matter, take care when changing it
1218 */
1219 tmp_ocsp = cb_arg->s_ocsp;
1220 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1221 cb_arg->s_ocsp = NULL;
1222 cb_arg->m_ocsp[index] = tmp_ocsp;
1223 cb_arg->is_single = 0;
1224 cb_arg->single_kt = 0;
1225
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001226 pkey = X509_get_pubkey(x);
1227 key_type = EVP_PKEY_base_id(pkey);
1228 EVP_PKEY_free(pkey);
1229
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001230 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001231 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001232 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001233 iocsp->refcount++;
1234 }
yanbzhube2774d2015-12-10 15:07:30 -05001235 }
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001236 HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001237
1238 ret = 0;
1239
1240 warn = NULL;
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001241 if (data->ocsp_response && ssl_sock_load_ocsp_response(data->ocsp_response, iocsp, data->ocsp_cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001242 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001243 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001244 }
1245
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001246
Remi Tricot-Le Bretona6c0a592023-03-13 15:56:32 +01001247 /* Do not insert the same certificate_ocsp structure in the
1248 * update tree more than once. */
1249 if (!ocsp) {
1250 /* Issuer certificate is not included in the certificate
1251 * chain, it will have to be treated separately during
1252 * ocsp response validation. */
1253 if (issuer == data->ocsp_issuer) {
1254 iocsp->issuer = issuer;
1255 X509_up_ref(issuer);
1256 }
1257 if (data->chain)
1258 iocsp->chain = X509_chain_up_ref(data->chain);
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001259
Remi Tricot-Le Bretona6c0a592023-03-13 15:56:32 +01001260 iocsp->uri = calloc(1, sizeof(*iocsp->uri));
1261 if (!chunk_dup(iocsp->uri, ocsp_uri)) {
1262 ha_free(&iocsp->uri);
1263 goto out;
1264 }
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001265
Remi Tricot-Le Bretona6c0a592023-03-13 15:56:32 +01001266 strcpy(iocsp->path, path);
Remi Tricot-Le Breton0c96ee42023-03-01 16:11:50 +01001267
Remi Tricot-Le Bretona6c0a592023-03-13 15:56:32 +01001268 if (data->ocsp_update_mode == SSL_SOCK_OCSP_UPDATE_ON) {
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001269 ssl_ocsp_update_insert(iocsp);
Remi Tricot-Le Breton86d1e0b2023-03-02 15:49:53 +01001270 /* If we are during init the update task is not
1271 * scheduled yet so a wakeup won't do anything.
1272 * Otherwise, if the OCSP was added through the CLI, we
1273 * wake the task up to manage the case of a new entry
1274 * that needs to be updated before the previous first
1275 * entry.
1276 */
1277 if (ocsp_update_task)
1278 task_wakeup(ocsp_update_task, TASK_WOKEN_MSG);
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001279 }
1280 }
1281
Emeric Brun4147b2e2014-06-16 18:36:30 +02001282out:
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001283 if (ret && data->ocsp_cid)
1284 OCSP_CERTID_free(data->ocsp_cid);
1285
1286 if (!ret && data->ocsp_response) {
1287 ha_free(&data->ocsp_response->area);
1288 ha_free(&data->ocsp_response);
1289 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001290
1291 if (ocsp)
Remi Tricot-Le Bretonaa529f72022-11-03 15:16:49 +01001292 ssl_sock_free_ocsp(ocsp);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001293
1294 if (warn)
1295 free(warn);
1296
Emeric Brun4147b2e2014-06-16 18:36:30 +02001297 return ret;
1298}
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01001299
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001300#endif
1301
1302#ifdef OPENSSL_IS_BORINGSSL
Remi Tricot-Le Breton0c96ee42023-03-01 16:11:50 +01001303static 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 +02001304{
William Lallemand4a660132019-10-14 14:51:41 +02001305 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 +02001306}
1307#endif
1308
William Lallemand4a660132019-10-14 14:51:41 +02001309
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001310#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001311
1312#define CT_EXTENSION_TYPE 18
1313
William Lallemand03c331c2020-05-13 10:10:01 +02001314int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001315
1316int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1317{
Willy Tarreau83061a82018-07-13 11:56:34 +02001318 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001319
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001320 *out = (unsigned char *) sctl->area;
1321 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001322
1323 return 1;
1324}
1325
1326int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1327{
1328 return 1;
1329}
1330
William Lallemanda17f4112019-10-10 15:16:44 +02001331static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001332{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001333 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001334
William Lallemanda17f4112019-10-10 15:16:44 +02001335 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 +01001336 goto out;
1337
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001338 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1339
1340 ret = 0;
1341
1342out:
1343 return ret;
1344}
1345
1346#endif
1347
Emeric Brune1f38db2012-09-03 20:36:47 +02001348void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1349{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001350 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001351#ifdef USE_QUIC
1352 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1353#endif /* USE_QUIC */
1354 struct ssl_sock_ctx *ctx = NULL;
1355
Emeric Brund8b2bb52014-01-28 15:43:53 +01001356 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001357 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001358
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001359 if (conn)
Willy Tarreau939b0bf2022-04-11 11:29:11 +02001360 ctx = conn_get_ssl_sock_ctx(conn);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001361#ifdef USE_QUIC
1362 else if (qc)
1363 ctx = qc->xprt_ctx;
1364#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01001365
1366 if (!ctx) {
1367 /* must never happen */
1368 ABORT_NOW();
1369 return;
1370 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001371
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001372#ifndef SSL_OP_NO_RENEGOTIATION
1373 /* Please note that BoringSSL defines this macro to zero so don't
1374 * change this to #if and do not assign a default value to this macro!
1375 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001376 if (where & SSL_CB_HANDSHAKE_START) {
1377 /* Disable renegotiation (CVE-2009-3555) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001378 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 +02001379 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001380 conn->err_code = CO_ER_SSL_RENEG;
1381 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001382 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001383#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001384
1385 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001386 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001387 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001388 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001389 consider that the buffering was activated,
1390 so we rise the output buffer size from 4k
1391 to 16k */
1392 write_bio = SSL_get_wbio(ssl);
1393 if (write_bio != SSL_get_rbio(ssl)) {
1394 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001395 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001396 }
1397 }
1398 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001399}
1400
Emeric Brune64aef12012-09-21 13:15:06 +02001401/* Callback is called for each certificate of the chain during a verify
1402 ok is set to 1 if preverify detect no error on current certificate.
1403 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001404int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001405{
1406 SSL *ssl;
1407 struct connection *conn;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001408 struct ssl_sock_ctx *ctx = NULL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001409 int err, depth;
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001410 X509 *client_crt;
1411 STACK_OF(X509) *certs;
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001412 struct bind_conf *bind_conf = NULL;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001413 struct quic_conn *qc = NULL;
Emeric Brune64aef12012-09-21 13:15:06 +02001414
1415 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001416 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001417 client_crt = SSL_get_ex_data(ssl, ssl_client_crt_ref_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001418
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001419 if (conn) {
1420 bind_conf = __objt_listener(conn->target)->bind_conf;
1421 ctx = __conn_get_ssl_sock_ctx(conn);
1422 }
1423#ifdef USE_QUIC
1424 else {
1425 qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
Amaury Denoyelleba303de2022-10-17 18:46:49 +02001426 BUG_ON(!qc); /* Must never happen */
1427 bind_conf = qc->li->bind_conf;
1428 ctx = qc->xprt_ctx;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001429 }
1430#endif
1431
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001432 BUG_ON(!ctx || !bind_conf);
Christopher Faulet881cce92022-11-23 09:27:13 +01001433 ALREADY_CHECKED(ctx);
1434 ALREADY_CHECKED(bind_conf);
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001435
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001436 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001437
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001438 depth = X509_STORE_CTX_get_error_depth(x_store);
1439 err = X509_STORE_CTX_get_error(x_store);
1440
Emeric Brun81c00f02012-09-21 14:31:21 +02001441 if (ok) /* no errors */
1442 return ok;
1443
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001444 /* Keep a reference to the client's certificate in order to be able to
1445 * dump some fetches values in a log even when the verification process
1446 * fails. */
1447 if (depth == 0) {
1448 X509_free(client_crt);
1449 client_crt = X509_STORE_CTX_get0_cert(x_store);
1450 if (client_crt) {
1451 X509_up_ref(client_crt);
1452 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
1453 }
1454 }
1455 else {
1456 /* An error occurred on a CA certificate of the certificate
1457 * chain, we might never call this verify callback on the client
1458 * certificate's depth (which is 0) so we try to store the
1459 * reference right now. */
Remi Tricot-Le Bretonf95c2952021-08-20 09:51:23 +02001460 certs = X509_STORE_CTX_get1_chain(x_store);
1461 if (certs) {
1462 client_crt = sk_X509_value(certs, 0);
1463 if (client_crt) {
1464 X509_up_ref(client_crt);
1465 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001466 }
1467 sk_X509_pop_free(certs, X509_free);
1468 }
1469 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001470
1471 /* check if CA error needs to be ignored */
1472 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001473 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1474 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1475 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001476 }
1477
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01001478 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01001479 cert_ignerr_bitfield_get(bind_conf->ca_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001480 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02001481
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001482 /* TODO: for QUIC connection, this error code is lost */
1483 if (conn)
1484 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001485 return 0;
1486 }
1487
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001488 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1489 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001490
Emeric Brun81c00f02012-09-21 14:31:21 +02001491 /* check if certificate error needs to be ignored */
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01001492 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01001493 cert_ignerr_bitfield_get(bind_conf->crt_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001494 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02001495
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001496 /* TODO: for QUIC connection, this error code is lost */
1497 if (conn)
1498 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001499 return 0;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001500
1501 err_ignored:
1502 ssl_sock_dump_errors(conn, qc);
1503 ERR_clear_error();
1504 return 1;
Emeric Brune64aef12012-09-21 13:15:06 +02001505}
1506
Dragan Dosen9ac98092020-05-11 15:51:45 +02001507#ifdef TLS1_RT_HEARTBEAT
1508static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1509 int content_type, const void *buf, size_t len,
1510 SSL *ssl)
1511{
1512 /* test heartbeat received (write_p is set to 0
1513 for a received record) */
1514 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02001515 struct ssl_sock_ctx *ctx = __conn_get_ssl_sock_ctx(conn);
Dragan Dosen9ac98092020-05-11 15:51:45 +02001516 const unsigned char *p = buf;
1517 unsigned int payload;
1518
1519 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1520
1521 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1522 if (*p != TLS1_HB_REQUEST)
1523 return;
1524
1525 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1526 goto kill_it;
1527
1528 payload = (p[1] * 256) + p[2];
1529 if (3 + payload + 16 <= len)
1530 return; /* OK no problem */
1531 kill_it:
1532 /* We have a clear heartbleed attack (CVE-2014-0160), the
1533 * advertised payload is larger than the advertised packet
1534 * length, so we have garbage in the buffer between the
1535 * payload and the end of the buffer (p+len). We can't know
1536 * if the SSL stack is patched, and we don't know if we can
1537 * safely wipe out the area between p+3+len and payload.
1538 * So instead, we prevent the response from being sent by
1539 * setting the max_send_fragment to 0 and we report an SSL
1540 * error, which will kill this connection. It will be reported
1541 * above as SSL_ERROR_SSL while an other handshake failure with
1542 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1543 */
1544 ssl->max_send_fragment = 0;
1545 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1546 }
1547}
1548#endif
1549
1550static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1551 int content_type, const void *buf, size_t len,
1552 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001553{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001554 struct ssl_capture *capture;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001555 uchar *msg;
1556 uchar *end;
1557 uchar *extensions_end;
1558 uchar *ec_start = NULL;
1559 uchar *ec_formats_start = NULL;
1560 uchar *list_end;
1561 ushort protocol_version;
1562 ushort extension_id;
1563 ushort ec_len = 0;
1564 uchar ec_formats_len = 0;
1565 int offset = 0;
1566 int rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001567
1568 /* This function is called for "from client" and "to server"
1569 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001570 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001571 */
1572
1573 /* "write_p" is set to 0 is the bytes are received messages,
1574 * otherwise it is set to 1.
1575 */
1576 if (write_p != 0)
1577 return;
1578
1579 /* content_type contains the type of message received or sent
1580 * according with the SSL/TLS protocol spec. This message is
1581 * encoded with one byte. The value 256 (two bytes) is used
1582 * for designing the SSL/TLS record layer. According with the
1583 * rfc6101, the expected message (other than 256) are:
1584 * - change_cipher_spec(20)
1585 * - alert(21)
1586 * - handshake(22)
1587 * - application_data(23)
1588 * - (255)
1589 * We are interessed by the handshake and specially the client
1590 * hello.
1591 */
1592 if (content_type != 22)
1593 return;
1594
1595 /* The message length is at least 4 bytes, containing the
1596 * message type and the message length.
1597 */
1598 if (len < 4)
1599 return;
1600
1601 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001602 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001603 * - hello_request(0)
1604 * - client_hello(1)
1605 * - server_hello(2)
1606 * - certificate(11)
1607 * - server_key_exchange (12)
1608 * - certificate_request(13)
1609 * - server_hello_done(14)
1610 * We are interested by the client hello.
1611 */
1612 msg = (unsigned char *)buf;
1613 if (msg[0] != 1)
1614 return;
1615
1616 /* Next three bytes are the length of the message. The total length
1617 * must be this decoded length + 4. If the length given as argument
1618 * is not the same, we abort the protocol dissector.
1619 */
1620 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1621 if (len < rec_len + 4)
1622 return;
1623 msg += 4;
1624 end = msg + rec_len;
1625 if (end < msg)
1626 return;
1627
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001628 /* Expect 2 bytes for protocol version
1629 * (1 byte for major and 1 byte for minor)
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001630 */
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001631 if (msg + 2 > end)
1632 return;
1633 protocol_version = (msg[0] << 8) + msg[1];
1634 msg += 2;
1635
1636 /* Expect the random, composed by 4 bytes for the unix time and
1637 * 28 bytes for unix payload. So we jump 4 + 28.
1638 */
1639 msg += 4 + 28;
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001640 if (msg > end)
1641 return;
1642
1643 /* Next, is session id:
1644 * if present, we have to jump by length + 1 for the size information
1645 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001646 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001647 if (msg[0] > 0)
1648 msg += msg[0];
1649 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001650 if (msg > end)
1651 return;
1652
1653 /* Next two bytes are the ciphersuite length. */
1654 if (msg + 2 > end)
1655 return;
1656 rec_len = (msg[0] << 8) + msg[1];
1657 msg += 2;
1658 if (msg + rec_len > end || msg + rec_len < msg)
1659 return;
1660
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001661 capture = pool_zalloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001662 if (!capture)
1663 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001664 /* Compute the xxh64 of the ciphersuite. */
1665 capture->xxh64 = XXH64(msg, rec_len, 0);
1666
1667 /* Capture the ciphersuite. */
Marcin Deranek310a2602021-07-13 19:04:24 +02001668 capture->ciphersuite_len = MIN(global_ssl.capture_buffer_size, rec_len);
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001669 capture->ciphersuite_offset = 0;
1670 memcpy(capture->data, msg, capture->ciphersuite_len);
1671 msg += rec_len;
1672 offset += capture->ciphersuite_len;
1673
1674 /* Initialize other data */
1675 capture->protocol_version = protocol_version;
1676
1677 /* Next, compression methods:
1678 * if present, we have to jump by length + 1 for the size information
1679 * if not present, we have to jump by 1 only
1680 */
1681 if (msg[0] > 0)
1682 msg += msg[0];
1683 msg += 1;
1684 if (msg > end)
1685 goto store_capture;
1686
1687 /* We reached extensions */
1688 if (msg + 2 > end)
1689 goto store_capture;
1690 rec_len = (msg[0] << 8) + msg[1];
1691 msg += 2;
1692 if (msg + rec_len > end || msg + rec_len < msg)
1693 goto store_capture;
1694 extensions_end = msg + rec_len;
1695 capture->extensions_offset = offset;
1696
1697 /* Parse each extension */
1698 while (msg + 4 < extensions_end) {
1699 /* Add 2 bytes of extension_id */
Marcin Deranek310a2602021-07-13 19:04:24 +02001700 if (global_ssl.capture_buffer_size >= offset + 2) {
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001701 capture->data[offset++] = msg[0];
1702 capture->data[offset++] = msg[1];
1703 capture->extensions_len += 2;
1704 }
1705 else
1706 break;
1707 extension_id = (msg[0] << 8) + msg[1];
1708 /* Length of the extension */
1709 rec_len = (msg[2] << 8) + msg[3];
1710
1711 /* Expect 2 bytes extension id + 2 bytes extension size */
1712 msg += 2 + 2;
1713 if (msg + rec_len > extensions_end || msg + rec_len < msg)
1714 goto store_capture;
1715 /* TLS Extensions
1716 * https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml */
1717 if (extension_id == 0x000a) {
1718 /* Elliptic Curves:
1719 * https://www.rfc-editor.org/rfc/rfc8422.html
1720 * https://www.rfc-editor.org/rfc/rfc7919.html */
1721 list_end = msg + rec_len;
1722 if (msg + 2 > list_end)
1723 goto store_capture;
1724 rec_len = (msg[0] << 8) + msg[1];
1725 msg += 2;
1726
1727 if (msg + rec_len > list_end || msg + rec_len < msg)
1728 goto store_capture;
1729 /* Store location/size of the list */
1730 ec_start = msg;
1731 ec_len = rec_len;
1732 }
1733 else if (extension_id == 0x000b) {
1734 /* Elliptic Curves Point Formats:
1735 * https://www.rfc-editor.org/rfc/rfc8422.html */
1736 list_end = msg + rec_len;
1737 if (msg + 1 > list_end)
1738 goto store_capture;
1739 rec_len = msg[0];
1740 msg += 1;
1741
1742 if (msg + rec_len > list_end || msg + rec_len < msg)
1743 goto store_capture;
1744 /* Store location/size of the list */
1745 ec_formats_start = msg;
1746 ec_formats_len = rec_len;
1747 }
1748 msg += rec_len;
1749 }
1750
1751 if (ec_start) {
1752 rec_len = ec_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001753 if (offset + rec_len > global_ssl.capture_buffer_size)
1754 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001755 memcpy(capture->data + offset, ec_start, rec_len);
1756 capture->ec_offset = offset;
1757 capture->ec_len = rec_len;
1758 offset += rec_len;
1759 }
1760 if (ec_formats_start) {
1761 rec_len = ec_formats_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001762 if (offset + rec_len > global_ssl.capture_buffer_size)
1763 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001764 memcpy(capture->data + offset, ec_formats_start, rec_len);
1765 capture->ec_formats_offset = offset;
1766 capture->ec_formats_len = rec_len;
1767 offset += rec_len;
1768 }
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001769
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001770 store_capture:
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001771 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001772}
William Lallemand7d42ef52020-07-06 11:41:30 +02001773
1774
William Lallemand722180a2021-06-09 16:46:12 +02001775#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001776static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1777 int content_type, const void *buf, size_t len,
1778 SSL *ssl)
1779{
1780 struct ssl_keylog *keylog;
1781
1782 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1783 return;
1784
Willy Tarreauf208ac02021-03-22 21:10:12 +01001785 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02001786 if (!keylog)
1787 return;
1788
William Lallemand7d42ef52020-07-06 11:41:30 +02001789 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
1790 pool_free(pool_head_ssl_keylog, keylog);
1791 return;
1792 }
1793}
1794#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001795
Emeric Brun29f037d2014-04-25 19:05:36 +02001796/* Callback is called for ssl protocol analyse */
1797void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1798{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001799 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1800 struct ssl_sock_msg_callback *cbk;
1801
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001802 /* Try to call all callback functions that were registered by using
1803 * ssl_sock_register_msg_callback().
1804 */
1805 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1806 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1807 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001808}
1809
Bernard Spil13c53f82018-02-15 13:34:58 +01001810#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001811static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1812 const unsigned char *in, unsigned int inlen,
1813 void *arg)
1814{
1815 struct server *srv = arg;
1816
1817 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1818 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1819 return SSL_TLSEXT_ERR_OK;
1820 return SSL_TLSEXT_ERR_NOACK;
1821}
1822#endif
1823
1824#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001825/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001826 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001827 */
1828static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1829 unsigned int *len, void *arg)
1830{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001831 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001832
1833 *data = (const unsigned char *)conf->npn_str;
1834 *len = conf->npn_len;
1835 return SSL_TLSEXT_ERR_OK;
1836}
1837#endif
1838
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001839#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001840/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001841 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001842 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001843static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1844 unsigned char *outlen,
1845 const unsigned char *server,
1846 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001847{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001848 struct ssl_bind_conf *conf = arg;
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001849#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001850 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001851#endif
Willy Tarreauab861d32013-04-02 02:30:41 +02001852
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001853 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1854 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01001855#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001856 if (qc)
1857 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01001858#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001859 return SSL_TLSEXT_ERR_NOACK;
1860 }
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001861
1862#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001863 if (qc && !quic_set_app_ops(qc, *out, *outlen)) {
1864 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001865 return SSL_TLSEXT_ERR_NOACK;
1866 }
1867#endif
1868
Willy Tarreauab861d32013-04-02 02:30:41 +02001869 return SSL_TLSEXT_ERR_OK;
1870}
1871#endif
1872
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001873#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001874#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001875
cui flitera94bedc2022-08-29 14:42:57 +08001876/* Configure a DNS SAN extension on a certificate. */
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001877int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
1878 int failure = 0;
1879 X509_EXTENSION *san_ext = NULL;
1880 CONF *conf = NULL;
1881 struct buffer *san_name = get_trash_chunk();
1882
1883 conf = NCONF_new(NULL);
1884 if (!conf) {
1885 failure = 1;
1886 goto cleanup;
1887 }
1888
1889 /* Build an extension based on the DNS entry above */
1890 chunk_appendf(san_name, "DNS:%s", servername);
1891 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
1892 if (!san_ext) {
1893 failure = 1;
1894 goto cleanup;
1895 }
1896
1897 /* Add the extension */
1898 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
1899 failure = 1;
1900 goto cleanup;
1901 }
1902
1903 /* Success */
1904 failure = 0;
1905
1906cleanup:
1907 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
1908 if (NULL != conf) NCONF_free(conf);
1909
1910 return failure;
1911}
1912
Christopher Faulet30548802015-06-11 13:39:32 +02001913/* Create a X509 certificate with the specified servername and serial. This
1914 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001915static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001916ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001917{
Shimi Gersner5846c492020-08-23 13:58:12 +03001918 X509 *cacert = bind_conf->ca_sign_ckch->cert;
1919 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001920 SSL_CTX *ssl_ctx = NULL;
1921 X509 *newcrt = NULL;
1922 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001923 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001924 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001925 X509_NAME *name;
1926 const EVP_MD *digest;
1927 X509V3_CTX ctx;
1928 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001929 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001930
Christopher Faulet48a83322017-07-28 16:56:09 +02001931 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05001932#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001933 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1934#else
1935 tmp_ssl = SSL_new(bind_conf->default_ctx);
1936 if (tmp_ssl)
1937 pkey = SSL_get_privatekey(tmp_ssl);
1938#endif
1939 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001940 goto mkcert_error;
1941
1942 /* Create the certificate */
1943 if (!(newcrt = X509_new()))
1944 goto mkcert_error;
1945
1946 /* Set version number for the certificate (X509v3) and the serial
1947 * number */
1948 if (X509_set_version(newcrt, 2L) != 1)
1949 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02001950 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001951
1952 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001953 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1954 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001955 goto mkcert_error;
1956
1957 /* set public key in the certificate */
1958 if (X509_set_pubkey(newcrt, pkey) != 1)
1959 goto mkcert_error;
1960
1961 /* Set issuer name from the CA */
1962 if (!(name = X509_get_subject_name(cacert)))
1963 goto mkcert_error;
1964 if (X509_set_issuer_name(newcrt, name) != 1)
1965 goto mkcert_error;
1966
1967 /* Set the subject name using the same, but the CN */
1968 name = X509_NAME_dup(name);
1969 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1970 (const unsigned char *)servername,
1971 -1, -1, 0) != 1) {
1972 X509_NAME_free(name);
1973 goto mkcert_error;
1974 }
1975 if (X509_set_subject_name(newcrt, name) != 1) {
1976 X509_NAME_free(name);
1977 goto mkcert_error;
1978 }
1979 X509_NAME_free(name);
1980
1981 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001982 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001983 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1984 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1985 X509_EXTENSION *ext;
1986
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001987 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001988 goto mkcert_error;
1989 if (!X509_add_ext(newcrt, ext, -1)) {
1990 X509_EXTENSION_free(ext);
1991 goto mkcert_error;
1992 }
1993 X509_EXTENSION_free(ext);
1994 }
1995
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001996 /* Add SAN extension */
1997 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
1998 goto mkcert_error;
1999 }
2000
Christopher Faulet31af49d2015-06-09 17:29:50 +02002001 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002002
2003 key_type = EVP_PKEY_base_id(capkey);
2004
2005 if (key_type == EVP_PKEY_DSA)
2006 digest = EVP_sha1();
2007 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002008 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002009 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02002010 digest = EVP_sha256();
2011 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05002012#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02002013 int nid;
2014
2015 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
2016 goto mkcert_error;
2017 if (!(digest = EVP_get_digestbynid(nid)))
2018 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02002019#else
2020 goto mkcert_error;
2021#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02002022 }
2023
Christopher Faulet31af49d2015-06-09 17:29:50 +02002024 if (!(X509_sign(newcrt, capkey, digest)))
2025 goto mkcert_error;
2026
2027 /* Create and set the new SSL_CTX */
2028 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
2029 goto mkcert_error;
2030 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
2031 goto mkcert_error;
2032 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
2033 goto mkcert_error;
2034 if (!SSL_CTX_check_private_key(ssl_ctx))
2035 goto mkcert_error;
2036
Shimi Gersner5846c492020-08-23 13:58:12 +03002037 /* Build chaining the CA cert and the rest of the chain, keep these order */
2038#if defined(SSL_CTX_add1_chain_cert)
2039 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
2040 goto mkcert_error;
2041 }
2042
2043 if (bind_conf->ca_sign_ckch->chain) {
2044 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2045 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2046 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2047 goto mkcert_error;
2048 }
2049 }
2050 }
2051#endif
2052
Christopher Faulet31af49d2015-06-09 17:29:50 +02002053 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002054
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002055#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002056#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002057 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002058#else
2059 ssl_sock_set_tmp_dh_from_pkey(ssl_ctx, pkey);
2060#endif
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002061#endif
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002062
2063#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
2064#if defined(SSL_CTX_set1_curves_list)
2065 {
2066 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
2067 if (!SSL_CTX_set1_curves_list(ssl_ctx, ecdhe))
2068 goto end;
2069 }
2070#endif
2071#else
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002072#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2073 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002074 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002075 EC_KEY *ecc;
2076 int nid;
2077
2078 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2079 goto end;
2080 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2081 goto end;
2082 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2083 EC_KEY_free(ecc);
2084 }
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002085#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
2086#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002087 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002088 return ssl_ctx;
2089
2090 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002091 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002092 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002093 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2094 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002095 return NULL;
2096}
2097
Christopher Faulet7969a332015-10-09 11:15:03 +02002098
Christopher Faulet30548802015-06-11 13:39:32 +02002099/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002100 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002101SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002102ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002103{
2104 struct lru64 *lru = NULL;
2105
2106 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002107 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002108 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002109 if (lru && lru->domain) {
2110 if (ssl)
2111 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002112 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002113 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002114 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002115 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002116 }
2117 return NULL;
2118}
2119
Emeric Brun821bb9b2017-06-15 16:37:39 +02002120/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2121 * function is not thread-safe, it should only be used to check if a certificate
2122 * exists in the lru cache (with no warranty it will not be removed by another
2123 * thread). It is kept for backward compatibility. */
2124SSL_CTX *
2125ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2126{
2127 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2128}
2129
Christopher Fauletd2cab922015-07-28 16:03:47 +02002130/* Set a certificate int the LRU cache used to store generated
2131 * certificate. Return 0 on success, otherwise -1 */
2132int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002133ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002134{
2135 struct lru64 *lru = NULL;
2136
2137 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002138 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002139 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002140 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002141 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002142 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002143 }
Christopher Faulet30548802015-06-11 13:39:32 +02002144 if (lru->domain && lru->data)
2145 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002146 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002147 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002148 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002149 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002150 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002151}
2152
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002153/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002154unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002155ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002156{
2157 return XXH32(data, len, ssl_ctx_lru_seed);
2158}
2159
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002160/* Generate a cert and immediately assign it to the SSL session so that the cert's
2161 * refcount is maintained regardless of the cert's presence in the LRU cache.
2162 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002163static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002164ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002165{
Shimi Gersner5846c492020-08-23 13:58:12 +03002166 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002167 SSL_CTX *ssl_ctx = NULL;
2168 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002169 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002170
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002171 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002172 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002173 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002174 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002175 if (lru && lru->domain)
2176 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002177 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002178 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002179 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002180 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002181 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002182 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002183 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002184 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002185 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002186 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002187 SSL_set_SSL_CTX(ssl, ssl_ctx);
2188 /* No LRU cache, this CTX will be released as soon as the session dies */
2189 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002190 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002191 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002192 return 0;
2193}
2194static int
2195ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2196{
2197 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002198 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002199
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002200 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002201 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002202 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002203 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002204 }
2205 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002206}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002207#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002208
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002209#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002210
2211static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002212{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002213#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002214 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002215 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2216#endif
2217}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002218static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2219 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002220 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2221}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002222static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002223#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002224 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002225 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2226#endif
2227}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002228static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002229#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002230 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002231 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2232#endif
2233}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002234/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002235static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2236/* Unusable in this context. */
2237static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2238static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2239static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2240static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2241static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002242#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002243
2244static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2245 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002246 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2247}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002248static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2249 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2250 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2251}
2252static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2253 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002254 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2255}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002256static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2257 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2258 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2259}
2260static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2261 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002262 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2263}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002264static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2265 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2266 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2267}
2268static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2269 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002270 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2271}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002272static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2273 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2274 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2275}
2276static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002277#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002278 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002279 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2280#endif
2281}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002282static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002283#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002284 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2285 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002286#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002287}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002288#endif
2289static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2290static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002291
William Lallemand7fd8b452020-05-07 15:20:43 +02002292struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002293 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2294 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2295 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2296 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2297 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2298 {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 +02002299};
2300
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002301static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2302{
2303 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2304 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2305 SSL_set_SSL_CTX(ssl, ctx);
2306}
2307
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002308#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002309
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002310int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002311{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002312 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002313 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002314
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002315 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || (s->options & BC_O_GENERATE_CERTS))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002316 return SSL_TLSEXT_ERR_OK;
2317 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002318}
2319
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002320#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002321int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002322{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002323 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002324#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002325int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002326{
2327#endif
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002328 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2329#ifdef USE_QUIC
2330 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2331#endif /* USE_QUIC */
2332 struct bind_conf *s = NULL;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002333 const uint8_t *extension_data;
2334 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002335 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002336
2337 char *wildp = NULL;
2338 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002339 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002340 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002341 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002342 int i;
2343
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002344 if (conn)
2345 s = __objt_listener(conn->target)->bind_conf;
2346#ifdef USE_QUIC
2347 else if (qc)
2348 s = qc->li->bind_conf;
2349#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01002350
2351 if (!s) {
2352 /* must never happen */
2353 ABORT_NOW();
2354 return 0;
2355 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002356
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002357#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002358 if (qc) {
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002359 /* Look for the QUIC transport parameters. */
2360#ifdef OPENSSL_IS_BORINGSSL
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002361 if (!SSL_early_callback_ctx_extension_get(ctx, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002362 &extension_data, &extension_len))
2363#else
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002364 if (!SSL_client_hello_get0_ext(ssl, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002365 &extension_data, &extension_len))
2366#endif
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002367 {
2368 /* This is not redundant. It we only return 0 without setting
2369 * <*al>, this has as side effect to generate another TLS alert
2370 * which would be set after calling quic_set_tls_alert().
2371 */
2372 *al = SSL_AD_MISSING_EXTENSION;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002373 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002374 return 0;
2375 }
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002376
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002377 if (!quic_transport_params_store(qc, 0, extension_data,
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002378 extension_data + extension_len))
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002379 goto abort;
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002380
2381 qc->flags |= QUIC_FL_CONN_TX_TP_RECEIVED;
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002382 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002383#endif /* USE_QUIC */
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002384
Olivier Houchard9679ac92017-10-27 14:58:08 +02002385 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002386 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002387#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002388 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2389 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002390#else
2391 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2392#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002393 /*
2394 * The server_name extension was given too much extensibility when it
2395 * was written, so parsing the normal case is a bit complex.
2396 */
2397 size_t len;
2398 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002399 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002400 /* Extract the length of the supplied list of names. */
2401 len = (*extension_data++) << 8;
2402 len |= *extension_data++;
2403 if (len + 2 != extension_len)
2404 goto abort;
2405 /*
2406 * The list in practice only has a single element, so we only consider
2407 * the first one.
2408 */
2409 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2410 goto abort;
2411 extension_len = len - 1;
2412 /* Now we can finally pull out the byte array with the actual hostname. */
2413 if (extension_len <= 2)
2414 goto abort;
2415 len = (*extension_data++) << 8;
2416 len |= *extension_data++;
2417 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2418 || memchr(extension_data, 0, len) != NULL)
2419 goto abort;
2420 servername = extension_data;
2421 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002422 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002423#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002424 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002425 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002426 }
2427#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002428 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002429 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002430 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002431 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002432 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002433 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002434 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002435 goto abort;
2436 }
2437
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002438 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002439#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002440 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002441#else
2442 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2443#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002444 uint8_t sign;
2445 size_t len;
2446 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002447 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002448 len = (*extension_data++) << 8;
2449 len |= *extension_data++;
2450 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002451 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002452 if (len % 2 != 0)
2453 goto abort;
2454 for (; len > 0; len -= 2) {
2455 extension_data++; /* hash */
2456 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002457 switch (sign) {
2458 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002459 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002460 break;
2461 case TLSEXT_signature_ecdsa:
2462 has_ecdsa_sig = 1;
2463 break;
2464 default:
2465 continue;
2466 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002467 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002468 break;
2469 }
2470 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002471 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002472 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002473 }
2474 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002475 const SSL_CIPHER *cipher;
2476 size_t len;
2477 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002478 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002479#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002480 len = ctx->cipher_suites_len;
2481 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002482#else
2483 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2484#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002485 if (len % 2 != 0)
2486 goto abort;
2487 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002488#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002489 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002490 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002491#else
2492 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2493#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002494 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002495 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002496 break;
2497 }
2498 }
2499 }
2500
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002501 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002502 trash.area[i] = tolower(servername[i]);
2503 if (!wildp && (trash.area[i] == '.'))
2504 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002505 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002506 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002507
William Lallemand150bfa82019-09-19 17:12:49 +02002508 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002509
William Lallemand94bd3192020-08-14 14:43:35 +02002510 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2511 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002512 for (i = 0; i < 2; i++) {
2513 if (i == 0) /* lookup in full qualified names */
2514 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002515 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002516 node = ebst_lookup(&s->sni_w_ctx, wildp);
2517 else
2518 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002519
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002520 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002521
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002522 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002523 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002524 struct sni_ctx *sni, *sni_tmp;
2525 int skip = 0;
2526
2527 if (i == 1 && wildp) { /* wildcard */
2528 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2529 sni = container_of(n, struct sni_ctx, name);
2530 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002531 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002532 skip = 1;
2533 break;
2534 }
2535 }
2536 if (skip)
2537 continue;
2538 }
2539
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002540 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002541 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002542 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002543 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002544 break;
2545 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002546 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002547 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002548 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002549 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002550 if (!node_anonymous)
2551 node_anonymous = n;
2552 break;
2553 }
2554 }
2555 }
William Lallemand94bd3192020-08-14 14:43:35 +02002556 }
2557 /* Once the certificates are found, select them depending on what is
2558 * supported in the client and by key_signature priority order: EDSA >
2559 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002560 if (has_ecdsa_sig && node_ecdsa)
2561 node = node_ecdsa;
2562 else if (has_rsa_sig && node_rsa)
2563 node = node_rsa;
2564 else if (node_anonymous)
2565 node = node_anonymous;
2566 else if (node_ecdsa)
2567 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2568 else
2569 node = node_rsa; /* no rsa signature case (far far away) */
2570
William Lallemand94bd3192020-08-14 14:43:35 +02002571 if (node) {
2572 /* switch ctx */
2573 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2574 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2575 if (conf) {
2576 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2577 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2578 if (conf->early_data)
2579 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002580 }
William Lallemand94bd3192020-08-14 14:43:35 +02002581 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2582 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002583 }
William Lallemand150bfa82019-09-19 17:12:49 +02002584
William Lallemand02010472019-10-18 11:02:19 +02002585 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002586#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002587 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002588 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002589 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002590 }
2591#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002592 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002593 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002594 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002595 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002596 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
William Lallemand7980dff2021-11-18 17:46:26 +01002597 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002598 }
William Lallemand7980dff2021-11-18 17:46:26 +01002599
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01002600 /* We are about to raise an handshake error so the servername extension
2601 * callback will never be called and the SNI will never be stored in the
2602 * SSL context. In order for the ssl_fc_sni sample fetch to still work
2603 * in such a case, we store the SNI ourselves as an ex_data information
2604 * in the SSL context.
2605 */
2606 {
2607 char *client_sni = pool_alloc(ssl_sock_client_sni_pool);
2608 if (client_sni) {
2609 strncpy(client_sni, trash.area, TLSEXT_MAXLEN_host_name);
2610 client_sni[TLSEXT_MAXLEN_host_name] = '\0';
2611 SSL_set_ex_data(ssl, ssl_client_sni_index, client_sni);
2612 }
2613 }
2614
William Lallemand7980dff2021-11-18 17:46:26 +01002615 /* other cases fallback on abort, if strict-sni is set but no node was found */
2616
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002617 abort:
2618 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002619 if (conn)
2620 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002621#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002622 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002623#else
2624 *al = SSL_AD_UNRECOGNIZED_NAME;
2625 return 0;
2626#endif
William Lallemand7980dff2021-11-18 17:46:26 +01002627
2628allow_early:
2629#ifdef OPENSSL_IS_BORINGSSL
2630 if (allow_early)
2631 SSL_set_early_data_enabled(ssl, 1);
2632#else
2633 if (!allow_early)
2634 SSL_set_max_early_data(ssl, 0);
2635#endif
2636 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002637}
2638
William Lallemand002e2062021-11-18 15:25:16 +01002639#else /* ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002640
Emeric Brunfc0421f2012-09-07 17:30:07 +02002641/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2642 * warning when no match is found, which implies the default (first) cert
2643 * will keep being used.
2644 */
William Lallemand844009d2022-09-02 15:27:32 +02002645int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002646{
2647 const char *servername;
2648 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002649 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002650 struct bind_conf *s = priv;
William Lallemand70a6e632022-09-07 11:21:34 +02002651#ifdef USE_QUIC
2652 const uint8_t *extension_data;
2653 size_t extension_len;
2654 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2655#endif /* USE_QUIC */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002656 int i;
2657 (void)al; /* shut gcc stupid warning */
2658
William Lallemand70a6e632022-09-07 11:21:34 +02002659#ifdef USE_QUIC
2660 if (qc) {
2661
2662 /* Look for the QUIC transport parameters. */
2663 SSL_get_peer_quic_transport_params(ssl, &extension_data, &extension_len);
2664 if (extension_len == 0) {
2665 /* This is not redundant. It we only return 0 without setting
2666 * <*al>, this has as side effect to generate another TLS alert
2667 * which would be set after calling quic_set_tls_alert().
2668 */
2669 *al = SSL_AD_MISSING_EXTENSION;
2670 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
2671 return SSL_TLSEXT_ERR_NOACK;
2672 }
2673
2674 if (!quic_transport_params_store(qc, 0, extension_data,
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002675 extension_data + extension_len))
William Lallemand70a6e632022-09-07 11:21:34 +02002676 return SSL_TLSEXT_ERR_NOACK;
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002677
2678 qc->flags |= QUIC_FL_CONN_TX_TP_RECEIVED;
William Lallemand70a6e632022-09-07 11:21:34 +02002679 }
2680#endif /* USE_QUIC */
2681
Emeric Brunfc0421f2012-09-07 17:30:07 +02002682 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002683 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002684#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002685 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002686 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002687#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002688 if (s->strict_sni)
2689 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002690 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002691 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002692 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002693 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002694 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002695
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002696 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002697 if (!servername[i])
2698 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002699 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002700 if (!wildp && (trash.area[i] == '.'))
2701 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002702 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002703 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002704
William Lallemand150bfa82019-09-19 17:12:49 +02002705 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002706 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002707 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002708 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2709 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002710 if (!container_of(n, struct sni_ctx, name)->neg) {
2711 node = n;
2712 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002713 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002714 }
2715 if (!node && wildp) {
2716 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002717 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2718 /* lookup a not neg filter */
2719 if (!container_of(n, struct sni_ctx, name)->neg) {
2720 node = n;
2721 break;
2722 }
2723 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002724 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002725 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002726#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002727 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(servername, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002728 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002729 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002730 return SSL_TLSEXT_ERR_OK;
2731 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002732#endif
William Lallemand21724f02019-11-04 17:56:13 +01002733 if (s->strict_sni) {
2734 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002735 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002736 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002737 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002738 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002739 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002740 }
2741
2742 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002743 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002744 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002745 return SSL_TLSEXT_ERR_OK;
2746}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002747#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002748#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2749
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002750#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002751
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002752static inline HASSL_DH *ssl_new_dh_fromdata(BIGNUM *p, BIGNUM *g)
2753{
2754#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2755 OSSL_PARAM_BLD *tmpl = NULL;
2756 OSSL_PARAM *params = NULL;
2757 EVP_PKEY_CTX *ctx = NULL;
2758 EVP_PKEY *pkey = NULL;
2759
2760 if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
2761 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
2762 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)
2763 || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
2764 goto end;
2765 }
2766 ctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2767 if (ctx == NULL
2768 || !EVP_PKEY_fromdata_init(ctx)
2769 || !EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params)) {
2770 goto end;
2771 }
2772
2773end:
2774 EVP_PKEY_CTX_free(ctx);
2775 OSSL_PARAM_free(params);
2776 OSSL_PARAM_BLD_free(tmpl);
Remi Tricot-Le Bretona2c21db2022-11-03 15:16:47 +01002777 BN_free(p);
2778 BN_free(g);
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002779 return pkey;
2780#else
2781
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002782 HASSL_DH *dh = DH_new();
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002783
2784 if (!dh)
2785 return NULL;
2786
2787 DH_set0_pqg(dh, p, NULL, g);
2788
2789 return dh;
2790#endif
2791}
2792
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02002793#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002794static inline HASSL_DH *ssl_get_dh_by_nid(int nid)
2795{
2796#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2797 OSSL_PARAM params[2];
2798 EVP_PKEY *pkey = NULL;
2799 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2800 const char *named_group = NULL;
2801
2802 if (!pctx)
2803 goto end;
2804
2805 named_group = OBJ_nid2ln(nid);
2806
2807 if (!named_group)
2808 goto end;
2809
2810 params[0] = OSSL_PARAM_construct_utf8_string("group", (char*)named_group, 0);
2811 params[1] = OSSL_PARAM_construct_end();
2812
2813 if (EVP_PKEY_keygen_init(pctx) && EVP_PKEY_CTX_set_params(pctx, params))
2814 EVP_PKEY_generate(pctx, &pkey);
2815
2816end:
2817 EVP_PKEY_CTX_free(pctx);
2818 return pkey;
2819#else
2820
2821 HASSL_DH *dh = NULL;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002822 dh = DH_new_by_nid(nid);
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002823 return dh;
2824#endif
2825}
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02002826#endif
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002827
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002828
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002829static HASSL_DH * ssl_get_dh_1024(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002830{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002831 static unsigned char dh1024_p[]={
2832 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2833 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2834 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2835 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2836 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2837 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2838 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2839 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2840 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2841 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2842 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2843 };
2844 static unsigned char dh1024_g[]={
2845 0x02,
2846 };
2847
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002848 BIGNUM *p;
2849 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002850
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002851 HASSL_DH *dh = NULL;
2852
2853 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2854 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
2855
2856 if (p && g)
2857 dh = ssl_new_dh_fromdata(p, g);
2858
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002859 return dh;
2860}
2861
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002862static HASSL_DH *ssl_get_dh_2048(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002863{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002864#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02002865 static unsigned char dh2048_p[]={
2866 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2867 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2868 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2869 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2870 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2871 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2872 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2873 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2874 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2875 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2876 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2877 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2878 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2879 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2880 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2881 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2882 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2883 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2884 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2885 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2886 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2887 0xB7,0x1F,0x77,0xF3,
2888 };
2889 static unsigned char dh2048_g[]={
2890 0x02,
2891 };
2892
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002893 BIGNUM *p;
2894 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002895
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002896 HASSL_DH *dh = NULL;
2897
2898 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2899 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
2900
2901 if (p && g)
2902 dh = ssl_new_dh_fromdata(p, g);
2903
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002904 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002905#else
2906 return ssl_get_dh_by_nid(NID_ffdhe2048);
2907#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002908}
2909
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002910static HASSL_DH *ssl_get_dh_4096(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002911{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002912#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02002913 static unsigned char dh4096_p[]={
2914 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2915 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2916 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2917 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2918 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2919 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2920 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2921 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2922 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2923 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2924 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2925 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2926 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2927 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2928 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2929 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2930 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2931 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2932 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2933 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2934 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2935 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2936 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2937 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2938 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2939 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2940 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2941 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2942 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2943 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2944 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2945 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2946 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2947 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2948 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2949 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2950 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2951 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2952 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2953 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2954 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2955 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2956 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002957 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002958 static unsigned char dh4096_g[]={
2959 0x02,
2960 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002961
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002962 BIGNUM *p;
2963 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002964
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002965 HASSL_DH *dh = NULL;
2966
2967 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2968 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
2969
2970 if (p && g)
2971 dh = ssl_new_dh_fromdata(p, g);
2972
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002973 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002974#else
2975 return ssl_get_dh_by_nid(NID_ffdhe4096);
2976#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002977}
2978
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002979static HASSL_DH *ssl_get_tmp_dh(EVP_PKEY *pkey)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002980{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002981 HASSL_DH *dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002982 int type;
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002983 int keylen = 0;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002984
2985 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002986
Ilya Shipitsin52f2ff52022-07-23 23:55:19 +05002987 if (type == EVP_PKEY_EC) {
2988 keylen = global_ssl.default_dh_param;
2989 }
2990
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002991 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2992 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2993 */
2994 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2995 keylen = EVP_PKEY_bits(pkey);
2996 }
2997
Willy Tarreauef934602016-12-22 23:12:01 +01002998 if (keylen > global_ssl.default_dh_param) {
2999 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003000 }
3001
Remi Gacogned3a341a2015-05-29 16:26:17 +02003002 if (keylen >= 4096) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003003 if (!local_dh_4096)
3004 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02003005 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003006 }
3007 else if (keylen >= 2048) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003008 if (!local_dh_2048)
3009 local_dh_2048 = ssl_get_dh_2048();
Remi Gacogne8de54152014-07-15 11:36:40 +02003010 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003011 }
3012 else {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003013 if (!local_dh_1024)
3014 local_dh_1024 = ssl_get_dh_1024();
Remi Gacogne8de54152014-07-15 11:36:40 +02003015 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003016 }
3017
3018 return dh;
3019}
3020
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003021#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003022/* Returns Diffie-Hellman parameters matching the private key length
3023 but not exceeding global_ssl.default_dh_param */
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003024static HASSL_DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003025{
3026 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
3027
3028 return ssl_get_tmp_dh(pkey);
3029}
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003030#endif
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003031
Remi Tricot-Le Breton846eda92022-02-11 12:04:50 +01003032static int ssl_sock_set_tmp_dh(SSL_CTX *ctx, HASSL_DH *dh)
3033{
3034#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
3035 return SSL_CTX_set_tmp_dh(ctx, dh);
3036#else
3037 int retval = 0;
3038 HASSL_DH_up_ref(dh);
3039
3040 retval = SSL_CTX_set0_tmp_dh_pkey(ctx, dh);
3041
3042 if (!retval)
3043 HASSL_DH_free(dh);
3044
3045 return retval;
3046#endif
3047}
3048
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003049#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3050static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey)
3051{
3052 HASSL_DH *dh = NULL;
3053 if (pkey && (dh = ssl_get_tmp_dh(pkey))) {
3054 HASSL_DH_up_ref(dh);
3055 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dh))
3056 HASSL_DH_free(dh);
3057 }
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003058}
3059#endif
3060
Remi Tricot-Le Breton09ebb332022-02-11 12:04:48 +01003061HASSL_DH *ssl_sock_get_dh_from_bio(BIO *bio)
3062{
3063#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3064 HASSL_DH *dh = NULL;
3065 OSSL_DECODER_CTX *dctx = NULL;
3066 const char *format = "PEM";
3067 const char *keytype = "DH";
3068
3069 dctx = OSSL_DECODER_CTX_new_for_pkey(&dh, format, NULL, keytype,
3070 OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
3071 NULL, NULL);
3072
3073 if (dctx == NULL || OSSL_DECODER_CTX_get_num_decoders(dctx) == 0)
3074 goto end;
3075
3076 /* The DH parameters might not be the first section found in the PEM
3077 * file so we need to iterate over all of them until we find the right
3078 * one.
3079 */
3080 while (!BIO_eof(bio) && !dh)
3081 OSSL_DECODER_from_bio(dctx, bio);
3082
3083end:
3084 OSSL_DECODER_CTX_free(dctx);
3085 return dh;
3086#else
3087 HASSL_DH *dh = NULL;
3088
3089 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3090
3091 return dh;
3092#endif
3093}
3094
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003095static HASSL_DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003096{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003097 HASSL_DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02003098 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003099
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003100 if (in == NULL)
3101 goto end;
3102
Remi Gacogne47783ef2015-05-29 15:53:22 +02003103 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003104 goto end;
3105
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003106 dh = ssl_sock_get_dh_from_bio(in);
Remi Gacogne47783ef2015-05-29 15:53:22 +02003107
3108end:
3109 if (in)
3110 BIO_free(in);
3111
Emeric Brune1b4ed42018-08-16 15:14:12 +02003112 ERR_clear_error();
3113
Remi Gacogne47783ef2015-05-29 15:53:22 +02003114 return dh;
3115}
3116
3117int ssl_sock_load_global_dh_param_from_file(const char *filename)
3118{
3119 global_dh = ssl_sock_get_dh_from_file(filename);
3120
3121 if (global_dh) {
3122 return 0;
3123 }
3124
3125 return -1;
3126}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003127#endif
3128
William Lallemand9117de92019-10-04 00:29:42 +02003129/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02003130static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02003131 struct bind_conf *s, struct ssl_bind_conf *conf,
3132 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003133{
3134 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003135 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003136
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003137 if (*name == '!') {
3138 neg = 1;
3139 name++;
3140 }
3141 if (*name == '*') {
3142 wild = 1;
3143 name++;
3144 }
3145 /* !* filter is a nop */
3146 if (neg && wild)
3147 return order;
3148 if (*name) {
3149 int j, len;
3150 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003151 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02003152 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003153 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02003154 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003155 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003156
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003157 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02003158 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02003159 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003160 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02003161 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003162 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003163 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003164 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003165 sc->order = order++;
3166 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02003167 sc->wild = wild;
3168 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01003169 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02003170 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003171 }
3172 return order;
3173}
3174
William Lallemand6af03992019-07-23 15:00:54 +02003175/*
William Lallemand1d29c742019-10-04 00:53:29 +02003176 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
3177 * This function can't return an error.
3178 *
3179 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
3180 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003181void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02003182{
3183
3184 struct sni_ctx *sc0, *sc0b, *sc1;
3185 struct ebmb_node *node;
3186
3187 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
3188
3189 /* ignore if sc0 was already inserted in a tree */
3190 if (sc0->name.node.leaf_p)
3191 continue;
3192
3193 /* Check for duplicates. */
3194 if (sc0->wild)
3195 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
3196 else
3197 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
3198
3199 for (; node; node = ebmb_next_dup(node)) {
3200 sc1 = ebmb_entry(node, struct sni_ctx, name);
3201 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
3202 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
3203 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02003204 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02003205 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003206 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02003207 break;
William Lallemand1d29c742019-10-04 00:53:29 +02003208 }
3209 }
3210
3211 /* if duplicate, ignore the insertion */
3212 if (!sc0)
3213 continue;
3214
3215 if (sc0->wild)
3216 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
3217 else
3218 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003219 }
William Lallemand21724f02019-11-04 17:56:13 +01003220
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003221 /* replace the default_ctx if required with the instance's ctx. */
3222 if (ckch_inst->is_default) {
3223 SSL_CTX_free(bind_conf->default_ctx);
3224 SSL_CTX_up_ref(ckch_inst->ctx);
3225 bind_conf->default_ctx = ckch_inst->ctx;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003226 bind_conf->default_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02003227 }
3228}
3229
3230/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003231 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02003232 */
William Lallemande3af8fb2019-10-08 11:36:53 +02003233struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02003234
William Lallemand2954c472020-03-06 21:54:13 +01003235/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02003236struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02003237
Emeric Brun7a883362019-10-17 13:27:40 +02003238/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003239 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02003240 * DH parameter is loaded into the SSL_CTX and if there is no
3241 * DH parameter available in ckchs nor in global, the default
3242 * DH parameters are applied on the SSL_CTX.
3243 * Returns a bitfield containing the flags:
3244 * ERR_FATAL in any fatal error case
3245 * ERR_ALERT if a reason of the error is availabine in err
3246 * ERR_WARN if a warning is available into err
3247 * The value 0 means there is no error nor warning and
3248 * the operation succeed.
3249 */
William Lallemandfa892222019-07-23 16:06:08 +02003250#ifndef OPENSSL_NO_DH
William Lallemand52ddd992022-11-22 11:51:53 +01003251static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct ckch_data *data,
Emeric Brun7a883362019-10-17 13:27:40 +02003252 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02003253{
Emeric Brun7a883362019-10-17 13:27:40 +02003254 int ret = 0;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003255 HASSL_DH *dh = NULL;
William Lallemandfa892222019-07-23 16:06:08 +02003256
William Lallemand52ddd992022-11-22 11:51:53 +01003257 if (data && data->dh) {
3258 dh = data->dh;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003259 if (!ssl_sock_set_tmp_dh(ctx, dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003260 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
3261 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003262 memprintf(err, "%s, DH ciphers won't be available.\n",
3263 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003264 ret |= ERR_WARN;
3265 goto end;
3266 }
William Lallemandfa892222019-07-23 16:06:08 +02003267
3268 if (ssl_dh_ptr_index >= 0) {
3269 /* store a pointer to the DH params to avoid complaining about
3270 ssl-default-dh-param not being set for this SSL_CTX */
3271 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
3272 }
3273 }
3274 else if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003275 if (!ssl_sock_set_tmp_dh(ctx, global_dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003276 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
3277 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003278 memprintf(err, "%s, DH ciphers won't be available.\n",
3279 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003280 ret |= ERR_WARN;
3281 goto end;
3282 }
William Lallemandfa892222019-07-23 16:06:08 +02003283 }
3284 else {
3285 /* Clear openssl global errors stack */
3286 ERR_clear_error();
3287
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003288 /* We do not want DHE ciphers to be added to the cipher list
3289 * unless there is an explicit global dh option in the conf.
3290 */
3291 if (global_ssl.default_dh_param) {
3292 if (global_ssl.default_dh_param <= 1024) {
3293 /* we are limited to DH parameter of 1024 bits anyway */
3294 if (local_dh_1024 == NULL)
3295 local_dh_1024 = ssl_get_dh_1024();
William Lallemandfa892222019-07-23 16:06:08 +02003296
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003297 if (local_dh_1024 == NULL) {
3298 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3299 err && *err ? *err : "", path);
3300 ret |= ERR_ALERT | ERR_FATAL;
3301 goto end;
3302 }
William Lallemandfa892222019-07-23 16:06:08 +02003303
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003304 if (!ssl_sock_set_tmp_dh(ctx, local_dh_1024)) {
3305 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3306 err && *err ? *err : "", path);
3307 memprintf(err, "%s, DH ciphers won't be available.\n",
3308 err && *err ? *err : "");
3309 ret |= ERR_WARN;
3310 goto end;
3311 }
Emeric Bruna9363eb2019-10-17 14:53:03 +02003312 }
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003313 else {
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003314#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003315 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003316#else
William Lallemand52ddd992022-11-22 11:51:53 +01003317 ssl_sock_set_tmp_dh_from_pkey(ctx, data ? data->key : NULL);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003318#endif
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003319 }
William Lallemandfa892222019-07-23 16:06:08 +02003320 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003321 }
3322
William Lallemandf9568fc2019-10-16 18:27:58 +02003323end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003324 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003325 return ret;
3326}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003327#endif
William Lallemandfa892222019-07-23 16:06:08 +02003328
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003329
3330/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003331 * Returns a bitfield containing the flags:
3332 * ERR_FATAL in any fatal error case
3333 * ERR_ALERT if the reason of the error is available in err
3334 * ERR_WARN if a warning is available into err
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003335 * The caller is responsible of freeing the newly built or newly refcounted
3336 * find_chain element.
Emeric Bruna96b5822019-10-17 13:25:14 +02003337 * The value 0 means there is no error nor warning and
3338 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003339 */
William Lallemand52ddd992022-11-22 11:51:53 +01003340static int ssl_sock_load_cert_chain(const char *path, const struct ckch_data *data,
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003341 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003342{
Emeric Bruna96b5822019-10-17 13:25:14 +02003343 int errcode = 0;
William Lallemand45fed2c2022-11-15 16:56:03 +01003344 int ret;
3345
3346 ERR_clear_error();
Emeric Bruna96b5822019-10-17 13:25:14 +02003347
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003348 if (find_chain == NULL) {
3349 errcode |= ERR_FATAL;
3350 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003351 }
3352
William Lallemand52ddd992022-11-22 11:51:53 +01003353 if (!SSL_CTX_use_certificate(ctx, data->cert)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003354 ret = ERR_get_error();
3355 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s': %s.\n",
3356 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Emeric Bruna96b5822019-10-17 13:25:14 +02003357 errcode |= ERR_ALERT | ERR_FATAL;
3358 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003359 }
3360
William Lallemand52ddd992022-11-22 11:51:53 +01003361 if (data->chain) {
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003362 *find_chain = X509_chain_up_ref(data->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003363 } else {
3364 /* Find Certificate Chain in global */
3365 struct issuer_chain *issuer;
William Lallemand52ddd992022-11-22 11:51:53 +01003366 issuer = ssl_get0_issuer_chain(data->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003367 if (issuer)
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003368 *find_chain = X509_chain_up_ref(issuer->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003369 }
William Lallemand85888572020-02-27 14:48:35 +01003370
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003371 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003372 /* always put a null chain stack in the SSL_CTX so it does not
3373 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003374 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003375 }
3376
William Lallemand52ddd992022-11-22 11:51:53 +01003377 /* Load all certs in the data into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003378#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003379 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003380 ret = ERR_get_error();
3381 memprintf(err, "%sunable to load chain certificate into SSL Context '%s': %s. Make sure you are linking against Openssl >= 1.0.2.\n",
3382 err && *err ? *err : "", path, ERR_reason_error_string(ret));
William Lallemand935d8292020-08-12 20:02:10 +02003383 errcode |= ERR_ALERT | ERR_FATAL;
3384 goto end;
3385 }
William Lallemandf187ce62020-06-02 18:27:20 +02003386#else
3387 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003388 X509 *ca;
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003389 while ((ca = sk_X509_shift(*find_chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003390 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003391 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3392 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003393 X509_free(ca);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003394 errcode |= ERR_ALERT | ERR_FATAL;
3395 goto end;
3396 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003397 }
William Lallemandf187ce62020-06-02 18:27:20 +02003398#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003399
William Lallemand9a1d8392020-08-10 17:28:23 +02003400#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003401 /* remove the Root CA from the SSL_CTX if the option is activated */
3402 if (global_ssl.skip_self_issued_ca) {
3403 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3404 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3405 err && *err ? *err : "", path);
3406 errcode |= ERR_ALERT | ERR_FATAL;
3407 goto end;
3408 }
3409 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003410#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003411
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003412end:
3413 return errcode;
3414}
3415
3416
3417/* Loads the info in ckch into ctx
3418 * Returns a bitfield containing the flags:
3419 * ERR_FATAL in any fatal error case
3420 * ERR_ALERT if the reason of the error is available in err
3421 * ERR_WARN if a warning is available into err
3422 * The value 0 means there is no error nor warning and
3423 * the operation succeed.
3424 */
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01003425static 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 +01003426{
3427 int errcode = 0;
3428 STACK_OF(X509) *find_chain = NULL;
3429
William Lallemand5de49512022-10-27 14:41:07 +02003430 ERR_clear_error();
3431
William Lallemand52ddd992022-11-22 11:51:53 +01003432 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
William Lallemand5de49512022-10-27 14:41:07 +02003433 int ret;
3434
3435 ret = ERR_get_error();
3436 memprintf(err, "%sunable to load SSL private key into SSL Context '%s': %s.\n",
3437 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003438 errcode |= ERR_ALERT | ERR_FATAL;
3439 return errcode;
3440 }
3441
3442 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01003443 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003444 if (errcode & ERR_CODE)
3445 goto end;
3446
William Lallemandfa892222019-07-23 16:06:08 +02003447#ifndef OPENSSL_NO_DH
3448 /* store a NULL pointer to indicate we have not yet loaded
3449 a custom DH param file */
3450 if (ssl_dh_ptr_index >= 0) {
3451 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3452 }
3453
William Lallemand52ddd992022-11-22 11:51:53 +01003454 errcode |= ssl_sock_load_dh_params(ctx, data, path, err);
Emeric Brun7a883362019-10-17 13:27:40 +02003455 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003456 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3457 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003458 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003459 }
3460#endif
3461
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003462#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemand52ddd992022-11-22 11:51:53 +01003463 if (sctl_ex_index >= 0 && data->sctl) {
3464 if (ssl_sock_load_sctl(ctx, data->sctl) < 0) {
William Lallemanda17f4112019-10-10 15:16:44 +02003465 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003466 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003467 errcode |= ERR_ALERT | ERR_FATAL;
3468 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003469 }
3470 }
3471#endif
3472
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003473#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 +01003474 /* Load OCSP Info into context
3475 * If OCSP update mode is set to 'on', an entry will be created in the
3476 * ocsp tree even if no ocsp_response was known during init, unless the
3477 * frontend's conf disables ocsp update explicitely.
3478 */
Remi Tricot-Le Breton0c96ee42023-03-01 16:11:50 +01003479 if (ssl_sock_load_ocsp(path, ctx, data, find_chain) < 0) {
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01003480 if (data->ocsp_response)
Tim Duesterhus93128532019-11-23 23:45:10 +01003481 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 +01003482 err && *err ? *err : "", path);
3483 else
3484 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",
3485 err && *err ? *err : "", path);
3486 errcode |= ERR_ALERT | ERR_FATAL;
3487 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003488 }
William Lallemand246c0242019-10-11 08:59:13 +02003489#endif
3490
Emeric Bruna96b5822019-10-17 13:25:14 +02003491 end:
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003492 sk_X509_pop_free(find_chain, X509_free);
Emeric Bruna96b5822019-10-17 13:25:14 +02003493 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003494}
3495
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003496
3497/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
3498 * Returns a bitfield containing the flags:
3499 * ERR_FATAL in any fatal error case
3500 * ERR_ALERT if the reason of the error is available in err
3501 * ERR_WARN if a warning is available into err
3502 * The value 0 means there is no error nor warning and
3503 * the operation succeed.
3504 */
William Lallemand52ddd992022-11-22 11:51:53 +01003505static 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 +01003506 SSL_CTX *ctx, char **err)
3507{
3508 int errcode = 0;
3509 STACK_OF(X509) *find_chain = NULL;
3510
3511 /* Load the private key */
William Lallemand52ddd992022-11-22 11:51:53 +01003512 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003513 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3514 err && *err ? *err : "", path);
3515 errcode |= ERR_ALERT | ERR_FATAL;
3516 }
3517
3518 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01003519 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003520 if (errcode & ERR_CODE)
3521 goto end;
3522
3523 if (SSL_CTX_check_private_key(ctx) <= 0) {
3524 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3525 err && *err ? *err : "", path);
3526 errcode |= ERR_ALERT | ERR_FATAL;
3527 }
3528
3529end:
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003530 sk_X509_pop_free(find_chain, X509_free);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003531 return errcode;
3532}
3533
3534
William Lallemand614ca0d2019-10-07 13:52:11 +02003535/*
3536 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003537 *
3538 * Returns a bitfield containing the flags:
3539 * ERR_FATAL in any fatal error case
3540 * ERR_ALERT if the reason of the error is available in err
3541 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003542 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003543int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003544 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003545{
William Lallemandc9402072019-05-15 15:33:54 +02003546 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003547 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003548 int order = 0;
3549 X509_NAME *xname;
3550 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003551 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003552 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003553#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3554 STACK_OF(GENERAL_NAME) *names;
3555#endif
William Lallemand52ddd992022-11-22 11:51:53 +01003556 struct ckch_data *data;
William Lallemand614ca0d2019-10-07 13:52:11 +02003557 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003558 int errcode = 0;
3559
3560 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003561
William Lallemand52ddd992022-11-22 11:51:53 +01003562 if (!ckchs || !ckchs->data)
Emeric Brun054563d2019-10-17 13:16:58 +02003563 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003564
William Lallemand52ddd992022-11-22 11:51:53 +01003565 data = ckchs->data;
William Lallemand36b84632019-07-18 19:28:17 +02003566
William Lallemandc9402072019-05-15 15:33:54 +02003567 ctx = SSL_CTX_new(SSLv23_server_method());
3568 if (!ctx) {
3569 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3570 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003571 errcode |= ERR_ALERT | ERR_FATAL;
3572 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003573 }
3574
William Lallemand52ddd992022-11-22 11:51:53 +01003575 errcode |= ssl_sock_put_ckch_into_ctx(path, data, ctx, err);
Emeric Bruna96b5822019-10-17 13:25:14 +02003576 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003577 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003578
3579 ckch_inst = ckch_inst_new();
3580 if (!ckch_inst) {
3581 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3582 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003583 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003584 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003585 }
3586
William Lallemand52ddd992022-11-22 11:51:53 +01003587 pkey = X509_get_pubkey(data->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003588 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003589 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003590 switch(EVP_PKEY_base_id(pkey)) {
3591 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003592 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003593 break;
3594 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003595 kinfo.sig = TLSEXT_signature_ecdsa;
3596 break;
3597 case EVP_PKEY_DSA:
3598 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003599 break;
3600 }
3601 EVP_PKEY_free(pkey);
3602 }
3603
Emeric Brun50bcecc2013-04-22 13:05:23 +02003604 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003605 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003606 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 +02003607 if (order < 0) {
3608 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003609 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003610 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003611 }
3612 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003613 }
3614 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003615#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand52ddd992022-11-22 11:51:53 +01003616 names = X509_get_ext_d2i(data->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003617 if (names) {
3618 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3619 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3620 if (name->type == GEN_DNS) {
3621 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003622 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003623 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003624 if (order < 0) {
3625 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003626 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003627 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003628 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003629 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003630 }
3631 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003632 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003633 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003634#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand52ddd992022-11-22 11:51:53 +01003635 xname = X509_get_subject_name(data->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003636 i = -1;
3637 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3638 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003639 ASN1_STRING *value;
3640
3641 value = X509_NAME_ENTRY_get_data(entry);
3642 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003643 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003644 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003645 if (order < 0) {
3646 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003647 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003648 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003649 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003650 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003651 }
3652 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003653 /* we must not free the SSL_CTX anymore below, since it's already in
3654 * the tree, so it will be discovered and cleaned in time.
3655 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003656
Emeric Brunfc0421f2012-09-07 17:30:07 +02003657#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003658 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003659 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3660 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003661 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003662 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003663 }
3664#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003665 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003666 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003667 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003668 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003669 SSL_CTX_up_ref(ctx);
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003670 bind_conf->default_inst = ckch_inst;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003671 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003672
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003673 /* Always keep a reference to the newly constructed SSL_CTX in the
3674 * instance. This way if the instance has no SNIs, the SSL_CTX will
3675 * still be linked. */
3676 SSL_CTX_up_ref(ctx);
3677 ckch_inst->ctx = ctx;
3678
William Lallemand9117de92019-10-04 00:29:42 +02003679 /* everything succeed, the ckch instance can be used */
3680 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003681 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003682 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003683
William Lallemand02e19a52020-04-08 16:11:26 +02003684 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3685
Emeric Brun054563d2019-10-17 13:16:58 +02003686 *ckchi = ckch_inst;
3687 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003688
3689error:
3690 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003691 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003692 if (ckch_inst->is_default)
3693 SSL_CTX_free(ctx);
3694
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003695 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003696 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003697 }
William Lallemandd9199372019-10-04 15:37:05 +02003698 SSL_CTX_free(ctx);
3699
Emeric Brun054563d2019-10-17 13:16:58 +02003700 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003701}
3702
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003703
3704/*
3705 * This function allocate a ckch_inst that will be used on the backend side
3706 * (server line)
3707 *
3708 * Returns a bitfield containing the flags:
3709 * ERR_FATAL in any fatal error case
3710 * ERR_ALERT if the reason of the error is available in err
3711 * ERR_WARN if a warning is available into err
3712 */
3713int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01003714 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003715{
3716 SSL_CTX *ctx;
William Lallemand52ddd992022-11-22 11:51:53 +01003717 struct ckch_data *data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003718 struct ckch_inst *ckch_inst = NULL;
3719 int errcode = 0;
3720
3721 *ckchi = NULL;
3722
William Lallemand52ddd992022-11-22 11:51:53 +01003723 if (!ckchs || !ckchs->data)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003724 return ERR_FATAL;
3725
William Lallemand52ddd992022-11-22 11:51:53 +01003726 data = ckchs->data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003727
3728 ctx = SSL_CTX_new(SSLv23_client_method());
3729 if (!ctx) {
3730 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3731 err && *err ? *err : "", path);
3732 errcode |= ERR_ALERT | ERR_FATAL;
3733 goto error;
3734 }
3735
William Lallemand52ddd992022-11-22 11:51:53 +01003736 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, data, ctx, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003737 if (errcode & ERR_CODE)
3738 goto error;
3739
3740 ckch_inst = ckch_inst_new();
3741 if (!ckch_inst) {
3742 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3743 err && *err ? *err : "", path);
3744 errcode |= ERR_ALERT | ERR_FATAL;
3745 goto error;
3746 }
3747
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003748 /* everything succeed, the ckch instance can be used */
3749 ckch_inst->bind_conf = NULL;
3750 ckch_inst->ssl_conf = NULL;
3751 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01003752 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003753 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003754
3755 *ckchi = ckch_inst;
3756 return errcode;
3757
3758error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003759 SSL_CTX_free(ctx);
3760
3761 return errcode;
3762}
3763
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003764/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003765static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3766 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003767 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003768{
Emeric Brun054563d2019-10-17 13:16:58 +02003769 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003770
3771 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003772 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 +02003773
Emeric Brun054563d2019-10-17 13:16:58 +02003774 if (errcode & ERR_CODE)
3775 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003776
William Lallemand24bde432020-03-09 16:48:43 +01003777 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003778
3779 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003780 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003781 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003782}
3783
William Lallemanddb26e2b2021-01-26 12:01:46 +01003784/* This function generates a <struct ckch_inst *> for a <struct server *>, and
3785 * fill the SSL_CTX of the server.
3786 *
3787 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003788static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01003789 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003790{
3791 int errcode = 0;
3792
3793 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01003794 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003795
3796 if (errcode & ERR_CODE)
3797 return errcode;
3798
William Lallemanddb26e2b2021-01-26 12:01:46 +01003799 (*ckch_inst)->server = server;
3800 /* Keep the reference to the SSL_CTX in the server. */
3801 SSL_CTX_up_ref((*ckch_inst)->ctx);
3802 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003803 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003804 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003805 return errcode;
3806}
3807
William Lallemand6be66ec2020-03-06 22:26:32 +01003808
William Lallemand4c68bba2020-03-30 18:45:10 +02003809
3810
3811/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3812 * done once. Zero is returned if the operation fails. No error is returned
3813 * if the random is said as not implemented, because we expect that openssl
3814 * will use another method once needed.
3815 */
Amaury Denoyellec593bcd2021-05-19 15:35:29 +02003816int ssl_initialize_random(void)
William Lallemand4c68bba2020-03-30 18:45:10 +02003817{
3818 unsigned char random;
3819 static int random_initialized = 0;
3820
3821 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3822 random_initialized = 1;
3823
3824 return random_initialized;
3825}
3826
William Lallemand2954c472020-03-06 21:54:13 +01003827/* Load a crt-list file, this is done in 2 parts:
3828 * - store the content of the file in a crtlist structure with crtlist_entry structures
3829 * - generate the instances by iterating on entries in the crtlist struct
3830 *
3831 * Nothing is locked there, this function is used in the configuration parser.
3832 *
3833 * Returns a set of ERR_* flags possibly with an error in <err>.
3834 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003835int 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 +01003836{
3837 struct crtlist *crtlist = NULL;
3838 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003839 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003840 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003841 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003842 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003843
William Lallemand79d31ec2020-03-25 15:10:49 +01003844 bind_conf_node = malloc(sizeof(*bind_conf_node));
3845 if (!bind_conf_node) {
3846 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3847 cfgerr |= ERR_FATAL | ERR_ALERT;
3848 goto error;
3849 }
3850 bind_conf_node->next = NULL;
3851 bind_conf_node->bind_conf = bind_conf;
3852
William Lallemand41ca9302020-04-08 13:15:18 +02003853 /* strip trailing slashes, including first one */
3854 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3855 *end = 0;
3856
William Lallemand2954c472020-03-06 21:54:13 +01003857 /* look for an existing crtlist or create one */
3858 eb = ebst_lookup(&crtlists_tree, file);
3859 if (eb) {
3860 crtlist = ebmb_entry(eb, struct crtlist, node);
3861 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003862 /* load a crt-list OR a directory */
3863 if (dir)
3864 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3865 else
3866 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3867
William Lallemand2954c472020-03-06 21:54:13 +01003868 if (!(cfgerr & ERR_CODE))
3869 ebst_insert(&crtlists_tree, &crtlist->node);
3870 }
3871
3872 if (cfgerr & ERR_CODE) {
3873 cfgerr |= ERR_FATAL | ERR_ALERT;
3874 goto error;
3875 }
3876
3877 /* generates ckch instance from the crtlist_entry */
3878 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3879 struct ckch_store *store;
3880 struct ckch_inst *ckch_inst = NULL;
3881
3882 store = entry->node.key;
3883 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3884 if (cfgerr & ERR_CODE) {
3885 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3886 goto error;
3887 }
Willy Tarreau2b718102021-04-21 07:32:39 +02003888 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003889 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003890 }
William Lallemand2954c472020-03-06 21:54:13 +01003891
William Lallemand79d31ec2020-03-25 15:10:49 +01003892 /* add the bind_conf to the list */
3893 bind_conf_node->next = crtlist->bind_conf;
3894 crtlist->bind_conf = bind_conf_node;
3895
William Lallemand2954c472020-03-06 21:54:13 +01003896 return cfgerr;
3897error:
3898 {
William Lallemand49398312020-03-30 17:01:33 +02003899 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003900 struct ckch_inst *inst, *s_inst;
3901
William Lallemand49398312020-03-30 17:01:33 +02003902 lastentry = entry; /* which entry we tried to generate last */
3903 if (lastentry) {
3904 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3905 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3906 break;
3907
3908 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003909
William Lallemand49398312020-03-30 17:01:33 +02003910 /* this was not generated for this bind_conf, skip */
3911 if (inst->bind_conf != bind_conf)
3912 continue;
3913
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003914 /* free the sni_ctx and instance */
3915 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003916 }
William Lallemand2954c472020-03-06 21:54:13 +01003917 }
William Lallemand2954c472020-03-06 21:54:13 +01003918 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003919 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003920 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003921 return cfgerr;
3922}
3923
William Lallemand06b22a82020-03-16 14:45:55 +01003924/* Returns a set of ERR_* flags possibly with an error in <err>. */
3925int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3926{
3927 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01003928 int cfgerr = 0;
3929 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003930 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01003931 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01003932
3933 if ((ckchs = ckchs_lookup(path))) {
3934 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01003935 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3936 found++;
3937 } else if (stat(path, &buf) == 0) {
3938 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01003939 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003940 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003941 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003942 cfgerr |= ERR_ALERT | ERR_FATAL;
3943 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003944 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01003945 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003946 }
3947 } else {
3948 /* stat failed, could be a bundle */
3949 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02003950 char fp[MAXPATHLEN+1] = {0};
3951 int n = 0;
3952
3953 /* Load all possible certs and keys in separate ckch_store */
3954 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3955 struct stat buf;
3956 int ret;
3957
3958 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3959 if (ret > sizeof(fp))
3960 continue;
3961
3962 if ((ckchs = ckchs_lookup(fp))) {
3963 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01003964 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02003965 } else {
3966 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01003967 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003968 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02003969 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003970 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02003971 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3972 }
3973 }
3974 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01003975#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
3976 if (found) {
3977 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
3978 err && *err ? *err : "", path);
3979 cfgerr |= ERR_ALERT | ERR_FATAL;
3980 }
3981#endif
William Lallemand06b22a82020-03-16 14:45:55 +01003982 }
3983 }
William Lallemand06ce84a2020-11-20 15:36:13 +01003984 if (!found) {
3985 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3986 err && *err ? *err : "", path, strerror(errno));
3987 cfgerr |= ERR_ALERT | ERR_FATAL;
3988 }
William Lallemand06b22a82020-03-16 14:45:55 +01003989
3990 return cfgerr;
3991}
3992
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003993
3994/* Create a full ssl context and ckch instance that will be used for a specific
3995 * backend server (server configuration line).
3996 * Returns a set of ERR_* flags possibly with an error in <err>.
3997 */
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02003998int 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 +01003999{
4000 struct stat buf;
4001 int cfgerr = 0;
4002 struct ckch_store *ckchs;
4003 int found = 0; /* did we found a file to load ? */
4004
4005 if ((ckchs = ckchs_lookup(path))) {
4006 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01004007 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004008 found++;
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004009 } else {
4010 if (!create_if_none) {
4011 memprintf(err, "%sunable to stat SSL certificate '%s'.\n",
4012 err && *err ? *err : "", path);
4013 cfgerr |= ERR_ALERT | ERR_FATAL;
4014 goto out;
4015 }
4016
4017 if (stat(path, &buf) == 0) {
4018 /* We do not manage directories on backend side. */
4019 if (S_ISDIR(buf.st_mode) == 0) {
4020 ++found;
4021 ckchs = ckchs_load_cert_file(path, err);
4022 if (!ckchs)
4023 cfgerr |= ERR_ALERT | ERR_FATAL;
4024 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
4025 }
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004026 }
4027 }
4028 if (!found) {
4029 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
4030 err && *err ? *err : "", path, strerror(errno));
4031 cfgerr |= ERR_ALERT | ERR_FATAL;
4032 }
4033
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004034out:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004035 return cfgerr;
4036}
4037
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004038/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004039static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004040ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004041{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004042 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004043 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004044 SSL_OP_ALL | /* all known workarounds for bugs */
4045 SSL_OP_NO_SSLv2 |
4046 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02004047 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02004048 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004049 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02004050 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004051 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004052 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004053 SSL_MODE_ENABLE_PARTIAL_WRITE |
4054 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004055 SSL_MODE_RELEASE_BUFFERS |
4056 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004057 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004058 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004059 int flags = MC_SSL_O_ALL;
4060 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02004061 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004062
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004063 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004064 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004065
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004066 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004067 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
4068 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4069 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004070 else
4071 flags = conf_ssl_methods->flags;
4072
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004073 min = conf_ssl_methods->min;
4074 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02004075
4076 /* default minimum is TLSV12, */
4077 if (!min) {
4078 if (!max || (max >= default_min_ver)) {
4079 min = default_min_ver;
4080 } else {
4081 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). "
4082 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
4083 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
4084 min = max;
4085 }
4086 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004087 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004088 if (min)
4089 flags |= (methodVersions[min].flag - 1);
4090 if (max)
4091 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004092 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004093 min = max = CONF_TLSV_NONE;
4094 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004095 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004096 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004097 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004098 if (min) {
4099 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004100 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
4101 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4102 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
4103 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004104 hole = 0;
4105 }
4106 max = i;
4107 }
4108 else {
4109 min = max = i;
4110 }
4111 }
4112 else {
4113 if (min)
4114 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004115 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004116 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004117 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4118 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004119 cfgerr += 1;
4120 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004121 /* save real min/max in bind_conf */
4122 conf_ssl_methods->min = min;
4123 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004124
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004125#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004126 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004127 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004128 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004129 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004130 else
William Lallemandd0712f32020-06-11 17:34:00 +02004131 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
4132 /* clear every version flags in case SSL_CTX_new()
4133 * returns an SSL_CTX with disabled versions */
4134 SSL_CTX_clear_options(ctx, methodVersions[i].option);
4135
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004136 if (flags & methodVersions[i].flag)
4137 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02004138
4139 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004140#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004141 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004142 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4143 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02004144#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004145
4146 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
4147 options |= SSL_OP_NO_TICKET;
4148 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
4149 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08004150
4151#ifdef SSL_OP_NO_RENEGOTIATION
4152 options |= SSL_OP_NO_RENEGOTIATION;
4153#endif
4154
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004155 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004156
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004157#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004158 if (global_ssl.async)
4159 mode |= SSL_MODE_ASYNC;
4160#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004161 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004162 if (global_ssl.life_time)
4163 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004164
4165#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand4b7938d2022-09-07 10:54:17 +02004166# ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004167 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
4168 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004169# elif defined(HAVE_SSL_CLIENT_HELLO_CB)
4170# if defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01004171 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01004172 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
William Lallemand4b7938d2022-09-07 10:54:17 +02004173# endif /* ! SSL_OP_NO_ANTI_REPLAY */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02004174 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
4175 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004176# else /* ! OPENSSL_IS_BORINGSSL && ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004177 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004178# endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02004179 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
William Lallemand4b7938d2022-09-07 10:54:17 +02004180#endif /* ! SSL_CTRL_SET_TLSEXT_HOSTNAME */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004181 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004182}
4183
William Lallemand4f45bb92017-10-30 20:08:51 +01004184
4185static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
4186{
4187 if (first == block) {
4188 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4189 if (first->len > 0)
4190 sh_ssl_sess_tree_delete(sh_ssl_sess);
4191 }
4192}
4193
4194/* return first block from sh_ssl_sess */
4195static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
4196{
4197 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
4198
4199}
4200
4201/* store a session into the cache
4202 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
4203 * data: asn1 encoded session
4204 * data_len: asn1 encoded session length
4205 * Returns 1 id session was stored (else 0)
4206 */
4207static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
4208{
4209 struct shared_block *first;
4210 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
4211
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004212 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01004213 if (!first) {
4214 /* Could not retrieve enough free blocks to store that session */
4215 return 0;
4216 }
4217
4218 /* STORE the key in the first elem */
4219 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4220 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
4221 first->len = sizeof(struct sh_ssl_sess_hdr);
4222
4223 /* it returns the already existing node
4224 or current node if none, never returns null */
4225 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
4226 if (oldsh_ssl_sess != sh_ssl_sess) {
4227 /* NOTE: Row couldn't be in use because we lock read & write function */
4228 /* release the reserved row */
William Lallemand222e5a22023-01-31 14:12:28 +01004229 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 +01004230 shctx_row_dec_hot(ssl_shctx, first);
4231 /* replace the previous session already in the tree */
4232 sh_ssl_sess = oldsh_ssl_sess;
4233 /* ignore the previous session data, only use the header */
4234 first = sh_ssl_sess_first_block(sh_ssl_sess);
4235 shctx_row_inc_hot(ssl_shctx, first);
4236 first->len = sizeof(struct sh_ssl_sess_hdr);
4237 }
4238
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004239 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01004240 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004241 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01004242 }
4243
4244 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004245
4246 return 1;
4247}
William Lallemanded0b5ad2017-10-30 19:36:36 +01004248
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004249/* SSL callback used when a new session is created while connecting to a server */
4250static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4251{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004252 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004253 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004254
Willy Tarreau07d94e42018-09-20 10:57:52 +02004255 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004256
William Lallemand3ce6eed2021-02-08 10:43:44 +01004257 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4258 * one cache per thread, it only prevents to flush it from the CLI in
4259 * another thread */
4260
Olivier Houcharde6060c52017-11-16 17:42:52 +01004261 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4262 int len;
4263 unsigned char *ptr;
William Lallemande18d4e82021-11-17 02:59:21 +01004264 const char *sni;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004265
Olivier Houcharde6060c52017-11-16 17:42:52 +01004266 len = i2d_SSL_SESSION(sess, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01004267 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004268 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004269 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4270 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4271 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004272 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
4273 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004274 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4275 }
4276 if (s->ssl_ctx.reused_sess[tid].ptr) {
4277 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4278 &ptr);
4279 }
William Lallemande18d4e82021-11-17 02:59:21 +01004280
4281 if (s->ssl_ctx.reused_sess[tid].sni) {
4282 /* if the new sni is empty or isn' t the same as the old one */
4283 if ((!sni) || strcmp(s->ssl_ctx.reused_sess[tid].sni, sni) != 0) {
4284 ha_free(&s->ssl_ctx.reused_sess[tid].sni);
4285 if (sni)
4286 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4287 }
4288 } else if (sni) {
4289 /* if there wasn't an old sni but there is a new one */
4290 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4291 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004292 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004293 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004294 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004295 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004296 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004297 }
4298
4299 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004300}
4301
Olivier Houcharde6060c52017-11-16 17:42:52 +01004302
William Lallemanded0b5ad2017-10-30 19:36:36 +01004303/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004304int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004305{
4306 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4307 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4308 unsigned char *p;
4309 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004310 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004311 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004312
4313 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004314 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004315 * note: SSL_SESSION_set1_id is using
4316 * a memcpy so we need to use a different pointer
4317 * than sid_data or sid_ctx_data to avoid valgrind
4318 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004319 */
4320
4321 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004322
4323 /* copy value in an other buffer */
4324 memcpy(encid, sid_data, sid_length);
4325
4326 /* pad with 0 */
4327 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4328 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4329
4330 /* force length to zero to avoid ASN1 encoding */
4331 SSL_SESSION_set1_id(sess, encid, 0);
4332
4333 /* force length to zero to avoid ASN1 encoding */
4334 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004335
4336 /* check if buffer is large enough for the ASN1 encoded session */
4337 data_len = i2d_SSL_SESSION(sess, NULL);
4338 if (data_len > SHSESS_MAX_DATA_LEN)
4339 goto err;
4340
4341 p = encsess;
4342
4343 /* process ASN1 session encoding before the lock */
4344 i2d_SSL_SESSION(sess, &p);
4345
William Lallemanded0b5ad2017-10-30 19:36:36 +01004346
William Lallemanda3c77cf2017-10-30 23:44:40 +01004347 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004348 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004349 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004350 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004351err:
4352 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004353 SSL_SESSION_set1_id(sess, encid, sid_length);
4354 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004355
4356 return 0; /* do not increment session reference count */
4357}
4358
4359/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004360SSL_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 +01004361{
William Lallemand4f45bb92017-10-30 20:08:51 +01004362 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004363 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4364 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004365 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004366 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004367
Willy Tarreau4c19e992021-06-15 16:39:22 +02004368 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004369
4370 /* allow the session to be freed automatically by openssl */
4371 *do_copy = 0;
4372
4373 /* tree key is zeros padded sessionid */
4374 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4375 memcpy(tmpkey, key, key_len);
4376 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4377 key = tmpkey;
4378 }
4379
4380 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004381 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004382
4383 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004384 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4385 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004386 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004387 shctx_unlock(ssl_shctx);
Willy Tarreau4c19e992021-06-15 16:39:22 +02004388 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004389 return NULL;
4390 }
4391
William Lallemand4f45bb92017-10-30 20:08:51 +01004392 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4393 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004394
William Lallemand4f45bb92017-10-30 20:08:51 +01004395 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 +01004396
William Lallemanda3c77cf2017-10-30 23:44:40 +01004397 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004398
4399 /* decode ASN1 session */
4400 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004401 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004402 /* Reset session id and session id contenxt */
4403 if (sess) {
4404 SSL_SESSION_set1_id(sess, key, key_len);
4405 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4406 }
4407
4408 return sess;
4409}
4410
William Lallemand4f45bb92017-10-30 20:08:51 +01004411
William Lallemanded0b5ad2017-10-30 19:36:36 +01004412/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004413void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004414{
William Lallemand4f45bb92017-10-30 20:08:51 +01004415 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004416 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4417 unsigned int sid_length;
4418 const unsigned char *sid_data;
4419 (void)ctx;
4420
4421 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4422 /* tree key is zeros padded sessionid */
4423 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4424 memcpy(tmpkey, sid_data, sid_length);
4425 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4426 sid_data = tmpkey;
4427 }
4428
William Lallemanda3c77cf2017-10-30 23:44:40 +01004429 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004430
4431 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004432 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4433 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004434 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004435 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004436 }
4437
4438 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004439 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004440}
4441
4442/* Set session cache mode to server and disable openssl internal cache.
4443 * Set shared cache callbacks on an ssl context.
4444 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004445void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004446{
4447 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4448
4449 if (!ssl_shctx) {
4450 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4451 return;
4452 }
4453
4454 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4455 SSL_SESS_CACHE_NO_INTERNAL |
4456 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4457
4458 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004459 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4460 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4461 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004462}
William Lallemand7d42ef52020-07-06 11:41:30 +02004463
4464/*
4465 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4466 *
4467 * The format is:
4468 * * <Label> <space> <ClientRandom> <space> <Secret>
4469 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4470 */
4471
William Lallemand722180a2021-06-09 16:46:12 +02004472#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004473void SSL_CTX_keylog(const SSL *ssl, const char *line)
4474{
4475 struct ssl_keylog *keylog;
4476 char *lastarg = NULL;
4477 char *dst = NULL;
4478
4479 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4480 if (!keylog)
4481 return;
4482
4483 lastarg = strrchr(line, ' ');
4484 if (lastarg == NULL || ++lastarg == NULL)
4485 return;
4486
4487 dst = pool_alloc(pool_head_ssl_keylog_str);
4488 if (!dst)
4489 return;
4490
4491 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4492 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4493
4494 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4495 if (keylog->client_random)
4496 goto error;
4497 keylog->client_random = dst;
4498
4499 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4500 if (keylog->client_early_traffic_secret)
4501 goto error;
4502 keylog->client_early_traffic_secret = dst;
4503
4504 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4505 if(keylog->client_handshake_traffic_secret)
4506 goto error;
4507 keylog->client_handshake_traffic_secret = dst;
4508
4509 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4510 if (keylog->server_handshake_traffic_secret)
4511 goto error;
4512 keylog->server_handshake_traffic_secret = dst;
4513
4514 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4515 if (keylog->client_traffic_secret_0)
4516 goto error;
4517 keylog->client_traffic_secret_0 = dst;
4518
4519 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4520 if (keylog->server_traffic_secret_0)
4521 goto error;
4522 keylog->server_traffic_secret_0 = dst;
4523
4524 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4525 if (keylog->early_exporter_secret)
4526 goto error;
4527 keylog->early_exporter_secret = dst;
4528
4529 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4530 if (keylog->exporter_secret)
4531 goto error;
4532 keylog->exporter_secret = dst;
4533 } else {
4534 goto error;
4535 }
4536
4537 return;
4538
4539error:
4540 pool_free(pool_head_ssl_keylog_str, dst);
4541
4542 return;
4543}
4544#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004545
William Lallemand8b453912019-11-21 15:48:10 +01004546/*
4547 * This function applies the SSL configuration on a SSL_CTX
4548 * It returns an error code and fills the <err> buffer
4549 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004550static 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 +01004551{
4552 struct proxy *curproxy = bind_conf->frontend;
4553 int cfgerr = 0;
4554 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004555 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004556 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004557#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004558 const char *conf_ciphersuites;
4559#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004560 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004561
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004562 if (ssl_conf) {
4563 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4564 int i, min, max;
4565 int flags = MC_SSL_O_ALL;
4566
4567 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004568 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4569 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004570 if (min)
4571 flags |= (methodVersions[min].flag - 1);
4572 if (max)
4573 flags |= ~((methodVersions[max].flag << 1) - 1);
4574 min = max = CONF_TLSV_NONE;
4575 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4576 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4577 if (min)
4578 max = i;
4579 else
4580 min = max = i;
4581 }
4582 /* save real min/max */
4583 conf_ssl_methods->min = min;
4584 conf_ssl_methods->max = max;
4585 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004586 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4587 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004588 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004589 }
4590 }
4591
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004592 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004593 case SSL_SOCK_VERIFY_NONE:
4594 verify = SSL_VERIFY_NONE;
4595 break;
4596 case SSL_SOCK_VERIFY_OPTIONAL:
4597 verify = SSL_VERIFY_PEER;
4598 break;
4599 case SSL_SOCK_VERIFY_REQUIRED:
4600 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4601 break;
4602 }
4603 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4604 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004605 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 +01004606 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 +01004607 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 +01004608 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004609 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004610 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004611 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004612 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004613 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004614 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004615 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4616 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4617 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4618 cfgerr |= ERR_ALERT | ERR_FATAL;
4619 }
4620 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004621 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004622 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 +02004623 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004624 }
Emeric Brun850efd52014-01-29 12:24:34 +01004625 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004626 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4627 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004628 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004629 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004630#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004631 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004632 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4633
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004634 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004635 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4636 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004637 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004638 }
Emeric Brun561e5742012-10-02 15:20:55 +02004639 else {
4640 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4641 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004642 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004643#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004644 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004645 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004646#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004647 if(bind_conf->keys_ref) {
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +01004648 if (!SSL_CTX_set_tlsext_ticket_key_evp_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004649 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4650 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004651 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004652 }
4653 }
4654#endif
4655
William Lallemand4f45bb92017-10-30 20:08:51 +01004656 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004657 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4658 if (conf_ciphers &&
4659 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004660 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4661 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004662 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004663 }
4664
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004665#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004666 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4667 if (conf_ciphersuites &&
4668 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004669 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4670 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004671 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004672 }
4673#endif
4674
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004675#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02004676 if (!local_dh_1024)
4677 local_dh_1024 = ssl_get_dh_1024();
4678 if (!local_dh_2048)
4679 local_dh_2048 = ssl_get_dh_2048();
4680 if (!local_dh_4096)
4681 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02004682#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004683
Emeric Brunfc0421f2012-09-07 17:30:07 +02004684 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004685#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004686 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004687#endif
William Lallemand722180a2021-06-09 16:46:12 +02004688#ifdef HAVE_SSL_KEYLOG
William Lallemandb60a77b2022-11-18 15:00:15 +01004689 /* only activate the keylog callback if it was required to prevent performance loss */
4690 if (global_ssl.keylog > 0)
4691 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02004692#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004693
Bernard Spil13c53f82018-02-15 13:34:58 +01004694#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004695 ssl_conf_cur = NULL;
4696 if (ssl_conf && ssl_conf->npn_str)
4697 ssl_conf_cur = ssl_conf;
4698 else if (bind_conf->ssl_conf.npn_str)
4699 ssl_conf_cur = &bind_conf->ssl_conf;
4700 if (ssl_conf_cur)
4701 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004702#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004703#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004704 ssl_conf_cur = NULL;
4705 if (ssl_conf && ssl_conf->alpn_str)
4706 ssl_conf_cur = ssl_conf;
4707 else if (bind_conf->ssl_conf.alpn_str)
4708 ssl_conf_cur = &bind_conf->ssl_conf;
4709 if (ssl_conf_cur)
4710 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004711#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004712#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004713 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4714 if (conf_curves) {
4715 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004716 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4717 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004718 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004719 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004720 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004721 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004722#endif /* defined(SSL_CTX_set1_curves_list) */
4723
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004724 if (!conf_curves) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004725#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004726#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004727 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004728 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4729 NULL);
4730
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004731 if (ecdhe && SSL_CTX_set1_curves_list(ctx, ecdhe) == 0) {
4732 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4733 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
4734 cfgerr |= ERR_ALERT | ERR_FATAL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02004735 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004736#endif /* defined(SSL_CTX_set1_curves_list) */
Olivier Houchardc2aae742017-09-22 18:26:28 +02004737#else
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004738#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
4739 int i;
4740 EC_KEY *ecdh;
4741
Olivier Houchardc2aae742017-09-22 18:26:28 +02004742 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4743 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4744 ECDHE_DEFAULT_CURVE);
Emeric Brun2b58d042012-09-20 17:10:03 +02004745
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004746 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004747 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004748 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 +01004749 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004750 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004751 }
4752 else {
4753 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4754 EC_KEY_free(ecdh);
4755 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004756#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
4757#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Emeric Brun2b58d042012-09-20 17:10:03 +02004758 }
Emeric Brun2b58d042012-09-20 17:10:03 +02004759
Emeric Brunfc0421f2012-09-07 17:30:07 +02004760 return cfgerr;
4761}
4762
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004763
4764/*
4765 * Prepare the SSL_CTX based on the bind line configuration.
4766 * Since the CA file loading is made depending on the verify option of the bind
4767 * line, the link between the SSL_CTX and the CA file tree entry is made here.
4768 * If we want to create a link between the CA file entry and the corresponding
4769 * ckch instance (for CA file hot update), it needs to be done after
4770 * ssl_sock_prepare_ctx.
4771 * Returns 0 in case of success.
4772 */
4773int ssl_sock_prep_ctx_and_inst(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
4774 SSL_CTX *ctx, struct ckch_inst *ckch_inst, char **err)
4775{
4776 int errcode = 0;
4777
4778 errcode |= ssl_sock_prepare_ctx(bind_conf, ssl_conf, ctx, err);
4779 if (!errcode && ckch_inst)
4780 ckch_inst_add_cafile_link(ckch_inst, bind_conf, ssl_conf, NULL);
4781
4782 return errcode;
4783}
4784
Evan Broderbe554312013-06-27 00:05:25 -07004785static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4786{
4787 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4788 size_t prefixlen, suffixlen;
4789
4790 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004791 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004792 return 1;
4793
Evan Broderbe554312013-06-27 00:05:25 -07004794 /* The rest of this logic is based on RFC 6125, section 6.4.3
4795 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4796
Emeric Bruna848dae2013-10-08 11:27:28 +02004797 pattern_wildcard = NULL;
4798 pattern_left_label_end = pattern;
4799 while (*pattern_left_label_end != '.') {
4800 switch (*pattern_left_label_end) {
4801 case 0:
4802 /* End of label not found */
4803 return 0;
4804 case '*':
4805 /* If there is more than one wildcards */
4806 if (pattern_wildcard)
4807 return 0;
4808 pattern_wildcard = pattern_left_label_end;
4809 break;
4810 }
4811 pattern_left_label_end++;
4812 }
4813
4814 /* If it's not trivial and there is no wildcard, it can't
4815 * match */
4816 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004817 return 0;
4818
4819 /* Make sure all labels match except the leftmost */
4820 hostname_left_label_end = strchr(hostname, '.');
4821 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004822 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004823 return 0;
4824
4825 /* Make sure the leftmost label of the hostname is long enough
4826 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004827 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004828 return 0;
4829
4830 /* Finally compare the string on either side of the
4831 * wildcard */
4832 prefixlen = pattern_wildcard - pattern;
4833 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004834 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4835 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004836 return 0;
4837
4838 return 1;
4839}
4840
4841static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4842{
4843 SSL *ssl;
4844 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004845 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004846 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004847 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004848
4849 int depth;
4850 X509 *cert;
4851 STACK_OF(GENERAL_NAME) *alt_names;
4852 int i;
4853 X509_NAME *cert_subject;
4854 char *str;
4855
4856 if (ok == 0)
4857 return ok;
4858
4859 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004860 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02004861 ssl_ctx = __conn_get_ssl_sock_ctx(conn);
Evan Broderbe554312013-06-27 00:05:25 -07004862
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004863 /* We're checking if the provided hostnames match the desired one. The
4864 * desired hostname comes from the SNI we presented if any, or if not
4865 * provided then it may have been explicitly stated using a "verifyhost"
4866 * directive. If neither is set, we don't care about the name so the
4867 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004868 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004869 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004870 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004871 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004872 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004873 if (!servername)
4874 return ok;
4875 }
Evan Broderbe554312013-06-27 00:05:25 -07004876
4877 /* We only need to verify the CN on the actual server cert,
4878 * not the indirect CAs */
4879 depth = X509_STORE_CTX_get_error_depth(ctx);
4880 if (depth != 0)
4881 return ok;
4882
4883 /* At this point, the cert is *not* OK unless we can find a
4884 * hostname match */
4885 ok = 0;
4886
4887 cert = X509_STORE_CTX_get_current_cert(ctx);
4888 /* It seems like this might happen if verify peer isn't set */
4889 if (!cert)
4890 return ok;
4891
4892 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4893 if (alt_names) {
4894 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4895 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4896 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004897#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004898 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4899#else
Evan Broderbe554312013-06-27 00:05:25 -07004900 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004901#endif
Evan Broderbe554312013-06-27 00:05:25 -07004902 ok = ssl_sock_srv_hostcheck(str, servername);
4903 OPENSSL_free(str);
4904 }
4905 }
4906 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004907 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004908 }
4909
4910 cert_subject = X509_get_subject_name(cert);
4911 i = -1;
4912 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4913 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004914 ASN1_STRING *value;
4915 value = X509_NAME_ENTRY_get_data(entry);
4916 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004917 ok = ssl_sock_srv_hostcheck(str, servername);
4918 OPENSSL_free(str);
4919 }
4920 }
4921
Willy Tarreau71d058c2017-07-26 20:09:56 +02004922 /* report the mismatch and indicate if SNI was used or not */
4923 if (!ok && !conn->err_code)
4924 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004925 return ok;
4926}
4927
Emeric Brun94324a42012-10-11 14:00:19 +02004928/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004929int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004930{
4931 int cfgerr = 0;
William Lallemand2c776f12021-12-28 18:47:17 +01004932 SSL_CTX *ctx;
William Lallemand0adafb32022-12-13 18:17:44 +01004933 /* Automatic memory computations need to know we use SSL there
4934 * If this is an internal proxy, don't use it for the computation */
William Lallemand04007cb2022-12-14 10:34:36 +01004935 if (!(srv->proxy->cap & PR_CAP_INT))
William Lallemand0adafb32022-12-13 18:17:44 +01004936 global.ssl_used_backend = 1;
Willy Tarreaufce03112015-01-15 21:32:40 +01004937
4938 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004939 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004940 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004941 ha_alert("out of memory.\n");
Emeric Brun821bb9b2017-06-15 16:37:39 +02004942 cfgerr++;
4943 return cfgerr;
4944 }
4945 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004946 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004947 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004948
William Lallemand2c776f12021-12-28 18:47:17 +01004949 if (srv->ssl_ctx.client_crt) {
4950 const int create_if_none = srv->flags & SRV_F_DYNAMIC ? 0 : 1;
4951 char *err = NULL;
4952 int err_code = 0;
4953
4954 /* If there is a crt keyword there, the SSL_CTX will be created here. */
4955 err_code = ssl_sock_load_srv_cert(srv->ssl_ctx.client_crt, srv, create_if_none, &err);
4956 if (err_code != ERR_NONE) {
4957 if ((err_code & ERR_WARN) && !(err_code & ERR_ALERT))
4958 ha_warning("%s", err);
4959 else
4960 ha_alert("%s", err);
4961
4962 if (err_code & (ERR_FATAL|ERR_ABORT))
4963 cfgerr++;
4964 }
4965 ha_free(&err);
4966 }
4967
4968 ctx = srv->ssl_ctx.ctx;
4969
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004970 /* The context will be uninitialized if there wasn't any "cert" option
4971 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004972 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004973 ctx = SSL_CTX_new(SSLv23_client_method());
4974 if (!ctx) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004975 ha_alert("unable to allocate ssl context.\n");
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004976 cfgerr++;
4977 return cfgerr;
4978 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004979
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004980 srv->ssl_ctx.ctx = ctx;
4981 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004982
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004983 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 +01004984
4985 return cfgerr;
4986}
4987
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004988/* Initialize an SSL context that will be used on the backend side.
4989 * Returns an error count.
4990 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004991static int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004992{
4993 struct proxy *curproxy = srv->proxy;
4994 int cfgerr = 0;
4995 long options =
4996 SSL_OP_ALL | /* all known workarounds for bugs */
4997 SSL_OP_NO_SSLv2 |
4998 SSL_OP_NO_COMPRESSION;
4999 long mode =
5000 SSL_MODE_ENABLE_PARTIAL_WRITE |
5001 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
5002 SSL_MODE_RELEASE_BUFFERS |
5003 SSL_MODE_SMALL_BUFFERS;
5004 int verify = SSL_VERIFY_NONE;
5005 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
5006 int i, min, max, hole;
5007 int flags = MC_SSL_O_ALL;
5008
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005009 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005010 ha_warning("no-sslv3/no-tlsv1x are ignored for this server. "
5011 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n");
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005012 else
5013 flags = conf_ssl_methods->flags;
5014
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005015 /* Real min and max should be determinate with configuration and openssl's capabilities */
5016 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005017 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005018 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005019 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005020
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005021 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005022 min = max = CONF_TLSV_NONE;
5023 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005024 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005025 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005026 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005027 if (min) {
5028 if (hole) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005029 ha_warning("%s '%s': SSL/TLS versions range not contiguous for server '%s'. "
Christopher Faulet767a84b2017-11-24 16:50:31 +01005030 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
5031 proxy_type_str(curproxy), curproxy->id, srv->id,
5032 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005033 hole = 0;
5034 }
5035 max = i;
5036 }
5037 else {
5038 min = max = i;
5039 }
5040 }
5041 else {
5042 if (min)
5043 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005044 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005045 if (!min) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005046 ha_alert("%s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01005047 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005048 cfgerr += 1;
5049 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005050
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005051#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005052 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08005053 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005054 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005055 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005056 else
5057 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
5058 if (flags & methodVersions[i].flag)
5059 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005060#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005061 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005062 methodVersions[min].ctx_set_version(ctx, SET_MIN);
5063 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005064#endif
5065
5066 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
5067 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005068 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005069
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005070#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005071 if (global_ssl.async)
5072 mode |= SSL_MODE_ASYNC;
5073#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005074 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005075
Emeric Brun850efd52014-01-29 12:24:34 +01005076 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
5077 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01005078 switch (srv->ssl_ctx.verify) {
5079 case SSL_SOCK_VERIFY_NONE:
5080 verify = SSL_VERIFY_NONE;
5081 break;
5082 case SSL_SOCK_VERIFY_REQUIRED:
5083 verify = SSL_VERIFY_PEER;
5084 break;
5085 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005086 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02005087 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01005088 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02005089 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02005090 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005091 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005092 ha_alert("unable to set CA file '%s'.\n",
5093 srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005094 cfgerr++;
5095 }
5096 }
Emeric Brun850efd52014-01-29 12:24:34 +01005097 else {
5098 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005099 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 +01005100 else
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005101 ha_alert("verify is enabled but no CA file specified.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01005102 cfgerr++;
5103 }
Emeric Brunef42d922012-10-11 16:11:36 +02005104#ifdef X509_V_FLAG_CRL_CHECK
5105 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005106 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02005107
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01005108 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005109 ha_alert("unable to configure CRL file '%s'.\n",
5110 srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005111 cfgerr++;
5112 }
5113 else {
5114 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5115 }
5116 }
5117#endif
5118 }
5119
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005120 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5121 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02005122 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005123 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005124 ha_alert("unable to set SSL cipher list to '%s'.\n",
5125 srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02005126 cfgerr++;
5127 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005128
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05005129#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005130 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005131 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005132 ha_alert("unable to set TLS 1.3 cipher suites to '%s'.\n",
5133 srv->ssl_ctx.ciphersuites);
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005134 cfgerr++;
5135 }
5136#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01005137#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
5138 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005139 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01005140#endif
5141#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5142 if (srv->ssl_ctx.alpn_str)
5143 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
5144#endif
5145
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005146
5147 return cfgerr;
5148}
5149
5150/*
5151 * Prepare the frontend's SSL_CTX based on the server line configuration.
5152 * Since the CA file loading is made depending on the verify option of the
5153 * server line, the link between the SSL_CTX and the CA file tree entry is
5154 * made here.
5155 * If we want to create a link between the CA file entry and the corresponding
5156 * ckch instance (for CA file hot update), it needs to be done after
5157 * ssl_sock_prepare_srv_ssl_ctx.
5158 * Returns an error count.
5159 */
5160int ssl_sock_prep_srv_ctx_and_inst(const struct server *srv, SSL_CTX *ctx,
5161 struct ckch_inst *ckch_inst)
5162{
5163 int cfgerr = 0;
5164
5165 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, ctx);
5166 if (!cfgerr && ckch_inst)
5167 ckch_inst_add_cafile_link(ckch_inst, NULL, NULL, srv);
Emeric Brun94324a42012-10-11 14:00:19 +02005168
5169 return cfgerr;
5170}
5171
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005172
Frédéric Lécailleec216522020-11-23 14:33:30 +01005173/*
5174 * Create an initial CTX used to start the SSL connections.
5175 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
5176 * Returns 0 if succeeded, or something >0 if not.
5177 */
5178#ifdef USE_QUIC
5179static int ssl_initial_ctx(struct bind_conf *bind_conf)
5180{
5181 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
5182 return ssl_quic_initial_ctx(bind_conf);
5183 else
5184 return ssl_sock_initial_ctx(bind_conf);
5185}
5186#else
5187static int ssl_initial_ctx(struct bind_conf *bind_conf)
5188{
5189 return ssl_sock_initial_ctx(bind_conf);
5190}
5191#endif
5192
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005193/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005194 * be NULL, in which case nothing is done. Returns the number of errors
5195 * encountered.
5196 */
Willy Tarreau03209342016-12-22 17:08:28 +01005197int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005198{
5199 struct ebmb_node *node;
5200 struct sni_ctx *sni;
5201 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01005202 int errcode = 0;
5203 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02005204
Willy Tarreaufce03112015-01-15 21:32:40 +01005205 /* Automatic memory computations need to know we use SSL there */
5206 global.ssl_used_frontend = 1;
5207
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005208 /* Create initial_ctx used to start the ssl connection before do switchctx */
5209 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01005210 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005211 /* It should not be necessary to call this function, but it's
5212 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01005213 to initial_ctx in ssl_initial_ctx. */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005214 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, NULL, bind_conf->initial_ctx, NULL, &errmsg);
5215 }
5216 if (bind_conf->default_ctx) {
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005217 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 +01005218 }
Emeric Brun0bed9942014-10-30 19:25:24 +01005219
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005220 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005221 while (node) {
5222 sni = ebmb_entry(node, struct sni_ctx, name);
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005223 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005224 /* only initialize the CTX on its first occurrence and
5225 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005226 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
5227 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005228 node = ebmb_next(node);
5229 }
5230
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005231 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005232 while (node) {
5233 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01005234 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005235 /* only initialize the CTX on its first occurrence and
5236 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005237 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005238 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005239 node = ebmb_next(node);
5240 }
William Lallemand8b453912019-11-21 15:48:10 +01005241
5242 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005243 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005244 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005245 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005246 err++;
5247 }
5248
5249 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005250 return err;
5251}
5252
Willy Tarreau55d37912016-12-21 23:38:39 +01005253/* Prepares all the contexts for a bind_conf and allocates the shared SSL
5254 * context if needed. Returns < 0 on error, 0 on success. The warnings and
5255 * alerts are directly emitted since the rest of the stack does it below.
5256 */
5257int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
5258{
5259 struct proxy *px = bind_conf->frontend;
5260 int alloc_ctx;
5261 int err;
5262
Willy Tarreau11ba4042022-05-20 15:56:32 +02005263 if (!(bind_conf->options & BC_O_USE_SSL)) {
Willy Tarreau55d37912016-12-21 23:38:39 +01005264 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005265 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
5266 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01005267 }
5268 return 0;
5269 }
5270 if (!bind_conf->default_ctx) {
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005271 if (bind_conf->strict_sni && !(bind_conf->options & BC_O_GENERATE_CERTS)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005272 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5273 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005274 }
5275 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005276 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5277 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005278 return -1;
5279 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005280 }
William Lallemandc61c0b32017-12-04 18:46:39 +01005281 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005282 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02005283 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
Willy Tarreau91358592021-06-15 08:08:04 +02005284 sizeof(*sh_ssl_sess_tree), (global.nbthread > 1));
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02005285 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005286 if (alloc_ctx == SHCTX_E_INIT_LOCK)
5287 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");
5288 else
5289 ha_alert("Unable to allocate SSL session cache.\n");
5290 return -1;
5291 }
5292 /* free block callback */
5293 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5294 /* init the root tree within the extra space */
5295 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5296 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01005297 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005298 err = 0;
5299 /* initialize all certificate contexts */
5300 err += ssl_sock_prepare_all_ctx(bind_conf);
5301
5302 /* initialize CA variables if the certificates generation is enabled */
5303 err += ssl_sock_load_ca(bind_conf);
5304
5305 return -err;
5306}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005307
William Lallemand231610a2021-12-30 11:25:43 +01005308/* release ssl context allocated for servers. Most of the field free here
5309 * must also be allocated in srv_ssl_settings_cpy() */
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005310void ssl_sock_free_srv_ctx(struct server *srv)
5311{
Olivier Houchardc7566002018-11-20 23:33:50 +01005312#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
William Lallemand231610a2021-12-30 11:25:43 +01005313 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005314#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005315#ifdef OPENSSL_NPN_NEGOTIATED
William Lallemand231610a2021-12-30 11:25:43 +01005316 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005317#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005318 if (srv->ssl_ctx.reused_sess) {
5319 int i;
5320
William Lallemande18d4e82021-11-17 02:59:21 +01005321 for (i = 0; i < global.nbthread; i++) {
Willy Tarreaue709e822021-02-26 21:06:32 +01005322 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
William Lallemande18d4e82021-11-17 02:59:21 +01005323 ha_free(&srv->ssl_ctx.reused_sess[i].sni);
5324 }
Willy Tarreaue709e822021-02-26 21:06:32 +01005325 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005326 }
5327
Willy Tarreaue709e822021-02-26 21:06:32 +01005328 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005329 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005330 srv->ssl_ctx.ctx = NULL;
5331 }
William Lallemand231610a2021-12-30 11:25:43 +01005332
5333 ha_free(&srv->ssl_ctx.ca_file);
5334 ha_free(&srv->ssl_ctx.crl_file);
5335 ha_free(&srv->ssl_ctx.client_crt);
5336 ha_free(&srv->ssl_ctx.verify_host);
5337#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5338 ha_free(&srv->sni_expr);
William Lallemand43c2ce42022-03-16 17:48:19 +01005339 release_sample_expr(srv->ssl_ctx.sni);
5340 srv->ssl_ctx.sni = NULL;
William Lallemand231610a2021-12-30 11:25:43 +01005341#endif
5342 ha_free(&srv->ssl_ctx.ciphers);
5343#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
5344 ha_free(&srv->ssl_ctx.ciphersuites);
5345#endif
William Lallemande69563f2021-12-30 14:45:19 +01005346 /* If there is a certificate we must unlink the ckch instance */
5347 ckch_inst_free(srv->ssl_ctx.inst);
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005348}
5349
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005350/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005351 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5352 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005353void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005354{
5355 struct ebmb_node *node, *back;
5356 struct sni_ctx *sni;
5357
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005358 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005359 while (node) {
5360 sni = ebmb_entry(node, struct sni_ctx, name);
5361 back = ebmb_next(node);
5362 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005363 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005364 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005365 free(sni);
5366 node = back;
5367 }
5368
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005369 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005370 while (node) {
5371 sni = ebmb_entry(node, struct sni_ctx, name);
5372 back = ebmb_next(node);
5373 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005374 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005375 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005376 free(sni);
5377 node = back;
5378 }
William Lallemandb2408692020-06-24 09:54:29 +02005379
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005380 SSL_CTX_free(bind_conf->initial_ctx);
5381 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005382 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005383 bind_conf->default_ctx = NULL;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005384 bind_conf->default_inst = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005385 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005386}
William Lallemandb2408692020-06-24 09:54:29 +02005387
5388
5389void ssl_sock_deinit()
5390{
5391 crtlist_deinit(); /* must be free'd before the ckchs */
5392 ckch_deinit();
5393}
5394REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005395
Willy Tarreau795cdab2016-12-22 17:30:54 +01005396/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5397void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5398{
5399 ssl_sock_free_ca(bind_conf);
5400 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005401 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005402 free(bind_conf->ca_sign_file);
5403 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005404 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005405 free(bind_conf->keys_ref->filename);
5406 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005407 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005408 free(bind_conf->keys_ref);
5409 }
5410 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005411 bind_conf->ca_sign_pass = NULL;
5412 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005413}
5414
Christopher Faulet31af49d2015-06-09 17:29:50 +02005415/* Load CA cert file and private key used to generate certificates */
5416int
Willy Tarreau03209342016-12-22 17:08:28 +01005417ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005418{
Willy Tarreau03209342016-12-22 17:08:28 +01005419 struct proxy *px = bind_conf->frontend;
William Lallemand52ddd992022-11-22 11:51:53 +01005420 struct ckch_data *data = NULL;
Shimi Gersner5846c492020-08-23 13:58:12 +03005421 int ret = 0;
5422 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005423
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005424 if (!(bind_conf->options & BC_O_GENERATE_CERTS))
Shimi Gersner5846c492020-08-23 13:58:12 +03005425 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005426
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005427#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005428 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005429 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005430 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005431 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005432 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005433#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005434
Christopher Faulet31af49d2015-06-09 17:29:50 +02005435 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005436 ha_alert("Proxy '%s': cannot enable certificate generation, "
5437 "no CA certificate File configured at [%s:%d].\n",
5438 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005439 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005440 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005441
Shimi Gersner5846c492020-08-23 13:58:12 +03005442 /* Allocate cert structure */
William Lallemand52ddd992022-11-22 11:51:53 +01005443 data = calloc(1, sizeof(*data));
5444 if (!data) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005445 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5446 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5447 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005448 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005449
5450 /* Try to parse file */
William Lallemand52ddd992022-11-22 11:51:53 +01005451 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, data, &err)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005452 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5453 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005454 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005455 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005456 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005457
5458 /* Fail if missing cert or pkey */
William Lallemand52ddd992022-11-22 11:51:53 +01005459 if ((!data->cert) || (!data->key)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005460 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5461 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5462 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005463 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005464
Shimi Gersner5846c492020-08-23 13:58:12 +03005465 /* Final assignment to bind */
William Lallemand52ddd992022-11-22 11:51:53 +01005466 bind_conf->ca_sign_ckch = data;
Shimi Gersner5846c492020-08-23 13:58:12 +03005467 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005468
Shimi Gersner5846c492020-08-23 13:58:12 +03005469 failed:
William Lallemand52ddd992022-11-22 11:51:53 +01005470 if (data) {
5471 ssl_sock_free_cert_key_and_chain_contents(data);
5472 free(data);
Shimi Gersner5846c492020-08-23 13:58:12 +03005473 }
5474
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005475 bind_conf->options &= ~BC_O_GENERATE_CERTS;
Shimi Gersner5846c492020-08-23 13:58:12 +03005476 ret++;
5477 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005478}
5479
5480/* Release CA cert and private key used to generate certificated */
5481void
5482ssl_sock_free_ca(struct bind_conf *bind_conf)
5483{
Shimi Gersner5846c492020-08-23 13:58:12 +03005484 if (bind_conf->ca_sign_ckch) {
5485 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005486 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005487 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005488}
5489
Emeric Brun46591952012-05-18 15:47:34 +02005490/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005491 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5492 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5493 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5494 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005495 * 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 +01005496 * as parameters to this function.
5497 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5498 * CO_ER_SSL_NO_MEM.
5499 */
5500int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5501 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5502{
5503 int retry = 1;
5504
5505 retry:
5506 /* Alloc a new SSL session. */
5507 *ssl = SSL_new(ssl_ctx);
5508 if (!*ssl) {
5509 if (!retry--)
5510 goto err;
5511
5512 pool_gc(NULL);
5513 goto retry;
5514 }
5515
5516 *bio = BIO_new(bio_meth);
5517 if (!*bio) {
5518 SSL_free(*ssl);
5519 *ssl = NULL;
5520 if (!retry--)
5521 goto err;
5522
5523 pool_gc(NULL);
5524 goto retry;
5525 }
5526
5527 BIO_set_data(*bio, ctx);
5528 SSL_set_bio(*ssl, *bio, *bio);
5529
5530 /* set connection pointer. */
5531 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5532 SSL_free(*ssl);
5533 *ssl = NULL;
5534 if (!retry--)
5535 goto err;
5536
5537 pool_gc(NULL);
5538 goto retry;
5539 }
5540
5541 return 0;
5542
5543 err:
5544 conn->err_code = CO_ER_SSL_NO_MEM;
5545 return -1;
5546}
5547
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005548/* This function is called when all the XPRT have been initialized. We can
5549 * now attempt to start the SSL handshake.
5550 */
5551static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5552{
5553 struct ssl_sock_ctx *ctx = xprt_ctx;
5554
5555 if (ctx->xprt->start) {
5556 int ret;
5557
5558 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5559 if (ret < 0)
5560 return ret;
5561 }
5562 tasklet_wakeup(ctx->wait_event.tasklet);
5563
5564 return 0;
5565}
5566
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005567/*
Emeric Brun46591952012-05-18 15:47:34 +02005568 * This function is called if SSL * context is not yet allocated. The function
5569 * is designed to be called before any other data-layer operation and sets the
5570 * handshake flag on the connection. It is safe to call it multiple times.
5571 * It returns 0 on success and -1 in error case.
5572 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005573static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005574{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005575 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005576 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005577 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005578 return 0;
5579
Olivier Houchard66ab4982019-02-26 18:37:15 +01005580 ctx = pool_alloc(ssl_sock_ctx_pool);
5581 if (!ctx) {
5582 conn->err_code = CO_ER_SSL_NO_MEM;
5583 return -1;
5584 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005585 ctx->wait_event.tasklet = tasklet_new();
5586 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005587 conn->err_code = CO_ER_SSL_NO_MEM;
5588 pool_free(ssl_sock_ctx_pool, ctx);
5589 return -1;
5590 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005591 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5592 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005593 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005594 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005595 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005596 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005597 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005598 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005599 ctx->xprt_st = 0;
5600 ctx->xprt_ctx = NULL;
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005601 ctx->error_code = 0;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005602
5603 /* Only work with sockets for now, this should be adapted when we'll
5604 * add QUIC support.
5605 */
5606 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005607 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005608 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5609 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005610 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005611
Willy Tarreau82531f62021-10-06 12:15:18 +02005612 if (global.maxsslconn && global.sslconns >= global.maxsslconn) {
Willy Tarreau20879a02012-12-03 16:32:10 +01005613 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005614 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005615 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005616
Emeric Brun46591952012-05-18 15:47:34 +02005617 /* If it is in client mode initiate SSL session
5618 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005619 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005620 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5621 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005622 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005623
Olivier Houchard66ab4982019-02-26 18:37:15 +01005624 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005625 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005626 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5627 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5628 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 +01005629 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005630 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005631 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005632 } else if (sess) {
5633 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005634 }
5635 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005636 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005637
Emeric Brun46591952012-05-18 15:47:34 +02005638 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005639 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005640
Willy Tarreau82531f62021-10-06 12:15:18 +02005641 _HA_ATOMIC_INC(&global.sslconns);
5642 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005643 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005644 return 0;
5645 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005646 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005647 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005648
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005649 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5650 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005651 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005652
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005653#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005654 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005655 b_alloc(&ctx->early_buf);
5656 SSL_set_max_early_data(ctx->ssl,
5657 /* Only allow early data if we managed to allocate
5658 * a buffer.
5659 */
5660 (!b_is_null(&ctx->early_buf)) ?
5661 global.tune.bufsize - global.tune.maxrewrite : 0);
5662 }
5663#endif
5664
Olivier Houchard66ab4982019-02-26 18:37:15 +01005665 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005666
Emeric Brun46591952012-05-18 15:47:34 +02005667 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005668 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005669#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005670 if (bc->ssl_conf.early_data)
5671 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005672#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005673
Willy Tarreau82531f62021-10-06 12:15:18 +02005674 _HA_ATOMIC_INC(&global.sslconns);
5675 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005676 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005677 return 0;
5678 }
5679 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005680 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005681err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005682 if (ctx && ctx->wait_event.tasklet)
5683 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005684 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005685 return -1;
5686}
5687
5688
5689/* This is the callback which is used when an SSL handshake is pending. It
5690 * updates the FD status if it wants some polling before being called again.
5691 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5692 * otherwise it returns non-zero and removes itself from the connection's
5693 * flags (the bit is provided in <flag> by the caller).
5694 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005695static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005696{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005697 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Emeric Brun46591952012-05-18 15:47:34 +02005698 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005699 struct ssl_counters *counters = NULL;
5700 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005701 struct listener *li;
5702 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005703 socklen_t lskerr;
5704 int skerr;
5705
Emeric Brun46591952012-05-18 15:47:34 +02005706
Willy Tarreau3c728722014-01-23 13:50:42 +01005707 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005708 return 0;
5709
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005710 /* get counters */
5711 switch (obj_type(conn->target)) {
5712 case OBJ_TYPE_LISTENER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005713 li = __objt_listener(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005714 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5715 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5716 &ssl_stats_module);
5717 break;
5718
5719 case OBJ_TYPE_SERVER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005720 srv = __objt_server(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005721 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5722 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5723 &ssl_stats_module);
5724 break;
5725
5726 default:
5727 break;
5728 }
5729
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005730 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005731 goto out_error;
5732
Willy Tarreau06300382021-02-02 15:42:25 +01005733 /* don't start calculating a handshake on a dead connection */
5734 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5735 goto out_error;
5736
5737 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5738 * status from the lower layers, so let's check the FD directly. Ideally
5739 * the xprt layers should provide some status indicating their knowledge
5740 * of shutdowns or error.
5741 */
Willy Tarreau07ecfc52022-04-11 18:07:03 +02005742 BUG_ON(conn->flags & CO_FL_FDLESS);
5743
Willy Tarreau06300382021-02-02 15:42:25 +01005744 skerr = 0;
5745 lskerr = sizeof(skerr);
5746 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5747 skerr != 0)
5748 goto out_error;
5749
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005750#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005751 /*
5752 * Check if we have early data. If we do, we have to read them
5753 * before SSL_do_handshake() is called, And there's no way to
5754 * detect early data, except to try to read them
5755 */
5756 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005757 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005758
Olivier Houchard54907bb2019-12-19 15:02:39 +01005759 while (1) {
5760 ret = SSL_read_early_data(ctx->ssl,
5761 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5762 &read_data);
5763 if (ret == SSL_READ_EARLY_DATA_ERROR)
5764 goto check_error;
5765 if (read_data > 0) {
5766 conn->flags |= CO_FL_EARLY_DATA;
5767 b_add(&ctx->early_buf, read_data);
5768 }
5769 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5770 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5771 if (!b_data(&ctx->early_buf))
5772 b_free(&ctx->early_buf);
5773 break;
5774 }
5775 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005776 }
5777#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005778 /* If we use SSL_do_handshake to process a reneg initiated by
5779 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5780 * Usually SSL_write and SSL_read are used and process implicitly
5781 * the reneg handshake.
5782 * Here we use SSL_peek as a workaround for reneg.
5783 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005784 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005785 char c;
5786
Olivier Houchard66ab4982019-02-26 18:37:15 +01005787 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005788 if (ret <= 0) {
5789 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005790 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005791
Emeric Brun674b7432012-11-08 19:21:55 +01005792 if (ret == SSL_ERROR_WANT_WRITE) {
5793 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005794 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005795 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005796 return 0;
5797 }
5798 else if (ret == SSL_ERROR_WANT_READ) {
5799 /* handshake may have been completed but we have
5800 * no more data to read.
5801 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005802 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005803 ret = 1;
5804 goto reneg_ok;
5805 }
5806 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005807 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005808 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005809 return 0;
5810 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005811#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005812 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005813 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005814 return 0;
5815 }
5816#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005817 else if (ret == SSL_ERROR_SYSCALL) {
5818 /* if errno is null, then connection was successfully established */
5819 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5820 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005821 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005822#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5823 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005824 conn->err_code = CO_ER_SSL_HANDSHAKE;
5825#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005826 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005827#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005828 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005829 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005830 empty_handshake = state == TLS_ST_BEFORE;
5831#else
Lukas Tribus49799162019-07-08 14:29:15 +02005832 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5833 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005834#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005835 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005836 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005837 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005838 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5839 else
5840 conn->err_code = CO_ER_SSL_EMPTY;
5841 }
5842 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005843 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005844 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5845 else
5846 conn->err_code = CO_ER_SSL_ABORT;
5847 }
5848 }
5849 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005850 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005851 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005852 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005853 conn->err_code = CO_ER_SSL_HANDSHAKE;
5854 }
Lukas Tribus49799162019-07-08 14:29:15 +02005855#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005856 }
Emeric Brun674b7432012-11-08 19:21:55 +01005857 goto out_error;
5858 }
5859 else {
5860 /* Fail on all other handshake errors */
5861 /* Note: OpenSSL may leave unread bytes in the socket's
5862 * buffer, causing an RST to be emitted upon close() on
5863 * TCP sockets. We first try to drain possibly pending
5864 * data to avoid this as much as possible.
5865 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005866 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005867 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005868 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005869 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005870 goto out_error;
5871 }
5872 }
5873 /* read some data: consider handshake completed */
5874 goto reneg_ok;
5875 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005876 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005877check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005878 if (ret != 1) {
5879 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005880 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005881
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005882 if (!ctx->error_code)
5883 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton7c6898e2021-07-29 09:45:51 +02005884
Emeric Brun46591952012-05-18 15:47:34 +02005885 if (ret == SSL_ERROR_WANT_WRITE) {
5886 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005887 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005888 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005889 return 0;
5890 }
5891 else if (ret == SSL_ERROR_WANT_READ) {
5892 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005893 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005894 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5895 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005896 return 0;
5897 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005898#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005899 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005900 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005901 return 0;
5902 }
5903#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005904 else if (ret == SSL_ERROR_SYSCALL) {
5905 /* if errno is null, then connection was successfully established */
5906 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5907 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005908 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005909#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5910 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005911 conn->err_code = CO_ER_SSL_HANDSHAKE;
5912#else
5913 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005914#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005915 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005916 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005917 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005918#else
Lukas Tribus49799162019-07-08 14:29:15 +02005919 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5920 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005921#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005922 if (empty_handshake) {
5923 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005924 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005925 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5926 else
5927 conn->err_code = CO_ER_SSL_EMPTY;
5928 }
5929 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005930 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005931 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5932 else
5933 conn->err_code = CO_ER_SSL_ABORT;
5934 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005935 }
5936 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005937 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005938 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5939 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005940 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005941 }
Lukas Tribus49799162019-07-08 14:29:15 +02005942#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005943 }
Willy Tarreau89230192012-09-28 20:22:13 +02005944 goto out_error;
5945 }
Emeric Brun46591952012-05-18 15:47:34 +02005946 else {
5947 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005948 /* Note: OpenSSL may leave unread bytes in the socket's
5949 * buffer, causing an RST to be emitted upon close() on
5950 * TCP sockets. We first try to drain possibly pending
5951 * data to avoid this as much as possible.
5952 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005953 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005954 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005955 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005956 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005957 goto out_error;
5958 }
5959 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005960#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005961 else {
5962 /*
5963 * If the server refused the early data, we have to send a
5964 * 425 to the client, as we no longer have the data to sent
5965 * them again.
5966 */
5967 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005968 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005969 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5970 goto out_error;
5971 }
5972 }
5973 }
5974#endif
5975
Emeric Brun46591952012-05-18 15:47:34 +02005976
Emeric Brun674b7432012-11-08 19:21:55 +01005977reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005978
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005979#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00005980 /* ASYNC engine API doesn't support moving read/write
5981 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005982 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005983 */
5984 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005985 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005986#endif
Emeric Brun46591952012-05-18 15:47:34 +02005987 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005988 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005989 if (objt_server(conn->target)) {
5990 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5991 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5992 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005993 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005994 else {
5995 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5996 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5997 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5998 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005999
Willy Tarreau42995282020-11-06 13:19:18 +01006000 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006001 HA_ATOMIC_INC(&counters->sess);
6002 HA_ATOMIC_INC(&counters_px->sess);
Willy Tarreau42995282020-11-06 13:19:18 +01006003 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006004 }
Willy Tarreau42995282020-11-06 13:19:18 +01006005 else if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006006 HA_ATOMIC_INC(&counters->reused_sess);
6007 HA_ATOMIC_INC(&counters_px->reused_sess);
Emeric Brun46591952012-05-18 15:47:34 +02006008 }
6009
6010 /* The connection is now established at both layers, it's time to leave */
6011 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
6012 return 1;
6013
6014 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006015 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006016 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006017 ERR_clear_error();
6018
Emeric Brun9fa89732012-10-04 17:09:56 +02006019 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01006020 if (objt_server(conn->target)) {
6021 struct server *s = __objt_server(conn->target);
6022 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
6023 * one cache per thread, it only prevents to flush it from the CLI in
6024 * another thread */
6025
6026 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01006027 if (s->ssl_ctx.reused_sess[tid].ptr)
6028 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01006029 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02006030 }
6031
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006032 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006033 HA_ATOMIC_INC(&counters->failed_handshake);
6034 HA_ATOMIC_INC(&counters_px->failed_handshake);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006035 }
6036
Emeric Brun46591952012-05-18 15:47:34 +02006037 /* Fail on all other handshake errors */
6038 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01006039 if (!conn->err_code)
6040 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006041 return 0;
6042}
6043
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006044/* Called from the upper layer, to subscribe <es> to events <event_type>. The
6045 * event subscriber <es> is not allowed to change from a previous call as long
6046 * as at least one event is still subscribed. The <event_type> must only be a
6047 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
6048 * unless the transport layer was already released.
6049 */
6050static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006051{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006052 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006053
Olivier Houchard0ff28652019-06-24 18:57:39 +02006054 if (!ctx)
6055 return -1;
6056
Willy Tarreau113d52b2020-01-10 09:20:26 +01006057 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006058 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006059
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006060 ctx->subs = es;
6061 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006062
6063 /* we may have to subscribe to lower layers for new events */
6064 event_type &= ~ctx->wait_event.events;
6065 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
6066 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006067 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006068}
6069
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006070/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
6071 * The <es> pointer is not allowed to differ from the one passed to the
6072 * subscribe() call. It always returns zero.
6073 */
6074static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006075{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006076 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006077
Willy Tarreau113d52b2020-01-10 09:20:26 +01006078 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006079 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006080
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006081 es->events &= ~event_type;
6082 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01006083 ctx->subs = NULL;
6084
6085 /* If we subscribed, and we're not doing the handshake,
6086 * then we subscribed because the upper layer asked for it,
6087 * as the upper layer is no longer interested, we can
6088 * unsubscribe too.
6089 */
6090 event_type &= ctx->wait_event.events;
6091 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
6092 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006093
6094 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006095}
6096
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006097/* The connection has been taken over, so destroy the old tasklet and create
6098 * a new one. The original thread ID must be passed into orig_tid
6099 * It should be called with the takeover lock for the old thread held.
6100 * Returns 0 on success, and -1 on failure
6101 */
6102static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
6103{
6104 struct ssl_sock_ctx *ctx = xprt_ctx;
6105 struct tasklet *tl = tasklet_new();
6106
6107 if (!tl)
6108 return -1;
6109
6110 ctx->wait_event.tasklet->context = NULL;
6111 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
6112 ctx->wait_event.tasklet = tl;
6113 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
6114 ctx->wait_event.tasklet->context = ctx;
6115 return 0;
6116}
6117
Willy Tarreau41491682021-03-02 17:29:56 +01006118/* notify the next xprt that the connection is about to become idle and that it
6119 * may be stolen at any time after the function returns and that any tasklet in
6120 * the chain must be careful before dereferencing its context.
6121 */
6122static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
6123{
6124 struct ssl_sock_ctx *ctx = xprt_ctx;
6125
6126 if (!ctx || !ctx->wait_event.tasklet)
6127 return;
6128
6129 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6130 if (ctx->xprt)
6131 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
6132}
6133
6134/* notify the next xprt that the connection is not idle anymore and that it may
6135 * not be stolen before the next xprt_set_idle().
6136 */
6137static void ssl_set_used(struct connection *conn, void *xprt_ctx)
6138{
6139 struct ssl_sock_ctx *ctx = xprt_ctx;
6140
6141 if (!ctx || !ctx->wait_event.tasklet)
6142 return;
6143
6144 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6145 if (ctx->xprt)
6146 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
6147}
6148
Olivier Houchard2e055482019-05-27 19:50:12 +02006149/* Use the provided XPRT as an underlying XPRT, and provide the old one.
6150 * Returns 0 on success, and non-zero on failure.
6151 */
6152static 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)
6153{
6154 struct ssl_sock_ctx *ctx = xprt_ctx;
6155
6156 if (oldxprt_ops != NULL)
6157 *oldxprt_ops = ctx->xprt;
6158 if (oldxprt_ctx != NULL)
6159 *oldxprt_ctx = ctx->xprt_ctx;
6160 ctx->xprt = toadd_ops;
6161 ctx->xprt_ctx = toadd_ctx;
6162 return 0;
6163}
6164
Olivier Houchard5149b592019-05-23 17:47:36 +02006165/* Remove the specified xprt. If if it our underlying XPRT, remove it and
6166 * return 0, otherwise just call the remove_xprt method from the underlying
6167 * XPRT.
6168 */
6169static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
6170{
6171 struct ssl_sock_ctx *ctx = xprt_ctx;
6172
6173 if (ctx->xprt_ctx == toremove_ctx) {
6174 ctx->xprt_ctx = newctx;
6175 ctx->xprt = newops;
6176 return 0;
6177 }
6178 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
6179}
6180
Willy Tarreau144f84a2021-03-02 16:09:26 +01006181struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02006182{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006183 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006184 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006185 struct connection *conn;
6186 int conn_in_list;
6187 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006188
Willy Tarreau41491682021-03-02 17:29:56 +01006189 if (state & TASK_F_USR1) {
6190 /* the tasklet was idling on an idle connection, it might have
6191 * been stolen, let's be careful!
6192 */
6193 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6194 if (tl->context == NULL) {
6195 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6196 tasklet_free(tl);
6197 return NULL;
6198 }
6199 conn = ctx->conn;
6200 conn_in_list = conn->flags & CO_FL_LIST_MASK;
6201 if (conn_in_list)
6202 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006203 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01006204 } else {
6205 conn = ctx->conn;
6206 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006207 }
Willy Tarreau41491682021-03-02 17:29:56 +01006208
Olivier Houchardea8dd942019-05-20 14:02:16 +02006209 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01006210 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006211 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006212 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
6213 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01006214 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006215 }
6216 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006217 /* If we had an error, or the handshake is done and I/O is available,
6218 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01006219 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02006220 * we can't be sure conn_fd_handler() will be called again.
6221 */
6222 if ((ctx->conn->flags & CO_FL_ERROR) ||
6223 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006224 int woke = 0;
6225
6226 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006227 if (ctx->subs) {
6228 tasklet_wakeup(ctx->subs->tasklet);
6229 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006230 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006231 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006232 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006233
Olivier Houchardea8dd942019-05-20 14:02:16 +02006234 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01006235 * upper layers know. If we have no mux, create it,
6236 * and once we have a mux, call its wake method if we didn't
6237 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02006238 */
6239 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01006240 if (!ctx->conn->mux)
6241 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006242 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006243 ret = ctx->conn->mux->wake(ctx->conn);
6244 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006245 }
6246 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006247#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006248 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006249 else if (b_data(&ctx->early_buf) && ctx->subs &&
6250 ctx->subs->events & SUB_RETRY_RECV) {
6251 tasklet_wakeup(ctx->subs->tasklet);
6252 ctx->subs->events &= ~SUB_RETRY_RECV;
6253 if (!ctx->subs->events)
6254 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01006255 }
6256#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006257leave:
6258 if (!ret && conn_in_list) {
6259 struct server *srv = objt_server(conn->target);
6260
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006261 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006262 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau85223482022-09-29 20:32:43 +02006263 eb64_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006264 else
Willy Tarreau85223482022-09-29 20:32:43 +02006265 eb64_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006266 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006267 }
Willy Tarreau74163142021-03-13 11:30:19 +01006268 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006269}
6270
Emeric Brun46591952012-05-18 15:47:34 +02006271/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01006272 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02006273 * buffer wraps, in which case a second call may be performed. The connection's
6274 * flags are updated with whatever special event is detected (error, read0,
6275 * empty). The caller is responsible for taking care of those events and
6276 * avoiding the call if inappropriate. The function does not call the
6277 * connection's polling update function, so the caller is responsible for this.
6278 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006279static 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 +02006280{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006281 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02006282 ssize_t ret;
6283 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02006284
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006285 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006286 goto out_error;
6287
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006288#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006289 if (b_data(&ctx->early_buf)) {
6290 try = b_contig_space(buf);
6291 if (try > b_data(&ctx->early_buf))
6292 try = b_data(&ctx->early_buf);
6293 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
6294 b_add(buf, try);
6295 b_del(&ctx->early_buf, try);
6296 if (b_data(&ctx->early_buf) == 0)
6297 b_free(&ctx->early_buf);
6298 return try;
6299 }
6300#endif
6301
Willy Tarreau911db9b2020-01-23 16:27:54 +01006302 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006303 /* a handshake was requested */
6304 return 0;
6305
Emeric Brun46591952012-05-18 15:47:34 +02006306 /* read the largest possible block. For this, we perform only one call
6307 * to recv() unless the buffer wraps and we exactly fill the first hunk,
6308 * in which case we accept to do it once again. A new attempt is made on
6309 * EINTR too.
6310 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01006311 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006312
Willy Tarreau591d4452018-06-15 17:21:00 +02006313 try = b_contig_space(buf);
6314 if (!try)
6315 break;
6316
Willy Tarreauabf08d92014-01-14 11:31:27 +01006317 if (try > count)
6318 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02006319
Olivier Houchard66ab4982019-02-26 18:37:15 +01006320 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02006321
Emeric Brune1f38db2012-09-03 20:36:47 +02006322 if (conn->flags & CO_FL_ERROR) {
6323 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006324 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006325 }
Emeric Brun46591952012-05-18 15:47:34 +02006326 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006327 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006328 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006329 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006330 }
Emeric Brun46591952012-05-18 15:47:34 +02006331 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006332 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006333 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006334 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006335 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006336 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006337#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006338 /* Async mode can be re-enabled, because we're leaving data state.*/
6339 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006340 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006341#endif
Emeric Brun46591952012-05-18 15:47:34 +02006342 break;
6343 }
6344 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006345 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006346 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6347 SUB_RETRY_RECV,
6348 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006349 /* handshake is running, and it may need to re-enable read */
6350 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006351#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006352 /* Async mode can be re-enabled, because we're leaving data state.*/
6353 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006354 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006355#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006356 break;
6357 }
Emeric Brun46591952012-05-18 15:47:34 +02006358 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006359 } else if (ret == SSL_ERROR_ZERO_RETURN)
6360 goto read0;
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006361 else if (ret == SSL_ERROR_SSL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006362 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6363 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006364 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006365 conn->err_code = CO_ERR_SSL_FATAL;
6366 }
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006367 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6368 * stack before shutting down the connection for
6369 * reading. */
Willy Tarreauacef5e22022-04-25 20:32:15 +02006370 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN || errno == EWOULDBLOCK))
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006371 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006372 /* otherwise it's a real error */
6373 goto out_error;
6374 }
6375 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006376 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006377 return done;
6378
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006379 clear_ssl_error:
6380 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006381 ssl_sock_dump_errors(conn, NULL);
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006382 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006383 read0:
6384 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006385 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006386
Emeric Brun46591952012-05-18 15:47:34 +02006387 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006388 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006389 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006390 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006391 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006392 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006393}
6394
6395
Willy Tarreau787db9a2018-06-14 18:31:46 +02006396/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6397 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6398 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006399 * Only one call to send() is performed, unless the buffer wraps, in which case
6400 * a second call may be performed. The connection's flags are updated with
6401 * whatever special event is detected (error, empty). The caller is responsible
6402 * for taking care of those events and avoiding the call if inappropriate. The
6403 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006404 * is responsible for this. The buffer's output is not adjusted, it's up to the
6405 * caller to take care of this. It's up to the caller to update the buffer's
6406 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006407 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006408static 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 +02006409{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006410 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006411 ssize_t ret;
6412 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006413
6414 done = 0;
6415
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006416 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006417 goto out_error;
6418
Willy Tarreau911db9b2020-01-23 16:27:54 +01006419 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006420 /* a handshake was requested */
6421 return 0;
6422
6423 /* send the largest possible block. For this we perform only one call
6424 * to send() unless the buffer wraps and we exactly fill the first hunk,
6425 * in which case we accept to do it once again.
6426 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006427 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006428#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006429 size_t written_data;
6430#endif
6431
Willy Tarreau787db9a2018-06-14 18:31:46 +02006432 try = b_contig_data(buf, done);
6433 if (try > count)
6434 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006435
Thomas Prückl10243932022-04-27 13:04:54 +02006436 if (global_ssl.hard_max_record && try > global_ssl.hard_max_record)
6437 try = global_ssl.hard_max_record;
6438
Willy Tarreau7bed9452014-02-02 02:00:24 +01006439 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006440 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006441 global_ssl.max_record && try > global_ssl.max_record) {
6442 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006443 }
6444 else {
6445 /* we need to keep the information about the fact that
6446 * we're not limiting the upcoming send(), because if it
6447 * fails, we'll have to retry with at least as many data.
6448 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006449 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006450 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006451
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006452#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006453 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006454 unsigned int max_early;
6455
Olivier Houchard522eea72017-11-03 16:27:47 +01006456 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006457 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006458 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006459 if (SSL_get0_session(ctx->ssl))
6460 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006461 else
6462 max_early = 0;
6463 }
6464
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006465 if (try + ctx->sent_early_data > max_early) {
6466 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006467 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006468 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006469 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006470 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006471 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006472 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006473 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006474 if (ret == 1) {
6475 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006476 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006477 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006478 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006479 /* Initiate the handshake, now */
6480 tasklet_wakeup(ctx->wait_event.tasklet);
6481 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006482
Olivier Houchardc2aae742017-09-22 18:26:28 +02006483 }
6484
6485 } else
6486#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006487 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006488
Emeric Brune1f38db2012-09-03 20:36:47 +02006489 if (conn->flags & CO_FL_ERROR) {
6490 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006491 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006492 }
Emeric Brun46591952012-05-18 15:47:34 +02006493 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006494 /* A send succeeded, so we can consider ourself connected */
6495 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006496 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006497 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006498 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006499 }
6500 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006501 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006502
Emeric Brun46591952012-05-18 15:47:34 +02006503 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006504 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006505 /* handshake is running, and it may need to re-enable write */
6506 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006507 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006508#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006509 /* Async mode can be re-enabled, because we're leaving data state.*/
6510 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006511 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006512#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006513 break;
6514 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006515
Emeric Brun46591952012-05-18 15:47:34 +02006516 break;
6517 }
6518 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006519 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006520 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006521 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6522 SUB_RETRY_RECV,
6523 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006524#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006525 /* Async mode can be re-enabled, because we're leaving data state.*/
6526 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006527 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006528#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006529 break;
6530 }
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006531 else if (ret == SSL_ERROR_SSL || ret == SSL_ERROR_SYSCALL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006532 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6533
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02006534 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006535 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006536 conn->err_code = CO_ERR_SSL_FATAL;
6537 }
Emeric Brun46591952012-05-18 15:47:34 +02006538 goto out_error;
6539 }
6540 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006541 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006542 return done;
6543
6544 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006545 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006546 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006547 ERR_clear_error();
6548
Emeric Brun46591952012-05-18 15:47:34 +02006549 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006550 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006551}
6552
Willy Tarreau832e2422021-05-13 10:11:03 +02006553void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006554
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006555 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006556
Olivier Houchardea8dd942019-05-20 14:02:16 +02006557
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006558 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006559 if (ctx->wait_event.events != 0)
6560 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6561 ctx->wait_event.events,
6562 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006563 if (ctx->subs) {
6564 ctx->subs->events = 0;
6565 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006566 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006567
Olivier Houchard692c1d02019-05-23 18:41:47 +02006568 if (ctx->xprt->close)
6569 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006570#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006571 if (global_ssl.async) {
6572 OSSL_ASYNC_FD all_fd[32], afd;
6573 size_t num_all_fds = 0;
6574 int i;
6575
Olivier Houchard66ab4982019-02-26 18:37:15 +01006576 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006577 if (num_all_fds > 32) {
6578 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6579 return;
6580 }
6581
Olivier Houchard66ab4982019-02-26 18:37:15 +01006582 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006583
6584 /* If an async job is pending, we must try to
6585 to catch the end using polling before calling
6586 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006587 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006588 for (i=0 ; i < num_all_fds ; i++) {
6589 /* switch on an handler designed to
6590 * handle the SSL_free
6591 */
6592 afd = all_fd[i];
6593 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006594 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006595 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006596 /* To ensure that the fd cache won't be used
6597 * and we'll catch a real RD event.
6598 */
6599 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006600 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006601 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006602 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006603 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006604 return;
6605 }
Emeric Brun3854e012017-05-17 20:42:48 +02006606 /* Else we can remove the fds from the fdtab
6607 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006608 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006609 * because the fd is owned by the engine.
6610 * the engine is responsible to close
6611 */
Emeric Brun7d392a52022-07-01 17:36:50 +02006612 for (i=0 ; i < num_all_fds ; i++) {
6613 /* We want to remove the fd from the fdtab
6614 * but we flag it to disown because the
6615 * close is performed by the engine itself
6616 */
6617 fdtab[all_fd[i]].state |= FD_DISOWN;
6618 fd_delete(all_fd[i]);
6619 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006620 }
6621#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006622 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006623 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006624 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006625 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau82531f62021-10-06 12:15:18 +02006626 _HA_ATOMIC_DEC(&global.sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006627 }
Emeric Brun46591952012-05-18 15:47:34 +02006628}
6629
6630/* This function tries to perform a clean shutdown on an SSL connection, and in
6631 * any case, flags the connection as reusable if no handshake was in progress.
6632 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006633static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006634{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006635 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006636
Willy Tarreau911db9b2020-01-23 16:27:54 +01006637 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006638 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006639 if (!clean)
6640 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006641 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006642 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006643 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006644 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006645 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006646 ERR_clear_error();
6647 }
Emeric Brun46591952012-05-18 15:47:34 +02006648}
6649
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006650
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006651/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006652int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6653{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006654 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemandd4f946c2019-12-05 10:26:40 +01006655 X509 *crt;
6656
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006657 if (!ctx)
William Lallemandd4f946c2019-12-05 10:26:40 +01006658 return 0;
William Lallemandd4f946c2019-12-05 10:26:40 +01006659 crt = SSL_get_certificate(ctx->ssl);
6660 if (!crt)
6661 return 0;
6662
6663 return cert_get_pkey_algo(crt, out);
6664}
6665
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006666/* used for ppv2 cert signature (can be used for logging) */
6667const char *ssl_sock_get_cert_sig(struct connection *conn)
6668{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006669 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006670
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006671 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6672 X509 *crt;
6673
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006674 if (!ctx)
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006675 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006676 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006677 if (!crt)
6678 return NULL;
6679 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6680 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6681}
6682
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006683/* used for ppv2 authority */
6684const char *ssl_sock_get_sni(struct connection *conn)
6685{
6686#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006687 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006688
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006689 if (!ctx)
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006690 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006691 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006692#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006693 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006694#endif
6695}
6696
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006697/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006698const char *ssl_sock_get_cipher_name(struct connection *conn)
6699{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006700 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006701
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006702 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006703 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006704 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006705}
6706
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006707/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006708const char *ssl_sock_get_proto_version(struct connection *conn)
6709{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006710 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006711
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006712 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006713 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006714 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006715}
6716
Olivier Houchardab28a322018-12-21 19:45:40 +01006717void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6718{
6719#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006720 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006721
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006722 if (!ctx)
Olivier Houcharde488ea82019-06-28 14:10:33 +02006723 return;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006724 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006725#endif
6726}
6727
Willy Tarreau119a4082016-12-22 21:58:38 +01006728/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6729 * to disable SNI.
6730 */
Willy Tarreau63076412015-07-10 11:33:32 +02006731void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6732{
6733#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006734 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemande18d4e82021-11-17 02:59:21 +01006735 struct server *s;
Willy Tarreau119a4082016-12-22 21:58:38 +01006736 char *prev_name;
6737
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006738 if (!ctx)
Willy Tarreau63076412015-07-10 11:33:32 +02006739 return;
Willy Tarreau77bfa662021-12-23 11:12:13 +01006740
6741 BUG_ON(!(conn->flags & CO_FL_WAIT_L6_CONN));
6742 BUG_ON(!(conn->flags & CO_FL_SSL_WAIT_HS));
6743
William Lallemande18d4e82021-11-17 02:59:21 +01006744 s = __objt_server(conn->target);
Willy Tarreau63076412015-07-10 11:33:32 +02006745
Willy Tarreau119a4082016-12-22 21:58:38 +01006746 /* if the SNI changes, we must destroy the reusable context so that a
William Lallemande18d4e82021-11-17 02:59:21 +01006747 * new connection will present a new SNI. compare with the SNI
6748 * previously stored in the reused_sess */
6749 /* the RWLOCK is used to ensure that we are not trying to flush the
6750 * cache from the CLI */
6751
6752 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
6753 prev_name = s->ssl_ctx.reused_sess[tid].sni;
Willy Tarreau119a4082016-12-22 21:58:38 +01006754 if ((!prev_name && hostname) ||
6755 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006756 SSL_set_session(ctx->ssl, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01006757 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau119a4082016-12-22 21:58:38 +01006758
Olivier Houchard66ab4982019-02-26 18:37:15 +01006759 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006760#endif
6761}
6762
Emeric Brun0abf8362014-06-24 18:26:41 +02006763/* Extract peer certificate's common name into the chunk dest
6764 * Returns
6765 * the len of the extracted common name
6766 * or 0 if no CN found in DN
6767 * or -1 on error case (i.e. no peer certificate)
6768 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006769int ssl_sock_get_remote_common_name(struct connection *conn,
6770 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006771{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006772 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
David Safb76832014-05-08 23:42:08 -04006773 X509 *crt = NULL;
6774 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006775 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006776 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006777 .area = (char *)&find_cn,
6778 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006779 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006780 int result = -1;
David Safb76832014-05-08 23:42:08 -04006781
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006782 if (!ctx)
Emeric Brun0abf8362014-06-24 18:26:41 +02006783 goto out;
David Safb76832014-05-08 23:42:08 -04006784
6785 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006786 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006787 if (!crt)
6788 goto out;
6789
6790 name = X509_get_subject_name(crt);
6791 if (!name)
6792 goto out;
David Safb76832014-05-08 23:42:08 -04006793
Emeric Brun0abf8362014-06-24 18:26:41 +02006794 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6795out:
David Safb76832014-05-08 23:42:08 -04006796 if (crt)
6797 X509_free(crt);
6798
6799 return result;
6800}
6801
Dave McCowan328fb582014-07-30 10:39:13 -04006802/* returns 1 if client passed a certificate for this session, 0 if not */
6803int ssl_sock_get_cert_used_sess(struct connection *conn)
6804{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006805 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dave McCowan328fb582014-07-30 10:39:13 -04006806 X509 *crt = NULL;
6807
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006808 if (!ctx)
Dave McCowan328fb582014-07-30 10:39:13 -04006809 return 0;
6810
6811 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006812 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006813 if (!crt)
6814 return 0;
6815
6816 X509_free(crt);
6817 return 1;
6818}
6819
6820/* returns 1 if client passed a certificate for this connection, 0 if not */
6821int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006822{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006823 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006824
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006825 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006826 return 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006827 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006828}
6829
6830/* returns result from SSL verify */
6831unsigned int ssl_sock_get_verify_result(struct connection *conn)
6832{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006833 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006834
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006835 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006836 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006837 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006838}
6839
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006840/* Returns the application layer protocol name in <str> and <len> when known.
6841 * Zero is returned if the protocol name was not found, otherwise non-zero is
6842 * returned. The string is allocated in the SSL context and doesn't have to be
6843 * freed by the caller. NPN is also checked if available since older versions
6844 * of openssl (1.0.1) which are more common in field only support this one.
6845 */
Amaury Denoyelle71e588c2021-11-12 11:23:29 +01006846int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006847{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006848#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6849 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006850 struct ssl_sock_ctx *ctx = xprt_ctx;
6851 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006852 return 0;
6853
6854 *str = NULL;
6855
6856#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006857 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006858 if (*str)
6859 return 1;
6860#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006861#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006862 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006863 if (*str)
6864 return 1;
6865#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006866#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006867 return 0;
6868}
6869
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006870/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006871int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006872{
6873 X509 *ca;
6874 X509_NAME *name = NULL;
6875 ASN1_OCTET_STRING *skid = NULL;
6876 STACK_OF(X509) *chain = NULL;
6877 struct issuer_chain *issuer;
6878 struct eb64_node *node;
6879 char *path;
6880 u64 key;
6881 int ret = 0;
6882
6883 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6884 if (chain == NULL) {
6885 chain = sk_X509_new_null();
6886 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6887 name = X509_get_subject_name(ca);
6888 }
6889 if (!sk_X509_push(chain, ca)) {
6890 X509_free(ca);
6891 goto end;
6892 }
6893 }
6894 if (!chain) {
6895 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6896 goto end;
6897 }
6898 if (!skid) {
6899 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6900 goto end;
6901 }
6902 if (!name) {
6903 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6904 goto end;
6905 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01006906 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006907 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006908 issuer = container_of(node, typeof(*issuer), node);
6909 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6910 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6911 goto end;
6912 }
6913 }
6914 issuer = calloc(1, sizeof *issuer);
6915 path = strdup(fp);
6916 if (!issuer || !path) {
6917 free(issuer);
6918 free(path);
6919 goto end;
6920 }
6921 issuer->node.key = key;
6922 issuer->path = path;
6923 issuer->chain = chain;
6924 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006925 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006926 ret = 1;
6927 end:
6928 if (skid)
6929 ASN1_OCTET_STRING_free(skid);
6930 if (chain)
6931 sk_X509_pop_free(chain, X509_free);
6932 return ret;
6933}
6934
William Lallemandda8584c2020-05-14 10:14:37 +02006935 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006936{
6937 AUTHORITY_KEYID *akid;
6938 struct issuer_chain *issuer = NULL;
6939
6940 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01006941 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006942 struct eb64_node *node;
6943 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01006944 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006945 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6946 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6947 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6948 issuer = ti;
6949 break;
6950 }
6951 }
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006952 }
Remi Tricot-Le Breton1621dc12022-11-03 15:16:48 +01006953 AUTHORITY_KEYID_free(akid);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006954 return issuer;
6955}
6956
William Lallemanddad31052020-05-14 17:47:32 +02006957void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006958{
6959 struct eb64_node *node, *back;
6960 struct issuer_chain *issuer;
6961
William Lallemande0f3fd52020-02-25 14:53:06 +01006962 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006963 while (node) {
6964 issuer = container_of(node, typeof(*issuer), node);
6965 back = eb64_next(node);
6966 eb64_delete(node);
6967 free(issuer->path);
6968 sk_X509_pop_free(issuer->chain, X509_free);
6969 free(issuer);
6970 node = back;
6971 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006972}
6973
William Lallemandd7bfbe22022-04-11 18:41:24 +02006974#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006975static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01006976 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006977
Emeric Brun3854e012017-05-17 20:42:48 +02006978 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006979 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006980 err_code = ERR_ABORT;
6981 }
6982 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006983}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006984#endif
6985
Willy Tarreaude5675a2021-01-20 14:41:29 +01006986/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006987 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01006988 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01006989static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01006990{
6991 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006992 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006993
6994 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006995 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006996
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006997 if (sctx->conn != conn) {
6998 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
6999 ret = 1;
7000 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01007001 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
7002
7003 if (sctx->xprt) {
7004 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
7005 if (sctx->xprt_ctx)
7006 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
7007 }
7008
7009 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007010
7011 /* as soon as a shutdown is reported the lower layer unregisters its
7012 * subscriber, so the situations below are transient and rare enough to
7013 * be reported as suspicious. In any case they shouldn't last.
7014 */
7015 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
7016 ret = 1;
7017 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
7018 ret = 1;
7019
Willy Tarreaude5675a2021-01-20 14:41:29 +01007020 chunk_appendf(&trash, " .subs=%p", sctx->subs);
7021 if (sctx->subs) {
7022 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007023 if (sctx->subs->tasklet->calls >= 1000000)
7024 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007025 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
7026 sctx->subs->tasklet->calls,
7027 sctx->subs->tasklet->context);
7028 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
7029 chunk_appendf(&trash, ")");
7030 }
7031 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
7032 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007033 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007034}
7035
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007036#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02007037/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007038 * each reference. The variable <ref> must point to the current node's list
7039 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02007040 */
William Lallemand32af2032016-10-29 18:09:35 +02007041static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007042struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02007043{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007044 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007045 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02007046
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007047 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007048 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007049 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02007050
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007051 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02007052}
7053
7054static inline
7055struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
7056{
7057 int id;
7058 char *error;
7059
7060 /* If the reference starts by a '#', this is numeric id. */
7061 if (reference[0] == '#') {
7062 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
7063 id = strtol(reference + 1, &error, 10);
7064 if (*error != '\0')
7065 return NULL;
7066
7067 /* Perform the unique id lookup. */
7068 return tlskeys_ref_lookupid(id);
7069 }
7070
7071 /* Perform the string lookup. */
7072 return tlskeys_ref_lookup(reference);
7073}
7074#endif
7075
7076
7077#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7078
Willy Tarreaua9380522022-05-05 08:50:17 +02007079/* dumps all tls keys. Relies on the show_keys_ctx context from the appctx. */
Willy Tarreaubd338642022-05-05 08:59:17 +02007080static int cli_io_handler_tlskeys_files(struct appctx *appctx)
7081{
Willy Tarreaua9380522022-05-05 08:50:17 +02007082 struct show_keys_ctx *ctx = appctx->svcctx;
William Lallemand32af2032016-10-29 18:09:35 +02007083
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007084 switch (ctx->state) {
7085 case SHOW_KEYS_INIT:
William Lallemand32af2032016-10-29 18:09:35 +02007086 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08007087 * quit the function with returning 0. The function is called
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007088 * later and restart at the state "SHOW_KEYS_INIT".
William Lallemand32af2032016-10-29 18:09:35 +02007089 */
7090 chunk_reset(&trash);
7091
Willy Tarreaubd338642022-05-05 08:59:17 +02007092 if (ctx->dump_entries)
William Lallemand32af2032016-10-29 18:09:35 +02007093 chunk_appendf(&trash, "# id secret\n");
7094 else
7095 chunk_appendf(&trash, "# id (file)\n");
7096
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007097 if (applet_putchk(appctx, &trash) == -1)
William Lallemand32af2032016-10-29 18:09:35 +02007098 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007099
William Lallemand32af2032016-10-29 18:09:35 +02007100 /* Now, we start the browsing of the references lists.
7101 * Note that the following call to LIST_ELEM return bad pointer. The only
7102 * available field of this pointer is <list>. It is used with the function
7103 * tlskeys_list_get_next() for retruning the first available entry
7104 */
Willy Tarreaua9380522022-05-05 08:50:17 +02007105 if (ctx->next_ref == NULL)
7106 ctx->next_ref = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007107
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007108 ctx->state = SHOW_KEYS_LIST;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007109 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007110
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007111 case SHOW_KEYS_LIST:
Willy Tarreaua9380522022-05-05 08:50:17 +02007112 while (ctx->next_ref) {
7113 struct tls_keys_ref *ref = ctx->next_ref;
William Lallemand32af2032016-10-29 18:09:35 +02007114
7115 chunk_reset(&trash);
Willy Tarreaubd338642022-05-05 08:59:17 +02007116 if (ctx->dump_entries && ctx->next_index == 0)
William Lallemand32af2032016-10-29 18:09:35 +02007117 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007118
Willy Tarreaua9380522022-05-05 08:50:17 +02007119 if (ctx->next_index == 0)
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007120 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
7121
Willy Tarreaubd338642022-05-05 08:59:17 +02007122 if (ctx->dump_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01007123 int head;
7124
7125 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
7126 head = ref->tls_ticket_enc_index;
Willy Tarreaua9380522022-05-05 08:50:17 +02007127 while (ctx->next_index < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02007128 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02007129
7130 chunk_reset(t2);
7131 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01007132 if (ref->key_size_bits == 128) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007133 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007134 sizeof(struct tls_sess_key_128),
7135 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007136 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007137 t2->area);
7138 }
7139 else if (ref->key_size_bits == 256) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007140 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007141 sizeof(struct tls_sess_key_256),
7142 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007143 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007144 t2->area);
7145 }
7146 else {
7147 /* This case should never happen */
Willy Tarreaua9380522022-05-05 08:50:17 +02007148 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, ctx->next_index);
Emeric Brun9e754772019-01-10 17:51:55 +01007149 }
William Lallemand32af2032016-10-29 18:09:35 +02007150
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007151 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007152 /* let's try again later from this stream. We add ourselves into
7153 * this stream's users so that it can remove us upon termination.
7154 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01007155 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
William Lallemand32af2032016-10-29 18:09:35 +02007156 return 0;
7157 }
Willy Tarreaua9380522022-05-05 08:50:17 +02007158 ctx->next_index++;
William Lallemand32af2032016-10-29 18:09:35 +02007159 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01007160 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaua9380522022-05-05 08:50:17 +02007161 ctx->next_index = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007162 }
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007163 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007164 /* let's try again later from this stream. We add ourselves into
7165 * this stream's users so that it can remove us upon termination.
7166 */
William Lallemand32af2032016-10-29 18:09:35 +02007167 return 0;
7168 }
7169
Willy Tarreaua9380522022-05-05 08:50:17 +02007170 if (ctx->names_only == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02007171 break;
7172
7173 /* get next list entry and check the end of the list */
Willy Tarreaua9380522022-05-05 08:50:17 +02007174 ctx->next_ref = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007175 }
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007176 ctx->state = SHOW_KEYS_DONE;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007177 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007178
7179 default:
William Lallemand32af2032016-10-29 18:09:35 +02007180 return 1;
7181 }
7182 return 0;
7183}
7184
Willy Tarreaua9380522022-05-05 08:50:17 +02007185/* Prepares a "show_keys_ctx" and sets the appropriate io_handler if needed */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007186static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007187{
Willy Tarreaua9380522022-05-05 08:50:17 +02007188 struct show_keys_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
7189
William Lallemand32af2032016-10-29 18:09:35 +02007190 /* no parameter, shows only file list */
7191 if (!*args[2]) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007192 ctx->names_only = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007193 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007194 }
7195
7196 if (args[2][0] == '*') {
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007197 /* list every TLS ticket keys */
7198 ctx->names_only = 1;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007199 } else {
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007200 ctx->next_ref = tlskeys_ref_lookup_ref(args[2]);
7201 if (!ctx->next_ref)
7202 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007203 }
7204
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007205 ctx->dump_entries = 1;
7206 return 0;
7207}
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007208
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007209static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
7210{
7211 struct tls_keys_ref *ref;
7212 int ret;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007213
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007214 /* Expect two parameters: the filename and the new new TLS key in encoding */
7215 if (!*args[3] || !*args[4])
7216 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 +02007217
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007218 ref = tlskeys_ref_lookup_ref(args[3]);
7219 if (!ref)
7220 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007221
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007222 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
7223 if (ret < 0)
7224 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007225
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007226 trash.data = ret;
7227 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
7228 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007229
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007230 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007231}
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007232#endif
7233
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007234
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007235#ifdef HAVE_SSL_PROVIDERS
7236struct provider_name {
7237 const char *name;
7238 struct list list;
7239};
7240
7241
7242static int ssl_provider_get_name_cb(OSSL_PROVIDER *provider, void *cbdata)
7243{
7244 struct list *provider_names = cbdata;
7245 struct provider_name *item = NULL;
7246 const char *name = OSSL_PROVIDER_get0_name(provider);
7247
7248 if (!provider_names)
7249 return 0;
7250
7251 item = calloc(1, sizeof(*item));
7252
7253 if (!item)
7254 return 0;
7255
7256 item->name = name;
7257 LIST_APPEND(provider_names, &item->list);
7258
7259 return 1;
7260}
7261
7262static void ssl_provider_get_name_list(struct list *provider_names)
7263{
7264 if (!provider_names)
7265 return;
7266
7267 OSSL_PROVIDER_do_all(NULL, ssl_provider_get_name_cb, provider_names);
7268}
7269
7270static void ssl_provider_clear_name_list(struct list *provider_names)
7271{
7272 struct provider_name *item = NULL, *item_s = NULL;
7273
7274 if (provider_names) {
7275 list_for_each_entry_safe(item, item_s, provider_names, list) {
7276 LIST_DELETE(&item->list);
7277 free(item);
7278 }
7279 }
7280}
7281
7282static int cli_io_handler_show_providers(struct appctx *appctx)
7283{
7284 struct buffer *trash = get_trash_chunk();
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007285 struct list provider_names;
7286 struct provider_name *name;
7287
7288 LIST_INIT(&provider_names);
7289
7290 chunk_appendf(trash, "Loaded providers : \n");
7291
7292 ssl_provider_get_name_list(&provider_names);
7293
7294 list_for_each_entry(name, &provider_names, list) {
7295 chunk_appendf(trash, "\t- %s\n", name->name);
7296 }
7297
7298 ssl_provider_clear_name_list(&provider_names);
7299
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007300 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007301 goto yield;
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007302
7303 return 1;
7304
7305yield:
7306 return 0;
7307}
7308#endif
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01007309
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007310
William Lallemand32af2032016-10-29 18:09:35 +02007311/* register cli keywords */
7312static struct cli_kw_list cli_kws = {{ },{
7313#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01007314 { { "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 },
7315 { { "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 +02007316#endif
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007317#ifdef HAVE_SSL_PROVIDERS
7318 { { "show", "ssl", "providers", NULL }, "show ssl providers : show loaded SSL providers", NULL, cli_io_handler_show_providers },
7319#endif
William Lallemand32af2032016-10-29 18:09:35 +02007320 { { NULL }, NULL, NULL, NULL }
7321}};
7322
Willy Tarreau0108d902018-11-25 19:14:37 +01007323INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02007324
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02007325/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02007326struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02007327 .snd_buf = ssl_sock_from_buf,
7328 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01007329 .subscribe = ssl_subscribe,
7330 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02007331 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02007332 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02007333 .rcv_pipe = NULL,
7334 .snd_pipe = NULL,
7335 .shutr = NULL,
7336 .shutw = ssl_sock_shutw,
7337 .close = ssl_sock_close,
7338 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01007339 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01007340 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01007341 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01007342 .prepare_srv = ssl_sock_prepare_srv_ctx,
7343 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007344 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02007345 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01007346 .set_idle = ssl_set_idle,
7347 .set_used = ssl_set_used,
Willy Tarreaude827952022-04-11 10:43:28 +02007348 .get_ssl_sock_ctx = ssl_sock_get_ctx,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01007349 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01007350 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02007351};
7352
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007353enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
7354 struct session *sess, struct stream *s, int flags)
7355{
7356 struct connection *conn;
7357
7358 conn = objt_conn(sess->origin);
7359
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007360 if (conn) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007361 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007362 sc_ep_set(s->scf, SE_FL_WAIT_FOR_HS);
Christopher Faulet6e1bbc42022-12-12 08:08:15 +01007363 s->req.flags |= CF_READ_EVENT;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007364 return ACT_RET_YIELD;
7365 }
7366 }
7367 return (ACT_RET_CONT);
7368}
7369
7370static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
7371{
7372 rule->action_ptr = ssl_action_wait_for_hs;
7373
7374 return ACT_RET_PRS_OK;
7375}
7376
7377static struct action_kw_list http_req_actions = {ILH, {
7378 { "wait-for-handshake", ssl_parse_wait_for_hs },
7379 { /* END */ }
7380}};
7381
Willy Tarreau0108d902018-11-25 19:14:37 +01007382INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
7383
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007384#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007385
7386static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7387{
7388 if (ptr) {
7389 chunk_destroy(ptr);
7390 free(ptr);
7391 }
7392}
7393
7394#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007395
William Lallemand76b4a122020-08-04 17:41:39 +02007396
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007397static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7398{
Willy Tarreaubafbe012017-11-24 17:34:44 +01007399 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007400}
William Lallemand7d42ef52020-07-06 11:41:30 +02007401
William Lallemand722180a2021-06-09 16:46:12 +02007402#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007403static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7404{
7405 struct ssl_keylog *keylog;
7406
7407 if (!ptr)
7408 return;
7409
7410 keylog = ptr;
7411
7412 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7413 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7414 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7415 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7416 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7417 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7418 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7419 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7420
7421 pool_free(pool_head_ssl_keylog, ptr);
7422}
7423#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007424
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007425static void ssl_sock_clt_crt_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7426{
7427 if (!ptr)
7428 return;
7429
7430 X509_free((X509*)ptr);
7431}
7432
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01007433static void ssl_sock_clt_sni_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7434{
7435 pool_free(ssl_sock_client_sni_pool, ptr);
7436}
7437
Willy Tarreau92faadf2012-10-10 23:04:25 +02007438static void __ssl_sock_init(void)
7439{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007440#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007441 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007442 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007443#endif
Emeric Brun46591952012-05-18 15:47:34 +02007444
Willy Tarreauef934602016-12-22 23:12:01 +01007445 if (global_ssl.listen_default_ciphers)
7446 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7447 if (global_ssl.connect_default_ciphers)
7448 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007449#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007450 if (global_ssl.listen_default_ciphersuites)
7451 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7452 if (global_ssl.connect_default_ciphersuites)
7453 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7454#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007455
Willy Tarreau13e14102016-12-22 20:25:26 +01007456 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007457#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007458 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007459#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007460#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007461 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007462 n = sk_SSL_COMP_num(cm);
7463 while (n--) {
7464 (void) sk_SSL_COMP_pop(cm);
7465 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007466#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007467
Willy Tarreau5db847a2019-05-09 14:13:35 +02007468#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007469 ssl_locking_init();
7470#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007471#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007472 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
7473#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007474
7475#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7476 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
7477#endif
7478
Thierry FOURNIER28962c92018-06-17 21:37:05 +02007479 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02007480 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 +01007481#ifdef USE_QUIC
7482 ssl_qc_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7483#endif /* USE_QUIC */
William Lallemand722180a2021-06-09 16:46:12 +02007484#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007485 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
7486#endif
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007487 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 +01007488 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 +02007489#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00007490 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007491 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007492#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01007493#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7494 hap_register_post_check(tlskeys_finalize_config);
7495#endif
Willy Tarreau80713382018-11-26 10:19:54 +01007496
7497 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
7498 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
7499
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007500 hap_register_post_deinit(ssl_free_global_issuers);
7501
Willy Tarreau80713382018-11-26 10:19:54 +01007502#ifndef OPENSSL_NO_DH
7503 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7504 hap_register_post_deinit(ssl_free_dh);
7505#endif
William Lallemandd7bfbe22022-04-11 18:41:24 +02007506#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Willy Tarreau80713382018-11-26 10:19:54 +01007507 hap_register_post_deinit(ssl_free_engines);
7508#endif
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02007509#ifdef HAVE_SSL_PROVIDERS
7510 hap_register_post_deinit(ssl_unload_providers);
7511#endif
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01007512#if HA_OPENSSL_VERSION_NUMBER < 0x3000000fL
Willy Tarreau80713382018-11-26 10:19:54 +01007513 /* Load SSL string for the verbose & debug mode. */
7514 ERR_load_SSL_strings();
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01007515#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007516 ha_meth = BIO_meth_new(0x666, "ha methods");
7517 BIO_meth_set_write(ha_meth, ha_ssl_write);
7518 BIO_meth_set_read(ha_meth, ha_ssl_read);
7519 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
7520 BIO_meth_set_create(ha_meth, ha_ssl_new);
7521 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
7522 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
7523 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02007524
7525 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007526
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01007527 HA_SPIN_INIT(&ocsp_tree_lock);
7528
Dragan Dosen9ac98092020-05-11 15:51:45 +02007529 /* Try to register dedicated SSL/TLS protocol message callbacks for
7530 * heartbleed attack (CVE-2014-0160) and clienthello.
7531 */
7532 hap_register_post_check(ssl_sock_register_msg_callbacks);
7533
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007534 /* Try to free all callbacks that were registered by using
7535 * ssl_sock_register_msg_callback().
7536 */
7537 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01007538}
Willy Tarreau79367f92022-04-25 19:18:24 +02007539INITCALL0(STG_REGISTER, __ssl_sock_init);
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01007540
Willy Tarreau80713382018-11-26 10:19:54 +01007541/* Compute and register the version string */
7542static void ssl_register_build_options()
7543{
7544 char *ptr = NULL;
7545 int i;
7546
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007547 memprintf(&ptr, "Built with OpenSSL version : "
7548#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007549 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007550#else /* OPENSSL_IS_BORINGSSL */
7551 OPENSSL_VERSION_TEXT
7552 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08007553 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02007554 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007555#endif
7556 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007557#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007558 "no (library version too old)"
7559#elif defined(OPENSSL_NO_TLSEXT)
7560 "no (disabled via OPENSSL_NO_TLSEXT)"
7561#else
7562 "yes"
7563#endif
7564 "", ptr);
7565
7566 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
7567#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
7568 "yes"
7569#else
7570#ifdef OPENSSL_NO_TLSEXT
7571 "no (because of OPENSSL_NO_TLSEXT)"
7572#else
7573 "no (version might be too old, 0.9.8f min needed)"
7574#endif
7575#endif
7576 "", ptr);
7577
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02007578 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
7579 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
7580 if (methodVersions[i].option)
7581 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007582
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007583#ifdef HAVE_SSL_PROVIDERS
7584 {
7585 struct list provider_names;
7586 struct provider_name *name;
7587 LIST_INIT(&provider_names);
7588 ssl_provider_get_name_list(&provider_names);
7589
7590 memprintf(&ptr, "%s\nOpenSSL providers loaded :", ptr);
7591
7592 list_for_each_entry(name, &provider_names, list) {
7593 memprintf(&ptr, "%s %s", ptr, name->name);
7594 }
7595
7596 ssl_provider_clear_name_list(&provider_names);
7597 }
7598#endif
7599
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007600 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01007601}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007602
Willy Tarreau80713382018-11-26 10:19:54 +01007603INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02007604
William Lallemandd7bfbe22022-04-11 18:41:24 +02007605#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00007606void ssl_free_engines(void) {
7607 struct ssl_engine_list *wl, *wlb;
7608 /* free up engine list */
7609 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
7610 ENGINE_finish(wl->e);
7611 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02007612 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00007613 free(wl);
7614 }
7615}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007616#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02007617
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02007618#ifdef HAVE_SSL_PROVIDERS
7619void ssl_unload_providers(void) {
7620 struct ssl_provider_list *prov, *provb;
7621 list_for_each_entry_safe(prov, provb, &openssl_providers, list) {
7622 OSSL_PROVIDER_unload(prov->provider);
7623 LIST_DELETE(&prov->list);
7624 free(prov);
7625 }
7626}
7627#endif
7628
Remi Gacogned3a23c32015-05-28 16:39:47 +02007629#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00007630void ssl_free_dh(void) {
7631 if (local_dh_1024) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007632 HASSL_DH_free(local_dh_1024);
Grant Zhang872f9c22017-01-21 01:10:18 +00007633 local_dh_1024 = NULL;
7634 }
7635 if (local_dh_2048) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007636 HASSL_DH_free(local_dh_2048);
Grant Zhang872f9c22017-01-21 01:10:18 +00007637 local_dh_2048 = NULL;
7638 }
7639 if (local_dh_4096) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007640 HASSL_DH_free(local_dh_4096);
Grant Zhang872f9c22017-01-21 01:10:18 +00007641 local_dh_4096 = NULL;
7642 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02007643 if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007644 HASSL_DH_free(global_dh);
Remi Gacogne47783ef2015-05-29 15:53:22 +02007645 global_dh = NULL;
7646 }
Grant Zhang872f9c22017-01-21 01:10:18 +00007647}
7648#endif
7649
Grant Zhang872f9c22017-01-21 01:10:18 +00007650static void __ssl_sock_deinit(void)
7651{
7652#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007653 if (ssl_ctx_lru_tree) {
7654 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007655 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02007656 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02007657#endif
7658
Willy Tarreau5db847a2019-05-09 14:13:35 +02007659#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007660 ERR_remove_state(0);
7661 ERR_free_strings();
7662
7663 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08007664#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007665
Willy Tarreau5db847a2019-05-09 14:13:35 +02007666#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007667 CRYPTO_cleanup_all_ex_data();
7668#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007669 BIO_meth_free(ha_meth);
Remi Tricot-Le Breton6477bbd2022-12-20 11:11:13 +01007670
7671#if !defined OPENSSL_NO_OCSP
7672 ssl_destroy_ocsp_update_task();
7673#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007674}
Willy Tarreau79367f92022-04-25 19:18:24 +02007675REGISTER_POST_DEINIT(__ssl_sock_deinit);
Remi Gacogned3a23c32015-05-28 16:39:47 +02007676
William Dauchyf6370442020-11-14 19:25:33 +01007677
Emeric Brun46591952012-05-18 15:47:34 +02007678/*
7679 * Local variables:
7680 * c-indent-level: 8
7681 * c-basic-offset: 8
7682 * End:
7683 */