blob: 0fea7dd09932fa973b5c45fac957717a1fd224ae [file] [log] [blame]
yanbzhu08ce6ab2015-12-02 13:01:29 -05001
Emeric Brun46591952012-05-18 15:47:34 +02002/*
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02003 * SSL/TLS transport layer over SOCK_STREAM sockets
Emeric Brun46591952012-05-18 15:47:34 +02004 *
5 * Copyright (C) 2012 EXCELIANCE, Emeric Brun <ebrun@exceliance.fr>
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version
10 * 2 of the License, or (at your option) any later version.
11 *
Willy Tarreau69845df2012-09-10 09:43:09 +020012 * Acknowledgement:
13 * We'd like to specially thank the Stud project authors for a very clean
14 * and well documented code which helped us understand how the OpenSSL API
15 * ought to be used in non-blocking mode. This is one difficult part which
16 * is not easy to get from the OpenSSL doc, and reading the Stud code made
17 * it much more obvious than the examples in the OpenSSL package. Keep up
18 * the good works, guys !
19 *
20 * Stud is an extremely efficient and scalable SSL/TLS proxy which combines
21 * particularly well with haproxy. For more info about this project, visit :
22 * https://github.com/bumptech/stud
23 *
Emeric Brun46591952012-05-18 15:47:34 +020024 */
25
Willy Tarreau8d164dc2019-05-10 09:35:00 +020026/* Note: do NOT include openssl/xxx.h here, do it in openssl-compat.h */
Emeric Brun46591952012-05-18 15:47:34 +020027#define _GNU_SOURCE
Emeric Brunfc0421f2012-09-07 17:30:07 +020028#include <ctype.h>
29#include <dirent.h>
Emeric Brun46591952012-05-18 15:47:34 +020030#include <errno.h>
Emeric Brun46591952012-05-18 15:47:34 +020031#include <stdio.h>
32#include <stdlib.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020033#include <string.h>
34#include <unistd.h>
Emeric Brun46591952012-05-18 15:47:34 +020035
36#include <sys/socket.h>
37#include <sys/stat.h>
38#include <sys/types.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020039#include <netdb.h>
Emeric Brun46591952012-05-18 15:47:34 +020040#include <netinet/tcp.h>
41
Willy Tarreaub2551052020-06-09 09:07:15 +020042#include <import/ebpttree.h>
43#include <import/ebsttree.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020044#include <import/lru.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020045
Willy Tarreaub2551052020-06-09 09:07:15 +020046#include <haproxy/api.h>
Willy Tarreaua9380522022-05-05 08:50:17 +020047#include <haproxy/applet.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020048#include <haproxy/arg.h>
49#include <haproxy/base64.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020050#include <haproxy/channel.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020051#include <haproxy/chunk.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020052#include <haproxy/cli.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020053#include <haproxy/connection.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020054#include <haproxy/dynbuf.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020055#include <haproxy/errors.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020056#include <haproxy/fd.h>
57#include <haproxy/freq_ctr.h>
Willy Tarreau762d7a52020-06-04 11:23:07 +020058#include <haproxy/frontend.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020059#include <haproxy/global.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020060#include <haproxy/http_rules.h>
Willy Tarreauaeed4a82020-06-04 22:01:04 +020061#include <haproxy/log.h>
Willy Tarreau6019fab2020-05-27 16:26:00 +020062#include <haproxy/openssl-compat.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020063#include <haproxy/pattern-t.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020064#include <haproxy/proto_tcp.h>
Willy Tarreaua264d962020-06-04 22:29:18 +020065#include <haproxy/proxy.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020066#include <haproxy/sample.h>
67#include <haproxy/sc_strm.h>
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020068#include <haproxy/quic_conn.h>
Frédéric Lécaille748ece62022-05-21 23:58:40 +020069#include <haproxy/quic_tp.h>
Willy Tarreau1e56f922020-06-04 23:20:13 +020070#include <haproxy/server.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020071#include <haproxy/shctx.h>
Willy Tarreau47d7f902020-06-04 14:25:47 +020072#include <haproxy/ssl_ckch.h>
Willy Tarreau52d88722020-06-04 14:29:23 +020073#include <haproxy/ssl_crtlist.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020074#include <haproxy/ssl_sock.h>
Willy Tarreaub2bd8652020-06-04 14:21:22 +020075#include <haproxy/ssl_utils.h>
Amaury Denoyelle9963fa72020-11-03 17:10:00 +010076#include <haproxy/stats.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020077#include <haproxy/stconn.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020078#include <haproxy/stream-t.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020079#include <haproxy/task.h>
Willy Tarreauc2f7c582020-06-02 18:15:32 +020080#include <haproxy/ticks.h>
Willy Tarreau92b4f132020-06-01 11:05:15 +020081#include <haproxy/time.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020082#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020083#include <haproxy/vars.h>
Tim Duesterhusd5fc8fc2021-09-11 17:51:13 +020084#include <haproxy/xxhash.h>
Remi Tricot-Le Breton2e7d1eb2022-01-11 10:11:10 +010085#include <haproxy/istbuf.h>
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +010086#include <haproxy/ssl_ocsp.h>
Emeric Brun46591952012-05-18 15:47:34 +020087
Emeric Brun46591952012-05-18 15:47:34 +020088
Willy Tarreau9356dac2019-05-10 09:22:53 +020089/* ***** READ THIS before adding code here! *****
90 *
91 * Due to API incompatibilities between multiple OpenSSL versions and their
92 * derivatives, it's often tempting to add macros to (re-)define certain
93 * symbols. Please do not do this here, and do it in common/openssl-compat.h
94 * exclusively so that the whole code consistently uses the same macros.
95 *
96 * Whenever possible if a macro is missing in certain versions, it's better
97 * to conditionally define it in openssl-compat.h than using lots of ifdefs.
98 */
99
Emeric Brunece0c332017-12-06 13:51:49 +0100100int nb_engines = 0;
Emeric Brune1f38db2012-09-03 20:36:47 +0200101
William Lallemande0f3fd52020-02-25 14:53:06 +0100102static struct eb_root cert_issuer_tree = EB_ROOT; /* issuers tree from "issuers-chain-path" */
103
William Lallemand7fd8b452020-05-07 15:20:43 +0200104struct global_ssl global_ssl = {
Willy Tarreauef934602016-12-22 23:12:01 +0100105#ifdef LISTEN_DEFAULT_CIPHERS
106 .listen_default_ciphers = LISTEN_DEFAULT_CIPHERS,
107#endif
108#ifdef CONNECT_DEFAULT_CIPHERS
109 .connect_default_ciphers = CONNECT_DEFAULT_CIPHERS,
110#endif
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +0500111#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200112 .listen_default_ciphersuites = LISTEN_DEFAULT_CIPHERSUITES,
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200113 .connect_default_ciphersuites = CONNECT_DEFAULT_CIPHERSUITES,
114#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100115 .listen_default_ssloptions = BC_SSL_O_NONE,
116 .connect_default_ssloptions = SRV_SSL_O_NONE,
117
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +0200118 .listen_default_sslmethods.flags = MC_SSL_O_ALL,
119 .listen_default_sslmethods.min = CONF_TLSV_NONE,
120 .listen_default_sslmethods.max = CONF_TLSV_NONE,
121 .connect_default_sslmethods.flags = MC_SSL_O_ALL,
122 .connect_default_sslmethods.min = CONF_TLSV_NONE,
123 .connect_default_sslmethods.max = CONF_TLSV_NONE,
124
Willy Tarreauef934602016-12-22 23:12:01 +0100125#ifdef DEFAULT_SSL_MAX_RECORD
126 .max_record = DEFAULT_SSL_MAX_RECORD,
127#endif
Thomas Prückl10243932022-04-27 13:04:54 +0200128 .hard_max_record = 0,
Willy Tarreauef934602016-12-22 23:12:01 +0100129 .default_dh_param = SSL_DEFAULT_DH_PARAM,
130 .ctx_cache = DEFAULT_SSL_CTX_CACHE,
Marcin Deranek310a2602021-07-13 19:04:24 +0200131 .capture_buffer_size = 0,
William Lallemand3af48e72020-02-03 17:15:52 +0100132 .extra_files = SSL_GF_ALL,
William Lallemand8e8581e2020-10-20 17:36:46 +0200133 .extra_files_noext = 0,
William Lallemand722180a2021-06-09 16:46:12 +0200134#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200135 .keylog = 0
136#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100137};
138
Olivier Houcharda8955d52019-04-07 22:00:38 +0200139static BIO_METHOD *ha_meth;
140
Willy Tarreaub8dec4a2022-06-23 11:02:08 +0200141DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx", sizeof(struct ssl_sock_ctx));
Olivier Houchard66ab4982019-02-26 18:37:15 +0100142
Willy Tarreaub8dec4a2022-06-23 11:02:08 +0200143DECLARE_STATIC_POOL(ssl_sock_client_sni_pool, "ssl_sock_client_sni", TLSEXT_MAXLEN_host_name + 1);
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100144
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100145/* ssl stats module */
146enum {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100147 SSL_ST_SESS,
148 SSL_ST_REUSED_SESS,
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100149 SSL_ST_FAILED_HANDSHAKE,
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100150
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100151 SSL_ST_STATS_COUNT /* must be the last member of the enum */
152};
153
154static struct name_desc ssl_stats[] = {
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100155 [SSL_ST_SESS] = { .name = "ssl_sess",
156 .desc = "Total number of ssl sessions established" },
157 [SSL_ST_REUSED_SESS] = { .name = "ssl_reused_sess",
158 .desc = "Total number of ssl sessions reused" },
159 [SSL_ST_FAILED_HANDSHAKE] = { .name = "ssl_failed_handshake",
160 .desc = "Total number of failed handshake" },
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100161};
162
163static struct ssl_counters {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100164 long long sess;
165 long long reused_sess;
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100166 long long failed_handshake;
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100167} ssl_counters;
168
169static void ssl_fill_stats(void *data, struct field *stats)
170{
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100171 struct ssl_counters *counters = data;
172
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100173 stats[SSL_ST_SESS] = mkf_u64(FN_COUNTER, counters->sess);
174 stats[SSL_ST_REUSED_SESS] = mkf_u64(FN_COUNTER, counters->reused_sess);
175 stats[SSL_ST_FAILED_HANDSHAKE] = mkf_u64(FN_COUNTER, counters->failed_handshake);
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100176}
177
178static struct stats_module ssl_stats_module = {
179 .name = "ssl",
180 .fill_stats = ssl_fill_stats,
181 .stats = ssl_stats,
182 .stats_count = SSL_ST_STATS_COUNT,
183 .counters = &ssl_counters,
184 .counters_size = sizeof(ssl_counters),
185 .domain_flags = MK_STATS_PROXY_DOMAIN(STATS_PX_CAP_FE|STATS_PX_CAP_LI|STATS_PX_CAP_BE|STATS_PX_CAP_SRV),
186 .clearable = 1,
187};
188
189INITCALL1(STG_REGISTER, stats_register_module, &ssl_stats_module);
190
Willy Tarreaua9380522022-05-05 08:50:17 +0200191/* CLI context for "show tls-keys" */
192struct show_keys_ctx {
193 struct tls_keys_ref *next_ref; /* next reference to be dumped */
194 int names_only; /* non-zero = only show file names */
195 int next_index; /* next index to be dumped */
Willy Tarreaubd338642022-05-05 08:59:17 +0200196 int dump_entries; /* dump entries also */
Willy Tarreau9c5a38c2022-05-05 09:03:44 +0200197 enum {
198 SHOW_KEYS_INIT = 0,
199 SHOW_KEYS_LIST,
200 SHOW_KEYS_DONE,
201 } state; /* phase of the current dump */
Willy Tarreaua9380522022-05-05 08:50:17 +0200202};
203
Willy Tarreau691d5032021-01-20 14:55:01 +0100204/* ssl_sock_io_cb is exported to see it resolved in "show fd" */
Willy Tarreau144f84a2021-03-02 16:09:26 +0100205struct task *ssl_sock_io_cb(struct task *, void *, unsigned int);
Olivier Houchard000694c2019-05-23 14:45:12 +0200206static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
Olivier Houchardea8dd942019-05-20 14:02:16 +0200207
Olivier Houcharda8955d52019-04-07 22:00:38 +0200208/* Methods to implement OpenSSL BIO */
209static int ha_ssl_write(BIO *h, const char *buf, int num)
210{
211 struct buffer tmpbuf;
212 struct ssl_sock_ctx *ctx;
213 int ret;
214
215 ctx = BIO_get_data(h);
216 tmpbuf.size = num;
217 tmpbuf.area = (void *)(uintptr_t)buf;
218 tmpbuf.data = num;
219 tmpbuf.head = 0;
220 ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200221 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200222 BIO_set_retry_write(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200223 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200224 } else if (ret == 0)
225 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200226 return ret;
227}
228
229static int ha_ssl_gets(BIO *h, char *buf, int size)
230{
231
232 return 0;
233}
234
235static int ha_ssl_puts(BIO *h, const char *str)
236{
237
238 return ha_ssl_write(h, str, strlen(str));
239}
240
241static int ha_ssl_read(BIO *h, char *buf, int size)
242{
243 struct buffer tmpbuf;
244 struct ssl_sock_ctx *ctx;
245 int ret;
246
247 ctx = BIO_get_data(h);
248 tmpbuf.size = size;
249 tmpbuf.area = buf;
250 tmpbuf.data = 0;
251 tmpbuf.head = 0;
252 ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200253 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200254 BIO_set_retry_read(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200255 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200256 } else if (ret == 0)
257 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200258
259 return ret;
260}
261
262static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
263{
264 int ret = 0;
265 switch (cmd) {
266 case BIO_CTRL_DUP:
267 case BIO_CTRL_FLUSH:
268 ret = 1;
269 break;
270 }
271 return ret;
272}
273
274static int ha_ssl_new(BIO *h)
275{
276 BIO_set_init(h, 1);
277 BIO_set_data(h, NULL);
278 BIO_clear_flags(h, ~0);
279 return 1;
280}
281
282static int ha_ssl_free(BIO *data)
283{
284
285 return 1;
286}
287
288
Willy Tarreau5db847a2019-05-09 14:13:35 +0200289#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100290
Emeric Brun821bb9b2017-06-15 16:37:39 +0200291static HA_RWLOCK_T *ssl_rwlocks;
292
293
294unsigned long ssl_id_function(void)
295{
296 return (unsigned long)tid;
297}
298
299void ssl_locking_function(int mode, int n, const char * file, int line)
300{
301 if (mode & CRYPTO_LOCK) {
302 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100303 HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200304 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100305 HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200306 }
307 else {
308 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100309 HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200310 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100311 HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200312 }
313}
314
315static int ssl_locking_init(void)
316{
317 int i;
318
319 ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
320 if (!ssl_rwlocks)
321 return -1;
322
323 for (i = 0 ; i < CRYPTO_num_locks() ; i++)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100324 HA_RWLOCK_INIT(&ssl_rwlocks[i]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200325
326 CRYPTO_set_id_callback(ssl_id_function);
327 CRYPTO_set_locking_callback(ssl_locking_function);
328
329 return 0;
330}
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100331
Emeric Brun821bb9b2017-06-15 16:37:39 +0200332#endif
333
Willy Tarreauaf613e82020-06-05 08:40:51 +0200334__decl_thread(HA_SPINLOCK_T ckch_lock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200335
William Lallemandbc6ca7c2019-10-29 23:48:19 +0100336
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200337
338/* mimic what X509_STORE_load_locations do with store_ctx */
339static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
340{
Remi Tricot-Le Bretond75b99e2021-05-17 11:45:55 +0200341 X509_STORE *store = NULL;
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +0100342 struct cafile_entry *ca_e = ssl_store_get_cafile_entry(path, 0);
343 if (ca_e)
344 store = ca_e->ca_store;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200345 if (store_ctx && store) {
346 int i;
347 X509_OBJECT *obj;
348 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
349 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
350 obj = sk_X509_OBJECT_value(objs, i);
351 switch (X509_OBJECT_get_type(obj)) {
352 case X509_LU_X509:
353 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
354 break;
355 case X509_LU_CRL:
356 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
357 break;
358 default:
359 break;
360 }
361 }
362 return 1;
363 }
364 return 0;
365}
366
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500367/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200368static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
369{
370 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
371 return ssl_set_cert_crl_file(store_ctx, path);
372}
373
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200374/*
375 Extract CA_list from CA_file already in tree.
376 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
377 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
378*/
379static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
380{
381 struct ebmb_node *eb;
382 struct cafile_entry *ca_e;
383
384 eb = ebst_lookup(&cafile_tree, path);
385 if (!eb)
386 return NULL;
387 ca_e = ebmb_entry(eb, struct cafile_entry, node);
388
389 if (ca_e->ca_list == NULL) {
390 int i;
391 unsigned long key;
392 struct eb_root ca_name_tree = EB_ROOT;
393 struct eb64_node *node, *back;
394 struct {
395 struct eb64_node node;
396 X509_NAME *xname;
397 } *ca_name;
398 STACK_OF(X509_OBJECT) *objs;
399 STACK_OF(X509_NAME) *skn;
400 X509 *x;
401 X509_NAME *xn;
402
403 skn = sk_X509_NAME_new_null();
404 /* take x509 from cafile_tree */
405 objs = X509_STORE_get0_objects(ca_e->ca_store);
406 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
407 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
408 if (!x)
409 continue;
410 xn = X509_get_subject_name(x);
411 if (!xn)
412 continue;
413 /* Check for duplicates. */
414 key = X509_NAME_hash(xn);
415 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
416 node && ca_name == NULL;
417 node = eb64_next(node)) {
418 ca_name = container_of(node, typeof(*ca_name), node);
419 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
420 ca_name = NULL;
421 }
422 /* find a duplicate */
423 if (ca_name)
424 continue;
425 ca_name = calloc(1, sizeof *ca_name);
426 xn = X509_NAME_dup(xn);
427 if (!ca_name ||
428 !xn ||
429 !sk_X509_NAME_push(skn, xn)) {
430 free(ca_name);
431 X509_NAME_free(xn);
432 sk_X509_NAME_pop_free(skn, X509_NAME_free);
433 sk_X509_NAME_free(skn);
434 skn = NULL;
435 break;
436 }
437 ca_name->node.key = key;
438 ca_name->xname = xn;
439 eb64_insert(&ca_name_tree, &ca_name->node);
440 }
441 ca_e->ca_list = skn;
442 /* remove temporary ca_name tree */
443 node = eb64_first(&ca_name_tree);
444 while (node) {
445 ca_name = container_of(node, typeof(*ca_name), node);
446 back = eb64_next(node);
447 eb64_delete(node);
448 free(ca_name);
449 node = back;
450 }
451 }
452 return ca_e->ca_list;
453}
454
Willy Tarreauff882702021-04-10 17:23:00 +0200455struct pool_head *pool_head_ssl_capture __read_mostly = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200456int ssl_capture_ptr_index = -1;
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +0100457int ssl_app_data_index = -1;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +0100458#ifdef USE_QUIC
459int ssl_qc_app_data_index = -1;
460#endif /* USE_QUIC */
Willy Tarreauef934602016-12-22 23:12:01 +0100461
William Lallemand722180a2021-06-09 16:46:12 +0200462#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200463int ssl_keylog_index = -1;
Willy Tarreauff882702021-04-10 17:23:00 +0200464struct pool_head *pool_head_ssl_keylog __read_mostly = NULL;
465struct pool_head *pool_head_ssl_keylog_str __read_mostly = NULL;
William Lallemand7d42ef52020-07-06 11:41:30 +0200466#endif
467
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +0200468int ssl_client_crt_ref_index = -1;
469
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100470/* Used to store the client's SNI in case of ClientHello callback error */
471int ssl_client_sni_index = -1;
472
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200473#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
474struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
475#endif
476
William Lallemandd7bfbe22022-04-11 18:41:24 +0200477#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200478unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000479struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
480struct ssl_engine_list {
481 struct list list;
482 ENGINE *e;
483};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200484#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000485
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +0200486#ifdef HAVE_SSL_PROVIDERS
487struct list openssl_providers = LIST_HEAD_INIT(openssl_providers);
488struct ssl_provider_list {
489 struct list list;
490 OSSL_PROVIDER *provider;
491};
492#endif
493
Remi Gacogne8de54152014-07-15 11:36:40 +0200494#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200495static int ssl_dh_ptr_index = -1;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +0100496static HASSL_DH *global_dh = NULL;
497static HASSL_DH *local_dh_1024 = NULL;
498static HASSL_DH *local_dh_2048 = NULL;
499static HASSL_DH *local_dh_4096 = NULL;
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100500#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +0100501static DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100502#else
503static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey);
504#endif
Remi Gacogne8de54152014-07-15 11:36:40 +0200505#endif /* OPENSSL_NO_DH */
506
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100507#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200508/* X509V3 Extensions that will be added on generated certificates */
509#define X509V3_EXT_SIZE 5
510static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
511 "basicConstraints",
512 "nsComment",
513 "subjectKeyIdentifier",
514 "authorityKeyIdentifier",
515 "keyUsage",
516};
517static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
518 "CA:FALSE",
519 "\"OpenSSL Generated Certificate\"",
520 "hash",
521 "keyid,issuer:always",
522 "nonRepudiation,digitalSignature,keyEncipherment"
523};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200524/* LRU cache to store generated certificate */
525static struct lru64_head *ssl_ctx_lru_tree = NULL;
526static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200527static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100528__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200529
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200530#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
531
yanbzhube2774d2015-12-10 15:07:30 -0500532/* The order here matters for picking a default context,
533 * keep the most common keytype at the bottom of the list
534 */
535const char *SSL_SOCK_KEYTYPE_NAMES[] = {
536 "dsa",
537 "ecdsa",
538 "rsa"
539};
yanbzhube2774d2015-12-10 15:07:30 -0500540
William Lallemandc3cd35f2017-11-28 11:04:43 +0100541static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100542static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
543
Dragan Dosen9ac98092020-05-11 15:51:45 +0200544/* Dedicated callback functions for heartbeat and clienthello.
545 */
546#ifdef TLS1_RT_HEARTBEAT
547static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
548 int content_type, const void *buf, size_t len,
549 SSL *ssl);
550#endif
551static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
552 int content_type, const void *buf, size_t len,
553 SSL *ssl);
554
William Lallemand722180a2021-06-09 16:46:12 +0200555#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200556static void ssl_init_keylog(struct connection *conn, int write_p, int version,
557 int content_type, const void *buf, size_t len,
558 SSL *ssl);
559#endif
560
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200561/* List head of all registered SSL/TLS protocol message callbacks. */
562struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
563
564/* Registers the function <func> in order to be called on SSL/TLS protocol
565 * message processing. It will return 0 if the function <func> is not set
566 * or if it fails to allocate memory.
567 */
568int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
569{
570 struct ssl_sock_msg_callback *cbk;
571
572 if (!func)
573 return 0;
574
575 cbk = calloc(1, sizeof(*cbk));
576 if (!cbk) {
577 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
578 return 0;
579 }
580
581 cbk->func = func;
582
Willy Tarreau2b718102021-04-21 07:32:39 +0200583 LIST_APPEND(&ssl_sock_msg_callbacks, &cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200584
585 return 1;
586}
587
Dragan Dosen9ac98092020-05-11 15:51:45 +0200588/* Used to register dedicated SSL/TLS protocol message callbacks.
589 */
590static int ssl_sock_register_msg_callbacks(void)
591{
592#ifdef TLS1_RT_HEARTBEAT
593 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
594 return ERR_ABORT;
595#endif
Marcin Deranek310a2602021-07-13 19:04:24 +0200596 if (global_ssl.capture_buffer_size > 0) {
Dragan Dosen9ac98092020-05-11 15:51:45 +0200597 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
598 return ERR_ABORT;
599 }
William Lallemand722180a2021-06-09 16:46:12 +0200600#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200601 if (global_ssl.keylog > 0) {
602 if (!ssl_sock_register_msg_callback(ssl_init_keylog))
603 return ERR_ABORT;
604 }
605#endif
606
Christopher Fauletfc633b62020-11-06 15:24:23 +0100607 return ERR_NONE;
Dragan Dosen9ac98092020-05-11 15:51:45 +0200608}
609
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200610/* Used to free all SSL/TLS protocol message callbacks that were
611 * registered by using ssl_sock_register_msg_callback().
612 */
613static void ssl_sock_unregister_msg_callbacks(void)
614{
615 struct ssl_sock_msg_callback *cbk, *cbkback;
616
617 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +0200618 LIST_DELETE(&cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200619 free(cbk);
620 }
621}
622
Willy Tarreaude827952022-04-11 10:43:28 +0200623static struct ssl_sock_ctx *ssl_sock_get_ctx(struct connection *conn)
624{
625 if (!conn || conn->xprt != xprt_get(XPRT_SSL) || !conn->xprt_ctx)
626 return NULL;
627
628 return (struct ssl_sock_ctx *)conn->xprt_ctx;
629}
630
Dragan Doseneb607fe2020-05-11 17:17:06 +0200631SSL *ssl_sock_get_ssl_object(struct connection *conn)
632{
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200633 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dragan Doseneb607fe2020-05-11 17:17:06 +0200634
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200635 return ctx ? ctx->ssl : NULL;
Dragan Doseneb607fe2020-05-11 17:17:06 +0200636}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100637/*
638 * This function gives the detail of the SSL error. It is used only
639 * if the debug mode and the verbose mode are activated. It dump all
640 * the SSL error until the stack was empty.
641 */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +0200642static forceinline void ssl_sock_dump_errors(struct connection *conn,
643 struct quic_conn *qc)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100644{
645 unsigned long ret;
646
647 if (unlikely(global.mode & MODE_DEBUG)) {
648 while(1) {
Remi Tricot-Le Breton1effd9a2022-02-11 12:04:44 +0100649 const char *func = NULL;
650 ERR_peek_error_func(&func);
651
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100652 ret = ERR_get_error();
653 if (ret == 0)
654 return;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +0200655 if (conn) {
656 fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
657 conn_fd(conn), ret,
658 func, ERR_reason_error_string(ret));
659 }
660#ifdef USE_QUIC
661 else {
662 /* TODO: we are not sure <conn> is always initialized for QUIC connections */
663 fprintf(stderr, "qc @%p OpenSSL error[0x%lx] %s: %s\n", qc, ret,
664 func, ERR_reason_error_string(ret));
665 }
666#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100667 }
668 }
669}
670
yanbzhube2774d2015-12-10 15:07:30 -0500671
William Lallemandd7bfbe22022-04-11 18:41:24 +0200672#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200673int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000674{
675 int err_code = ERR_ABORT;
676 ENGINE *engine;
677 struct ssl_engine_list *el;
678
679 /* grab the structural reference to the engine */
680 engine = ENGINE_by_id(engine_id);
681 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100682 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000683 goto fail_get;
684 }
685
686 if (!ENGINE_init(engine)) {
687 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100688 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000689 goto fail_init;
690 }
691
692 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100693 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000694 goto fail_set_method;
695 }
696
697 el = calloc(1, sizeof(*el));
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200698 if (!el)
699 goto fail_alloc;
Grant Zhang872f9c22017-01-21 01:10:18 +0000700 el->e = engine;
Willy Tarreau2b718102021-04-21 07:32:39 +0200701 LIST_INSERT(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100702 nb_engines++;
703 if (global_ssl.async)
704 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000705 return 0;
706
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200707fail_alloc:
Grant Zhang872f9c22017-01-21 01:10:18 +0000708fail_set_method:
709 /* release the functional reference from ENGINE_init() */
710 ENGINE_finish(engine);
711
712fail_init:
713 /* release the structural reference from ENGINE_by_id() */
714 ENGINE_free(engine);
715
716fail_get:
717 return err_code;
718}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200719#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000720
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +0200721#ifdef HAVE_SSL_PROVIDERS
722int ssl_init_provider(const char *provider_name)
723{
724 int err_code = ERR_ABORT;
725 struct ssl_provider_list *prov = NULL;
726
727 prov = calloc(1, sizeof(*prov));
728 if (!prov) {
729 ha_alert("ssl-provider %s: memory allocation failure\n", provider_name);
730 goto error;
731 }
732
733 if ((prov->provider = OSSL_PROVIDER_load(NULL, provider_name)) == NULL) {
734 ha_alert("ssl-provider %s: unknown provider\n", provider_name);
735 goto error;
736 }
737
738 LIST_INSERT(&openssl_providers, &prov->list);
739
740 return 0;
741
742error:
743 ha_free(&prov);
744 return err_code;
745}
746#endif /* HAVE_SSL_PROVIDERS */
747
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +0500748#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +0200749/*
750 * openssl async fd handler
751 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200752void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000753{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200754 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000755
Emeric Brun3854e012017-05-17 20:42:48 +0200756 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000757 * to poll this fd until it is requested
758 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000759 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000760 fd_cant_recv(fd);
761
762 /* crypto engine is available, let's notify the associated
763 * connection that it can pursue its processing.
764 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200765 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000766}
767
Emeric Brun3854e012017-05-17 20:42:48 +0200768/*
769 * openssl async delayed SSL_free handler
770 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200771void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000772{
773 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200774 OSSL_ASYNC_FD all_fd[32];
775 size_t num_all_fds = 0;
776 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000777
Emeric Brun3854e012017-05-17 20:42:48 +0200778 /* We suppose that the async job for a same SSL *
779 * are serialized. So if we are awake it is
780 * because the running job has just finished
781 * and we can remove all async fds safely
782 */
783 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
784 if (num_all_fds > 32) {
785 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
786 return;
787 }
788
789 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
Emeric Brun7d392a52022-07-01 17:36:50 +0200790 for (i=0 ; i < num_all_fds ; i++) {
791 /* We want to remove the fd from the fdtab
792 * but we flag it to disown because the
793 * close is performed by the engine itself
794 */
795 fdtab[all_fd[i]].state |= FD_DISOWN;
796 fd_delete(all_fd[i]);
797 }
Emeric Brun3854e012017-05-17 20:42:48 +0200798
799 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000800 SSL_free(ssl);
Willy Tarreau82531f62021-10-06 12:15:18 +0200801 _HA_ATOMIC_DEC(&global.sslconns);
Willy Tarreau4781b152021-04-06 13:53:36 +0200802 _HA_ATOMIC_DEC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000803}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000804/*
Emeric Brun3854e012017-05-17 20:42:48 +0200805 * function used to manage a returned SSL_ERROR_WANT_ASYNC
806 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000807 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200808static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000809{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100810 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200811 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200812 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000813 size_t num_add_fds = 0;
814 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200815 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000816
817 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
818 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200819 if (num_add_fds > 32 || num_del_fds > 32) {
820 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000821 return;
822 }
823
Emeric Brun3854e012017-05-17 20:42:48 +0200824 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000825
Emeric Brun3854e012017-05-17 20:42:48 +0200826 /* We remove unused fds from the fdtab */
Emeric Brun7d392a52022-07-01 17:36:50 +0200827 for (i=0 ; i < num_del_fds ; i++) {
828 /* We want to remove the fd from the fdtab
829 * but we flag it to disown because the
830 * close is performed by the engine itself
831 */
832 fdtab[del_fd[i]].state |= FD_DISOWN;
833 fd_delete(del_fd[i]);
834 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000835
Emeric Brun3854e012017-05-17 20:42:48 +0200836 /* We add new fds to the fdtab */
837 for (i=0 ; i < num_add_fds ; i++) {
Willy Tarreau27a32452022-07-07 08:29:00 +0200838 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tgid, ti->ltid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000839 }
840
Emeric Brun3854e012017-05-17 20:42:48 +0200841 num_add_fds = 0;
842 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
843 if (num_add_fds > 32) {
844 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
845 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000846 }
Emeric Brun3854e012017-05-17 20:42:48 +0200847
848 /* We activate the polling for all known async fds */
849 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000850 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200851 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000852 /* To ensure that the fd cache won't be used
853 * We'll prefer to catch a real RD event
854 * because handling an EAGAIN on this fd will
855 * result in a context switch and also
856 * some engines uses a fd in blocking mode.
857 */
858 fd_cant_recv(add_fd[i]);
859 }
Emeric Brun3854e012017-05-17 20:42:48 +0200860
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000861}
862#endif
863
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100864
865/*
866 * Initialize an HMAC context <hctx> using the <key> and <md> parameters.
867 * Returns -1 in case of error, 1 otherwise.
868 */
869static int ssl_hmac_init(MAC_CTX *hctx, unsigned char *key, int key_len, const EVP_MD *md)
870{
871#ifdef HAVE_OSSL_PARAM
872 OSSL_PARAM params[3];
873
874 params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, key, key_len);
875 params[1] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, (char*)EVP_MD_name(md), 0);
876 params[2] = OSSL_PARAM_construct_end();
877 if (EVP_MAC_CTX_set_params(hctx, params) == 0)
878 return -1; /* error in mac initialisation */
879
880#else
881 HMAC_Init_ex(hctx, key, key_len, md, NULL);
882#endif
883 return 1;
884}
885
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100886#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +0100887
888static int ssl_tlsext_ticket_key_cb(SSL *s, unsigned char key_name[16], unsigned char *iv, EVP_CIPHER_CTX *ectx, MAC_CTX *hctx, int enc)
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100889{
Frédéric Lécaille6aec1f32022-09-06 17:04:55 +0200890 struct tls_keys_ref *ref = NULL;
Emeric Brun9e754772019-01-10 17:51:55 +0100891 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100892 int head;
893 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +0100894 int ret = -1; /* error by default */
Frédéric Lécaille6aec1f32022-09-06 17:04:55 +0200895 struct connection *conn = SSL_get_ex_data(s, ssl_app_data_index);
896#ifdef USE_QUIC
897 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
898#endif
899
900 if (conn)
901 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
902#ifdef USE_QUIC
903 else if (qc)
904 ref = qc->li->bind_conf->keys_ref;
905#endif
906
907 if (!ref) {
908 /* must never happen */
909 ABORT_NOW();
910 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100911
Christopher Faulet16f45c82018-02-16 11:23:49 +0100912 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
913
914 keys = ref->tlskeys;
915 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100916
917 if (enc) {
918 memcpy(key_name, keys[head].name, 16);
919
920 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +0100921 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100922
Emeric Brun9e754772019-01-10 17:51:55 +0100923 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100924
Emeric Brun9e754772019-01-10 17:51:55 +0100925 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
926 goto end;
927
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100928 if (ssl_hmac_init(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
929 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100930 ret = 1;
931 }
932 else if (ref->key_size_bits == 256 ) {
933
934 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
935 goto end;
936
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100937 if (ssl_hmac_init(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
938 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100939 ret = 1;
940 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100941 } else {
942 for (i = 0; i < TLS_TICKETS_NO; i++) {
943 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
944 goto found;
945 }
Christopher Faulet16f45c82018-02-16 11:23:49 +0100946 ret = 0;
947 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100948
Christopher Faulet16f45c82018-02-16 11:23:49 +0100949 found:
Emeric Brun9e754772019-01-10 17:51:55 +0100950 if (ref->key_size_bits == 128) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100951 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
952 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100953 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
954 goto end;
955 /* 2 for key renewal, 1 if current key is still valid */
956 ret = i ? 2 : 1;
957 }
958 else if (ref->key_size_bits == 256) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +0100959 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
960 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +0100961 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
962 goto end;
963 /* 2 for key renewal, 1 if current key is still valid */
964 ret = i ? 2 : 1;
965 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +0100966 }
Emeric Brun9e754772019-01-10 17:51:55 +0100967
Christopher Faulet16f45c82018-02-16 11:23:49 +0100968 end:
969 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
970 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200971}
972
973struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
974{
975 struct tls_keys_ref *ref;
976
977 list_for_each_entry(ref, &tlskeys_reference, list)
978 if (ref->filename && strcmp(filename, ref->filename) == 0)
979 return ref;
980 return NULL;
981}
982
983struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
984{
985 struct tls_keys_ref *ref;
986
987 list_for_each_entry(ref, &tlskeys_reference, list)
988 if (ref->unique_id == unique_id)
989 return ref;
990 return NULL;
991}
992
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500993/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +0100994 * match existing ones, this function returns -1
995 * else it returns 0 on success.
996 */
997int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +0200998 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +0100999{
Emeric Brun9e754772019-01-10 17:51:55 +01001000 if (ref->key_size_bits == 128) {
1001 if (tlskey->data != sizeof(struct tls_sess_key_128))
1002 return -1;
1003 }
1004 else if (ref->key_size_bits == 256) {
1005 if (tlskey->data != sizeof(struct tls_sess_key_256))
1006 return -1;
1007 }
1008 else
1009 return -1;
1010
Christopher Faulet16f45c82018-02-16 11:23:49 +01001011 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001012 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1013 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001014 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1015 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001016
1017 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001018}
1019
Willy Tarreau83061a82018-07-13 11:56:34 +02001020int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001021{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001022 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1023
1024 if(!ref) {
1025 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1026 return 1;
1027 }
Emeric Brun9e754772019-01-10 17:51:55 +01001028 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1029 memprintf(err, "Invalid key size");
1030 return 1;
1031 }
1032
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001033 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001034}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001035
1036/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001037 * automatic ids. It's called just after the basic checks. It returns
1038 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001039 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001040static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001041{
1042 int i = 0;
1043 struct tls_keys_ref *ref, *ref2, *ref3;
1044 struct list tkr = LIST_HEAD_INIT(tkr);
1045
1046 list_for_each_entry(ref, &tlskeys_reference, list) {
1047 if (ref->unique_id == -1) {
1048 /* Look for the first free id. */
1049 while (1) {
1050 list_for_each_entry(ref2, &tlskeys_reference, list) {
1051 if (ref2->unique_id == i) {
1052 i++;
1053 break;
1054 }
1055 }
1056 if (&ref2->list == &tlskeys_reference)
1057 break;
1058 }
1059
1060 /* Uses the unique id and increment it for the next entry. */
1061 ref->unique_id = i;
1062 i++;
1063 }
1064 }
1065
1066 /* This sort the reference list by id. */
1067 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001068 LIST_DELETE(&ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001069 list_for_each_entry(ref3, &tkr, list) {
1070 if (ref->unique_id < ref3->unique_id) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001071 LIST_APPEND(&ref3->list, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001072 break;
1073 }
1074 }
1075 if (&ref3->list == &tkr)
Willy Tarreau2b718102021-04-21 07:32:39 +02001076 LIST_APPEND(&tkr, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001077 }
1078
1079 /* swap root */
Willy Tarreau2b718102021-04-21 07:32:39 +02001080 LIST_INSERT(&tkr, &tlskeys_reference);
1081 LIST_DELETE(&tkr);
Christopher Fauletfc633b62020-11-06 15:24:23 +01001082 return ERR_NONE;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001083}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001084#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1085
William Lallemand4a660132019-10-14 14:51:41 +02001086
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001087#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001088/*
1089 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001090 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1091 * status extension, the issuer's certificate is mandatory. It should be
1092 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001093 *
William Lallemand246c0242019-10-11 08:59:13 +02001094 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1095 * OCSP response. If file is empty or content is not a valid OCSP response,
1096 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1097 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001098 *
1099 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001100 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001101 */
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001102static int ssl_sock_load_ocsp(SSL_CTX *ctx, struct ckch_data *data, STACK_OF(X509) *chain)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001103{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001104 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001105 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001106 struct certificate_ocsp *ocsp = NULL, *iocsp;
1107 char *warn = NULL;
1108 unsigned char *p;
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01001109#ifndef USE_OPENSSL_WOLFSSL
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001110 void (*callback) (void);
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01001111#else
1112 tlsextStatusCb callback;
1113#endif
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001114 struct buffer *ocsp_uri = get_trash_chunk();
Emeric Brun4147b2e2014-06-16 18:36:30 +02001115
Emeric Brun4147b2e2014-06-16 18:36:30 +02001116
William Lallemand52ddd992022-11-22 11:51:53 +01001117 x = data->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001118 if (!x)
1119 goto out;
1120
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001121 if (data->ocsp_update_mode == SSL_SOCK_OCSP_UPDATE_ON) {
1122 ssl_ocsp_get_uri_from_cert(x, ocsp_uri, NULL);
1123 /* We should have an "OCSP URI" field in order for auto update to work. */
1124 if (b_data(ocsp_uri) == 0)
1125 goto out;
1126 }
1127
1128 /* In case of ocsp update mode set to 'on', this function might be
1129 * called with no known ocsp response. If no ocsp uri can be found in
1130 * the certificate, nothing needs to be done here. */
1131 if (!data->ocsp_response) {
1132 if (data->ocsp_update_mode != SSL_SOCK_OCSP_UPDATE_ON || b_data(ocsp_uri) == 0) {
1133 ret = 0;
1134 goto out;
1135 }
1136 }
1137
William Lallemand52ddd992022-11-22 11:51:53 +01001138 issuer = data->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001139 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1140 if (chain) {
1141 /* check if one of the certificate of the chain is the issuer */
1142 for (i = 0; i < sk_X509_num(chain); i++) {
1143 X509 *ti = sk_X509_value(chain, i);
1144 if (X509_check_issued(ti, x) == X509_V_OK) {
1145 issuer = ti;
1146 break;
1147 }
1148 }
1149 }
William Lallemand246c0242019-10-11 08:59:13 +02001150 if (!issuer)
1151 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001152
Remi Tricot-Le Breton2d1daa82023-01-09 12:02:47 +01001153 if (!data->ocsp_cid)
1154 data->ocsp_cid = OCSP_cert_to_id(0, x, issuer);
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001155 if (!data->ocsp_cid)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001156 goto out;
1157
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001158 i = i2d_OCSP_CERTID(data->ocsp_cid, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001159 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1160 goto out;
1161
Vincent Bernat02779b62016-04-03 13:48:43 +02001162 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001163 if (!ocsp)
1164 goto out;
1165
1166 p = ocsp->key_data;
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001167 ocsp->key_length = i2d_OCSP_CERTID(data->ocsp_cid, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001168
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001169 HA_SPIN_LOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001170 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1171 if (iocsp == ocsp)
1172 ocsp = NULL;
1173
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001174#ifndef SSL_CTX_get_tlsext_status_cb
1175# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1176 *cb = (void (*) (void))ctx->tlsext_status_cb;
1177#endif
1178 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1179
1180 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001181 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001182 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001183
William Lallemanda560c062020-07-31 11:43:20 +02001184 cb_arg = calloc(1, sizeof(*cb_arg));
1185 if (!cb_arg)
1186 goto out;
1187
yanbzhube2774d2015-12-10 15:07:30 -05001188 cb_arg->is_single = 1;
1189 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001190 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001191
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001192 pkey = X509_get_pubkey(x);
1193 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1194 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001195
1196 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001197 SSL_CTX_set_ex_data(ctx, ocsp_ex_index, cb_arg); /* we use the ex_data instead of the cb_arg function here, so we can use the cleanup callback to free */
1198
yanbzhube2774d2015-12-10 15:07:30 -05001199 } else {
1200 /*
1201 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1202 * Update that cb_arg with the new cert's staple
1203 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001204 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001205 struct certificate_ocsp *tmp_ocsp;
1206 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001207 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001208 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001209
William Lallemand76b4a122020-08-04 17:41:39 +02001210 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001211
1212 /*
1213 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1214 * the order of operations below matter, take care when changing it
1215 */
1216 tmp_ocsp = cb_arg->s_ocsp;
1217 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1218 cb_arg->s_ocsp = NULL;
1219 cb_arg->m_ocsp[index] = tmp_ocsp;
1220 cb_arg->is_single = 0;
1221 cb_arg->single_kt = 0;
1222
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001223 pkey = X509_get_pubkey(x);
1224 key_type = EVP_PKEY_base_id(pkey);
1225 EVP_PKEY_free(pkey);
1226
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001227 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001228 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001229 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001230 iocsp->refcount++;
1231 }
yanbzhube2774d2015-12-10 15:07:30 -05001232 }
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001233 HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001234
1235 ret = 0;
1236
1237 warn = NULL;
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001238 if (data->ocsp_response && ssl_sock_load_ocsp_response(data->ocsp_response, iocsp, data->ocsp_cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001239 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001240 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001241 }
1242
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001243 if (data->ocsp_update_mode == SSL_SOCK_OCSP_UPDATE_ON) {
1244
1245 /* Do not insert the same certificate_ocsp structure in the
1246 * update tree more than once. */
1247 if (!ocsp) {
Remi Tricot-Le Breton112b16a2023-01-09 12:02:44 +01001248 /* Issuer certificate is not included in the certificate
1249 * chain, it will have to be treated separately during
1250 * ocsp response validation. */
1251 if (issuer == data->ocsp_issuer) {
1252 iocsp->issuer = issuer;
1253 X509_up_ref(issuer);
1254 }
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001255 if (data->chain)
1256 iocsp->chain = X509_chain_up_ref(data->chain);
1257
Remi Tricot-Le Breton648c83e2023-01-09 12:02:48 +01001258 iocsp->uri = calloc(1, sizeof(*iocsp->uri));
1259 if (!chunk_dup(iocsp->uri, ocsp_uri)) {
1260 ha_free(&iocsp->uri);
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001261 goto out;
Remi Tricot-Le Breton648c83e2023-01-09 12:02:48 +01001262 }
Remi Tricot-Le Bretonb55be8c2022-12-20 11:11:12 +01001263
1264 ssl_ocsp_update_insert(iocsp);
1265 }
1266 }
1267
Emeric Brun4147b2e2014-06-16 18:36:30 +02001268out:
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001269 if (ret && data->ocsp_cid)
1270 OCSP_CERTID_free(data->ocsp_cid);
1271
1272 if (!ret && data->ocsp_response) {
1273 ha_free(&data->ocsp_response->area);
1274 ha_free(&data->ocsp_response);
1275 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001276
1277 if (ocsp)
Remi Tricot-Le Bretonaa529f72022-11-03 15:16:49 +01001278 ssl_sock_free_ocsp(ocsp);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001279
1280 if (warn)
1281 free(warn);
1282
Emeric Brun4147b2e2014-06-16 18:36:30 +02001283 return ret;
1284}
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01001285
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001286#endif
1287
1288#ifdef OPENSSL_IS_BORINGSSL
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001289static int ssl_sock_load_ocsp(SSL_CTX *ctx, struct ckch_data *data, STACK_OF(X509) *chain)
Emmanuel Hocdet2c32d8f2017-05-22 14:58:00 +02001290{
William Lallemand4a660132019-10-14 14:51:41 +02001291 return SSL_CTX_set_ocsp_response(ctx, (const uint8_t *)ckch->ocsp_response->area, ckch->ocsp_response->data);
Emmanuel Hocdet2c32d8f2017-05-22 14:58:00 +02001292}
1293#endif
1294
William Lallemand4a660132019-10-14 14:51:41 +02001295
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001296#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001297
1298#define CT_EXTENSION_TYPE 18
1299
William Lallemand03c331c2020-05-13 10:10:01 +02001300int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001301
1302int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1303{
Willy Tarreau83061a82018-07-13 11:56:34 +02001304 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001305
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001306 *out = (unsigned char *) sctl->area;
1307 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001308
1309 return 1;
1310}
1311
1312int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1313{
1314 return 1;
1315}
1316
William Lallemanda17f4112019-10-10 15:16:44 +02001317static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001318{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001319 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001320
William Lallemanda17f4112019-10-10 15:16:44 +02001321 if (!SSL_CTX_add_server_custom_ext(ctx, CT_EXTENSION_TYPE, ssl_sock_sctl_add_cbk, NULL, sctl, ssl_sock_sctl_parse_cbk, NULL))
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001322 goto out;
1323
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001324 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1325
1326 ret = 0;
1327
1328out:
1329 return ret;
1330}
1331
1332#endif
1333
Emeric Brune1f38db2012-09-03 20:36:47 +02001334void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1335{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001336 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001337#ifdef USE_QUIC
1338 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1339#endif /* USE_QUIC */
1340 struct ssl_sock_ctx *ctx = NULL;
1341
Emeric Brund8b2bb52014-01-28 15:43:53 +01001342 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001343 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001344
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001345 if (conn)
Willy Tarreau939b0bf2022-04-11 11:29:11 +02001346 ctx = conn_get_ssl_sock_ctx(conn);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001347#ifdef USE_QUIC
1348 else if (qc)
1349 ctx = qc->xprt_ctx;
1350#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01001351
1352 if (!ctx) {
1353 /* must never happen */
1354 ABORT_NOW();
1355 return;
1356 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001357
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001358#ifndef SSL_OP_NO_RENEGOTIATION
1359 /* Please note that BoringSSL defines this macro to zero so don't
1360 * change this to #if and do not assign a default value to this macro!
1361 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001362 if (where & SSL_CB_HANDSHAKE_START) {
1363 /* Disable renegotiation (CVE-2009-3555) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001364 if (conn && (conn->flags & (CO_FL_WAIT_L6_CONN | CO_FL_EARLY_SSL_HS | CO_FL_EARLY_DATA)) == 0) {
Emeric Brune1f38db2012-09-03 20:36:47 +02001365 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001366 conn->err_code = CO_ER_SSL_RENEG;
1367 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001368 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001369#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001370
1371 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001372 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001373 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001374 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001375 consider that the buffering was activated,
1376 so we rise the output buffer size from 4k
1377 to 16k */
1378 write_bio = SSL_get_wbio(ssl);
1379 if (write_bio != SSL_get_rbio(ssl)) {
1380 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001381 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001382 }
1383 }
1384 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001385}
1386
Emeric Brune64aef12012-09-21 13:15:06 +02001387/* Callback is called for each certificate of the chain during a verify
1388 ok is set to 1 if preverify detect no error on current certificate.
1389 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001390int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001391{
1392 SSL *ssl;
1393 struct connection *conn;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001394 struct ssl_sock_ctx *ctx = NULL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001395 int err, depth;
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001396 X509 *client_crt;
1397 STACK_OF(X509) *certs;
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001398 struct bind_conf *bind_conf = NULL;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001399 struct quic_conn *qc = NULL;
Emeric Brune64aef12012-09-21 13:15:06 +02001400
1401 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001402 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001403 client_crt = SSL_get_ex_data(ssl, ssl_client_crt_ref_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001404
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001405 if (conn) {
1406 bind_conf = __objt_listener(conn->target)->bind_conf;
1407 ctx = __conn_get_ssl_sock_ctx(conn);
1408 }
1409#ifdef USE_QUIC
1410 else {
1411 qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
Amaury Denoyelleba303de2022-10-17 18:46:49 +02001412 BUG_ON(!qc); /* Must never happen */
1413 bind_conf = qc->li->bind_conf;
1414 ctx = qc->xprt_ctx;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001415 }
1416#endif
1417
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001418 BUG_ON(!ctx || !bind_conf);
Christopher Faulet881cce92022-11-23 09:27:13 +01001419 ALREADY_CHECKED(ctx);
1420 ALREADY_CHECKED(bind_conf);
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001421
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001422 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001423
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001424 depth = X509_STORE_CTX_get_error_depth(x_store);
1425 err = X509_STORE_CTX_get_error(x_store);
1426
Emeric Brun81c00f02012-09-21 14:31:21 +02001427 if (ok) /* no errors */
1428 return ok;
1429
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001430 /* Keep a reference to the client's certificate in order to be able to
1431 * dump some fetches values in a log even when the verification process
1432 * fails. */
1433 if (depth == 0) {
1434 X509_free(client_crt);
1435 client_crt = X509_STORE_CTX_get0_cert(x_store);
1436 if (client_crt) {
1437 X509_up_ref(client_crt);
1438 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
1439 }
1440 }
1441 else {
1442 /* An error occurred on a CA certificate of the certificate
1443 * chain, we might never call this verify callback on the client
1444 * certificate's depth (which is 0) so we try to store the
1445 * reference right now. */
Remi Tricot-Le Bretonf95c2952021-08-20 09:51:23 +02001446 certs = X509_STORE_CTX_get1_chain(x_store);
1447 if (certs) {
1448 client_crt = sk_X509_value(certs, 0);
1449 if (client_crt) {
1450 X509_up_ref(client_crt);
1451 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001452 }
1453 sk_X509_pop_free(certs, X509_free);
1454 }
1455 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001456
1457 /* check if CA error needs to be ignored */
1458 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001459 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1460 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1461 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001462 }
1463
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01001464 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01001465 cert_ignerr_bitfield_get(bind_conf->ca_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001466 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02001467
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001468 /* TODO: for QUIC connection, this error code is lost */
1469 if (conn)
1470 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001471 return 0;
1472 }
1473
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001474 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1475 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001476
Emeric Brun81c00f02012-09-21 14:31:21 +02001477 /* check if certificate error needs to be ignored */
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01001478 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01001479 cert_ignerr_bitfield_get(bind_conf->crt_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001480 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02001481
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001482 /* TODO: for QUIC connection, this error code is lost */
1483 if (conn)
1484 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001485 return 0;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001486
1487 err_ignored:
1488 ssl_sock_dump_errors(conn, qc);
1489 ERR_clear_error();
1490 return 1;
Emeric Brune64aef12012-09-21 13:15:06 +02001491}
1492
Dragan Dosen9ac98092020-05-11 15:51:45 +02001493#ifdef TLS1_RT_HEARTBEAT
1494static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1495 int content_type, const void *buf, size_t len,
1496 SSL *ssl)
1497{
1498 /* test heartbeat received (write_p is set to 0
1499 for a received record) */
1500 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02001501 struct ssl_sock_ctx *ctx = __conn_get_ssl_sock_ctx(conn);
Dragan Dosen9ac98092020-05-11 15:51:45 +02001502 const unsigned char *p = buf;
1503 unsigned int payload;
1504
1505 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1506
1507 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1508 if (*p != TLS1_HB_REQUEST)
1509 return;
1510
1511 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1512 goto kill_it;
1513
1514 payload = (p[1] * 256) + p[2];
1515 if (3 + payload + 16 <= len)
1516 return; /* OK no problem */
1517 kill_it:
1518 /* We have a clear heartbleed attack (CVE-2014-0160), the
1519 * advertised payload is larger than the advertised packet
1520 * length, so we have garbage in the buffer between the
1521 * payload and the end of the buffer (p+len). We can't know
1522 * if the SSL stack is patched, and we don't know if we can
1523 * safely wipe out the area between p+3+len and payload.
1524 * So instead, we prevent the response from being sent by
1525 * setting the max_send_fragment to 0 and we report an SSL
1526 * error, which will kill this connection. It will be reported
1527 * above as SSL_ERROR_SSL while an other handshake failure with
1528 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1529 */
1530 ssl->max_send_fragment = 0;
1531 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1532 }
1533}
1534#endif
1535
1536static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1537 int content_type, const void *buf, size_t len,
1538 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001539{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001540 struct ssl_capture *capture;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001541 uchar *msg;
1542 uchar *end;
1543 uchar *extensions_end;
1544 uchar *ec_start = NULL;
1545 uchar *ec_formats_start = NULL;
1546 uchar *list_end;
1547 ushort protocol_version;
1548 ushort extension_id;
1549 ushort ec_len = 0;
1550 uchar ec_formats_len = 0;
1551 int offset = 0;
1552 int rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001553
1554 /* This function is called for "from client" and "to server"
1555 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001556 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001557 */
1558
1559 /* "write_p" is set to 0 is the bytes are received messages,
1560 * otherwise it is set to 1.
1561 */
1562 if (write_p != 0)
1563 return;
1564
1565 /* content_type contains the type of message received or sent
1566 * according with the SSL/TLS protocol spec. This message is
1567 * encoded with one byte. The value 256 (two bytes) is used
1568 * for designing the SSL/TLS record layer. According with the
1569 * rfc6101, the expected message (other than 256) are:
1570 * - change_cipher_spec(20)
1571 * - alert(21)
1572 * - handshake(22)
1573 * - application_data(23)
1574 * - (255)
1575 * We are interessed by the handshake and specially the client
1576 * hello.
1577 */
1578 if (content_type != 22)
1579 return;
1580
1581 /* The message length is at least 4 bytes, containing the
1582 * message type and the message length.
1583 */
1584 if (len < 4)
1585 return;
1586
1587 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001588 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001589 * - hello_request(0)
1590 * - client_hello(1)
1591 * - server_hello(2)
1592 * - certificate(11)
1593 * - server_key_exchange (12)
1594 * - certificate_request(13)
1595 * - server_hello_done(14)
1596 * We are interested by the client hello.
1597 */
1598 msg = (unsigned char *)buf;
1599 if (msg[0] != 1)
1600 return;
1601
1602 /* Next three bytes are the length of the message. The total length
1603 * must be this decoded length + 4. If the length given as argument
1604 * is not the same, we abort the protocol dissector.
1605 */
1606 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1607 if (len < rec_len + 4)
1608 return;
1609 msg += 4;
1610 end = msg + rec_len;
1611 if (end < msg)
1612 return;
1613
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001614 /* Expect 2 bytes for protocol version
1615 * (1 byte for major and 1 byte for minor)
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001616 */
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001617 if (msg + 2 > end)
1618 return;
1619 protocol_version = (msg[0] << 8) + msg[1];
1620 msg += 2;
1621
1622 /* Expect the random, composed by 4 bytes for the unix time and
1623 * 28 bytes for unix payload. So we jump 4 + 28.
1624 */
1625 msg += 4 + 28;
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001626 if (msg > end)
1627 return;
1628
1629 /* Next, is session id:
1630 * if present, we have to jump by length + 1 for the size information
1631 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001632 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001633 if (msg[0] > 0)
1634 msg += msg[0];
1635 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001636 if (msg > end)
1637 return;
1638
1639 /* Next two bytes are the ciphersuite length. */
1640 if (msg + 2 > end)
1641 return;
1642 rec_len = (msg[0] << 8) + msg[1];
1643 msg += 2;
1644 if (msg + rec_len > end || msg + rec_len < msg)
1645 return;
1646
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001647 capture = pool_zalloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001648 if (!capture)
1649 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001650 /* Compute the xxh64 of the ciphersuite. */
1651 capture->xxh64 = XXH64(msg, rec_len, 0);
1652
1653 /* Capture the ciphersuite. */
Marcin Deranek310a2602021-07-13 19:04:24 +02001654 capture->ciphersuite_len = MIN(global_ssl.capture_buffer_size, rec_len);
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001655 capture->ciphersuite_offset = 0;
1656 memcpy(capture->data, msg, capture->ciphersuite_len);
1657 msg += rec_len;
1658 offset += capture->ciphersuite_len;
1659
1660 /* Initialize other data */
1661 capture->protocol_version = protocol_version;
1662
1663 /* Next, compression methods:
1664 * if present, we have to jump by length + 1 for the size information
1665 * if not present, we have to jump by 1 only
1666 */
1667 if (msg[0] > 0)
1668 msg += msg[0];
1669 msg += 1;
1670 if (msg > end)
1671 goto store_capture;
1672
1673 /* We reached extensions */
1674 if (msg + 2 > end)
1675 goto store_capture;
1676 rec_len = (msg[0] << 8) + msg[1];
1677 msg += 2;
1678 if (msg + rec_len > end || msg + rec_len < msg)
1679 goto store_capture;
1680 extensions_end = msg + rec_len;
1681 capture->extensions_offset = offset;
1682
1683 /* Parse each extension */
1684 while (msg + 4 < extensions_end) {
1685 /* Add 2 bytes of extension_id */
Marcin Deranek310a2602021-07-13 19:04:24 +02001686 if (global_ssl.capture_buffer_size >= offset + 2) {
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001687 capture->data[offset++] = msg[0];
1688 capture->data[offset++] = msg[1];
1689 capture->extensions_len += 2;
1690 }
1691 else
1692 break;
1693 extension_id = (msg[0] << 8) + msg[1];
1694 /* Length of the extension */
1695 rec_len = (msg[2] << 8) + msg[3];
1696
1697 /* Expect 2 bytes extension id + 2 bytes extension size */
1698 msg += 2 + 2;
1699 if (msg + rec_len > extensions_end || msg + rec_len < msg)
1700 goto store_capture;
1701 /* TLS Extensions
1702 * https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml */
1703 if (extension_id == 0x000a) {
1704 /* Elliptic Curves:
1705 * https://www.rfc-editor.org/rfc/rfc8422.html
1706 * https://www.rfc-editor.org/rfc/rfc7919.html */
1707 list_end = msg + rec_len;
1708 if (msg + 2 > list_end)
1709 goto store_capture;
1710 rec_len = (msg[0] << 8) + msg[1];
1711 msg += 2;
1712
1713 if (msg + rec_len > list_end || msg + rec_len < msg)
1714 goto store_capture;
1715 /* Store location/size of the list */
1716 ec_start = msg;
1717 ec_len = rec_len;
1718 }
1719 else if (extension_id == 0x000b) {
1720 /* Elliptic Curves Point Formats:
1721 * https://www.rfc-editor.org/rfc/rfc8422.html */
1722 list_end = msg + rec_len;
1723 if (msg + 1 > list_end)
1724 goto store_capture;
1725 rec_len = msg[0];
1726 msg += 1;
1727
1728 if (msg + rec_len > list_end || msg + rec_len < msg)
1729 goto store_capture;
1730 /* Store location/size of the list */
1731 ec_formats_start = msg;
1732 ec_formats_len = rec_len;
1733 }
1734 msg += rec_len;
1735 }
1736
1737 if (ec_start) {
1738 rec_len = ec_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001739 if (offset + rec_len > global_ssl.capture_buffer_size)
1740 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001741 memcpy(capture->data + offset, ec_start, rec_len);
1742 capture->ec_offset = offset;
1743 capture->ec_len = rec_len;
1744 offset += rec_len;
1745 }
1746 if (ec_formats_start) {
1747 rec_len = ec_formats_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001748 if (offset + rec_len > global_ssl.capture_buffer_size)
1749 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001750 memcpy(capture->data + offset, ec_formats_start, rec_len);
1751 capture->ec_formats_offset = offset;
1752 capture->ec_formats_len = rec_len;
1753 offset += rec_len;
1754 }
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001755
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001756 store_capture:
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001757 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001758}
William Lallemand7d42ef52020-07-06 11:41:30 +02001759
1760
William Lallemand722180a2021-06-09 16:46:12 +02001761#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001762static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1763 int content_type, const void *buf, size_t len,
1764 SSL *ssl)
1765{
1766 struct ssl_keylog *keylog;
1767
1768 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1769 return;
1770
Willy Tarreauf208ac02021-03-22 21:10:12 +01001771 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02001772 if (!keylog)
1773 return;
1774
William Lallemand7d42ef52020-07-06 11:41:30 +02001775 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
1776 pool_free(pool_head_ssl_keylog, keylog);
1777 return;
1778 }
1779}
1780#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001781
Emeric Brun29f037d2014-04-25 19:05:36 +02001782/* Callback is called for ssl protocol analyse */
1783void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1784{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001785 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1786 struct ssl_sock_msg_callback *cbk;
1787
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001788 /* Try to call all callback functions that were registered by using
1789 * ssl_sock_register_msg_callback().
1790 */
1791 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1792 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1793 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001794}
1795
Bernard Spil13c53f82018-02-15 13:34:58 +01001796#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001797static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1798 const unsigned char *in, unsigned int inlen,
1799 void *arg)
1800{
1801 struct server *srv = arg;
1802
1803 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1804 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1805 return SSL_TLSEXT_ERR_OK;
1806 return SSL_TLSEXT_ERR_NOACK;
1807}
1808#endif
1809
1810#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001811/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001812 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001813 */
1814static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1815 unsigned int *len, void *arg)
1816{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001817 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001818
1819 *data = (const unsigned char *)conf->npn_str;
1820 *len = conf->npn_len;
1821 return SSL_TLSEXT_ERR_OK;
1822}
1823#endif
1824
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001825#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001826/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001827 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001828 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001829static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1830 unsigned char *outlen,
1831 const unsigned char *server,
1832 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001833{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001834 struct ssl_bind_conf *conf = arg;
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001835#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001836 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001837#endif
Willy Tarreauab861d32013-04-02 02:30:41 +02001838
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001839 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1840 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01001841#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001842 if (qc)
1843 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01001844#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001845 return SSL_TLSEXT_ERR_NOACK;
1846 }
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001847
1848#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001849 if (qc && !quic_set_app_ops(qc, *out, *outlen)) {
1850 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01001851 return SSL_TLSEXT_ERR_NOACK;
1852 }
1853#endif
1854
Willy Tarreauab861d32013-04-02 02:30:41 +02001855 return SSL_TLSEXT_ERR_OK;
1856}
1857#endif
1858
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001859#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001860#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001861
cui flitera94bedc2022-08-29 14:42:57 +08001862/* Configure a DNS SAN extension on a certificate. */
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001863int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
1864 int failure = 0;
1865 X509_EXTENSION *san_ext = NULL;
1866 CONF *conf = NULL;
1867 struct buffer *san_name = get_trash_chunk();
1868
1869 conf = NCONF_new(NULL);
1870 if (!conf) {
1871 failure = 1;
1872 goto cleanup;
1873 }
1874
1875 /* Build an extension based on the DNS entry above */
1876 chunk_appendf(san_name, "DNS:%s", servername);
1877 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
1878 if (!san_ext) {
1879 failure = 1;
1880 goto cleanup;
1881 }
1882
1883 /* Add the extension */
1884 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
1885 failure = 1;
1886 goto cleanup;
1887 }
1888
1889 /* Success */
1890 failure = 0;
1891
1892cleanup:
1893 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
1894 if (NULL != conf) NCONF_free(conf);
1895
1896 return failure;
1897}
1898
Christopher Faulet30548802015-06-11 13:39:32 +02001899/* Create a X509 certificate with the specified servername and serial. This
1900 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001901static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001902ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001903{
Shimi Gersner5846c492020-08-23 13:58:12 +03001904 X509 *cacert = bind_conf->ca_sign_ckch->cert;
1905 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001906 SSL_CTX *ssl_ctx = NULL;
1907 X509 *newcrt = NULL;
1908 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001909 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001910 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001911 X509_NAME *name;
1912 const EVP_MD *digest;
1913 X509V3_CTX ctx;
1914 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001915 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001916
Christopher Faulet48a83322017-07-28 16:56:09 +02001917 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05001918#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001919 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1920#else
1921 tmp_ssl = SSL_new(bind_conf->default_ctx);
1922 if (tmp_ssl)
1923 pkey = SSL_get_privatekey(tmp_ssl);
1924#endif
1925 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001926 goto mkcert_error;
1927
1928 /* Create the certificate */
1929 if (!(newcrt = X509_new()))
1930 goto mkcert_error;
1931
1932 /* Set version number for the certificate (X509v3) and the serial
1933 * number */
1934 if (X509_set_version(newcrt, 2L) != 1)
1935 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02001936 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001937
1938 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001939 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1940 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001941 goto mkcert_error;
1942
1943 /* set public key in the certificate */
1944 if (X509_set_pubkey(newcrt, pkey) != 1)
1945 goto mkcert_error;
1946
1947 /* Set issuer name from the CA */
1948 if (!(name = X509_get_subject_name(cacert)))
1949 goto mkcert_error;
1950 if (X509_set_issuer_name(newcrt, name) != 1)
1951 goto mkcert_error;
1952
1953 /* Set the subject name using the same, but the CN */
1954 name = X509_NAME_dup(name);
1955 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1956 (const unsigned char *)servername,
1957 -1, -1, 0) != 1) {
1958 X509_NAME_free(name);
1959 goto mkcert_error;
1960 }
1961 if (X509_set_subject_name(newcrt, name) != 1) {
1962 X509_NAME_free(name);
1963 goto mkcert_error;
1964 }
1965 X509_NAME_free(name);
1966
1967 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001968 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02001969 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1970 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1971 X509_EXTENSION *ext;
1972
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001973 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001974 goto mkcert_error;
1975 if (!X509_add_ext(newcrt, ext, -1)) {
1976 X509_EXTENSION_free(ext);
1977 goto mkcert_error;
1978 }
1979 X509_EXTENSION_free(ext);
1980 }
1981
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001982 /* Add SAN extension */
1983 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
1984 goto mkcert_error;
1985 }
1986
Christopher Faulet31af49d2015-06-09 17:29:50 +02001987 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001988
1989 key_type = EVP_PKEY_base_id(capkey);
1990
1991 if (key_type == EVP_PKEY_DSA)
1992 digest = EVP_sha1();
1993 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001994 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001995 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02001996 digest = EVP_sha256();
1997 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05001998#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02001999 int nid;
2000
2001 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
2002 goto mkcert_error;
2003 if (!(digest = EVP_get_digestbynid(nid)))
2004 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02002005#else
2006 goto mkcert_error;
2007#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02002008 }
2009
Christopher Faulet31af49d2015-06-09 17:29:50 +02002010 if (!(X509_sign(newcrt, capkey, digest)))
2011 goto mkcert_error;
2012
2013 /* Create and set the new SSL_CTX */
2014 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
2015 goto mkcert_error;
2016 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
2017 goto mkcert_error;
2018 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
2019 goto mkcert_error;
2020 if (!SSL_CTX_check_private_key(ssl_ctx))
2021 goto mkcert_error;
2022
Shimi Gersner5846c492020-08-23 13:58:12 +03002023 /* Build chaining the CA cert and the rest of the chain, keep these order */
2024#if defined(SSL_CTX_add1_chain_cert)
2025 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
2026 goto mkcert_error;
2027 }
2028
2029 if (bind_conf->ca_sign_ckch->chain) {
2030 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2031 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2032 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2033 goto mkcert_error;
2034 }
2035 }
2036 }
2037#endif
2038
Christopher Faulet31af49d2015-06-09 17:29:50 +02002039 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002040
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002041#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002042#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002043 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002044#else
2045 ssl_sock_set_tmp_dh_from_pkey(ssl_ctx, pkey);
2046#endif
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002047#endif
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002048
2049#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
2050#if defined(SSL_CTX_set1_curves_list)
2051 {
2052 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
2053 if (!SSL_CTX_set1_curves_list(ssl_ctx, ecdhe))
2054 goto end;
2055 }
2056#endif
2057#else
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002058#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2059 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002060 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002061 EC_KEY *ecc;
2062 int nid;
2063
2064 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2065 goto end;
2066 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2067 goto end;
2068 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2069 EC_KEY_free(ecc);
2070 }
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002071#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
2072#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002073 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002074 return ssl_ctx;
2075
2076 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002077 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002078 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002079 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2080 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002081 return NULL;
2082}
2083
Christopher Faulet7969a332015-10-09 11:15:03 +02002084
Christopher Faulet30548802015-06-11 13:39:32 +02002085/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002086 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002087SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002088ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002089{
2090 struct lru64 *lru = NULL;
2091
2092 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002093 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002094 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002095 if (lru && lru->domain) {
2096 if (ssl)
2097 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002098 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002099 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002100 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002101 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002102 }
2103 return NULL;
2104}
2105
Emeric Brun821bb9b2017-06-15 16:37:39 +02002106/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2107 * function is not thread-safe, it should only be used to check if a certificate
2108 * exists in the lru cache (with no warranty it will not be removed by another
2109 * thread). It is kept for backward compatibility. */
2110SSL_CTX *
2111ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2112{
2113 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2114}
2115
Christopher Fauletd2cab922015-07-28 16:03:47 +02002116/* Set a certificate int the LRU cache used to store generated
2117 * certificate. Return 0 on success, otherwise -1 */
2118int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002119ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002120{
2121 struct lru64 *lru = NULL;
2122
2123 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002124 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002125 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002126 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002127 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002128 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002129 }
Christopher Faulet30548802015-06-11 13:39:32 +02002130 if (lru->domain && lru->data)
2131 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002132 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002133 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002134 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002135 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002136 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002137}
2138
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002139/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002140unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002141ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002142{
2143 return XXH32(data, len, ssl_ctx_lru_seed);
2144}
2145
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002146/* Generate a cert and immediately assign it to the SSL session so that the cert's
2147 * refcount is maintained regardless of the cert's presence in the LRU cache.
2148 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002149static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002150ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002151{
Shimi Gersner5846c492020-08-23 13:58:12 +03002152 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002153 SSL_CTX *ssl_ctx = NULL;
2154 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002155 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002156
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002157 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002158 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002159 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002160 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002161 if (lru && lru->domain)
2162 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002163 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002164 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002165 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002166 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002167 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002168 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002169 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002170 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002171 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002172 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002173 SSL_set_SSL_CTX(ssl, ssl_ctx);
2174 /* No LRU cache, this CTX will be released as soon as the session dies */
2175 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002176 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002177 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002178 return 0;
2179}
2180static int
2181ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2182{
2183 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002184 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002185
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002186 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002187 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002188 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002189 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002190 }
2191 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002192}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002193#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002194
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002195#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002196
2197static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002198{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002199#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002200 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002201 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2202#endif
2203}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002204static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2205 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002206 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2207}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002208static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002209#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002210 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002211 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2212#endif
2213}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002214static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002215#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002216 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002217 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2218#endif
2219}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002220/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002221static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2222/* Unusable in this context. */
2223static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2224static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2225static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2226static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2227static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002228#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002229
2230static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2231 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002232 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2233}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002234static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2235 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2236 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2237}
2238static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2239 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002240 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2241}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002242static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2243 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2244 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2245}
2246static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2247 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002248 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2249}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002250static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2251 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2252 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2253}
2254static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2255 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002256 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2257}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002258static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2259 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2260 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2261}
2262static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002263#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002264 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002265 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2266#endif
2267}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002268static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002269#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002270 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2271 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002272#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002273}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002274#endif
2275static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2276static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002277
William Lallemand7fd8b452020-05-07 15:20:43 +02002278struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002279 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2280 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2281 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2282 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2283 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2284 {SSL_OP_NO_TLSv1_3, MC_SSL_O_NO_TLSV13, ctx_set_TLSv13_func, ssl_set_TLSv13_func, "TLSv1.3"}, /* CONF_TLSV13 */
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002285};
2286
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002287static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2288{
2289 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2290 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2291 SSL_set_SSL_CTX(ssl, ctx);
2292}
2293
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002294#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002295
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002296int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002297{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002298 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002299 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002300
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002301 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || (s->options & BC_O_GENERATE_CERTS))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002302 return SSL_TLSEXT_ERR_OK;
2303 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002304}
2305
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002306#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002307int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002308{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002309 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002310#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002311int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002312{
2313#endif
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002314 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2315#ifdef USE_QUIC
2316 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2317#endif /* USE_QUIC */
2318 struct bind_conf *s = NULL;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002319 const uint8_t *extension_data;
2320 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002321 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002322
2323 char *wildp = NULL;
2324 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002325 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002326 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002327 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002328 int i;
2329
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002330 if (conn)
2331 s = __objt_listener(conn->target)->bind_conf;
2332#ifdef USE_QUIC
2333 else if (qc)
2334 s = qc->li->bind_conf;
2335#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01002336
2337 if (!s) {
2338 /* must never happen */
2339 ABORT_NOW();
2340 return 0;
2341 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002342
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002343#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002344 if (qc) {
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002345 /* Look for the QUIC transport parameters. */
2346#ifdef OPENSSL_IS_BORINGSSL
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002347 if (!SSL_early_callback_ctx_extension_get(ctx, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002348 &extension_data, &extension_len))
2349#else
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002350 if (!SSL_client_hello_get0_ext(ssl, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002351 &extension_data, &extension_len))
2352#endif
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002353 {
2354 /* This is not redundant. It we only return 0 without setting
2355 * <*al>, this has as side effect to generate another TLS alert
2356 * which would be set after calling quic_set_tls_alert().
2357 */
2358 *al = SSL_AD_MISSING_EXTENSION;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002359 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002360 return 0;
2361 }
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002362
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002363 if (!quic_transport_params_store(qc, 0, extension_data,
Frédéric Lécaille301425b2022-06-14 17:40:39 +02002364 extension_data + extension_len) ||
2365 !qc_conn_finalize(qc, 0))
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002366 goto abort;
2367 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002368#endif /* USE_QUIC */
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002369
Olivier Houchard9679ac92017-10-27 14:58:08 +02002370 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002371 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002372#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002373 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2374 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002375#else
2376 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2377#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002378 /*
2379 * The server_name extension was given too much extensibility when it
2380 * was written, so parsing the normal case is a bit complex.
2381 */
2382 size_t len;
2383 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002384 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002385 /* Extract the length of the supplied list of names. */
2386 len = (*extension_data++) << 8;
2387 len |= *extension_data++;
2388 if (len + 2 != extension_len)
2389 goto abort;
2390 /*
2391 * The list in practice only has a single element, so we only consider
2392 * the first one.
2393 */
2394 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2395 goto abort;
2396 extension_len = len - 1;
2397 /* Now we can finally pull out the byte array with the actual hostname. */
2398 if (extension_len <= 2)
2399 goto abort;
2400 len = (*extension_data++) << 8;
2401 len |= *extension_data++;
2402 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2403 || memchr(extension_data, 0, len) != NULL)
2404 goto abort;
2405 servername = extension_data;
2406 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002407 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002408#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002409 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002410 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002411 }
2412#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002413 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002414 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002415 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002416 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002417 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002418 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002419 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002420 goto abort;
2421 }
2422
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002423 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002424#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002425 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002426#else
2427 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2428#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002429 uint8_t sign;
2430 size_t len;
2431 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002432 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002433 len = (*extension_data++) << 8;
2434 len |= *extension_data++;
2435 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002436 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002437 if (len % 2 != 0)
2438 goto abort;
2439 for (; len > 0; len -= 2) {
2440 extension_data++; /* hash */
2441 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002442 switch (sign) {
2443 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002444 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002445 break;
2446 case TLSEXT_signature_ecdsa:
2447 has_ecdsa_sig = 1;
2448 break;
2449 default:
2450 continue;
2451 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002452 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002453 break;
2454 }
2455 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002456 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002457 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002458 }
2459 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002460 const SSL_CIPHER *cipher;
2461 size_t len;
2462 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002463 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002464#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002465 len = ctx->cipher_suites_len;
2466 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002467#else
2468 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2469#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002470 if (len % 2 != 0)
2471 goto abort;
2472 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002473#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002474 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002475 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002476#else
2477 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2478#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002479 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002480 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002481 break;
2482 }
2483 }
2484 }
2485
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002486 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002487 trash.area[i] = tolower(servername[i]);
2488 if (!wildp && (trash.area[i] == '.'))
2489 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002490 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002491 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002492
William Lallemand150bfa82019-09-19 17:12:49 +02002493 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002494
William Lallemand94bd3192020-08-14 14:43:35 +02002495 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2496 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002497 for (i = 0; i < 2; i++) {
2498 if (i == 0) /* lookup in full qualified names */
2499 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002500 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002501 node = ebst_lookup(&s->sni_w_ctx, wildp);
2502 else
2503 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002504
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002505 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002506
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002507 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002508 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002509 struct sni_ctx *sni, *sni_tmp;
2510 int skip = 0;
2511
2512 if (i == 1 && wildp) { /* wildcard */
2513 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2514 sni = container_of(n, struct sni_ctx, name);
2515 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002516 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002517 skip = 1;
2518 break;
2519 }
2520 }
2521 if (skip)
2522 continue;
2523 }
2524
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002525 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002526 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002527 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002528 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002529 break;
2530 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002531 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002532 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002533 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002534 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002535 if (!node_anonymous)
2536 node_anonymous = n;
2537 break;
2538 }
2539 }
2540 }
William Lallemand94bd3192020-08-14 14:43:35 +02002541 }
2542 /* Once the certificates are found, select them depending on what is
2543 * supported in the client and by key_signature priority order: EDSA >
2544 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002545 if (has_ecdsa_sig && node_ecdsa)
2546 node = node_ecdsa;
2547 else if (has_rsa_sig && node_rsa)
2548 node = node_rsa;
2549 else if (node_anonymous)
2550 node = node_anonymous;
2551 else if (node_ecdsa)
2552 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2553 else
2554 node = node_rsa; /* no rsa signature case (far far away) */
2555
William Lallemand94bd3192020-08-14 14:43:35 +02002556 if (node) {
2557 /* switch ctx */
2558 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2559 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2560 if (conf) {
2561 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2562 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2563 if (conf->early_data)
2564 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002565 }
William Lallemand94bd3192020-08-14 14:43:35 +02002566 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2567 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002568 }
William Lallemand150bfa82019-09-19 17:12:49 +02002569
William Lallemand02010472019-10-18 11:02:19 +02002570 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002571#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002572 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002573 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002574 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002575 }
2576#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002577 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002578 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002579 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002580 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002581 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
William Lallemand7980dff2021-11-18 17:46:26 +01002582 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002583 }
William Lallemand7980dff2021-11-18 17:46:26 +01002584
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01002585 /* We are about to raise an handshake error so the servername extension
2586 * callback will never be called and the SNI will never be stored in the
2587 * SSL context. In order for the ssl_fc_sni sample fetch to still work
2588 * in such a case, we store the SNI ourselves as an ex_data information
2589 * in the SSL context.
2590 */
2591 {
2592 char *client_sni = pool_alloc(ssl_sock_client_sni_pool);
2593 if (client_sni) {
2594 strncpy(client_sni, trash.area, TLSEXT_MAXLEN_host_name);
2595 client_sni[TLSEXT_MAXLEN_host_name] = '\0';
2596 SSL_set_ex_data(ssl, ssl_client_sni_index, client_sni);
2597 }
2598 }
2599
William Lallemand7980dff2021-11-18 17:46:26 +01002600 /* other cases fallback on abort, if strict-sni is set but no node was found */
2601
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002602 abort:
2603 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002604 if (conn)
2605 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002606#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002607 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002608#else
2609 *al = SSL_AD_UNRECOGNIZED_NAME;
2610 return 0;
2611#endif
William Lallemand7980dff2021-11-18 17:46:26 +01002612
2613allow_early:
2614#ifdef OPENSSL_IS_BORINGSSL
2615 if (allow_early)
2616 SSL_set_early_data_enabled(ssl, 1);
2617#else
2618 if (!allow_early)
2619 SSL_set_max_early_data(ssl, 0);
2620#endif
2621 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002622}
2623
William Lallemand002e2062021-11-18 15:25:16 +01002624#else /* ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002625
Emeric Brunfc0421f2012-09-07 17:30:07 +02002626/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2627 * warning when no match is found, which implies the default (first) cert
2628 * will keep being used.
2629 */
William Lallemand844009d2022-09-02 15:27:32 +02002630int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002631{
2632 const char *servername;
2633 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002634 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002635 struct bind_conf *s = priv;
William Lallemand70a6e632022-09-07 11:21:34 +02002636#ifdef USE_QUIC
2637 const uint8_t *extension_data;
2638 size_t extension_len;
2639 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2640#endif /* USE_QUIC */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002641 int i;
2642 (void)al; /* shut gcc stupid warning */
2643
William Lallemand70a6e632022-09-07 11:21:34 +02002644#ifdef USE_QUIC
2645 if (qc) {
2646
2647 /* Look for the QUIC transport parameters. */
2648 SSL_get_peer_quic_transport_params(ssl, &extension_data, &extension_len);
2649 if (extension_len == 0) {
2650 /* This is not redundant. It we only return 0 without setting
2651 * <*al>, this has as side effect to generate another TLS alert
2652 * which would be set after calling quic_set_tls_alert().
2653 */
2654 *al = SSL_AD_MISSING_EXTENSION;
2655 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
2656 return SSL_TLSEXT_ERR_NOACK;
2657 }
2658
2659 if (!quic_transport_params_store(qc, 0, extension_data,
2660 extension_data + extension_len) ||
2661 !qc_conn_finalize(qc, 0)) {
2662 return SSL_TLSEXT_ERR_NOACK;
2663 }
2664 }
2665#endif /* USE_QUIC */
2666
Emeric Brunfc0421f2012-09-07 17:30:07 +02002667 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002668 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002669#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002670 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002671 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002672#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002673 if (s->strict_sni)
2674 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002675 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002676 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002677 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002678 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002679 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002680
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002681 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002682 if (!servername[i])
2683 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002684 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002685 if (!wildp && (trash.area[i] == '.'))
2686 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002687 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002688 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002689
William Lallemand150bfa82019-09-19 17:12:49 +02002690 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002691 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002692 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002693 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2694 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002695 if (!container_of(n, struct sni_ctx, name)->neg) {
2696 node = n;
2697 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002698 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002699 }
2700 if (!node && wildp) {
2701 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002702 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2703 /* lookup a not neg filter */
2704 if (!container_of(n, struct sni_ctx, name)->neg) {
2705 node = n;
2706 break;
2707 }
2708 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002709 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002710 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002711#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002712 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(servername, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002713 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002714 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002715 return SSL_TLSEXT_ERR_OK;
2716 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002717#endif
William Lallemand21724f02019-11-04 17:56:13 +01002718 if (s->strict_sni) {
2719 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002720 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002721 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002722 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002723 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002724 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002725 }
2726
2727 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002728 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002729 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002730 return SSL_TLSEXT_ERR_OK;
2731}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002732#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002733#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2734
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002735#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002736
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002737static inline HASSL_DH *ssl_new_dh_fromdata(BIGNUM *p, BIGNUM *g)
2738{
2739#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2740 OSSL_PARAM_BLD *tmpl = NULL;
2741 OSSL_PARAM *params = NULL;
2742 EVP_PKEY_CTX *ctx = NULL;
2743 EVP_PKEY *pkey = NULL;
2744
2745 if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
2746 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
2747 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)
2748 || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
2749 goto end;
2750 }
2751 ctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2752 if (ctx == NULL
2753 || !EVP_PKEY_fromdata_init(ctx)
2754 || !EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params)) {
2755 goto end;
2756 }
2757
2758end:
2759 EVP_PKEY_CTX_free(ctx);
2760 OSSL_PARAM_free(params);
2761 OSSL_PARAM_BLD_free(tmpl);
Remi Tricot-Le Bretona2c21db2022-11-03 15:16:47 +01002762 BN_free(p);
2763 BN_free(g);
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002764 return pkey;
2765#else
2766
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002767 HASSL_DH *dh = DH_new();
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002768
2769 if (!dh)
2770 return NULL;
2771
2772 DH_set0_pqg(dh, p, NULL, g);
2773
2774 return dh;
2775#endif
2776}
2777
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02002778#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002779static inline HASSL_DH *ssl_get_dh_by_nid(int nid)
2780{
2781#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2782 OSSL_PARAM params[2];
2783 EVP_PKEY *pkey = NULL;
2784 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2785 const char *named_group = NULL;
2786
2787 if (!pctx)
2788 goto end;
2789
2790 named_group = OBJ_nid2ln(nid);
2791
2792 if (!named_group)
2793 goto end;
2794
2795 params[0] = OSSL_PARAM_construct_utf8_string("group", (char*)named_group, 0);
2796 params[1] = OSSL_PARAM_construct_end();
2797
2798 if (EVP_PKEY_keygen_init(pctx) && EVP_PKEY_CTX_set_params(pctx, params))
2799 EVP_PKEY_generate(pctx, &pkey);
2800
2801end:
2802 EVP_PKEY_CTX_free(pctx);
2803 return pkey;
2804#else
2805
2806 HASSL_DH *dh = NULL;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002807 dh = DH_new_by_nid(nid);
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002808 return dh;
2809#endif
2810}
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02002811#endif
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002812
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002813
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002814static HASSL_DH * ssl_get_dh_1024(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002815{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002816 static unsigned char dh1024_p[]={
2817 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2818 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2819 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2820 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2821 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2822 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2823 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2824 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2825 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2826 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2827 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2828 };
2829 static unsigned char dh1024_g[]={
2830 0x02,
2831 };
2832
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002833 BIGNUM *p;
2834 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002835
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002836 HASSL_DH *dh = NULL;
2837
2838 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2839 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
2840
2841 if (p && g)
2842 dh = ssl_new_dh_fromdata(p, g);
2843
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002844 return dh;
2845}
2846
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002847static HASSL_DH *ssl_get_dh_2048(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002848{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002849#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02002850 static unsigned char dh2048_p[]={
2851 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2852 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2853 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2854 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2855 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2856 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2857 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2858 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2859 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2860 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2861 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2862 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2863 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2864 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2865 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2866 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2867 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2868 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2869 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2870 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2871 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2872 0xB7,0x1F,0x77,0xF3,
2873 };
2874 static unsigned char dh2048_g[]={
2875 0x02,
2876 };
2877
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002878 BIGNUM *p;
2879 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002880
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002881 HASSL_DH *dh = NULL;
2882
2883 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2884 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
2885
2886 if (p && g)
2887 dh = ssl_new_dh_fromdata(p, g);
2888
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002889 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002890#else
2891 return ssl_get_dh_by_nid(NID_ffdhe2048);
2892#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002893}
2894
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002895static HASSL_DH *ssl_get_dh_4096(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002896{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002897#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02002898 static unsigned char dh4096_p[]={
2899 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2900 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2901 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2902 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2903 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2904 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2905 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2906 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2907 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2908 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2909 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2910 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2911 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2912 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2913 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2914 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2915 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2916 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2917 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2918 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2919 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2920 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2921 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2922 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2923 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2924 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2925 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2926 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2927 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2928 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2929 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2930 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2931 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2932 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2933 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2934 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2935 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2936 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2937 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2938 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2939 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2940 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2941 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002942 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002943 static unsigned char dh4096_g[]={
2944 0x02,
2945 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002946
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002947 BIGNUM *p;
2948 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02002949
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002950 HASSL_DH *dh = NULL;
2951
2952 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2953 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
2954
2955 if (p && g)
2956 dh = ssl_new_dh_fromdata(p, g);
2957
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002958 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002959#else
2960 return ssl_get_dh_by_nid(NID_ffdhe4096);
2961#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002962}
2963
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002964static HASSL_DH *ssl_get_tmp_dh(EVP_PKEY *pkey)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002965{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002966 HASSL_DH *dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002967 int type;
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002968 int keylen = 0;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002969
2970 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002971
Ilya Shipitsin52f2ff52022-07-23 23:55:19 +05002972 if (type == EVP_PKEY_EC) {
2973 keylen = global_ssl.default_dh_param;
2974 }
2975
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002976 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2977 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2978 */
2979 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2980 keylen = EVP_PKEY_bits(pkey);
2981 }
2982
Willy Tarreauef934602016-12-22 23:12:01 +01002983 if (keylen > global_ssl.default_dh_param) {
2984 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002985 }
2986
Remi Gacogned3a341a2015-05-29 16:26:17 +02002987 if (keylen >= 4096) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01002988 if (!local_dh_4096)
2989 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02002990 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002991 }
2992 else if (keylen >= 2048) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01002993 if (!local_dh_2048)
2994 local_dh_2048 = ssl_get_dh_2048();
Remi Gacogne8de54152014-07-15 11:36:40 +02002995 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002996 }
2997 else {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01002998 if (!local_dh_1024)
2999 local_dh_1024 = ssl_get_dh_1024();
Remi Gacogne8de54152014-07-15 11:36:40 +02003000 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003001 }
3002
3003 return dh;
3004}
3005
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003006#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003007/* Returns Diffie-Hellman parameters matching the private key length
3008 but not exceeding global_ssl.default_dh_param */
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003009static HASSL_DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003010{
3011 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
3012
3013 return ssl_get_tmp_dh(pkey);
3014}
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003015#endif
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003016
Remi Tricot-Le Breton846eda92022-02-11 12:04:50 +01003017static int ssl_sock_set_tmp_dh(SSL_CTX *ctx, HASSL_DH *dh)
3018{
3019#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
3020 return SSL_CTX_set_tmp_dh(ctx, dh);
3021#else
3022 int retval = 0;
3023 HASSL_DH_up_ref(dh);
3024
3025 retval = SSL_CTX_set0_tmp_dh_pkey(ctx, dh);
3026
3027 if (!retval)
3028 HASSL_DH_free(dh);
3029
3030 return retval;
3031#endif
3032}
3033
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003034#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3035static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey)
3036{
3037 HASSL_DH *dh = NULL;
3038 if (pkey && (dh = ssl_get_tmp_dh(pkey))) {
3039 HASSL_DH_up_ref(dh);
3040 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dh))
3041 HASSL_DH_free(dh);
3042 }
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003043}
3044#endif
3045
Remi Tricot-Le Breton09ebb332022-02-11 12:04:48 +01003046HASSL_DH *ssl_sock_get_dh_from_bio(BIO *bio)
3047{
3048#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3049 HASSL_DH *dh = NULL;
3050 OSSL_DECODER_CTX *dctx = NULL;
3051 const char *format = "PEM";
3052 const char *keytype = "DH";
3053
3054 dctx = OSSL_DECODER_CTX_new_for_pkey(&dh, format, NULL, keytype,
3055 OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
3056 NULL, NULL);
3057
3058 if (dctx == NULL || OSSL_DECODER_CTX_get_num_decoders(dctx) == 0)
3059 goto end;
3060
3061 /* The DH parameters might not be the first section found in the PEM
3062 * file so we need to iterate over all of them until we find the right
3063 * one.
3064 */
3065 while (!BIO_eof(bio) && !dh)
3066 OSSL_DECODER_from_bio(dctx, bio);
3067
3068end:
3069 OSSL_DECODER_CTX_free(dctx);
3070 return dh;
3071#else
3072 HASSL_DH *dh = NULL;
3073
3074 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3075
3076 return dh;
3077#endif
3078}
3079
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003080static HASSL_DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003081{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003082 HASSL_DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02003083 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003084
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003085 if (in == NULL)
3086 goto end;
3087
Remi Gacogne47783ef2015-05-29 15:53:22 +02003088 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003089 goto end;
3090
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003091 dh = ssl_sock_get_dh_from_bio(in);
Remi Gacogne47783ef2015-05-29 15:53:22 +02003092
3093end:
3094 if (in)
3095 BIO_free(in);
3096
Emeric Brune1b4ed42018-08-16 15:14:12 +02003097 ERR_clear_error();
3098
Remi Gacogne47783ef2015-05-29 15:53:22 +02003099 return dh;
3100}
3101
3102int ssl_sock_load_global_dh_param_from_file(const char *filename)
3103{
3104 global_dh = ssl_sock_get_dh_from_file(filename);
3105
3106 if (global_dh) {
3107 return 0;
3108 }
3109
3110 return -1;
3111}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003112#endif
3113
William Lallemand9117de92019-10-04 00:29:42 +02003114/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02003115static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02003116 struct bind_conf *s, struct ssl_bind_conf *conf,
3117 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003118{
3119 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003120 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003121
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003122 if (*name == '!') {
3123 neg = 1;
3124 name++;
3125 }
3126 if (*name == '*') {
3127 wild = 1;
3128 name++;
3129 }
3130 /* !* filter is a nop */
3131 if (neg && wild)
3132 return order;
3133 if (*name) {
3134 int j, len;
3135 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003136 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02003137 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003138 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02003139 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003140 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003141
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003142 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02003143 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02003144 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003145 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02003146 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003147 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003148 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003149 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003150 sc->order = order++;
3151 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02003152 sc->wild = wild;
3153 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01003154 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02003155 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003156 }
3157 return order;
3158}
3159
William Lallemand6af03992019-07-23 15:00:54 +02003160/*
William Lallemand1d29c742019-10-04 00:53:29 +02003161 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
3162 * This function can't return an error.
3163 *
3164 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
3165 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003166void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02003167{
3168
3169 struct sni_ctx *sc0, *sc0b, *sc1;
3170 struct ebmb_node *node;
3171
3172 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
3173
3174 /* ignore if sc0 was already inserted in a tree */
3175 if (sc0->name.node.leaf_p)
3176 continue;
3177
3178 /* Check for duplicates. */
3179 if (sc0->wild)
3180 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
3181 else
3182 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
3183
3184 for (; node; node = ebmb_next_dup(node)) {
3185 sc1 = ebmb_entry(node, struct sni_ctx, name);
3186 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
3187 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
3188 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02003189 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02003190 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003191 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02003192 break;
William Lallemand1d29c742019-10-04 00:53:29 +02003193 }
3194 }
3195
3196 /* if duplicate, ignore the insertion */
3197 if (!sc0)
3198 continue;
3199
3200 if (sc0->wild)
3201 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
3202 else
3203 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003204 }
William Lallemand21724f02019-11-04 17:56:13 +01003205
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003206 /* replace the default_ctx if required with the instance's ctx. */
3207 if (ckch_inst->is_default) {
3208 SSL_CTX_free(bind_conf->default_ctx);
3209 SSL_CTX_up_ref(ckch_inst->ctx);
3210 bind_conf->default_ctx = ckch_inst->ctx;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003211 bind_conf->default_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02003212 }
3213}
3214
3215/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003216 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02003217 */
William Lallemande3af8fb2019-10-08 11:36:53 +02003218struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02003219
William Lallemand2954c472020-03-06 21:54:13 +01003220/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02003221struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02003222
Emeric Brun7a883362019-10-17 13:27:40 +02003223/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003224 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02003225 * DH parameter is loaded into the SSL_CTX and if there is no
3226 * DH parameter available in ckchs nor in global, the default
3227 * DH parameters are applied on the SSL_CTX.
3228 * Returns a bitfield containing the flags:
3229 * ERR_FATAL in any fatal error case
3230 * ERR_ALERT if a reason of the error is availabine in err
3231 * ERR_WARN if a warning is available into err
3232 * The value 0 means there is no error nor warning and
3233 * the operation succeed.
3234 */
William Lallemandfa892222019-07-23 16:06:08 +02003235#ifndef OPENSSL_NO_DH
William Lallemand52ddd992022-11-22 11:51:53 +01003236static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct ckch_data *data,
Emeric Brun7a883362019-10-17 13:27:40 +02003237 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02003238{
Emeric Brun7a883362019-10-17 13:27:40 +02003239 int ret = 0;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003240 HASSL_DH *dh = NULL;
William Lallemandfa892222019-07-23 16:06:08 +02003241
William Lallemand52ddd992022-11-22 11:51:53 +01003242 if (data && data->dh) {
3243 dh = data->dh;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003244 if (!ssl_sock_set_tmp_dh(ctx, dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003245 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
3246 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003247 memprintf(err, "%s, DH ciphers won't be available.\n",
3248 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003249 ret |= ERR_WARN;
3250 goto end;
3251 }
William Lallemandfa892222019-07-23 16:06:08 +02003252
3253 if (ssl_dh_ptr_index >= 0) {
3254 /* store a pointer to the DH params to avoid complaining about
3255 ssl-default-dh-param not being set for this SSL_CTX */
3256 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
3257 }
3258 }
3259 else if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003260 if (!ssl_sock_set_tmp_dh(ctx, global_dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003261 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
3262 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003263 memprintf(err, "%s, DH ciphers won't be available.\n",
3264 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003265 ret |= ERR_WARN;
3266 goto end;
3267 }
William Lallemandfa892222019-07-23 16:06:08 +02003268 }
3269 else {
3270 /* Clear openssl global errors stack */
3271 ERR_clear_error();
3272
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003273 /* We do not want DHE ciphers to be added to the cipher list
3274 * unless there is an explicit global dh option in the conf.
3275 */
3276 if (global_ssl.default_dh_param) {
3277 if (global_ssl.default_dh_param <= 1024) {
3278 /* we are limited to DH parameter of 1024 bits anyway */
3279 if (local_dh_1024 == NULL)
3280 local_dh_1024 = ssl_get_dh_1024();
William Lallemandfa892222019-07-23 16:06:08 +02003281
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003282 if (local_dh_1024 == NULL) {
3283 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3284 err && *err ? *err : "", path);
3285 ret |= ERR_ALERT | ERR_FATAL;
3286 goto end;
3287 }
William Lallemandfa892222019-07-23 16:06:08 +02003288
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003289 if (!ssl_sock_set_tmp_dh(ctx, local_dh_1024)) {
3290 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3291 err && *err ? *err : "", path);
3292 memprintf(err, "%s, DH ciphers won't be available.\n",
3293 err && *err ? *err : "");
3294 ret |= ERR_WARN;
3295 goto end;
3296 }
Emeric Bruna9363eb2019-10-17 14:53:03 +02003297 }
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003298 else {
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003299#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003300 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003301#else
William Lallemand52ddd992022-11-22 11:51:53 +01003302 ssl_sock_set_tmp_dh_from_pkey(ctx, data ? data->key : NULL);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003303#endif
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003304 }
William Lallemandfa892222019-07-23 16:06:08 +02003305 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003306 }
3307
William Lallemandf9568fc2019-10-16 18:27:58 +02003308end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003309 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003310 return ret;
3311}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003312#endif
William Lallemandfa892222019-07-23 16:06:08 +02003313
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003314
3315/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003316 * Returns a bitfield containing the flags:
3317 * ERR_FATAL in any fatal error case
3318 * ERR_ALERT if the reason of the error is available in err
3319 * ERR_WARN if a warning is available into err
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003320 * The caller is responsible of freeing the newly built or newly refcounted
3321 * find_chain element.
Emeric Bruna96b5822019-10-17 13:25:14 +02003322 * The value 0 means there is no error nor warning and
3323 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003324 */
William Lallemand52ddd992022-11-22 11:51:53 +01003325static int ssl_sock_load_cert_chain(const char *path, const struct ckch_data *data,
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003326 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003327{
Emeric Bruna96b5822019-10-17 13:25:14 +02003328 int errcode = 0;
William Lallemand45fed2c2022-11-15 16:56:03 +01003329 int ret;
3330
3331 ERR_clear_error();
Emeric Bruna96b5822019-10-17 13:25:14 +02003332
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003333 if (find_chain == NULL) {
3334 errcode |= ERR_FATAL;
3335 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003336 }
3337
William Lallemand52ddd992022-11-22 11:51:53 +01003338 if (!SSL_CTX_use_certificate(ctx, data->cert)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003339 ret = ERR_get_error();
3340 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s': %s.\n",
3341 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Emeric Bruna96b5822019-10-17 13:25:14 +02003342 errcode |= ERR_ALERT | ERR_FATAL;
3343 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003344 }
3345
William Lallemand52ddd992022-11-22 11:51:53 +01003346 if (data->chain) {
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003347 *find_chain = X509_chain_up_ref(data->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003348 } else {
3349 /* Find Certificate Chain in global */
3350 struct issuer_chain *issuer;
William Lallemand52ddd992022-11-22 11:51:53 +01003351 issuer = ssl_get0_issuer_chain(data->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003352 if (issuer)
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003353 *find_chain = X509_chain_up_ref(issuer->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003354 }
William Lallemand85888572020-02-27 14:48:35 +01003355
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003356 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003357 /* always put a null chain stack in the SSL_CTX so it does not
3358 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003359 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003360 }
3361
William Lallemand52ddd992022-11-22 11:51:53 +01003362 /* Load all certs in the data into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003363#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003364 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003365 ret = ERR_get_error();
3366 memprintf(err, "%sunable to load chain certificate into SSL Context '%s': %s. Make sure you are linking against Openssl >= 1.0.2.\n",
3367 err && *err ? *err : "", path, ERR_reason_error_string(ret));
William Lallemand935d8292020-08-12 20:02:10 +02003368 errcode |= ERR_ALERT | ERR_FATAL;
3369 goto end;
3370 }
William Lallemandf187ce62020-06-02 18:27:20 +02003371#else
3372 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003373 X509 *ca;
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003374 while ((ca = sk_X509_shift(*find_chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003375 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003376 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3377 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003378 X509_free(ca);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003379 errcode |= ERR_ALERT | ERR_FATAL;
3380 goto end;
3381 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003382 }
William Lallemandf187ce62020-06-02 18:27:20 +02003383#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003384
William Lallemand9a1d8392020-08-10 17:28:23 +02003385#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003386 /* remove the Root CA from the SSL_CTX if the option is activated */
3387 if (global_ssl.skip_self_issued_ca) {
3388 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3389 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3390 err && *err ? *err : "", path);
3391 errcode |= ERR_ALERT | ERR_FATAL;
3392 goto end;
3393 }
3394 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003395#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003396
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003397end:
3398 return errcode;
3399}
3400
3401
3402/* Loads the info in ckch into ctx
3403 * Returns a bitfield containing the flags:
3404 * ERR_FATAL in any fatal error case
3405 * ERR_ALERT if the reason of the error is available in err
3406 * ERR_WARN if a warning is available into err
3407 * The value 0 means there is no error nor warning and
3408 * the operation succeed.
3409 */
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01003410static 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 +01003411{
3412 int errcode = 0;
3413 STACK_OF(X509) *find_chain = NULL;
3414
William Lallemand5de49512022-10-27 14:41:07 +02003415 ERR_clear_error();
3416
William Lallemand52ddd992022-11-22 11:51:53 +01003417 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
William Lallemand5de49512022-10-27 14:41:07 +02003418 int ret;
3419
3420 ret = ERR_get_error();
3421 memprintf(err, "%sunable to load SSL private key into SSL Context '%s': %s.\n",
3422 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003423 errcode |= ERR_ALERT | ERR_FATAL;
3424 return errcode;
3425 }
3426
3427 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01003428 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003429 if (errcode & ERR_CODE)
3430 goto end;
3431
William Lallemandfa892222019-07-23 16:06:08 +02003432#ifndef OPENSSL_NO_DH
3433 /* store a NULL pointer to indicate we have not yet loaded
3434 a custom DH param file */
3435 if (ssl_dh_ptr_index >= 0) {
3436 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3437 }
3438
William Lallemand52ddd992022-11-22 11:51:53 +01003439 errcode |= ssl_sock_load_dh_params(ctx, data, path, err);
Emeric Brun7a883362019-10-17 13:27:40 +02003440 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003441 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3442 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003443 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003444 }
3445#endif
3446
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003447#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemand52ddd992022-11-22 11:51:53 +01003448 if (sctl_ex_index >= 0 && data->sctl) {
3449 if (ssl_sock_load_sctl(ctx, data->sctl) < 0) {
William Lallemanda17f4112019-10-10 15:16:44 +02003450 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003451 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003452 errcode |= ERR_ALERT | ERR_FATAL;
3453 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003454 }
3455 }
3456#endif
3457
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003458#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 +01003459 /* Load OCSP Info into context
3460 * If OCSP update mode is set to 'on', an entry will be created in the
3461 * ocsp tree even if no ocsp_response was known during init, unless the
3462 * frontend's conf disables ocsp update explicitely.
3463 */
3464 if (ssl_sock_load_ocsp(ctx, data, find_chain) < 0) {
3465 if (data->ocsp_response)
Tim Duesterhus93128532019-11-23 23:45:10 +01003466 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 +01003467 err && *err ? *err : "", path);
3468 else
3469 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",
3470 err && *err ? *err : "", path);
3471 errcode |= ERR_ALERT | ERR_FATAL;
3472 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003473 }
William Lallemand246c0242019-10-11 08:59:13 +02003474#endif
3475
Emeric Bruna96b5822019-10-17 13:25:14 +02003476 end:
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003477 sk_X509_pop_free(find_chain, X509_free);
Emeric Bruna96b5822019-10-17 13:25:14 +02003478 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003479}
3480
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003481
3482/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
3483 * Returns a bitfield containing the flags:
3484 * ERR_FATAL in any fatal error case
3485 * ERR_ALERT if the reason of the error is available in err
3486 * ERR_WARN if a warning is available into err
3487 * The value 0 means there is no error nor warning and
3488 * the operation succeed.
3489 */
William Lallemand52ddd992022-11-22 11:51:53 +01003490static 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 +01003491 SSL_CTX *ctx, char **err)
3492{
3493 int errcode = 0;
3494 STACK_OF(X509) *find_chain = NULL;
3495
3496 /* Load the private key */
William Lallemand52ddd992022-11-22 11:51:53 +01003497 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003498 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3499 err && *err ? *err : "", path);
3500 errcode |= ERR_ALERT | ERR_FATAL;
3501 }
3502
3503 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01003504 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003505 if (errcode & ERR_CODE)
3506 goto end;
3507
3508 if (SSL_CTX_check_private_key(ctx) <= 0) {
3509 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3510 err && *err ? *err : "", path);
3511 errcode |= ERR_ALERT | ERR_FATAL;
3512 }
3513
3514end:
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003515 sk_X509_pop_free(find_chain, X509_free);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003516 return errcode;
3517}
3518
3519
William Lallemand614ca0d2019-10-07 13:52:11 +02003520/*
3521 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003522 *
3523 * Returns a bitfield containing the flags:
3524 * ERR_FATAL in any fatal error case
3525 * ERR_ALERT if the reason of the error is available in err
3526 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003527 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003528int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003529 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003530{
William Lallemandc9402072019-05-15 15:33:54 +02003531 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003532 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003533 int order = 0;
3534 X509_NAME *xname;
3535 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003536 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003537 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003538#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3539 STACK_OF(GENERAL_NAME) *names;
3540#endif
William Lallemand52ddd992022-11-22 11:51:53 +01003541 struct ckch_data *data;
William Lallemand614ca0d2019-10-07 13:52:11 +02003542 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003543 int errcode = 0;
3544
3545 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003546
William Lallemand52ddd992022-11-22 11:51:53 +01003547 if (!ckchs || !ckchs->data)
Emeric Brun054563d2019-10-17 13:16:58 +02003548 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003549
William Lallemand52ddd992022-11-22 11:51:53 +01003550 data = ckchs->data;
William Lallemand36b84632019-07-18 19:28:17 +02003551
William Lallemandc9402072019-05-15 15:33:54 +02003552 ctx = SSL_CTX_new(SSLv23_server_method());
3553 if (!ctx) {
3554 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3555 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003556 errcode |= ERR_ALERT | ERR_FATAL;
3557 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003558 }
3559
William Lallemand52ddd992022-11-22 11:51:53 +01003560 errcode |= ssl_sock_put_ckch_into_ctx(path, data, ctx, err);
Emeric Bruna96b5822019-10-17 13:25:14 +02003561 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003562 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003563
3564 ckch_inst = ckch_inst_new();
3565 if (!ckch_inst) {
3566 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3567 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003568 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003569 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003570 }
3571
William Lallemand52ddd992022-11-22 11:51:53 +01003572 pkey = X509_get_pubkey(data->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003573 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003574 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003575 switch(EVP_PKEY_base_id(pkey)) {
3576 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003577 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003578 break;
3579 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003580 kinfo.sig = TLSEXT_signature_ecdsa;
3581 break;
3582 case EVP_PKEY_DSA:
3583 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003584 break;
3585 }
3586 EVP_PKEY_free(pkey);
3587 }
3588
Emeric Brun50bcecc2013-04-22 13:05:23 +02003589 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003590 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003591 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 +02003592 if (order < 0) {
3593 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003594 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003595 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003596 }
3597 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003598 }
3599 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003600#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand52ddd992022-11-22 11:51:53 +01003601 names = X509_get_ext_d2i(data->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003602 if (names) {
3603 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3604 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3605 if (name->type == GEN_DNS) {
3606 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003607 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003608 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003609 if (order < 0) {
3610 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003611 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003612 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003613 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003614 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003615 }
3616 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003617 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003618 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003619#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand52ddd992022-11-22 11:51:53 +01003620 xname = X509_get_subject_name(data->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003621 i = -1;
3622 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3623 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003624 ASN1_STRING *value;
3625
3626 value = X509_NAME_ENTRY_get_data(entry);
3627 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003628 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003629 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003630 if (order < 0) {
3631 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003632 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003633 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003634 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003635 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003636 }
3637 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003638 /* we must not free the SSL_CTX anymore below, since it's already in
3639 * the tree, so it will be discovered and cleaned in time.
3640 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003641
Emeric Brunfc0421f2012-09-07 17:30:07 +02003642#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003643 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003644 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3645 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003646 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003647 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003648 }
3649#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003650 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003651 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003652 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003653 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003654 SSL_CTX_up_ref(ctx);
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003655 bind_conf->default_inst = ckch_inst;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003656 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003657
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003658 /* Always keep a reference to the newly constructed SSL_CTX in the
3659 * instance. This way if the instance has no SNIs, the SSL_CTX will
3660 * still be linked. */
3661 SSL_CTX_up_ref(ctx);
3662 ckch_inst->ctx = ctx;
3663
William Lallemand9117de92019-10-04 00:29:42 +02003664 /* everything succeed, the ckch instance can be used */
3665 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003666 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003667 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003668
William Lallemand02e19a52020-04-08 16:11:26 +02003669 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3670
Emeric Brun054563d2019-10-17 13:16:58 +02003671 *ckchi = ckch_inst;
3672 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003673
3674error:
3675 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003676 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003677 if (ckch_inst->is_default)
3678 SSL_CTX_free(ctx);
3679
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003680 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003681 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003682 }
William Lallemandd9199372019-10-04 15:37:05 +02003683 SSL_CTX_free(ctx);
3684
Emeric Brun054563d2019-10-17 13:16:58 +02003685 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003686}
3687
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003688
3689/*
3690 * This function allocate a ckch_inst that will be used on the backend side
3691 * (server line)
3692 *
3693 * Returns a bitfield containing the flags:
3694 * ERR_FATAL in any fatal error case
3695 * ERR_ALERT if the reason of the error is available in err
3696 * ERR_WARN if a warning is available into err
3697 */
3698int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01003699 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003700{
3701 SSL_CTX *ctx;
William Lallemand52ddd992022-11-22 11:51:53 +01003702 struct ckch_data *data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003703 struct ckch_inst *ckch_inst = NULL;
3704 int errcode = 0;
3705
3706 *ckchi = NULL;
3707
William Lallemand52ddd992022-11-22 11:51:53 +01003708 if (!ckchs || !ckchs->data)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003709 return ERR_FATAL;
3710
William Lallemand52ddd992022-11-22 11:51:53 +01003711 data = ckchs->data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003712
3713 ctx = SSL_CTX_new(SSLv23_client_method());
3714 if (!ctx) {
3715 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3716 err && *err ? *err : "", path);
3717 errcode |= ERR_ALERT | ERR_FATAL;
3718 goto error;
3719 }
3720
William Lallemand52ddd992022-11-22 11:51:53 +01003721 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, data, ctx, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003722 if (errcode & ERR_CODE)
3723 goto error;
3724
3725 ckch_inst = ckch_inst_new();
3726 if (!ckch_inst) {
3727 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3728 err && *err ? *err : "", path);
3729 errcode |= ERR_ALERT | ERR_FATAL;
3730 goto error;
3731 }
3732
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003733 /* everything succeed, the ckch instance can be used */
3734 ckch_inst->bind_conf = NULL;
3735 ckch_inst->ssl_conf = NULL;
3736 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01003737 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003738 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003739
3740 *ckchi = ckch_inst;
3741 return errcode;
3742
3743error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003744 SSL_CTX_free(ctx);
3745
3746 return errcode;
3747}
3748
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003749/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003750static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3751 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003752 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003753{
Emeric Brun054563d2019-10-17 13:16:58 +02003754 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003755
3756 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003757 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 +02003758
Emeric Brun054563d2019-10-17 13:16:58 +02003759 if (errcode & ERR_CODE)
3760 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003761
William Lallemand24bde432020-03-09 16:48:43 +01003762 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003763
3764 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003765 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003766 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003767}
3768
William Lallemanddb26e2b2021-01-26 12:01:46 +01003769/* This function generates a <struct ckch_inst *> for a <struct server *>, and
3770 * fill the SSL_CTX of the server.
3771 *
3772 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003773static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01003774 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003775{
3776 int errcode = 0;
3777
3778 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01003779 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003780
3781 if (errcode & ERR_CODE)
3782 return errcode;
3783
William Lallemanddb26e2b2021-01-26 12:01:46 +01003784 (*ckch_inst)->server = server;
3785 /* Keep the reference to the SSL_CTX in the server. */
3786 SSL_CTX_up_ref((*ckch_inst)->ctx);
3787 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003788 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003789 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003790 return errcode;
3791}
3792
William Lallemand6be66ec2020-03-06 22:26:32 +01003793
William Lallemand4c68bba2020-03-30 18:45:10 +02003794
3795
3796/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3797 * done once. Zero is returned if the operation fails. No error is returned
3798 * if the random is said as not implemented, because we expect that openssl
3799 * will use another method once needed.
3800 */
Amaury Denoyellec593bcd2021-05-19 15:35:29 +02003801int ssl_initialize_random(void)
William Lallemand4c68bba2020-03-30 18:45:10 +02003802{
3803 unsigned char random;
3804 static int random_initialized = 0;
3805
3806 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3807 random_initialized = 1;
3808
3809 return random_initialized;
3810}
3811
William Lallemand2954c472020-03-06 21:54:13 +01003812/* Load a crt-list file, this is done in 2 parts:
3813 * - store the content of the file in a crtlist structure with crtlist_entry structures
3814 * - generate the instances by iterating on entries in the crtlist struct
3815 *
3816 * Nothing is locked there, this function is used in the configuration parser.
3817 *
3818 * Returns a set of ERR_* flags possibly with an error in <err>.
3819 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003820int 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 +01003821{
3822 struct crtlist *crtlist = NULL;
3823 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003824 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003825 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003826 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003827 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003828
William Lallemand79d31ec2020-03-25 15:10:49 +01003829 bind_conf_node = malloc(sizeof(*bind_conf_node));
3830 if (!bind_conf_node) {
3831 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3832 cfgerr |= ERR_FATAL | ERR_ALERT;
3833 goto error;
3834 }
3835 bind_conf_node->next = NULL;
3836 bind_conf_node->bind_conf = bind_conf;
3837
William Lallemand41ca9302020-04-08 13:15:18 +02003838 /* strip trailing slashes, including first one */
3839 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3840 *end = 0;
3841
William Lallemand2954c472020-03-06 21:54:13 +01003842 /* look for an existing crtlist or create one */
3843 eb = ebst_lookup(&crtlists_tree, file);
3844 if (eb) {
3845 crtlist = ebmb_entry(eb, struct crtlist, node);
3846 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003847 /* load a crt-list OR a directory */
3848 if (dir)
3849 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3850 else
3851 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3852
William Lallemand2954c472020-03-06 21:54:13 +01003853 if (!(cfgerr & ERR_CODE))
3854 ebst_insert(&crtlists_tree, &crtlist->node);
3855 }
3856
3857 if (cfgerr & ERR_CODE) {
3858 cfgerr |= ERR_FATAL | ERR_ALERT;
3859 goto error;
3860 }
3861
3862 /* generates ckch instance from the crtlist_entry */
3863 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3864 struct ckch_store *store;
3865 struct ckch_inst *ckch_inst = NULL;
3866
3867 store = entry->node.key;
3868 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3869 if (cfgerr & ERR_CODE) {
3870 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3871 goto error;
3872 }
Willy Tarreau2b718102021-04-21 07:32:39 +02003873 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003874 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003875 }
William Lallemand2954c472020-03-06 21:54:13 +01003876
William Lallemand79d31ec2020-03-25 15:10:49 +01003877 /* add the bind_conf to the list */
3878 bind_conf_node->next = crtlist->bind_conf;
3879 crtlist->bind_conf = bind_conf_node;
3880
William Lallemand2954c472020-03-06 21:54:13 +01003881 return cfgerr;
3882error:
3883 {
William Lallemand49398312020-03-30 17:01:33 +02003884 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003885 struct ckch_inst *inst, *s_inst;
3886
William Lallemand49398312020-03-30 17:01:33 +02003887 lastentry = entry; /* which entry we tried to generate last */
3888 if (lastentry) {
3889 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3890 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3891 break;
3892
3893 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003894
William Lallemand49398312020-03-30 17:01:33 +02003895 /* this was not generated for this bind_conf, skip */
3896 if (inst->bind_conf != bind_conf)
3897 continue;
3898
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003899 /* free the sni_ctx and instance */
3900 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003901 }
William Lallemand2954c472020-03-06 21:54:13 +01003902 }
William Lallemand2954c472020-03-06 21:54:13 +01003903 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003904 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003905 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003906 return cfgerr;
3907}
3908
William Lallemand06b22a82020-03-16 14:45:55 +01003909/* Returns a set of ERR_* flags possibly with an error in <err>. */
3910int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3911{
3912 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01003913 int cfgerr = 0;
3914 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003915 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01003916 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01003917
3918 if ((ckchs = ckchs_lookup(path))) {
3919 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01003920 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3921 found++;
3922 } else if (stat(path, &buf) == 0) {
3923 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01003924 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003925 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003926 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003927 cfgerr |= ERR_ALERT | ERR_FATAL;
3928 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003929 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01003930 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003931 }
3932 } else {
3933 /* stat failed, could be a bundle */
3934 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02003935 char fp[MAXPATHLEN+1] = {0};
3936 int n = 0;
3937
3938 /* Load all possible certs and keys in separate ckch_store */
3939 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3940 struct stat buf;
3941 int ret;
3942
3943 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3944 if (ret > sizeof(fp))
3945 continue;
3946
3947 if ((ckchs = ckchs_lookup(fp))) {
3948 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01003949 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02003950 } else {
3951 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01003952 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003953 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02003954 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003955 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02003956 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3957 }
3958 }
3959 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01003960#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
3961 if (found) {
3962 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
3963 err && *err ? *err : "", path);
3964 cfgerr |= ERR_ALERT | ERR_FATAL;
3965 }
3966#endif
William Lallemand06b22a82020-03-16 14:45:55 +01003967 }
3968 }
William Lallemand06ce84a2020-11-20 15:36:13 +01003969 if (!found) {
3970 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3971 err && *err ? *err : "", path, strerror(errno));
3972 cfgerr |= ERR_ALERT | ERR_FATAL;
3973 }
William Lallemand06b22a82020-03-16 14:45:55 +01003974
3975 return cfgerr;
3976}
3977
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003978
3979/* Create a full ssl context and ckch instance that will be used for a specific
3980 * backend server (server configuration line).
3981 * Returns a set of ERR_* flags possibly with an error in <err>.
3982 */
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02003983int 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 +01003984{
3985 struct stat buf;
3986 int cfgerr = 0;
3987 struct ckch_store *ckchs;
3988 int found = 0; /* did we found a file to load ? */
3989
3990 if ((ckchs = ckchs_lookup(path))) {
3991 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01003992 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003993 found++;
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02003994 } else {
3995 if (!create_if_none) {
3996 memprintf(err, "%sunable to stat SSL certificate '%s'.\n",
3997 err && *err ? *err : "", path);
3998 cfgerr |= ERR_ALERT | ERR_FATAL;
3999 goto out;
4000 }
4001
4002 if (stat(path, &buf) == 0) {
4003 /* We do not manage directories on backend side. */
4004 if (S_ISDIR(buf.st_mode) == 0) {
4005 ++found;
4006 ckchs = ckchs_load_cert_file(path, err);
4007 if (!ckchs)
4008 cfgerr |= ERR_ALERT | ERR_FATAL;
4009 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
4010 }
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004011 }
4012 }
4013 if (!found) {
4014 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
4015 err && *err ? *err : "", path, strerror(errno));
4016 cfgerr |= ERR_ALERT | ERR_FATAL;
4017 }
4018
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004019out:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004020 return cfgerr;
4021}
4022
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004023/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004024static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004025ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004026{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004027 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004028 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004029 SSL_OP_ALL | /* all known workarounds for bugs */
4030 SSL_OP_NO_SSLv2 |
4031 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02004032 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02004033 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004034 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02004035 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004036 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004037 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004038 SSL_MODE_ENABLE_PARTIAL_WRITE |
4039 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004040 SSL_MODE_RELEASE_BUFFERS |
4041 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004042 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004043 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004044 int flags = MC_SSL_O_ALL;
4045 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02004046 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004047
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004048 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004049 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004050
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004051 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004052 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
4053 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4054 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004055 else
4056 flags = conf_ssl_methods->flags;
4057
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004058 min = conf_ssl_methods->min;
4059 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02004060
4061 /* default minimum is TLSV12, */
4062 if (!min) {
4063 if (!max || (max >= default_min_ver)) {
4064 min = default_min_ver;
4065 } else {
4066 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). "
4067 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
4068 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
4069 min = max;
4070 }
4071 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004072 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004073 if (min)
4074 flags |= (methodVersions[min].flag - 1);
4075 if (max)
4076 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004077 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004078 min = max = CONF_TLSV_NONE;
4079 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004080 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004081 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004082 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004083 if (min) {
4084 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004085 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
4086 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4087 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
4088 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004089 hole = 0;
4090 }
4091 max = i;
4092 }
4093 else {
4094 min = max = i;
4095 }
4096 }
4097 else {
4098 if (min)
4099 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004100 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004101 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004102 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4103 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004104 cfgerr += 1;
4105 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004106 /* save real min/max in bind_conf */
4107 conf_ssl_methods->min = min;
4108 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004109
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004110#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004111 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004112 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004113 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004114 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004115 else
William Lallemandd0712f32020-06-11 17:34:00 +02004116 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
4117 /* clear every version flags in case SSL_CTX_new()
4118 * returns an SSL_CTX with disabled versions */
4119 SSL_CTX_clear_options(ctx, methodVersions[i].option);
4120
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004121 if (flags & methodVersions[i].flag)
4122 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02004123
4124 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004125#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004126 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004127 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4128 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02004129#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004130
4131 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
4132 options |= SSL_OP_NO_TICKET;
4133 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
4134 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08004135
4136#ifdef SSL_OP_NO_RENEGOTIATION
4137 options |= SSL_OP_NO_RENEGOTIATION;
4138#endif
4139
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004140 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004141
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004142#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004143 if (global_ssl.async)
4144 mode |= SSL_MODE_ASYNC;
4145#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004146 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004147 if (global_ssl.life_time)
4148 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004149
4150#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand4b7938d2022-09-07 10:54:17 +02004151# ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004152 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
4153 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004154# elif defined(HAVE_SSL_CLIENT_HELLO_CB)
4155# if defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01004156 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01004157 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
William Lallemand4b7938d2022-09-07 10:54:17 +02004158# endif /* ! SSL_OP_NO_ANTI_REPLAY */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02004159 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
4160 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004161# else /* ! OPENSSL_IS_BORINGSSL && ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004162 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004163# endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02004164 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
William Lallemand4b7938d2022-09-07 10:54:17 +02004165#endif /* ! SSL_CTRL_SET_TLSEXT_HOSTNAME */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004166 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004167}
4168
William Lallemand4f45bb92017-10-30 20:08:51 +01004169
4170static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
4171{
4172 if (first == block) {
4173 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4174 if (first->len > 0)
4175 sh_ssl_sess_tree_delete(sh_ssl_sess);
4176 }
4177}
4178
4179/* return first block from sh_ssl_sess */
4180static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
4181{
4182 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
4183
4184}
4185
4186/* store a session into the cache
4187 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
4188 * data: asn1 encoded session
4189 * data_len: asn1 encoded session length
4190 * Returns 1 id session was stored (else 0)
4191 */
4192static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
4193{
4194 struct shared_block *first;
4195 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
4196
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004197 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01004198 if (!first) {
4199 /* Could not retrieve enough free blocks to store that session */
4200 return 0;
4201 }
4202
4203 /* STORE the key in the first elem */
4204 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4205 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
4206 first->len = sizeof(struct sh_ssl_sess_hdr);
4207
4208 /* it returns the already existing node
4209 or current node if none, never returns null */
4210 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
4211 if (oldsh_ssl_sess != sh_ssl_sess) {
4212 /* NOTE: Row couldn't be in use because we lock read & write function */
4213 /* release the reserved row */
4214 shctx_row_dec_hot(ssl_shctx, first);
4215 /* replace the previous session already in the tree */
4216 sh_ssl_sess = oldsh_ssl_sess;
4217 /* ignore the previous session data, only use the header */
4218 first = sh_ssl_sess_first_block(sh_ssl_sess);
4219 shctx_row_inc_hot(ssl_shctx, first);
4220 first->len = sizeof(struct sh_ssl_sess_hdr);
4221 }
4222
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004223 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01004224 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004225 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01004226 }
4227
4228 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004229
4230 return 1;
4231}
William Lallemanded0b5ad2017-10-30 19:36:36 +01004232
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004233/* SSL callback used when a new session is created while connecting to a server */
4234static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4235{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004236 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004237 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004238
Willy Tarreau07d94e42018-09-20 10:57:52 +02004239 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004240
William Lallemand3ce6eed2021-02-08 10:43:44 +01004241 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4242 * one cache per thread, it only prevents to flush it from the CLI in
4243 * another thread */
4244
Olivier Houcharde6060c52017-11-16 17:42:52 +01004245 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4246 int len;
4247 unsigned char *ptr;
William Lallemande18d4e82021-11-17 02:59:21 +01004248 const char *sni;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004249
Olivier Houcharde6060c52017-11-16 17:42:52 +01004250 len = i2d_SSL_SESSION(sess, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01004251 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004252 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004253 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4254 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4255 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004256 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
4257 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004258 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4259 }
4260 if (s->ssl_ctx.reused_sess[tid].ptr) {
4261 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4262 &ptr);
4263 }
William Lallemande18d4e82021-11-17 02:59:21 +01004264
4265 if (s->ssl_ctx.reused_sess[tid].sni) {
4266 /* if the new sni is empty or isn' t the same as the old one */
4267 if ((!sni) || strcmp(s->ssl_ctx.reused_sess[tid].sni, sni) != 0) {
4268 ha_free(&s->ssl_ctx.reused_sess[tid].sni);
4269 if (sni)
4270 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4271 }
4272 } else if (sni) {
4273 /* if there wasn't an old sni but there is a new one */
4274 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4275 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004276 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004277 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004278 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004279 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004280 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004281 }
4282
4283 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004284}
4285
Olivier Houcharde6060c52017-11-16 17:42:52 +01004286
William Lallemanded0b5ad2017-10-30 19:36:36 +01004287/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004288int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004289{
4290 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4291 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4292 unsigned char *p;
4293 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004294 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004295 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004296
4297 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004298 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004299 * note: SSL_SESSION_set1_id is using
4300 * a memcpy so we need to use a different pointer
4301 * than sid_data or sid_ctx_data to avoid valgrind
4302 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004303 */
4304
4305 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004306
4307 /* copy value in an other buffer */
4308 memcpy(encid, sid_data, sid_length);
4309
4310 /* pad with 0 */
4311 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4312 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4313
4314 /* force length to zero to avoid ASN1 encoding */
4315 SSL_SESSION_set1_id(sess, encid, 0);
4316
4317 /* force length to zero to avoid ASN1 encoding */
4318 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004319
4320 /* check if buffer is large enough for the ASN1 encoded session */
4321 data_len = i2d_SSL_SESSION(sess, NULL);
4322 if (data_len > SHSESS_MAX_DATA_LEN)
4323 goto err;
4324
4325 p = encsess;
4326
4327 /* process ASN1 session encoding before the lock */
4328 i2d_SSL_SESSION(sess, &p);
4329
William Lallemanded0b5ad2017-10-30 19:36:36 +01004330
William Lallemanda3c77cf2017-10-30 23:44:40 +01004331 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004332 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004333 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004334 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004335err:
4336 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004337 SSL_SESSION_set1_id(sess, encid, sid_length);
4338 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004339
4340 return 0; /* do not increment session reference count */
4341}
4342
4343/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004344SSL_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 +01004345{
William Lallemand4f45bb92017-10-30 20:08:51 +01004346 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004347 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4348 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004349 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004350 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004351
Willy Tarreau4c19e992021-06-15 16:39:22 +02004352 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004353
4354 /* allow the session to be freed automatically by openssl */
4355 *do_copy = 0;
4356
4357 /* tree key is zeros padded sessionid */
4358 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4359 memcpy(tmpkey, key, key_len);
4360 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4361 key = tmpkey;
4362 }
4363
4364 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004365 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004366
4367 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004368 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4369 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004370 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004371 shctx_unlock(ssl_shctx);
Willy Tarreau4c19e992021-06-15 16:39:22 +02004372 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004373 return NULL;
4374 }
4375
William Lallemand4f45bb92017-10-30 20:08:51 +01004376 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4377 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004378
William Lallemand4f45bb92017-10-30 20:08:51 +01004379 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 +01004380
William Lallemanda3c77cf2017-10-30 23:44:40 +01004381 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004382
4383 /* decode ASN1 session */
4384 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004385 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004386 /* Reset session id and session id contenxt */
4387 if (sess) {
4388 SSL_SESSION_set1_id(sess, key, key_len);
4389 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4390 }
4391
4392 return sess;
4393}
4394
William Lallemand4f45bb92017-10-30 20:08:51 +01004395
William Lallemanded0b5ad2017-10-30 19:36:36 +01004396/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004397void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004398{
William Lallemand4f45bb92017-10-30 20:08:51 +01004399 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004400 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4401 unsigned int sid_length;
4402 const unsigned char *sid_data;
4403 (void)ctx;
4404
4405 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4406 /* tree key is zeros padded sessionid */
4407 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4408 memcpy(tmpkey, sid_data, sid_length);
4409 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4410 sid_data = tmpkey;
4411 }
4412
William Lallemanda3c77cf2017-10-30 23:44:40 +01004413 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004414
4415 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004416 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4417 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004418 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004419 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004420 }
4421
4422 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004423 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004424}
4425
4426/* Set session cache mode to server and disable openssl internal cache.
4427 * Set shared cache callbacks on an ssl context.
4428 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004429void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004430{
4431 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4432
4433 if (!ssl_shctx) {
4434 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4435 return;
4436 }
4437
4438 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4439 SSL_SESS_CACHE_NO_INTERNAL |
4440 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4441
4442 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004443 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4444 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4445 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004446}
William Lallemand7d42ef52020-07-06 11:41:30 +02004447
4448/*
4449 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4450 *
4451 * The format is:
4452 * * <Label> <space> <ClientRandom> <space> <Secret>
4453 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4454 */
4455
William Lallemand722180a2021-06-09 16:46:12 +02004456#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004457void SSL_CTX_keylog(const SSL *ssl, const char *line)
4458{
4459 struct ssl_keylog *keylog;
4460 char *lastarg = NULL;
4461 char *dst = NULL;
4462
4463 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4464 if (!keylog)
4465 return;
4466
4467 lastarg = strrchr(line, ' ');
4468 if (lastarg == NULL || ++lastarg == NULL)
4469 return;
4470
4471 dst = pool_alloc(pool_head_ssl_keylog_str);
4472 if (!dst)
4473 return;
4474
4475 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4476 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4477
4478 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4479 if (keylog->client_random)
4480 goto error;
4481 keylog->client_random = dst;
4482
4483 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4484 if (keylog->client_early_traffic_secret)
4485 goto error;
4486 keylog->client_early_traffic_secret = dst;
4487
4488 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4489 if(keylog->client_handshake_traffic_secret)
4490 goto error;
4491 keylog->client_handshake_traffic_secret = dst;
4492
4493 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4494 if (keylog->server_handshake_traffic_secret)
4495 goto error;
4496 keylog->server_handshake_traffic_secret = dst;
4497
4498 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4499 if (keylog->client_traffic_secret_0)
4500 goto error;
4501 keylog->client_traffic_secret_0 = dst;
4502
4503 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4504 if (keylog->server_traffic_secret_0)
4505 goto error;
4506 keylog->server_traffic_secret_0 = dst;
4507
4508 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4509 if (keylog->early_exporter_secret)
4510 goto error;
4511 keylog->early_exporter_secret = dst;
4512
4513 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4514 if (keylog->exporter_secret)
4515 goto error;
4516 keylog->exporter_secret = dst;
4517 } else {
4518 goto error;
4519 }
4520
4521 return;
4522
4523error:
4524 pool_free(pool_head_ssl_keylog_str, dst);
4525
4526 return;
4527}
4528#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004529
William Lallemand8b453912019-11-21 15:48:10 +01004530/*
4531 * This function applies the SSL configuration on a SSL_CTX
4532 * It returns an error code and fills the <err> buffer
4533 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004534static 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 +01004535{
4536 struct proxy *curproxy = bind_conf->frontend;
4537 int cfgerr = 0;
4538 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004539 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004540 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004541#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004542 const char *conf_ciphersuites;
4543#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004544 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004545
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004546 if (ssl_conf) {
4547 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4548 int i, min, max;
4549 int flags = MC_SSL_O_ALL;
4550
4551 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004552 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4553 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004554 if (min)
4555 flags |= (methodVersions[min].flag - 1);
4556 if (max)
4557 flags |= ~((methodVersions[max].flag << 1) - 1);
4558 min = max = CONF_TLSV_NONE;
4559 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4560 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4561 if (min)
4562 max = i;
4563 else
4564 min = max = i;
4565 }
4566 /* save real min/max */
4567 conf_ssl_methods->min = min;
4568 conf_ssl_methods->max = max;
4569 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004570 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4571 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004572 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004573 }
4574 }
4575
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004576 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004577 case SSL_SOCK_VERIFY_NONE:
4578 verify = SSL_VERIFY_NONE;
4579 break;
4580 case SSL_SOCK_VERIFY_OPTIONAL:
4581 verify = SSL_VERIFY_PEER;
4582 break;
4583 case SSL_SOCK_VERIFY_REQUIRED:
4584 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4585 break;
4586 }
4587 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4588 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004589 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 +01004590 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 +01004591 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 +01004592 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004593 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004594 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004595 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004596 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004597 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004598 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004599 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4600 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4601 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4602 cfgerr |= ERR_ALERT | ERR_FATAL;
4603 }
4604 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004605 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004606 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 +02004607 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004608 }
Emeric Brun850efd52014-01-29 12:24:34 +01004609 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004610 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4611 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004612 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004613 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004614#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004615 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004616 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4617
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004618 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004619 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4620 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004621 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004622 }
Emeric Brun561e5742012-10-02 15:20:55 +02004623 else {
4624 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4625 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004626 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004627#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004628 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004629 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004630#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004631 if(bind_conf->keys_ref) {
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +01004632 if (!SSL_CTX_set_tlsext_ticket_key_evp_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004633 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4634 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004635 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004636 }
4637 }
4638#endif
4639
William Lallemand4f45bb92017-10-30 20:08:51 +01004640 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004641 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4642 if (conf_ciphers &&
4643 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004644 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4645 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004646 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004647 }
4648
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004649#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004650 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4651 if (conf_ciphersuites &&
4652 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004653 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4654 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004655 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004656 }
4657#endif
4658
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004659#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02004660 if (!local_dh_1024)
4661 local_dh_1024 = ssl_get_dh_1024();
4662 if (!local_dh_2048)
4663 local_dh_2048 = ssl_get_dh_2048();
4664 if (!local_dh_4096)
4665 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02004666#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004667
Emeric Brunfc0421f2012-09-07 17:30:07 +02004668 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004669#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004670 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004671#endif
William Lallemand722180a2021-06-09 16:46:12 +02004672#ifdef HAVE_SSL_KEYLOG
William Lallemandb60a77b2022-11-18 15:00:15 +01004673 /* only activate the keylog callback if it was required to prevent performance loss */
4674 if (global_ssl.keylog > 0)
4675 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02004676#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004677
Bernard Spil13c53f82018-02-15 13:34:58 +01004678#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004679 ssl_conf_cur = NULL;
4680 if (ssl_conf && ssl_conf->npn_str)
4681 ssl_conf_cur = ssl_conf;
4682 else if (bind_conf->ssl_conf.npn_str)
4683 ssl_conf_cur = &bind_conf->ssl_conf;
4684 if (ssl_conf_cur)
4685 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004686#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004687#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004688 ssl_conf_cur = NULL;
4689 if (ssl_conf && ssl_conf->alpn_str)
4690 ssl_conf_cur = ssl_conf;
4691 else if (bind_conf->ssl_conf.alpn_str)
4692 ssl_conf_cur = &bind_conf->ssl_conf;
4693 if (ssl_conf_cur)
4694 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004695#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004696#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004697 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4698 if (conf_curves) {
4699 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004700 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4701 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004702 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004703 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004704 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004705 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004706#endif /* defined(SSL_CTX_set1_curves_list) */
4707
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004708 if (!conf_curves) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004709#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004710#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004711 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004712 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4713 NULL);
4714
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004715 if (ecdhe && SSL_CTX_set1_curves_list(ctx, ecdhe) == 0) {
4716 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4717 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
4718 cfgerr |= ERR_ALERT | ERR_FATAL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02004719 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004720#endif /* defined(SSL_CTX_set1_curves_list) */
Olivier Houchardc2aae742017-09-22 18:26:28 +02004721#else
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004722#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
4723 int i;
4724 EC_KEY *ecdh;
4725
Olivier Houchardc2aae742017-09-22 18:26:28 +02004726 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4727 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4728 ECDHE_DEFAULT_CURVE);
Emeric Brun2b58d042012-09-20 17:10:03 +02004729
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004730 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004731 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004732 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 +01004733 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004734 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004735 }
4736 else {
4737 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4738 EC_KEY_free(ecdh);
4739 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004740#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
4741#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Emeric Brun2b58d042012-09-20 17:10:03 +02004742 }
Emeric Brun2b58d042012-09-20 17:10:03 +02004743
Emeric Brunfc0421f2012-09-07 17:30:07 +02004744 return cfgerr;
4745}
4746
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004747
4748/*
4749 * Prepare the SSL_CTX based on the bind line configuration.
4750 * Since the CA file loading is made depending on the verify option of the bind
4751 * line, the link between the SSL_CTX and the CA file tree entry is made here.
4752 * If we want to create a link between the CA file entry and the corresponding
4753 * ckch instance (for CA file hot update), it needs to be done after
4754 * ssl_sock_prepare_ctx.
4755 * Returns 0 in case of success.
4756 */
4757int ssl_sock_prep_ctx_and_inst(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
4758 SSL_CTX *ctx, struct ckch_inst *ckch_inst, char **err)
4759{
4760 int errcode = 0;
4761
4762 errcode |= ssl_sock_prepare_ctx(bind_conf, ssl_conf, ctx, err);
4763 if (!errcode && ckch_inst)
4764 ckch_inst_add_cafile_link(ckch_inst, bind_conf, ssl_conf, NULL);
4765
4766 return errcode;
4767}
4768
Evan Broderbe554312013-06-27 00:05:25 -07004769static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4770{
4771 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4772 size_t prefixlen, suffixlen;
4773
4774 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004775 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004776 return 1;
4777
Evan Broderbe554312013-06-27 00:05:25 -07004778 /* The rest of this logic is based on RFC 6125, section 6.4.3
4779 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4780
Emeric Bruna848dae2013-10-08 11:27:28 +02004781 pattern_wildcard = NULL;
4782 pattern_left_label_end = pattern;
4783 while (*pattern_left_label_end != '.') {
4784 switch (*pattern_left_label_end) {
4785 case 0:
4786 /* End of label not found */
4787 return 0;
4788 case '*':
4789 /* If there is more than one wildcards */
4790 if (pattern_wildcard)
4791 return 0;
4792 pattern_wildcard = pattern_left_label_end;
4793 break;
4794 }
4795 pattern_left_label_end++;
4796 }
4797
4798 /* If it's not trivial and there is no wildcard, it can't
4799 * match */
4800 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004801 return 0;
4802
4803 /* Make sure all labels match except the leftmost */
4804 hostname_left_label_end = strchr(hostname, '.');
4805 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004806 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004807 return 0;
4808
4809 /* Make sure the leftmost label of the hostname is long enough
4810 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004811 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004812 return 0;
4813
4814 /* Finally compare the string on either side of the
4815 * wildcard */
4816 prefixlen = pattern_wildcard - pattern;
4817 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004818 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4819 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004820 return 0;
4821
4822 return 1;
4823}
4824
4825static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4826{
4827 SSL *ssl;
4828 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004829 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004830 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004831 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004832
4833 int depth;
4834 X509 *cert;
4835 STACK_OF(GENERAL_NAME) *alt_names;
4836 int i;
4837 X509_NAME *cert_subject;
4838 char *str;
4839
4840 if (ok == 0)
4841 return ok;
4842
4843 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004844 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02004845 ssl_ctx = __conn_get_ssl_sock_ctx(conn);
Evan Broderbe554312013-06-27 00:05:25 -07004846
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004847 /* We're checking if the provided hostnames match the desired one. The
4848 * desired hostname comes from the SNI we presented if any, or if not
4849 * provided then it may have been explicitly stated using a "verifyhost"
4850 * directive. If neither is set, we don't care about the name so the
4851 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004852 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004853 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004854 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004855 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004856 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004857 if (!servername)
4858 return ok;
4859 }
Evan Broderbe554312013-06-27 00:05:25 -07004860
4861 /* We only need to verify the CN on the actual server cert,
4862 * not the indirect CAs */
4863 depth = X509_STORE_CTX_get_error_depth(ctx);
4864 if (depth != 0)
4865 return ok;
4866
4867 /* At this point, the cert is *not* OK unless we can find a
4868 * hostname match */
4869 ok = 0;
4870
4871 cert = X509_STORE_CTX_get_current_cert(ctx);
4872 /* It seems like this might happen if verify peer isn't set */
4873 if (!cert)
4874 return ok;
4875
4876 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4877 if (alt_names) {
4878 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4879 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4880 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004881#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004882 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4883#else
Evan Broderbe554312013-06-27 00:05:25 -07004884 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004885#endif
Evan Broderbe554312013-06-27 00:05:25 -07004886 ok = ssl_sock_srv_hostcheck(str, servername);
4887 OPENSSL_free(str);
4888 }
4889 }
4890 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004891 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004892 }
4893
4894 cert_subject = X509_get_subject_name(cert);
4895 i = -1;
4896 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4897 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004898 ASN1_STRING *value;
4899 value = X509_NAME_ENTRY_get_data(entry);
4900 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004901 ok = ssl_sock_srv_hostcheck(str, servername);
4902 OPENSSL_free(str);
4903 }
4904 }
4905
Willy Tarreau71d058c2017-07-26 20:09:56 +02004906 /* report the mismatch and indicate if SNI was used or not */
4907 if (!ok && !conn->err_code)
4908 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004909 return ok;
4910}
4911
Emeric Brun94324a42012-10-11 14:00:19 +02004912/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004913int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004914{
4915 int cfgerr = 0;
William Lallemand2c776f12021-12-28 18:47:17 +01004916 SSL_CTX *ctx;
William Lallemand0adafb32022-12-13 18:17:44 +01004917 /* Automatic memory computations need to know we use SSL there
4918 * If this is an internal proxy, don't use it for the computation */
William Lallemand04007cb2022-12-14 10:34:36 +01004919 if (!(srv->proxy->cap & PR_CAP_INT))
William Lallemand0adafb32022-12-13 18:17:44 +01004920 global.ssl_used_backend = 1;
Willy Tarreaufce03112015-01-15 21:32:40 +01004921
4922 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004923 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004924 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004925 ha_alert("out of memory.\n");
Emeric Brun821bb9b2017-06-15 16:37:39 +02004926 cfgerr++;
4927 return cfgerr;
4928 }
4929 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004930 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004931 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004932
William Lallemand2c776f12021-12-28 18:47:17 +01004933 if (srv->ssl_ctx.client_crt) {
4934 const int create_if_none = srv->flags & SRV_F_DYNAMIC ? 0 : 1;
4935 char *err = NULL;
4936 int err_code = 0;
4937
4938 /* If there is a crt keyword there, the SSL_CTX will be created here. */
4939 err_code = ssl_sock_load_srv_cert(srv->ssl_ctx.client_crt, srv, create_if_none, &err);
4940 if (err_code != ERR_NONE) {
4941 if ((err_code & ERR_WARN) && !(err_code & ERR_ALERT))
4942 ha_warning("%s", err);
4943 else
4944 ha_alert("%s", err);
4945
4946 if (err_code & (ERR_FATAL|ERR_ABORT))
4947 cfgerr++;
4948 }
4949 ha_free(&err);
4950 }
4951
4952 ctx = srv->ssl_ctx.ctx;
4953
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004954 /* The context will be uninitialized if there wasn't any "cert" option
4955 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004956 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004957 ctx = SSL_CTX_new(SSLv23_client_method());
4958 if (!ctx) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004959 ha_alert("unable to allocate ssl context.\n");
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004960 cfgerr++;
4961 return cfgerr;
4962 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004963
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004964 srv->ssl_ctx.ctx = ctx;
4965 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004966
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004967 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 +01004968
4969 return cfgerr;
4970}
4971
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004972/* Initialize an SSL context that will be used on the backend side.
4973 * Returns an error count.
4974 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004975static int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004976{
4977 struct proxy *curproxy = srv->proxy;
4978 int cfgerr = 0;
4979 long options =
4980 SSL_OP_ALL | /* all known workarounds for bugs */
4981 SSL_OP_NO_SSLv2 |
4982 SSL_OP_NO_COMPRESSION;
4983 long mode =
4984 SSL_MODE_ENABLE_PARTIAL_WRITE |
4985 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
4986 SSL_MODE_RELEASE_BUFFERS |
4987 SSL_MODE_SMALL_BUFFERS;
4988 int verify = SSL_VERIFY_NONE;
4989 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
4990 int i, min, max, hole;
4991 int flags = MC_SSL_O_ALL;
4992
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004993 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004994 ha_warning("no-sslv3/no-tlsv1x are ignored for this server. "
4995 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n");
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004996 else
4997 flags = conf_ssl_methods->flags;
4998
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004999 /* Real min and max should be determinate with configuration and openssl's capabilities */
5000 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005001 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005002 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005003 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005004
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005005 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005006 min = max = CONF_TLSV_NONE;
5007 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005008 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005009 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005010 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005011 if (min) {
5012 if (hole) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005013 ha_warning("%s '%s': SSL/TLS versions range not contiguous for server '%s'. "
Christopher Faulet767a84b2017-11-24 16:50:31 +01005014 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
5015 proxy_type_str(curproxy), curproxy->id, srv->id,
5016 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005017 hole = 0;
5018 }
5019 max = i;
5020 }
5021 else {
5022 min = max = i;
5023 }
5024 }
5025 else {
5026 if (min)
5027 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005028 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005029 if (!min) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005030 ha_alert("%s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01005031 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005032 cfgerr += 1;
5033 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005034
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005035#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005036 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08005037 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005038 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005039 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005040 else
5041 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
5042 if (flags & methodVersions[i].flag)
5043 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005044#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005045 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005046 methodVersions[min].ctx_set_version(ctx, SET_MIN);
5047 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005048#endif
5049
5050 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
5051 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005052 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005053
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005054#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005055 if (global_ssl.async)
5056 mode |= SSL_MODE_ASYNC;
5057#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005058 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005059
Emeric Brun850efd52014-01-29 12:24:34 +01005060 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
5061 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01005062 switch (srv->ssl_ctx.verify) {
5063 case SSL_SOCK_VERIFY_NONE:
5064 verify = SSL_VERIFY_NONE;
5065 break;
5066 case SSL_SOCK_VERIFY_REQUIRED:
5067 verify = SSL_VERIFY_PEER;
5068 break;
5069 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005070 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02005071 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01005072 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02005073 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02005074 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005075 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005076 ha_alert("unable to set CA file '%s'.\n",
5077 srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005078 cfgerr++;
5079 }
5080 }
Emeric Brun850efd52014-01-29 12:24:34 +01005081 else {
5082 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005083 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 +01005084 else
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005085 ha_alert("verify is enabled but no CA file specified.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01005086 cfgerr++;
5087 }
Emeric Brunef42d922012-10-11 16:11:36 +02005088#ifdef X509_V_FLAG_CRL_CHECK
5089 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005090 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02005091
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01005092 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005093 ha_alert("unable to configure CRL file '%s'.\n",
5094 srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005095 cfgerr++;
5096 }
5097 else {
5098 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5099 }
5100 }
5101#endif
5102 }
5103
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005104 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5105 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02005106 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005107 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005108 ha_alert("unable to set SSL cipher list to '%s'.\n",
5109 srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02005110 cfgerr++;
5111 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005112
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05005113#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005114 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005115 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005116 ha_alert("unable to set TLS 1.3 cipher suites to '%s'.\n",
5117 srv->ssl_ctx.ciphersuites);
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005118 cfgerr++;
5119 }
5120#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01005121#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
5122 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005123 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01005124#endif
5125#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5126 if (srv->ssl_ctx.alpn_str)
5127 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
5128#endif
5129
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005130
5131 return cfgerr;
5132}
5133
5134/*
5135 * Prepare the frontend's SSL_CTX based on the server line configuration.
5136 * Since the CA file loading is made depending on the verify option of the
5137 * server line, the link between the SSL_CTX and the CA file tree entry is
5138 * made here.
5139 * If we want to create a link between the CA file entry and the corresponding
5140 * ckch instance (for CA file hot update), it needs to be done after
5141 * ssl_sock_prepare_srv_ssl_ctx.
5142 * Returns an error count.
5143 */
5144int ssl_sock_prep_srv_ctx_and_inst(const struct server *srv, SSL_CTX *ctx,
5145 struct ckch_inst *ckch_inst)
5146{
5147 int cfgerr = 0;
5148
5149 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, ctx);
5150 if (!cfgerr && ckch_inst)
5151 ckch_inst_add_cafile_link(ckch_inst, NULL, NULL, srv);
Emeric Brun94324a42012-10-11 14:00:19 +02005152
5153 return cfgerr;
5154}
5155
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005156
Frédéric Lécailleec216522020-11-23 14:33:30 +01005157/*
5158 * Create an initial CTX used to start the SSL connections.
5159 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
5160 * Returns 0 if succeeded, or something >0 if not.
5161 */
5162#ifdef USE_QUIC
5163static int ssl_initial_ctx(struct bind_conf *bind_conf)
5164{
5165 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
5166 return ssl_quic_initial_ctx(bind_conf);
5167 else
5168 return ssl_sock_initial_ctx(bind_conf);
5169}
5170#else
5171static int ssl_initial_ctx(struct bind_conf *bind_conf)
5172{
5173 return ssl_sock_initial_ctx(bind_conf);
5174}
5175#endif
5176
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005177/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005178 * be NULL, in which case nothing is done. Returns the number of errors
5179 * encountered.
5180 */
Willy Tarreau03209342016-12-22 17:08:28 +01005181int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005182{
5183 struct ebmb_node *node;
5184 struct sni_ctx *sni;
5185 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01005186 int errcode = 0;
5187 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02005188
Willy Tarreaufce03112015-01-15 21:32:40 +01005189 /* Automatic memory computations need to know we use SSL there */
5190 global.ssl_used_frontend = 1;
5191
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005192 /* Create initial_ctx used to start the ssl connection before do switchctx */
5193 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01005194 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005195 /* It should not be necessary to call this function, but it's
5196 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01005197 to initial_ctx in ssl_initial_ctx. */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005198 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, NULL, bind_conf->initial_ctx, NULL, &errmsg);
5199 }
5200 if (bind_conf->default_ctx) {
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005201 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 +01005202 }
Emeric Brun0bed9942014-10-30 19:25:24 +01005203
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005204 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005205 while (node) {
5206 sni = ebmb_entry(node, struct sni_ctx, name);
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005207 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005208 /* only initialize the CTX on its first occurrence and
5209 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005210 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
5211 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005212 node = ebmb_next(node);
5213 }
5214
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005215 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005216 while (node) {
5217 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01005218 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005219 /* only initialize the CTX on its first occurrence and
5220 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005221 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005222 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005223 node = ebmb_next(node);
5224 }
William Lallemand8b453912019-11-21 15:48:10 +01005225
5226 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005227 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005228 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005229 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005230 err++;
5231 }
5232
5233 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005234 return err;
5235}
5236
Willy Tarreau55d37912016-12-21 23:38:39 +01005237/* Prepares all the contexts for a bind_conf and allocates the shared SSL
5238 * context if needed. Returns < 0 on error, 0 on success. The warnings and
5239 * alerts are directly emitted since the rest of the stack does it below.
5240 */
5241int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
5242{
5243 struct proxy *px = bind_conf->frontend;
5244 int alloc_ctx;
5245 int err;
5246
Willy Tarreau11ba4042022-05-20 15:56:32 +02005247 if (!(bind_conf->options & BC_O_USE_SSL)) {
Willy Tarreau55d37912016-12-21 23:38:39 +01005248 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005249 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
5250 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01005251 }
5252 return 0;
5253 }
5254 if (!bind_conf->default_ctx) {
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005255 if (bind_conf->strict_sni && !(bind_conf->options & BC_O_GENERATE_CERTS)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005256 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5257 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005258 }
5259 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005260 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5261 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005262 return -1;
5263 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005264 }
William Lallemandc61c0b32017-12-04 18:46:39 +01005265 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005266 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02005267 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
Willy Tarreau91358592021-06-15 08:08:04 +02005268 sizeof(*sh_ssl_sess_tree), (global.nbthread > 1));
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02005269 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005270 if (alloc_ctx == SHCTX_E_INIT_LOCK)
5271 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");
5272 else
5273 ha_alert("Unable to allocate SSL session cache.\n");
5274 return -1;
5275 }
5276 /* free block callback */
5277 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5278 /* init the root tree within the extra space */
5279 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5280 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01005281 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005282 err = 0;
5283 /* initialize all certificate contexts */
5284 err += ssl_sock_prepare_all_ctx(bind_conf);
5285
5286 /* initialize CA variables if the certificates generation is enabled */
5287 err += ssl_sock_load_ca(bind_conf);
5288
5289 return -err;
5290}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005291
William Lallemand231610a2021-12-30 11:25:43 +01005292/* release ssl context allocated for servers. Most of the field free here
5293 * must also be allocated in srv_ssl_settings_cpy() */
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005294void ssl_sock_free_srv_ctx(struct server *srv)
5295{
Olivier Houchardc7566002018-11-20 23:33:50 +01005296#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
William Lallemand231610a2021-12-30 11:25:43 +01005297 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005298#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005299#ifdef OPENSSL_NPN_NEGOTIATED
William Lallemand231610a2021-12-30 11:25:43 +01005300 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005301#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005302 if (srv->ssl_ctx.reused_sess) {
5303 int i;
5304
William Lallemande18d4e82021-11-17 02:59:21 +01005305 for (i = 0; i < global.nbthread; i++) {
Willy Tarreaue709e822021-02-26 21:06:32 +01005306 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
William Lallemande18d4e82021-11-17 02:59:21 +01005307 ha_free(&srv->ssl_ctx.reused_sess[i].sni);
5308 }
Willy Tarreaue709e822021-02-26 21:06:32 +01005309 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005310 }
5311
Willy Tarreaue709e822021-02-26 21:06:32 +01005312 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005313 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005314 srv->ssl_ctx.ctx = NULL;
5315 }
William Lallemand231610a2021-12-30 11:25:43 +01005316
5317 ha_free(&srv->ssl_ctx.ca_file);
5318 ha_free(&srv->ssl_ctx.crl_file);
5319 ha_free(&srv->ssl_ctx.client_crt);
5320 ha_free(&srv->ssl_ctx.verify_host);
5321#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5322 ha_free(&srv->sni_expr);
William Lallemand43c2ce42022-03-16 17:48:19 +01005323 release_sample_expr(srv->ssl_ctx.sni);
5324 srv->ssl_ctx.sni = NULL;
William Lallemand231610a2021-12-30 11:25:43 +01005325#endif
5326 ha_free(&srv->ssl_ctx.ciphers);
5327#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
5328 ha_free(&srv->ssl_ctx.ciphersuites);
5329#endif
William Lallemande69563f2021-12-30 14:45:19 +01005330 /* If there is a certificate we must unlink the ckch instance */
5331 ckch_inst_free(srv->ssl_ctx.inst);
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005332}
5333
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005334/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005335 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5336 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005337void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005338{
5339 struct ebmb_node *node, *back;
5340 struct sni_ctx *sni;
5341
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005342 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005343 while (node) {
5344 sni = ebmb_entry(node, struct sni_ctx, name);
5345 back = ebmb_next(node);
5346 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005347 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005348 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005349 free(sni);
5350 node = back;
5351 }
5352
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005353 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005354 while (node) {
5355 sni = ebmb_entry(node, struct sni_ctx, name);
5356 back = ebmb_next(node);
5357 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005358 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005359 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005360 free(sni);
5361 node = back;
5362 }
William Lallemandb2408692020-06-24 09:54:29 +02005363
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005364 SSL_CTX_free(bind_conf->initial_ctx);
5365 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005366 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005367 bind_conf->default_ctx = NULL;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005368 bind_conf->default_inst = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005369 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005370}
William Lallemandb2408692020-06-24 09:54:29 +02005371
5372
5373void ssl_sock_deinit()
5374{
5375 crtlist_deinit(); /* must be free'd before the ckchs */
5376 ckch_deinit();
5377}
5378REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005379
Willy Tarreau795cdab2016-12-22 17:30:54 +01005380/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5381void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5382{
5383 ssl_sock_free_ca(bind_conf);
5384 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005385 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005386 free(bind_conf->ca_sign_file);
5387 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005388 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005389 free(bind_conf->keys_ref->filename);
5390 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005391 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005392 free(bind_conf->keys_ref);
5393 }
5394 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005395 bind_conf->ca_sign_pass = NULL;
5396 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005397}
5398
Christopher Faulet31af49d2015-06-09 17:29:50 +02005399/* Load CA cert file and private key used to generate certificates */
5400int
Willy Tarreau03209342016-12-22 17:08:28 +01005401ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005402{
Willy Tarreau03209342016-12-22 17:08:28 +01005403 struct proxy *px = bind_conf->frontend;
William Lallemand52ddd992022-11-22 11:51:53 +01005404 struct ckch_data *data = NULL;
Shimi Gersner5846c492020-08-23 13:58:12 +03005405 int ret = 0;
5406 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005407
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005408 if (!(bind_conf->options & BC_O_GENERATE_CERTS))
Shimi Gersner5846c492020-08-23 13:58:12 +03005409 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005410
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005411#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005412 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005413 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005414 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005415 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005416 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005417#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005418
Christopher Faulet31af49d2015-06-09 17:29:50 +02005419 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005420 ha_alert("Proxy '%s': cannot enable certificate generation, "
5421 "no CA certificate File configured at [%s:%d].\n",
5422 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005423 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005424 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005425
Shimi Gersner5846c492020-08-23 13:58:12 +03005426 /* Allocate cert structure */
William Lallemand52ddd992022-11-22 11:51:53 +01005427 data = calloc(1, sizeof(*data));
5428 if (!data) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005429 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5430 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5431 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005432 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005433
5434 /* Try to parse file */
William Lallemand52ddd992022-11-22 11:51:53 +01005435 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, data, &err)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005436 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5437 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005438 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005439 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005440 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005441
5442 /* Fail if missing cert or pkey */
William Lallemand52ddd992022-11-22 11:51:53 +01005443 if ((!data->cert) || (!data->key)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005444 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5445 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5446 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005447 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005448
Shimi Gersner5846c492020-08-23 13:58:12 +03005449 /* Final assignment to bind */
William Lallemand52ddd992022-11-22 11:51:53 +01005450 bind_conf->ca_sign_ckch = data;
Shimi Gersner5846c492020-08-23 13:58:12 +03005451 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005452
Shimi Gersner5846c492020-08-23 13:58:12 +03005453 failed:
William Lallemand52ddd992022-11-22 11:51:53 +01005454 if (data) {
5455 ssl_sock_free_cert_key_and_chain_contents(data);
5456 free(data);
Shimi Gersner5846c492020-08-23 13:58:12 +03005457 }
5458
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005459 bind_conf->options &= ~BC_O_GENERATE_CERTS;
Shimi Gersner5846c492020-08-23 13:58:12 +03005460 ret++;
5461 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005462}
5463
5464/* Release CA cert and private key used to generate certificated */
5465void
5466ssl_sock_free_ca(struct bind_conf *bind_conf)
5467{
Shimi Gersner5846c492020-08-23 13:58:12 +03005468 if (bind_conf->ca_sign_ckch) {
5469 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005470 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005471 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005472}
5473
Emeric Brun46591952012-05-18 15:47:34 +02005474/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005475 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5476 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5477 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5478 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005479 * 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 +01005480 * as parameters to this function.
5481 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5482 * CO_ER_SSL_NO_MEM.
5483 */
5484int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5485 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5486{
5487 int retry = 1;
5488
5489 retry:
5490 /* Alloc a new SSL session. */
5491 *ssl = SSL_new(ssl_ctx);
5492 if (!*ssl) {
5493 if (!retry--)
5494 goto err;
5495
5496 pool_gc(NULL);
5497 goto retry;
5498 }
5499
5500 *bio = BIO_new(bio_meth);
5501 if (!*bio) {
5502 SSL_free(*ssl);
5503 *ssl = NULL;
5504 if (!retry--)
5505 goto err;
5506
5507 pool_gc(NULL);
5508 goto retry;
5509 }
5510
5511 BIO_set_data(*bio, ctx);
5512 SSL_set_bio(*ssl, *bio, *bio);
5513
5514 /* set connection pointer. */
5515 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5516 SSL_free(*ssl);
5517 *ssl = NULL;
5518 if (!retry--)
5519 goto err;
5520
5521 pool_gc(NULL);
5522 goto retry;
5523 }
5524
5525 return 0;
5526
5527 err:
5528 conn->err_code = CO_ER_SSL_NO_MEM;
5529 return -1;
5530}
5531
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005532/* This function is called when all the XPRT have been initialized. We can
5533 * now attempt to start the SSL handshake.
5534 */
5535static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5536{
5537 struct ssl_sock_ctx *ctx = xprt_ctx;
5538
5539 if (ctx->xprt->start) {
5540 int ret;
5541
5542 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5543 if (ret < 0)
5544 return ret;
5545 }
5546 tasklet_wakeup(ctx->wait_event.tasklet);
5547
5548 return 0;
5549}
5550
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005551/*
Emeric Brun46591952012-05-18 15:47:34 +02005552 * This function is called if SSL * context is not yet allocated. The function
5553 * is designed to be called before any other data-layer operation and sets the
5554 * handshake flag on the connection. It is safe to call it multiple times.
5555 * It returns 0 on success and -1 in error case.
5556 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005557static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005558{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005559 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005560 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005561 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005562 return 0;
5563
Olivier Houchard66ab4982019-02-26 18:37:15 +01005564 ctx = pool_alloc(ssl_sock_ctx_pool);
5565 if (!ctx) {
5566 conn->err_code = CO_ER_SSL_NO_MEM;
5567 return -1;
5568 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005569 ctx->wait_event.tasklet = tasklet_new();
5570 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005571 conn->err_code = CO_ER_SSL_NO_MEM;
5572 pool_free(ssl_sock_ctx_pool, ctx);
5573 return -1;
5574 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005575 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5576 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005577 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005578 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005579 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005580 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005581 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005582 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005583 ctx->xprt_st = 0;
5584 ctx->xprt_ctx = NULL;
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005585 ctx->error_code = 0;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005586
5587 /* Only work with sockets for now, this should be adapted when we'll
5588 * add QUIC support.
5589 */
5590 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005591 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005592 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5593 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005594 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005595
Willy Tarreau82531f62021-10-06 12:15:18 +02005596 if (global.maxsslconn && global.sslconns >= global.maxsslconn) {
Willy Tarreau20879a02012-12-03 16:32:10 +01005597 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005598 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005599 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005600
Emeric Brun46591952012-05-18 15:47:34 +02005601 /* If it is in client mode initiate SSL session
5602 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005603 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005604 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5605 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005606 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005607
Olivier Houchard66ab4982019-02-26 18:37:15 +01005608 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005609 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005610 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5611 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5612 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 +01005613 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005614 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005615 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005616 } else if (sess) {
5617 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005618 }
5619 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005620 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005621
Emeric Brun46591952012-05-18 15:47:34 +02005622 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005623 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005624
Willy Tarreau82531f62021-10-06 12:15:18 +02005625 _HA_ATOMIC_INC(&global.sslconns);
5626 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005627 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005628 return 0;
5629 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005630 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005631 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005632
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005633 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5634 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005635 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005636
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005637#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005638 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005639 b_alloc(&ctx->early_buf);
5640 SSL_set_max_early_data(ctx->ssl,
5641 /* Only allow early data if we managed to allocate
5642 * a buffer.
5643 */
5644 (!b_is_null(&ctx->early_buf)) ?
5645 global.tune.bufsize - global.tune.maxrewrite : 0);
5646 }
5647#endif
5648
Olivier Houchard66ab4982019-02-26 18:37:15 +01005649 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005650
Emeric Brun46591952012-05-18 15:47:34 +02005651 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005652 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005653#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005654 if (bc->ssl_conf.early_data)
5655 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005656#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005657
Willy Tarreau82531f62021-10-06 12:15:18 +02005658 _HA_ATOMIC_INC(&global.sslconns);
5659 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005660 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005661 return 0;
5662 }
5663 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005664 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005665err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005666 if (ctx && ctx->wait_event.tasklet)
5667 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005668 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005669 return -1;
5670}
5671
5672
5673/* This is the callback which is used when an SSL handshake is pending. It
5674 * updates the FD status if it wants some polling before being called again.
5675 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5676 * otherwise it returns non-zero and removes itself from the connection's
5677 * flags (the bit is provided in <flag> by the caller).
5678 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005679static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005680{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005681 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Emeric Brun46591952012-05-18 15:47:34 +02005682 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005683 struct ssl_counters *counters = NULL;
5684 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005685 struct listener *li;
5686 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005687 socklen_t lskerr;
5688 int skerr;
5689
Emeric Brun46591952012-05-18 15:47:34 +02005690
Willy Tarreau3c728722014-01-23 13:50:42 +01005691 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005692 return 0;
5693
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005694 /* get counters */
5695 switch (obj_type(conn->target)) {
5696 case OBJ_TYPE_LISTENER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005697 li = __objt_listener(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005698 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5699 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5700 &ssl_stats_module);
5701 break;
5702
5703 case OBJ_TYPE_SERVER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005704 srv = __objt_server(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005705 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5706 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5707 &ssl_stats_module);
5708 break;
5709
5710 default:
5711 break;
5712 }
5713
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005714 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005715 goto out_error;
5716
Willy Tarreau06300382021-02-02 15:42:25 +01005717 /* don't start calculating a handshake on a dead connection */
5718 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5719 goto out_error;
5720
5721 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5722 * status from the lower layers, so let's check the FD directly. Ideally
5723 * the xprt layers should provide some status indicating their knowledge
5724 * of shutdowns or error.
5725 */
Willy Tarreau07ecfc52022-04-11 18:07:03 +02005726 BUG_ON(conn->flags & CO_FL_FDLESS);
5727
Willy Tarreau06300382021-02-02 15:42:25 +01005728 skerr = 0;
5729 lskerr = sizeof(skerr);
5730 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5731 skerr != 0)
5732 goto out_error;
5733
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005734#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005735 /*
5736 * Check if we have early data. If we do, we have to read them
5737 * before SSL_do_handshake() is called, And there's no way to
5738 * detect early data, except to try to read them
5739 */
5740 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005741 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005742
Olivier Houchard54907bb2019-12-19 15:02:39 +01005743 while (1) {
5744 ret = SSL_read_early_data(ctx->ssl,
5745 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5746 &read_data);
5747 if (ret == SSL_READ_EARLY_DATA_ERROR)
5748 goto check_error;
5749 if (read_data > 0) {
5750 conn->flags |= CO_FL_EARLY_DATA;
5751 b_add(&ctx->early_buf, read_data);
5752 }
5753 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5754 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5755 if (!b_data(&ctx->early_buf))
5756 b_free(&ctx->early_buf);
5757 break;
5758 }
5759 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005760 }
5761#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005762 /* If we use SSL_do_handshake to process a reneg initiated by
5763 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5764 * Usually SSL_write and SSL_read are used and process implicitly
5765 * the reneg handshake.
5766 * Here we use SSL_peek as a workaround for reneg.
5767 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005768 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005769 char c;
5770
Olivier Houchard66ab4982019-02-26 18:37:15 +01005771 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005772 if (ret <= 0) {
5773 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005774 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005775
Emeric Brun674b7432012-11-08 19:21:55 +01005776 if (ret == SSL_ERROR_WANT_WRITE) {
5777 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005778 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005779 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005780 return 0;
5781 }
5782 else if (ret == SSL_ERROR_WANT_READ) {
5783 /* handshake may have been completed but we have
5784 * no more data to read.
5785 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005786 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005787 ret = 1;
5788 goto reneg_ok;
5789 }
5790 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005791 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005792 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005793 return 0;
5794 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005795#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005796 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005797 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005798 return 0;
5799 }
5800#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005801 else if (ret == SSL_ERROR_SYSCALL) {
5802 /* if errno is null, then connection was successfully established */
5803 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5804 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005805 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005806#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5807 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005808 conn->err_code = CO_ER_SSL_HANDSHAKE;
5809#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005810 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005811#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005812 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005813 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005814 empty_handshake = state == TLS_ST_BEFORE;
5815#else
Lukas Tribus49799162019-07-08 14:29:15 +02005816 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5817 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005818#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005819 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005820 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005821 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005822 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5823 else
5824 conn->err_code = CO_ER_SSL_EMPTY;
5825 }
5826 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005827 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005828 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5829 else
5830 conn->err_code = CO_ER_SSL_ABORT;
5831 }
5832 }
5833 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005834 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005835 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005836 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005837 conn->err_code = CO_ER_SSL_HANDSHAKE;
5838 }
Lukas Tribus49799162019-07-08 14:29:15 +02005839#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005840 }
Emeric Brun674b7432012-11-08 19:21:55 +01005841 goto out_error;
5842 }
5843 else {
5844 /* Fail on all other handshake errors */
5845 /* Note: OpenSSL may leave unread bytes in the socket's
5846 * buffer, causing an RST to be emitted upon close() on
5847 * TCP sockets. We first try to drain possibly pending
5848 * data to avoid this as much as possible.
5849 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005850 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005851 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005852 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005853 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005854 goto out_error;
5855 }
5856 }
5857 /* read some data: consider handshake completed */
5858 goto reneg_ok;
5859 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005860 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005861check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005862 if (ret != 1) {
5863 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005864 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005865
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005866 if (!ctx->error_code)
5867 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton7c6898e2021-07-29 09:45:51 +02005868
Emeric Brun46591952012-05-18 15:47:34 +02005869 if (ret == SSL_ERROR_WANT_WRITE) {
5870 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005871 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005872 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005873 return 0;
5874 }
5875 else if (ret == SSL_ERROR_WANT_READ) {
5876 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005877 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005878 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5879 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005880 return 0;
5881 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005882#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005883 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005884 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005885 return 0;
5886 }
5887#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005888 else if (ret == SSL_ERROR_SYSCALL) {
5889 /* if errno is null, then connection was successfully established */
5890 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5891 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005892 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005893#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5894 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005895 conn->err_code = CO_ER_SSL_HANDSHAKE;
5896#else
5897 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005898#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005899 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005900 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005901 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005902#else
Lukas Tribus49799162019-07-08 14:29:15 +02005903 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5904 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005905#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005906 if (empty_handshake) {
5907 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005908 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005909 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5910 else
5911 conn->err_code = CO_ER_SSL_EMPTY;
5912 }
5913 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005914 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005915 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5916 else
5917 conn->err_code = CO_ER_SSL_ABORT;
5918 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005919 }
5920 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005921 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005922 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5923 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005924 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005925 }
Lukas Tribus49799162019-07-08 14:29:15 +02005926#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005927 }
Willy Tarreau89230192012-09-28 20:22:13 +02005928 goto out_error;
5929 }
Emeric Brun46591952012-05-18 15:47:34 +02005930 else {
5931 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005932 /* Note: OpenSSL may leave unread bytes in the socket's
5933 * buffer, causing an RST to be emitted upon close() on
5934 * TCP sockets. We first try to drain possibly pending
5935 * data to avoid this as much as possible.
5936 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005937 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005938 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005939 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005940 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005941 goto out_error;
5942 }
5943 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005944#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005945 else {
5946 /*
5947 * If the server refused the early data, we have to send a
5948 * 425 to the client, as we no longer have the data to sent
5949 * them again.
5950 */
5951 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005952 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005953 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5954 goto out_error;
5955 }
5956 }
5957 }
5958#endif
5959
Emeric Brun46591952012-05-18 15:47:34 +02005960
Emeric Brun674b7432012-11-08 19:21:55 +01005961reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005962
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005963#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00005964 /* ASYNC engine API doesn't support moving read/write
5965 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005966 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005967 */
5968 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005969 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005970#endif
Emeric Brun46591952012-05-18 15:47:34 +02005971 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005972 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005973 if (objt_server(conn->target)) {
5974 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5975 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5976 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005977 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005978 else {
5979 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5980 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5981 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5982 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005983
Willy Tarreau42995282020-11-06 13:19:18 +01005984 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01005985 HA_ATOMIC_INC(&counters->sess);
5986 HA_ATOMIC_INC(&counters_px->sess);
Willy Tarreau42995282020-11-06 13:19:18 +01005987 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005988 }
Willy Tarreau42995282020-11-06 13:19:18 +01005989 else if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01005990 HA_ATOMIC_INC(&counters->reused_sess);
5991 HA_ATOMIC_INC(&counters_px->reused_sess);
Emeric Brun46591952012-05-18 15:47:34 +02005992 }
5993
5994 /* The connection is now established at both layers, it's time to leave */
5995 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5996 return 1;
5997
5998 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005999 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006000 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006001 ERR_clear_error();
6002
Emeric Brun9fa89732012-10-04 17:09:56 +02006003 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01006004 if (objt_server(conn->target)) {
6005 struct server *s = __objt_server(conn->target);
6006 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
6007 * one cache per thread, it only prevents to flush it from the CLI in
6008 * another thread */
6009
6010 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01006011 if (s->ssl_ctx.reused_sess[tid].ptr)
6012 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01006013 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02006014 }
6015
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006016 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006017 HA_ATOMIC_INC(&counters->failed_handshake);
6018 HA_ATOMIC_INC(&counters_px->failed_handshake);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006019 }
6020
Emeric Brun46591952012-05-18 15:47:34 +02006021 /* Fail on all other handshake errors */
6022 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01006023 if (!conn->err_code)
6024 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006025 return 0;
6026}
6027
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006028/* Called from the upper layer, to subscribe <es> to events <event_type>. The
6029 * event subscriber <es> is not allowed to change from a previous call as long
6030 * as at least one event is still subscribed. The <event_type> must only be a
6031 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
6032 * unless the transport layer was already released.
6033 */
6034static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006035{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006036 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006037
Olivier Houchard0ff28652019-06-24 18:57:39 +02006038 if (!ctx)
6039 return -1;
6040
Willy Tarreau113d52b2020-01-10 09:20:26 +01006041 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006042 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006043
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006044 ctx->subs = es;
6045 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006046
6047 /* we may have to subscribe to lower layers for new events */
6048 event_type &= ~ctx->wait_event.events;
6049 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
6050 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006051 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006052}
6053
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006054/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
6055 * The <es> pointer is not allowed to differ from the one passed to the
6056 * subscribe() call. It always returns zero.
6057 */
6058static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006059{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006060 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006061
Willy Tarreau113d52b2020-01-10 09:20:26 +01006062 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006063 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006064
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006065 es->events &= ~event_type;
6066 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01006067 ctx->subs = NULL;
6068
6069 /* If we subscribed, and we're not doing the handshake,
6070 * then we subscribed because the upper layer asked for it,
6071 * as the upper layer is no longer interested, we can
6072 * unsubscribe too.
6073 */
6074 event_type &= ctx->wait_event.events;
6075 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
6076 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006077
6078 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006079}
6080
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006081/* The connection has been taken over, so destroy the old tasklet and create
6082 * a new one. The original thread ID must be passed into orig_tid
6083 * It should be called with the takeover lock for the old thread held.
6084 * Returns 0 on success, and -1 on failure
6085 */
6086static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
6087{
6088 struct ssl_sock_ctx *ctx = xprt_ctx;
6089 struct tasklet *tl = tasklet_new();
6090
6091 if (!tl)
6092 return -1;
6093
6094 ctx->wait_event.tasklet->context = NULL;
6095 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
6096 ctx->wait_event.tasklet = tl;
6097 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
6098 ctx->wait_event.tasklet->context = ctx;
6099 return 0;
6100}
6101
Willy Tarreau41491682021-03-02 17:29:56 +01006102/* notify the next xprt that the connection is about to become idle and that it
6103 * may be stolen at any time after the function returns and that any tasklet in
6104 * the chain must be careful before dereferencing its context.
6105 */
6106static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
6107{
6108 struct ssl_sock_ctx *ctx = xprt_ctx;
6109
6110 if (!ctx || !ctx->wait_event.tasklet)
6111 return;
6112
6113 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6114 if (ctx->xprt)
6115 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
6116}
6117
6118/* notify the next xprt that the connection is not idle anymore and that it may
6119 * not be stolen before the next xprt_set_idle().
6120 */
6121static void ssl_set_used(struct connection *conn, void *xprt_ctx)
6122{
6123 struct ssl_sock_ctx *ctx = xprt_ctx;
6124
6125 if (!ctx || !ctx->wait_event.tasklet)
6126 return;
6127
6128 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6129 if (ctx->xprt)
6130 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
6131}
6132
Olivier Houchard2e055482019-05-27 19:50:12 +02006133/* Use the provided XPRT as an underlying XPRT, and provide the old one.
6134 * Returns 0 on success, and non-zero on failure.
6135 */
6136static 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)
6137{
6138 struct ssl_sock_ctx *ctx = xprt_ctx;
6139
6140 if (oldxprt_ops != NULL)
6141 *oldxprt_ops = ctx->xprt;
6142 if (oldxprt_ctx != NULL)
6143 *oldxprt_ctx = ctx->xprt_ctx;
6144 ctx->xprt = toadd_ops;
6145 ctx->xprt_ctx = toadd_ctx;
6146 return 0;
6147}
6148
Olivier Houchard5149b592019-05-23 17:47:36 +02006149/* Remove the specified xprt. If if it our underlying XPRT, remove it and
6150 * return 0, otherwise just call the remove_xprt method from the underlying
6151 * XPRT.
6152 */
6153static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
6154{
6155 struct ssl_sock_ctx *ctx = xprt_ctx;
6156
6157 if (ctx->xprt_ctx == toremove_ctx) {
6158 ctx->xprt_ctx = newctx;
6159 ctx->xprt = newops;
6160 return 0;
6161 }
6162 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
6163}
6164
Willy Tarreau144f84a2021-03-02 16:09:26 +01006165struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02006166{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006167 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006168 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006169 struct connection *conn;
6170 int conn_in_list;
6171 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006172
Willy Tarreau41491682021-03-02 17:29:56 +01006173 if (state & TASK_F_USR1) {
6174 /* the tasklet was idling on an idle connection, it might have
6175 * been stolen, let's be careful!
6176 */
6177 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6178 if (tl->context == NULL) {
6179 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6180 tasklet_free(tl);
6181 return NULL;
6182 }
6183 conn = ctx->conn;
6184 conn_in_list = conn->flags & CO_FL_LIST_MASK;
6185 if (conn_in_list)
6186 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006187 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01006188 } else {
6189 conn = ctx->conn;
6190 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006191 }
Willy Tarreau41491682021-03-02 17:29:56 +01006192
Olivier Houchardea8dd942019-05-20 14:02:16 +02006193 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01006194 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006195 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006196 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
6197 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01006198 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006199 }
6200 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006201 /* If we had an error, or the handshake is done and I/O is available,
6202 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01006203 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02006204 * we can't be sure conn_fd_handler() will be called again.
6205 */
6206 if ((ctx->conn->flags & CO_FL_ERROR) ||
6207 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006208 int woke = 0;
6209
6210 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006211 if (ctx->subs) {
6212 tasklet_wakeup(ctx->subs->tasklet);
6213 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006214 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006215 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006216 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006217
Olivier Houchardea8dd942019-05-20 14:02:16 +02006218 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01006219 * upper layers know. If we have no mux, create it,
6220 * and once we have a mux, call its wake method if we didn't
6221 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02006222 */
6223 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01006224 if (!ctx->conn->mux)
6225 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006226 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006227 ret = ctx->conn->mux->wake(ctx->conn);
6228 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006229 }
6230 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006231#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006232 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006233 else if (b_data(&ctx->early_buf) && ctx->subs &&
6234 ctx->subs->events & SUB_RETRY_RECV) {
6235 tasklet_wakeup(ctx->subs->tasklet);
6236 ctx->subs->events &= ~SUB_RETRY_RECV;
6237 if (!ctx->subs->events)
6238 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01006239 }
6240#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006241leave:
6242 if (!ret && conn_in_list) {
6243 struct server *srv = objt_server(conn->target);
6244
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006245 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006246 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau85223482022-09-29 20:32:43 +02006247 eb64_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006248 else
Willy Tarreau85223482022-09-29 20:32:43 +02006249 eb64_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006250 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006251 }
Willy Tarreau74163142021-03-13 11:30:19 +01006252 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006253}
6254
Emeric Brun46591952012-05-18 15:47:34 +02006255/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01006256 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02006257 * buffer wraps, in which case a second call may be performed. The connection's
6258 * flags are updated with whatever special event is detected (error, read0,
6259 * empty). The caller is responsible for taking care of those events and
6260 * avoiding the call if inappropriate. The function does not call the
6261 * connection's polling update function, so the caller is responsible for this.
6262 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006263static 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 +02006264{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006265 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02006266 ssize_t ret;
6267 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02006268
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006269 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006270 goto out_error;
6271
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006272#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006273 if (b_data(&ctx->early_buf)) {
6274 try = b_contig_space(buf);
6275 if (try > b_data(&ctx->early_buf))
6276 try = b_data(&ctx->early_buf);
6277 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
6278 b_add(buf, try);
6279 b_del(&ctx->early_buf, try);
6280 if (b_data(&ctx->early_buf) == 0)
6281 b_free(&ctx->early_buf);
6282 return try;
6283 }
6284#endif
6285
Willy Tarreau911db9b2020-01-23 16:27:54 +01006286 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006287 /* a handshake was requested */
6288 return 0;
6289
Emeric Brun46591952012-05-18 15:47:34 +02006290 /* read the largest possible block. For this, we perform only one call
6291 * to recv() unless the buffer wraps and we exactly fill the first hunk,
6292 * in which case we accept to do it once again. A new attempt is made on
6293 * EINTR too.
6294 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01006295 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006296
Willy Tarreau591d4452018-06-15 17:21:00 +02006297 try = b_contig_space(buf);
6298 if (!try)
6299 break;
6300
Willy Tarreauabf08d92014-01-14 11:31:27 +01006301 if (try > count)
6302 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02006303
Olivier Houchard66ab4982019-02-26 18:37:15 +01006304 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02006305
Emeric Brune1f38db2012-09-03 20:36:47 +02006306 if (conn->flags & CO_FL_ERROR) {
6307 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006308 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006309 }
Emeric Brun46591952012-05-18 15:47:34 +02006310 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006311 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006312 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006313 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006314 }
Emeric Brun46591952012-05-18 15:47:34 +02006315 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006316 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006317 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006318 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006319 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006320 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006321#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006322 /* Async mode can be re-enabled, because we're leaving data state.*/
6323 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006324 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006325#endif
Emeric Brun46591952012-05-18 15:47:34 +02006326 break;
6327 }
6328 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006329 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006330 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6331 SUB_RETRY_RECV,
6332 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006333 /* handshake is running, and it may need to re-enable read */
6334 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006335#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006336 /* Async mode can be re-enabled, because we're leaving data state.*/
6337 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006338 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006339#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006340 break;
6341 }
Emeric Brun46591952012-05-18 15:47:34 +02006342 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006343 } else if (ret == SSL_ERROR_ZERO_RETURN)
6344 goto read0;
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006345 else if (ret == SSL_ERROR_SSL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006346 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6347 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006348 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006349 conn->err_code = CO_ERR_SSL_FATAL;
6350 }
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006351 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6352 * stack before shutting down the connection for
6353 * reading. */
Willy Tarreauacef5e22022-04-25 20:32:15 +02006354 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN || errno == EWOULDBLOCK))
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006355 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006356 /* otherwise it's a real error */
6357 goto out_error;
6358 }
6359 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006360 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006361 return done;
6362
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006363 clear_ssl_error:
6364 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006365 ssl_sock_dump_errors(conn, NULL);
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006366 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006367 read0:
6368 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006369 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006370
Emeric Brun46591952012-05-18 15:47:34 +02006371 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006372 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006373 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006374 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006375 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006376 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006377}
6378
6379
Willy Tarreau787db9a2018-06-14 18:31:46 +02006380/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6381 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6382 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006383 * Only one call to send() is performed, unless the buffer wraps, in which case
6384 * a second call may be performed. The connection's flags are updated with
6385 * whatever special event is detected (error, empty). The caller is responsible
6386 * for taking care of those events and avoiding the call if inappropriate. The
6387 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006388 * is responsible for this. The buffer's output is not adjusted, it's up to the
6389 * caller to take care of this. It's up to the caller to update the buffer's
6390 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006391 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006392static 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 +02006393{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006394 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006395 ssize_t ret;
6396 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006397
6398 done = 0;
6399
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006400 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006401 goto out_error;
6402
Willy Tarreau911db9b2020-01-23 16:27:54 +01006403 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006404 /* a handshake was requested */
6405 return 0;
6406
6407 /* send the largest possible block. For this we perform only one call
6408 * to send() unless the buffer wraps and we exactly fill the first hunk,
6409 * in which case we accept to do it once again.
6410 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006411 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006412#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006413 size_t written_data;
6414#endif
6415
Willy Tarreau787db9a2018-06-14 18:31:46 +02006416 try = b_contig_data(buf, done);
6417 if (try > count)
6418 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006419
Thomas Prückl10243932022-04-27 13:04:54 +02006420 if (global_ssl.hard_max_record && try > global_ssl.hard_max_record)
6421 try = global_ssl.hard_max_record;
6422
Willy Tarreau7bed9452014-02-02 02:00:24 +01006423 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006424 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006425 global_ssl.max_record && try > global_ssl.max_record) {
6426 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006427 }
6428 else {
6429 /* we need to keep the information about the fact that
6430 * we're not limiting the upcoming send(), because if it
6431 * fails, we'll have to retry with at least as many data.
6432 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006433 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006434 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006435
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006436#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006437 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006438 unsigned int max_early;
6439
Olivier Houchard522eea72017-11-03 16:27:47 +01006440 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006441 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006442 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006443 if (SSL_get0_session(ctx->ssl))
6444 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006445 else
6446 max_early = 0;
6447 }
6448
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006449 if (try + ctx->sent_early_data > max_early) {
6450 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006451 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006452 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006453 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006454 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006455 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006456 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006457 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006458 if (ret == 1) {
6459 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006460 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006461 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006462 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006463 /* Initiate the handshake, now */
6464 tasklet_wakeup(ctx->wait_event.tasklet);
6465 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006466
Olivier Houchardc2aae742017-09-22 18:26:28 +02006467 }
6468
6469 } else
6470#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006471 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006472
Emeric Brune1f38db2012-09-03 20:36:47 +02006473 if (conn->flags & CO_FL_ERROR) {
6474 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006475 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006476 }
Emeric Brun46591952012-05-18 15:47:34 +02006477 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006478 /* A send succeeded, so we can consider ourself connected */
6479 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006480 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006481 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006482 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006483 }
6484 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006485 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006486
Emeric Brun46591952012-05-18 15:47:34 +02006487 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006488 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006489 /* handshake is running, and it may need to re-enable write */
6490 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006491 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006492#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006493 /* Async mode can be re-enabled, because we're leaving data state.*/
6494 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006495 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006496#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006497 break;
6498 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006499
Emeric Brun46591952012-05-18 15:47:34 +02006500 break;
6501 }
6502 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006503 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006504 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006505 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6506 SUB_RETRY_RECV,
6507 &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
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006513 break;
6514 }
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006515 else if (ret == SSL_ERROR_SSL || ret == SSL_ERROR_SYSCALL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006516 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6517
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02006518 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006519 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006520 conn->err_code = CO_ERR_SSL_FATAL;
6521 }
Emeric Brun46591952012-05-18 15:47:34 +02006522 goto out_error;
6523 }
6524 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006525 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006526 return done;
6527
6528 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006529 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006530 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006531 ERR_clear_error();
6532
Emeric Brun46591952012-05-18 15:47:34 +02006533 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006534 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006535}
6536
Willy Tarreau832e2422021-05-13 10:11:03 +02006537void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006538
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006539 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006540
Olivier Houchardea8dd942019-05-20 14:02:16 +02006541
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006542 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006543 if (ctx->wait_event.events != 0)
6544 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6545 ctx->wait_event.events,
6546 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006547 if (ctx->subs) {
6548 ctx->subs->events = 0;
6549 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006550 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006551
Olivier Houchard692c1d02019-05-23 18:41:47 +02006552 if (ctx->xprt->close)
6553 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006554#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006555 if (global_ssl.async) {
6556 OSSL_ASYNC_FD all_fd[32], afd;
6557 size_t num_all_fds = 0;
6558 int i;
6559
Olivier Houchard66ab4982019-02-26 18:37:15 +01006560 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006561 if (num_all_fds > 32) {
6562 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6563 return;
6564 }
6565
Olivier Houchard66ab4982019-02-26 18:37:15 +01006566 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006567
6568 /* If an async job is pending, we must try to
6569 to catch the end using polling before calling
6570 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006571 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006572 for (i=0 ; i < num_all_fds ; i++) {
6573 /* switch on an handler designed to
6574 * handle the SSL_free
6575 */
6576 afd = all_fd[i];
6577 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006578 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006579 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006580 /* To ensure that the fd cache won't be used
6581 * and we'll catch a real RD event.
6582 */
6583 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006584 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006585 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006586 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006587 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006588 return;
6589 }
Emeric Brun3854e012017-05-17 20:42:48 +02006590 /* Else we can remove the fds from the fdtab
6591 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006592 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006593 * because the fd is owned by the engine.
6594 * the engine is responsible to close
6595 */
Emeric Brun7d392a52022-07-01 17:36:50 +02006596 for (i=0 ; i < num_all_fds ; i++) {
6597 /* We want to remove the fd from the fdtab
6598 * but we flag it to disown because the
6599 * close is performed by the engine itself
6600 */
6601 fdtab[all_fd[i]].state |= FD_DISOWN;
6602 fd_delete(all_fd[i]);
6603 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006604 }
6605#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006606 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006607 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006608 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006609 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau82531f62021-10-06 12:15:18 +02006610 _HA_ATOMIC_DEC(&global.sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006611 }
Emeric Brun46591952012-05-18 15:47:34 +02006612}
6613
6614/* This function tries to perform a clean shutdown on an SSL connection, and in
6615 * any case, flags the connection as reusable if no handshake was in progress.
6616 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006617static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006618{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006619 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006620
Willy Tarreau911db9b2020-01-23 16:27:54 +01006621 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006622 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006623 if (!clean)
6624 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006625 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006626 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006627 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006628 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006629 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006630 ERR_clear_error();
6631 }
Emeric Brun46591952012-05-18 15:47:34 +02006632}
6633
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006634
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006635/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006636int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6637{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006638 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemandd4f946c2019-12-05 10:26:40 +01006639 X509 *crt;
6640
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006641 if (!ctx)
William Lallemandd4f946c2019-12-05 10:26:40 +01006642 return 0;
William Lallemandd4f946c2019-12-05 10:26:40 +01006643 crt = SSL_get_certificate(ctx->ssl);
6644 if (!crt)
6645 return 0;
6646
6647 return cert_get_pkey_algo(crt, out);
6648}
6649
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006650/* used for ppv2 cert signature (can be used for logging) */
6651const char *ssl_sock_get_cert_sig(struct connection *conn)
6652{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006653 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006654
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006655 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6656 X509 *crt;
6657
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006658 if (!ctx)
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006659 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006660 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006661 if (!crt)
6662 return NULL;
6663 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6664 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6665}
6666
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006667/* used for ppv2 authority */
6668const char *ssl_sock_get_sni(struct connection *conn)
6669{
6670#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006671 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006672
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006673 if (!ctx)
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006674 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006675 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006676#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006677 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006678#endif
6679}
6680
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006681/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006682const char *ssl_sock_get_cipher_name(struct connection *conn)
6683{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006684 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006685
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006686 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006687 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006688 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006689}
6690
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006691/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006692const char *ssl_sock_get_proto_version(struct connection *conn)
6693{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006694 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006695
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006696 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006697 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006698 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006699}
6700
Olivier Houchardab28a322018-12-21 19:45:40 +01006701void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6702{
6703#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006704 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006705
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006706 if (!ctx)
Olivier Houcharde488ea82019-06-28 14:10:33 +02006707 return;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006708 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006709#endif
6710}
6711
Willy Tarreau119a4082016-12-22 21:58:38 +01006712/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6713 * to disable SNI.
6714 */
Willy Tarreau63076412015-07-10 11:33:32 +02006715void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6716{
6717#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006718 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemande18d4e82021-11-17 02:59:21 +01006719 struct server *s;
Willy Tarreau119a4082016-12-22 21:58:38 +01006720 char *prev_name;
6721
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006722 if (!ctx)
Willy Tarreau63076412015-07-10 11:33:32 +02006723 return;
Willy Tarreau77bfa662021-12-23 11:12:13 +01006724
6725 BUG_ON(!(conn->flags & CO_FL_WAIT_L6_CONN));
6726 BUG_ON(!(conn->flags & CO_FL_SSL_WAIT_HS));
6727
William Lallemande18d4e82021-11-17 02:59:21 +01006728 s = __objt_server(conn->target);
Willy Tarreau63076412015-07-10 11:33:32 +02006729
Willy Tarreau119a4082016-12-22 21:58:38 +01006730 /* if the SNI changes, we must destroy the reusable context so that a
William Lallemande18d4e82021-11-17 02:59:21 +01006731 * new connection will present a new SNI. compare with the SNI
6732 * previously stored in the reused_sess */
6733 /* the RWLOCK is used to ensure that we are not trying to flush the
6734 * cache from the CLI */
6735
6736 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
6737 prev_name = s->ssl_ctx.reused_sess[tid].sni;
Willy Tarreau119a4082016-12-22 21:58:38 +01006738 if ((!prev_name && hostname) ||
6739 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006740 SSL_set_session(ctx->ssl, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01006741 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau119a4082016-12-22 21:58:38 +01006742
Olivier Houchard66ab4982019-02-26 18:37:15 +01006743 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006744#endif
6745}
6746
Emeric Brun0abf8362014-06-24 18:26:41 +02006747/* Extract peer certificate's common name into the chunk dest
6748 * Returns
6749 * the len of the extracted common name
6750 * or 0 if no CN found in DN
6751 * or -1 on error case (i.e. no peer certificate)
6752 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006753int ssl_sock_get_remote_common_name(struct connection *conn,
6754 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006755{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006756 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
David Safb76832014-05-08 23:42:08 -04006757 X509 *crt = NULL;
6758 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006759 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006760 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006761 .area = (char *)&find_cn,
6762 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006763 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006764 int result = -1;
David Safb76832014-05-08 23:42:08 -04006765
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006766 if (!ctx)
Emeric Brun0abf8362014-06-24 18:26:41 +02006767 goto out;
David Safb76832014-05-08 23:42:08 -04006768
6769 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006770 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006771 if (!crt)
6772 goto out;
6773
6774 name = X509_get_subject_name(crt);
6775 if (!name)
6776 goto out;
David Safb76832014-05-08 23:42:08 -04006777
Emeric Brun0abf8362014-06-24 18:26:41 +02006778 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6779out:
David Safb76832014-05-08 23:42:08 -04006780 if (crt)
6781 X509_free(crt);
6782
6783 return result;
6784}
6785
Dave McCowan328fb582014-07-30 10:39:13 -04006786/* returns 1 if client passed a certificate for this session, 0 if not */
6787int ssl_sock_get_cert_used_sess(struct connection *conn)
6788{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006789 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dave McCowan328fb582014-07-30 10:39:13 -04006790 X509 *crt = NULL;
6791
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006792 if (!ctx)
Dave McCowan328fb582014-07-30 10:39:13 -04006793 return 0;
6794
6795 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006796 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006797 if (!crt)
6798 return 0;
6799
6800 X509_free(crt);
6801 return 1;
6802}
6803
6804/* returns 1 if client passed a certificate for this connection, 0 if not */
6805int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006806{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006807 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006808
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006809 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006810 return 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006811 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006812}
6813
6814/* returns result from SSL verify */
6815unsigned int ssl_sock_get_verify_result(struct connection *conn)
6816{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006817 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006818
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006819 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006820 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006821 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006822}
6823
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006824/* Returns the application layer protocol name in <str> and <len> when known.
6825 * Zero is returned if the protocol name was not found, otherwise non-zero is
6826 * returned. The string is allocated in the SSL context and doesn't have to be
6827 * freed by the caller. NPN is also checked if available since older versions
6828 * of openssl (1.0.1) which are more common in field only support this one.
6829 */
Amaury Denoyelle71e588c2021-11-12 11:23:29 +01006830int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006831{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006832#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6833 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006834 struct ssl_sock_ctx *ctx = xprt_ctx;
6835 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006836 return 0;
6837
6838 *str = NULL;
6839
6840#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006841 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006842 if (*str)
6843 return 1;
6844#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006845#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006846 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006847 if (*str)
6848 return 1;
6849#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006850#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006851 return 0;
6852}
6853
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006854/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006855int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006856{
6857 X509 *ca;
6858 X509_NAME *name = NULL;
6859 ASN1_OCTET_STRING *skid = NULL;
6860 STACK_OF(X509) *chain = NULL;
6861 struct issuer_chain *issuer;
6862 struct eb64_node *node;
6863 char *path;
6864 u64 key;
6865 int ret = 0;
6866
6867 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6868 if (chain == NULL) {
6869 chain = sk_X509_new_null();
6870 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6871 name = X509_get_subject_name(ca);
6872 }
6873 if (!sk_X509_push(chain, ca)) {
6874 X509_free(ca);
6875 goto end;
6876 }
6877 }
6878 if (!chain) {
6879 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6880 goto end;
6881 }
6882 if (!skid) {
6883 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6884 goto end;
6885 }
6886 if (!name) {
6887 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6888 goto end;
6889 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01006890 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006891 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006892 issuer = container_of(node, typeof(*issuer), node);
6893 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6894 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6895 goto end;
6896 }
6897 }
6898 issuer = calloc(1, sizeof *issuer);
6899 path = strdup(fp);
6900 if (!issuer || !path) {
6901 free(issuer);
6902 free(path);
6903 goto end;
6904 }
6905 issuer->node.key = key;
6906 issuer->path = path;
6907 issuer->chain = chain;
6908 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006909 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006910 ret = 1;
6911 end:
6912 if (skid)
6913 ASN1_OCTET_STRING_free(skid);
6914 if (chain)
6915 sk_X509_pop_free(chain, X509_free);
6916 return ret;
6917}
6918
William Lallemandda8584c2020-05-14 10:14:37 +02006919 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006920{
6921 AUTHORITY_KEYID *akid;
6922 struct issuer_chain *issuer = NULL;
6923
6924 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01006925 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006926 struct eb64_node *node;
6927 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01006928 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006929 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6930 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6931 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6932 issuer = ti;
6933 break;
6934 }
6935 }
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006936 }
Remi Tricot-Le Breton1621dc12022-11-03 15:16:48 +01006937 AUTHORITY_KEYID_free(akid);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006938 return issuer;
6939}
6940
William Lallemanddad31052020-05-14 17:47:32 +02006941void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006942{
6943 struct eb64_node *node, *back;
6944 struct issuer_chain *issuer;
6945
William Lallemande0f3fd52020-02-25 14:53:06 +01006946 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006947 while (node) {
6948 issuer = container_of(node, typeof(*issuer), node);
6949 back = eb64_next(node);
6950 eb64_delete(node);
6951 free(issuer->path);
6952 sk_X509_pop_free(issuer->chain, X509_free);
6953 free(issuer);
6954 node = back;
6955 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006956}
6957
William Lallemandd7bfbe22022-04-11 18:41:24 +02006958#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006959static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01006960 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006961
Emeric Brun3854e012017-05-17 20:42:48 +02006962 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006963 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006964 err_code = ERR_ABORT;
6965 }
6966 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006967}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006968#endif
6969
Willy Tarreaude5675a2021-01-20 14:41:29 +01006970/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006971 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01006972 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01006973static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01006974{
6975 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006976 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006977
6978 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006979 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006980
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006981 if (sctx->conn != conn) {
6982 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
6983 ret = 1;
6984 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01006985 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
6986
6987 if (sctx->xprt) {
6988 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
6989 if (sctx->xprt_ctx)
6990 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
6991 }
6992
6993 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006994
6995 /* as soon as a shutdown is reported the lower layer unregisters its
6996 * subscriber, so the situations below are transient and rare enough to
6997 * be reported as suspicious. In any case they shouldn't last.
6998 */
6999 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
7000 ret = 1;
7001 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
7002 ret = 1;
7003
Willy Tarreaude5675a2021-01-20 14:41:29 +01007004 chunk_appendf(&trash, " .subs=%p", sctx->subs);
7005 if (sctx->subs) {
7006 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007007 if (sctx->subs->tasklet->calls >= 1000000)
7008 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007009 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
7010 sctx->subs->tasklet->calls,
7011 sctx->subs->tasklet->context);
7012 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
7013 chunk_appendf(&trash, ")");
7014 }
7015 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
7016 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007017 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007018}
7019
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007020#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02007021/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007022 * each reference. The variable <ref> must point to the current node's list
7023 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02007024 */
William Lallemand32af2032016-10-29 18:09:35 +02007025static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007026struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02007027{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007028 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007029 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02007030
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007031 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007032 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007033 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02007034
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007035 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02007036}
7037
7038static inline
7039struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
7040{
7041 int id;
7042 char *error;
7043
7044 /* If the reference starts by a '#', this is numeric id. */
7045 if (reference[0] == '#') {
7046 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
7047 id = strtol(reference + 1, &error, 10);
7048 if (*error != '\0')
7049 return NULL;
7050
7051 /* Perform the unique id lookup. */
7052 return tlskeys_ref_lookupid(id);
7053 }
7054
7055 /* Perform the string lookup. */
7056 return tlskeys_ref_lookup(reference);
7057}
7058#endif
7059
7060
7061#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7062
Willy Tarreaua9380522022-05-05 08:50:17 +02007063/* dumps all tls keys. Relies on the show_keys_ctx context from the appctx. */
Willy Tarreaubd338642022-05-05 08:59:17 +02007064static int cli_io_handler_tlskeys_files(struct appctx *appctx)
7065{
Willy Tarreaua9380522022-05-05 08:50:17 +02007066 struct show_keys_ctx *ctx = appctx->svcctx;
William Lallemand32af2032016-10-29 18:09:35 +02007067
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007068 switch (ctx->state) {
7069 case SHOW_KEYS_INIT:
William Lallemand32af2032016-10-29 18:09:35 +02007070 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08007071 * quit the function with returning 0. The function is called
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007072 * later and restart at the state "SHOW_KEYS_INIT".
William Lallemand32af2032016-10-29 18:09:35 +02007073 */
7074 chunk_reset(&trash);
7075
Willy Tarreaubd338642022-05-05 08:59:17 +02007076 if (ctx->dump_entries)
William Lallemand32af2032016-10-29 18:09:35 +02007077 chunk_appendf(&trash, "# id secret\n");
7078 else
7079 chunk_appendf(&trash, "# id (file)\n");
7080
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007081 if (applet_putchk(appctx, &trash) == -1)
William Lallemand32af2032016-10-29 18:09:35 +02007082 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007083
William Lallemand32af2032016-10-29 18:09:35 +02007084 /* Now, we start the browsing of the references lists.
7085 * Note that the following call to LIST_ELEM return bad pointer. The only
7086 * available field of this pointer is <list>. It is used with the function
7087 * tlskeys_list_get_next() for retruning the first available entry
7088 */
Willy Tarreaua9380522022-05-05 08:50:17 +02007089 if (ctx->next_ref == NULL)
7090 ctx->next_ref = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007091
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007092 ctx->state = SHOW_KEYS_LIST;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007093 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007094
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007095 case SHOW_KEYS_LIST:
Willy Tarreaua9380522022-05-05 08:50:17 +02007096 while (ctx->next_ref) {
7097 struct tls_keys_ref *ref = ctx->next_ref;
William Lallemand32af2032016-10-29 18:09:35 +02007098
7099 chunk_reset(&trash);
Willy Tarreaubd338642022-05-05 08:59:17 +02007100 if (ctx->dump_entries && ctx->next_index == 0)
William Lallemand32af2032016-10-29 18:09:35 +02007101 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007102
Willy Tarreaua9380522022-05-05 08:50:17 +02007103 if (ctx->next_index == 0)
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007104 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
7105
Willy Tarreaubd338642022-05-05 08:59:17 +02007106 if (ctx->dump_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01007107 int head;
7108
7109 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
7110 head = ref->tls_ticket_enc_index;
Willy Tarreaua9380522022-05-05 08:50:17 +02007111 while (ctx->next_index < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02007112 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02007113
7114 chunk_reset(t2);
7115 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01007116 if (ref->key_size_bits == 128) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007117 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007118 sizeof(struct tls_sess_key_128),
7119 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007120 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007121 t2->area);
7122 }
7123 else if (ref->key_size_bits == 256) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007124 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007125 sizeof(struct tls_sess_key_256),
7126 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007127 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007128 t2->area);
7129 }
7130 else {
7131 /* This case should never happen */
Willy Tarreaua9380522022-05-05 08:50:17 +02007132 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, ctx->next_index);
Emeric Brun9e754772019-01-10 17:51:55 +01007133 }
William Lallemand32af2032016-10-29 18:09:35 +02007134
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007135 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007136 /* let's try again later from this stream. We add ourselves into
7137 * this stream's users so that it can remove us upon termination.
7138 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01007139 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
William Lallemand32af2032016-10-29 18:09:35 +02007140 return 0;
7141 }
Willy Tarreaua9380522022-05-05 08:50:17 +02007142 ctx->next_index++;
William Lallemand32af2032016-10-29 18:09:35 +02007143 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01007144 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaua9380522022-05-05 08:50:17 +02007145 ctx->next_index = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007146 }
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007147 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007148 /* let's try again later from this stream. We add ourselves into
7149 * this stream's users so that it can remove us upon termination.
7150 */
William Lallemand32af2032016-10-29 18:09:35 +02007151 return 0;
7152 }
7153
Willy Tarreaua9380522022-05-05 08:50:17 +02007154 if (ctx->names_only == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02007155 break;
7156
7157 /* get next list entry and check the end of the list */
Willy Tarreaua9380522022-05-05 08:50:17 +02007158 ctx->next_ref = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007159 }
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007160 ctx->state = SHOW_KEYS_DONE;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007161 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007162
7163 default:
William Lallemand32af2032016-10-29 18:09:35 +02007164 return 1;
7165 }
7166 return 0;
7167}
7168
Willy Tarreaua9380522022-05-05 08:50:17 +02007169/* Prepares a "show_keys_ctx" and sets the appropriate io_handler if needed */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007170static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007171{
Willy Tarreaua9380522022-05-05 08:50:17 +02007172 struct show_keys_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
7173
William Lallemand32af2032016-10-29 18:09:35 +02007174 /* no parameter, shows only file list */
7175 if (!*args[2]) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007176 ctx->names_only = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007177 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007178 }
7179
7180 if (args[2][0] == '*') {
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007181 /* list every TLS ticket keys */
7182 ctx->names_only = 1;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007183 } else {
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007184 ctx->next_ref = tlskeys_ref_lookup_ref(args[2]);
7185 if (!ctx->next_ref)
7186 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007187 }
7188
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007189 ctx->dump_entries = 1;
7190 return 0;
7191}
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007192
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007193static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
7194{
7195 struct tls_keys_ref *ref;
7196 int ret;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007197
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007198 /* Expect two parameters: the filename and the new new TLS key in encoding */
7199 if (!*args[3] || !*args[4])
7200 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 +02007201
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007202 ref = tlskeys_ref_lookup_ref(args[3]);
7203 if (!ref)
7204 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007205
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007206 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
7207 if (ret < 0)
7208 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007209
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007210 trash.data = ret;
7211 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
7212 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007213
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007214 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007215}
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007216#endif
7217
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007218
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007219#ifdef HAVE_SSL_PROVIDERS
7220struct provider_name {
7221 const char *name;
7222 struct list list;
7223};
7224
7225
7226static int ssl_provider_get_name_cb(OSSL_PROVIDER *provider, void *cbdata)
7227{
7228 struct list *provider_names = cbdata;
7229 struct provider_name *item = NULL;
7230 const char *name = OSSL_PROVIDER_get0_name(provider);
7231
7232 if (!provider_names)
7233 return 0;
7234
7235 item = calloc(1, sizeof(*item));
7236
7237 if (!item)
7238 return 0;
7239
7240 item->name = name;
7241 LIST_APPEND(provider_names, &item->list);
7242
7243 return 1;
7244}
7245
7246static void ssl_provider_get_name_list(struct list *provider_names)
7247{
7248 if (!provider_names)
7249 return;
7250
7251 OSSL_PROVIDER_do_all(NULL, ssl_provider_get_name_cb, provider_names);
7252}
7253
7254static void ssl_provider_clear_name_list(struct list *provider_names)
7255{
7256 struct provider_name *item = NULL, *item_s = NULL;
7257
7258 if (provider_names) {
7259 list_for_each_entry_safe(item, item_s, provider_names, list) {
7260 LIST_DELETE(&item->list);
7261 free(item);
7262 }
7263 }
7264}
7265
7266static int cli_io_handler_show_providers(struct appctx *appctx)
7267{
7268 struct buffer *trash = get_trash_chunk();
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007269 struct list provider_names;
7270 struct provider_name *name;
7271
7272 LIST_INIT(&provider_names);
7273
7274 chunk_appendf(trash, "Loaded providers : \n");
7275
7276 ssl_provider_get_name_list(&provider_names);
7277
7278 list_for_each_entry(name, &provider_names, list) {
7279 chunk_appendf(trash, "\t- %s\n", name->name);
7280 }
7281
7282 ssl_provider_clear_name_list(&provider_names);
7283
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007284 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007285 goto yield;
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007286
7287 return 1;
7288
7289yield:
7290 return 0;
7291}
7292#endif
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01007293
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007294
William Lallemand32af2032016-10-29 18:09:35 +02007295/* register cli keywords */
7296static struct cli_kw_list cli_kws = {{ },{
7297#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01007298 { { "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 },
7299 { { "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 +02007300#endif
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007301#ifdef HAVE_SSL_PROVIDERS
7302 { { "show", "ssl", "providers", NULL }, "show ssl providers : show loaded SSL providers", NULL, cli_io_handler_show_providers },
7303#endif
William Lallemand32af2032016-10-29 18:09:35 +02007304 { { NULL }, NULL, NULL, NULL }
7305}};
7306
Willy Tarreau0108d902018-11-25 19:14:37 +01007307INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02007308
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02007309/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02007310struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02007311 .snd_buf = ssl_sock_from_buf,
7312 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01007313 .subscribe = ssl_subscribe,
7314 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02007315 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02007316 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02007317 .rcv_pipe = NULL,
7318 .snd_pipe = NULL,
7319 .shutr = NULL,
7320 .shutw = ssl_sock_shutw,
7321 .close = ssl_sock_close,
7322 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01007323 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01007324 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01007325 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01007326 .prepare_srv = ssl_sock_prepare_srv_ctx,
7327 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007328 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02007329 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01007330 .set_idle = ssl_set_idle,
7331 .set_used = ssl_set_used,
Willy Tarreaude827952022-04-11 10:43:28 +02007332 .get_ssl_sock_ctx = ssl_sock_get_ctx,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01007333 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01007334 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02007335};
7336
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007337enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
7338 struct session *sess, struct stream *s, int flags)
7339{
7340 struct connection *conn;
7341
7342 conn = objt_conn(sess->origin);
7343
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007344 if (conn) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007345 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007346 sc_ep_set(s->scf, SE_FL_WAIT_FOR_HS);
Christopher Faulet6e1bbc42022-12-12 08:08:15 +01007347 s->req.flags |= CF_READ_EVENT;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007348 return ACT_RET_YIELD;
7349 }
7350 }
7351 return (ACT_RET_CONT);
7352}
7353
7354static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
7355{
7356 rule->action_ptr = ssl_action_wait_for_hs;
7357
7358 return ACT_RET_PRS_OK;
7359}
7360
7361static struct action_kw_list http_req_actions = {ILH, {
7362 { "wait-for-handshake", ssl_parse_wait_for_hs },
7363 { /* END */ }
7364}};
7365
Willy Tarreau0108d902018-11-25 19:14:37 +01007366INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
7367
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007368#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007369
7370static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7371{
7372 if (ptr) {
7373 chunk_destroy(ptr);
7374 free(ptr);
7375 }
7376}
7377
7378#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007379
William Lallemand76b4a122020-08-04 17:41:39 +02007380
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007381static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7382{
Willy Tarreaubafbe012017-11-24 17:34:44 +01007383 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007384}
William Lallemand7d42ef52020-07-06 11:41:30 +02007385
William Lallemand722180a2021-06-09 16:46:12 +02007386#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007387static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7388{
7389 struct ssl_keylog *keylog;
7390
7391 if (!ptr)
7392 return;
7393
7394 keylog = ptr;
7395
7396 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7397 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7398 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7399 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7400 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7401 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7402 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7403 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7404
7405 pool_free(pool_head_ssl_keylog, ptr);
7406}
7407#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007408
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007409static void ssl_sock_clt_crt_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7410{
7411 if (!ptr)
7412 return;
7413
7414 X509_free((X509*)ptr);
7415}
7416
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01007417static void ssl_sock_clt_sni_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7418{
7419 pool_free(ssl_sock_client_sni_pool, ptr);
7420}
7421
Willy Tarreau92faadf2012-10-10 23:04:25 +02007422static void __ssl_sock_init(void)
7423{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007424#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007425 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007426 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007427#endif
Emeric Brun46591952012-05-18 15:47:34 +02007428
Willy Tarreauef934602016-12-22 23:12:01 +01007429 if (global_ssl.listen_default_ciphers)
7430 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7431 if (global_ssl.connect_default_ciphers)
7432 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007433#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007434 if (global_ssl.listen_default_ciphersuites)
7435 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7436 if (global_ssl.connect_default_ciphersuites)
7437 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7438#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007439
Willy Tarreau13e14102016-12-22 20:25:26 +01007440 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007441#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007442 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007443#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007444#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007445 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007446 n = sk_SSL_COMP_num(cm);
7447 while (n--) {
7448 (void) sk_SSL_COMP_pop(cm);
7449 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007450#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007451
Willy Tarreau5db847a2019-05-09 14:13:35 +02007452#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007453 ssl_locking_init();
7454#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007455#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007456 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
7457#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007458
7459#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7460 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
7461#endif
7462
Thierry FOURNIER28962c92018-06-17 21:37:05 +02007463 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02007464 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 +01007465#ifdef USE_QUIC
7466 ssl_qc_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7467#endif /* USE_QUIC */
William Lallemand722180a2021-06-09 16:46:12 +02007468#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007469 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
7470#endif
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007471 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 +01007472 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 +02007473#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00007474 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007475 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007476#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01007477#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7478 hap_register_post_check(tlskeys_finalize_config);
7479#endif
Willy Tarreau80713382018-11-26 10:19:54 +01007480
7481 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
7482 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
7483
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007484 hap_register_post_deinit(ssl_free_global_issuers);
7485
Willy Tarreau80713382018-11-26 10:19:54 +01007486#ifndef OPENSSL_NO_DH
7487 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7488 hap_register_post_deinit(ssl_free_dh);
7489#endif
William Lallemandd7bfbe22022-04-11 18:41:24 +02007490#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Willy Tarreau80713382018-11-26 10:19:54 +01007491 hap_register_post_deinit(ssl_free_engines);
7492#endif
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02007493#ifdef HAVE_SSL_PROVIDERS
7494 hap_register_post_deinit(ssl_unload_providers);
7495#endif
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01007496#if HA_OPENSSL_VERSION_NUMBER < 0x3000000fL
Willy Tarreau80713382018-11-26 10:19:54 +01007497 /* Load SSL string for the verbose & debug mode. */
7498 ERR_load_SSL_strings();
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01007499#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007500 ha_meth = BIO_meth_new(0x666, "ha methods");
7501 BIO_meth_set_write(ha_meth, ha_ssl_write);
7502 BIO_meth_set_read(ha_meth, ha_ssl_read);
7503 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
7504 BIO_meth_set_create(ha_meth, ha_ssl_new);
7505 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
7506 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
7507 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02007508
7509 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007510
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01007511 HA_SPIN_INIT(&ocsp_tree_lock);
7512
Dragan Dosen9ac98092020-05-11 15:51:45 +02007513 /* Try to register dedicated SSL/TLS protocol message callbacks for
7514 * heartbleed attack (CVE-2014-0160) and clienthello.
7515 */
7516 hap_register_post_check(ssl_sock_register_msg_callbacks);
7517
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007518 /* Try to free all callbacks that were registered by using
7519 * ssl_sock_register_msg_callback().
7520 */
7521 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01007522}
Willy Tarreau79367f92022-04-25 19:18:24 +02007523INITCALL0(STG_REGISTER, __ssl_sock_init);
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01007524
Willy Tarreau80713382018-11-26 10:19:54 +01007525/* Compute and register the version string */
7526static void ssl_register_build_options()
7527{
7528 char *ptr = NULL;
7529 int i;
7530
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007531 memprintf(&ptr, "Built with OpenSSL version : "
7532#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007533 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007534#else /* OPENSSL_IS_BORINGSSL */
7535 OPENSSL_VERSION_TEXT
7536 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08007537 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02007538 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007539#endif
7540 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007541#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007542 "no (library version too old)"
7543#elif defined(OPENSSL_NO_TLSEXT)
7544 "no (disabled via OPENSSL_NO_TLSEXT)"
7545#else
7546 "yes"
7547#endif
7548 "", ptr);
7549
7550 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
7551#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
7552 "yes"
7553#else
7554#ifdef OPENSSL_NO_TLSEXT
7555 "no (because of OPENSSL_NO_TLSEXT)"
7556#else
7557 "no (version might be too old, 0.9.8f min needed)"
7558#endif
7559#endif
7560 "", ptr);
7561
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02007562 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
7563 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
7564 if (methodVersions[i].option)
7565 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007566
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007567#ifdef HAVE_SSL_PROVIDERS
7568 {
7569 struct list provider_names;
7570 struct provider_name *name;
7571 LIST_INIT(&provider_names);
7572 ssl_provider_get_name_list(&provider_names);
7573
7574 memprintf(&ptr, "%s\nOpenSSL providers loaded :", ptr);
7575
7576 list_for_each_entry(name, &provider_names, list) {
7577 memprintf(&ptr, "%s %s", ptr, name->name);
7578 }
7579
7580 ssl_provider_clear_name_list(&provider_names);
7581 }
7582#endif
7583
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007584 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01007585}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007586
Willy Tarreau80713382018-11-26 10:19:54 +01007587INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02007588
William Lallemandd7bfbe22022-04-11 18:41:24 +02007589#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00007590void ssl_free_engines(void) {
7591 struct ssl_engine_list *wl, *wlb;
7592 /* free up engine list */
7593 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
7594 ENGINE_finish(wl->e);
7595 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02007596 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00007597 free(wl);
7598 }
7599}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007600#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02007601
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02007602#ifdef HAVE_SSL_PROVIDERS
7603void ssl_unload_providers(void) {
7604 struct ssl_provider_list *prov, *provb;
7605 list_for_each_entry_safe(prov, provb, &openssl_providers, list) {
7606 OSSL_PROVIDER_unload(prov->provider);
7607 LIST_DELETE(&prov->list);
7608 free(prov);
7609 }
7610}
7611#endif
7612
Remi Gacogned3a23c32015-05-28 16:39:47 +02007613#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00007614void ssl_free_dh(void) {
7615 if (local_dh_1024) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007616 HASSL_DH_free(local_dh_1024);
Grant Zhang872f9c22017-01-21 01:10:18 +00007617 local_dh_1024 = NULL;
7618 }
7619 if (local_dh_2048) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007620 HASSL_DH_free(local_dh_2048);
Grant Zhang872f9c22017-01-21 01:10:18 +00007621 local_dh_2048 = NULL;
7622 }
7623 if (local_dh_4096) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007624 HASSL_DH_free(local_dh_4096);
Grant Zhang872f9c22017-01-21 01:10:18 +00007625 local_dh_4096 = NULL;
7626 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02007627 if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007628 HASSL_DH_free(global_dh);
Remi Gacogne47783ef2015-05-29 15:53:22 +02007629 global_dh = NULL;
7630 }
Grant Zhang872f9c22017-01-21 01:10:18 +00007631}
7632#endif
7633
Grant Zhang872f9c22017-01-21 01:10:18 +00007634static void __ssl_sock_deinit(void)
7635{
7636#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007637 if (ssl_ctx_lru_tree) {
7638 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007639 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02007640 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02007641#endif
7642
Willy Tarreau5db847a2019-05-09 14:13:35 +02007643#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007644 ERR_remove_state(0);
7645 ERR_free_strings();
7646
7647 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08007648#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007649
Willy Tarreau5db847a2019-05-09 14:13:35 +02007650#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007651 CRYPTO_cleanup_all_ex_data();
7652#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007653 BIO_meth_free(ha_meth);
Remi Tricot-Le Breton6477bbd2022-12-20 11:11:13 +01007654
7655#if !defined OPENSSL_NO_OCSP
7656 ssl_destroy_ocsp_update_task();
7657#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007658}
Willy Tarreau79367f92022-04-25 19:18:24 +02007659REGISTER_POST_DEINIT(__ssl_sock_deinit);
Remi Gacogned3a23c32015-05-28 16:39:47 +02007660
William Dauchyf6370442020-11-14 19:25:33 +01007661
Emeric Brun46591952012-05-18 15:47:34 +02007662/*
7663 * Local variables:
7664 * c-indent-level: 8
7665 * c-basic-offset: 8
7666 * End:
7667 */