blob: 51d2d70464c0fca812d074c1d96088b0c54fc9f4 [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 */
William Lallemand222e5a22023-01-31 14:12:28 +01004214 first->len = 0; /* the len must be liberated in order not to call the release callback on it */
William Lallemand4f45bb92017-10-30 20:08:51 +01004215 shctx_row_dec_hot(ssl_shctx, first);
4216 /* replace the previous session already in the tree */
4217 sh_ssl_sess = oldsh_ssl_sess;
4218 /* ignore the previous session data, only use the header */
4219 first = sh_ssl_sess_first_block(sh_ssl_sess);
4220 shctx_row_inc_hot(ssl_shctx, first);
4221 first->len = sizeof(struct sh_ssl_sess_hdr);
4222 }
4223
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004224 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01004225 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004226 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01004227 }
4228
4229 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004230
4231 return 1;
4232}
William Lallemanded0b5ad2017-10-30 19:36:36 +01004233
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004234/* SSL callback used when a new session is created while connecting to a server */
4235static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4236{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004237 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004238 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004239
Willy Tarreau07d94e42018-09-20 10:57:52 +02004240 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004241
William Lallemand3ce6eed2021-02-08 10:43:44 +01004242 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4243 * one cache per thread, it only prevents to flush it from the CLI in
4244 * another thread */
4245
Olivier Houcharde6060c52017-11-16 17:42:52 +01004246 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4247 int len;
4248 unsigned char *ptr;
William Lallemande18d4e82021-11-17 02:59:21 +01004249 const char *sni;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004250
Olivier Houcharde6060c52017-11-16 17:42:52 +01004251 len = i2d_SSL_SESSION(sess, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01004252 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004253 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004254 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4255 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4256 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004257 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
4258 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004259 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4260 }
4261 if (s->ssl_ctx.reused_sess[tid].ptr) {
4262 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4263 &ptr);
4264 }
William Lallemande18d4e82021-11-17 02:59:21 +01004265
4266 if (s->ssl_ctx.reused_sess[tid].sni) {
4267 /* if the new sni is empty or isn' t the same as the old one */
4268 if ((!sni) || strcmp(s->ssl_ctx.reused_sess[tid].sni, sni) != 0) {
4269 ha_free(&s->ssl_ctx.reused_sess[tid].sni);
4270 if (sni)
4271 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4272 }
4273 } else if (sni) {
4274 /* if there wasn't an old sni but there is a new one */
4275 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4276 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004277 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004278 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004279 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004280 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004281 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004282 }
4283
4284 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004285}
4286
Olivier Houcharde6060c52017-11-16 17:42:52 +01004287
William Lallemanded0b5ad2017-10-30 19:36:36 +01004288/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004289int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004290{
4291 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4292 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4293 unsigned char *p;
4294 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004295 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004296 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004297
4298 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004299 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004300 * note: SSL_SESSION_set1_id is using
4301 * a memcpy so we need to use a different pointer
4302 * than sid_data or sid_ctx_data to avoid valgrind
4303 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004304 */
4305
4306 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004307
4308 /* copy value in an other buffer */
4309 memcpy(encid, sid_data, sid_length);
4310
4311 /* pad with 0 */
4312 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4313 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4314
4315 /* force length to zero to avoid ASN1 encoding */
4316 SSL_SESSION_set1_id(sess, encid, 0);
4317
4318 /* force length to zero to avoid ASN1 encoding */
4319 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004320
4321 /* check if buffer is large enough for the ASN1 encoded session */
4322 data_len = i2d_SSL_SESSION(sess, NULL);
4323 if (data_len > SHSESS_MAX_DATA_LEN)
4324 goto err;
4325
4326 p = encsess;
4327
4328 /* process ASN1 session encoding before the lock */
4329 i2d_SSL_SESSION(sess, &p);
4330
William Lallemanded0b5ad2017-10-30 19:36:36 +01004331
William Lallemanda3c77cf2017-10-30 23:44:40 +01004332 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004333 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004334 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004335 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004336err:
4337 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004338 SSL_SESSION_set1_id(sess, encid, sid_length);
4339 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004340
4341 return 0; /* do not increment session reference count */
4342}
4343
4344/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004345SSL_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 +01004346{
William Lallemand4f45bb92017-10-30 20:08:51 +01004347 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004348 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4349 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004350 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004351 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004352
Willy Tarreau4c19e992021-06-15 16:39:22 +02004353 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004354
4355 /* allow the session to be freed automatically by openssl */
4356 *do_copy = 0;
4357
4358 /* tree key is zeros padded sessionid */
4359 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4360 memcpy(tmpkey, key, key_len);
4361 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4362 key = tmpkey;
4363 }
4364
4365 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004366 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004367
4368 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004369 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4370 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004371 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004372 shctx_unlock(ssl_shctx);
Willy Tarreau4c19e992021-06-15 16:39:22 +02004373 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004374 return NULL;
4375 }
4376
William Lallemand4f45bb92017-10-30 20:08:51 +01004377 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4378 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004379
William Lallemand4f45bb92017-10-30 20:08:51 +01004380 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 +01004381
William Lallemanda3c77cf2017-10-30 23:44:40 +01004382 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004383
4384 /* decode ASN1 session */
4385 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004386 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004387 /* Reset session id and session id contenxt */
4388 if (sess) {
4389 SSL_SESSION_set1_id(sess, key, key_len);
4390 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4391 }
4392
4393 return sess;
4394}
4395
William Lallemand4f45bb92017-10-30 20:08:51 +01004396
William Lallemanded0b5ad2017-10-30 19:36:36 +01004397/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004398void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004399{
William Lallemand4f45bb92017-10-30 20:08:51 +01004400 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004401 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4402 unsigned int sid_length;
4403 const unsigned char *sid_data;
4404 (void)ctx;
4405
4406 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4407 /* tree key is zeros padded sessionid */
4408 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4409 memcpy(tmpkey, sid_data, sid_length);
4410 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4411 sid_data = tmpkey;
4412 }
4413
William Lallemanda3c77cf2017-10-30 23:44:40 +01004414 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004415
4416 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004417 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4418 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004419 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004420 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004421 }
4422
4423 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004424 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004425}
4426
4427/* Set session cache mode to server and disable openssl internal cache.
4428 * Set shared cache callbacks on an ssl context.
4429 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004430void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004431{
4432 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4433
4434 if (!ssl_shctx) {
4435 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4436 return;
4437 }
4438
4439 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4440 SSL_SESS_CACHE_NO_INTERNAL |
4441 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4442
4443 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004444 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4445 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4446 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004447}
William Lallemand7d42ef52020-07-06 11:41:30 +02004448
4449/*
4450 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4451 *
4452 * The format is:
4453 * * <Label> <space> <ClientRandom> <space> <Secret>
4454 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4455 */
4456
William Lallemand722180a2021-06-09 16:46:12 +02004457#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004458void SSL_CTX_keylog(const SSL *ssl, const char *line)
4459{
4460 struct ssl_keylog *keylog;
4461 char *lastarg = NULL;
4462 char *dst = NULL;
4463
4464 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4465 if (!keylog)
4466 return;
4467
4468 lastarg = strrchr(line, ' ');
4469 if (lastarg == NULL || ++lastarg == NULL)
4470 return;
4471
4472 dst = pool_alloc(pool_head_ssl_keylog_str);
4473 if (!dst)
4474 return;
4475
4476 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4477 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4478
4479 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4480 if (keylog->client_random)
4481 goto error;
4482 keylog->client_random = dst;
4483
4484 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4485 if (keylog->client_early_traffic_secret)
4486 goto error;
4487 keylog->client_early_traffic_secret = dst;
4488
4489 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4490 if(keylog->client_handshake_traffic_secret)
4491 goto error;
4492 keylog->client_handshake_traffic_secret = dst;
4493
4494 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4495 if (keylog->server_handshake_traffic_secret)
4496 goto error;
4497 keylog->server_handshake_traffic_secret = dst;
4498
4499 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4500 if (keylog->client_traffic_secret_0)
4501 goto error;
4502 keylog->client_traffic_secret_0 = dst;
4503
4504 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4505 if (keylog->server_traffic_secret_0)
4506 goto error;
4507 keylog->server_traffic_secret_0 = dst;
4508
4509 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4510 if (keylog->early_exporter_secret)
4511 goto error;
4512 keylog->early_exporter_secret = dst;
4513
4514 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4515 if (keylog->exporter_secret)
4516 goto error;
4517 keylog->exporter_secret = dst;
4518 } else {
4519 goto error;
4520 }
4521
4522 return;
4523
4524error:
4525 pool_free(pool_head_ssl_keylog_str, dst);
4526
4527 return;
4528}
4529#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004530
William Lallemand8b453912019-11-21 15:48:10 +01004531/*
4532 * This function applies the SSL configuration on a SSL_CTX
4533 * It returns an error code and fills the <err> buffer
4534 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004535static 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 +01004536{
4537 struct proxy *curproxy = bind_conf->frontend;
4538 int cfgerr = 0;
4539 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004540 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004541 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004542#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004543 const char *conf_ciphersuites;
4544#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004545 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004546
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004547 if (ssl_conf) {
4548 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4549 int i, min, max;
4550 int flags = MC_SSL_O_ALL;
4551
4552 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004553 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4554 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004555 if (min)
4556 flags |= (methodVersions[min].flag - 1);
4557 if (max)
4558 flags |= ~((methodVersions[max].flag << 1) - 1);
4559 min = max = CONF_TLSV_NONE;
4560 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4561 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4562 if (min)
4563 max = i;
4564 else
4565 min = max = i;
4566 }
4567 /* save real min/max */
4568 conf_ssl_methods->min = min;
4569 conf_ssl_methods->max = max;
4570 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004571 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4572 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004573 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004574 }
4575 }
4576
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004577 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004578 case SSL_SOCK_VERIFY_NONE:
4579 verify = SSL_VERIFY_NONE;
4580 break;
4581 case SSL_SOCK_VERIFY_OPTIONAL:
4582 verify = SSL_VERIFY_PEER;
4583 break;
4584 case SSL_SOCK_VERIFY_REQUIRED:
4585 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4586 break;
4587 }
4588 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4589 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004590 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 +01004591 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 +01004592 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 +01004593 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004594 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004595 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004596 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004597 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004598 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004599 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004600 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4601 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4602 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4603 cfgerr |= ERR_ALERT | ERR_FATAL;
4604 }
4605 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004606 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004607 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 +02004608 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004609 }
Emeric Brun850efd52014-01-29 12:24:34 +01004610 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004611 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4612 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004613 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004614 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004615#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004616 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004617 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4618
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004619 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004620 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4621 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004622 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004623 }
Emeric Brun561e5742012-10-02 15:20:55 +02004624 else {
4625 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4626 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004627 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004628#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004629 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004630 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004631#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004632 if(bind_conf->keys_ref) {
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +01004633 if (!SSL_CTX_set_tlsext_ticket_key_evp_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004634 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4635 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004636 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004637 }
4638 }
4639#endif
4640
William Lallemand4f45bb92017-10-30 20:08:51 +01004641 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004642 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4643 if (conf_ciphers &&
4644 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004645 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4646 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004647 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004648 }
4649
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004650#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004651 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4652 if (conf_ciphersuites &&
4653 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004654 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4655 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004656 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004657 }
4658#endif
4659
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004660#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02004661 if (!local_dh_1024)
4662 local_dh_1024 = ssl_get_dh_1024();
4663 if (!local_dh_2048)
4664 local_dh_2048 = ssl_get_dh_2048();
4665 if (!local_dh_4096)
4666 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02004667#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004668
Emeric Brunfc0421f2012-09-07 17:30:07 +02004669 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004670#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004671 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004672#endif
William Lallemand722180a2021-06-09 16:46:12 +02004673#ifdef HAVE_SSL_KEYLOG
William Lallemandb60a77b2022-11-18 15:00:15 +01004674 /* only activate the keylog callback if it was required to prevent performance loss */
4675 if (global_ssl.keylog > 0)
4676 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02004677#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004678
Bernard Spil13c53f82018-02-15 13:34:58 +01004679#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004680 ssl_conf_cur = NULL;
4681 if (ssl_conf && ssl_conf->npn_str)
4682 ssl_conf_cur = ssl_conf;
4683 else if (bind_conf->ssl_conf.npn_str)
4684 ssl_conf_cur = &bind_conf->ssl_conf;
4685 if (ssl_conf_cur)
4686 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004687#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004688#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004689 ssl_conf_cur = NULL;
4690 if (ssl_conf && ssl_conf->alpn_str)
4691 ssl_conf_cur = ssl_conf;
4692 else if (bind_conf->ssl_conf.alpn_str)
4693 ssl_conf_cur = &bind_conf->ssl_conf;
4694 if (ssl_conf_cur)
4695 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004696#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004697#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004698 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4699 if (conf_curves) {
4700 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004701 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4702 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004703 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004704 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004705 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004706 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004707#endif /* defined(SSL_CTX_set1_curves_list) */
4708
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004709 if (!conf_curves) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004710#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004711#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004712 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004713 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4714 NULL);
4715
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004716 if (ecdhe && SSL_CTX_set1_curves_list(ctx, ecdhe) == 0) {
4717 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4718 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
4719 cfgerr |= ERR_ALERT | ERR_FATAL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02004720 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004721#endif /* defined(SSL_CTX_set1_curves_list) */
Olivier Houchardc2aae742017-09-22 18:26:28 +02004722#else
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004723#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
4724 int i;
4725 EC_KEY *ecdh;
4726
Olivier Houchardc2aae742017-09-22 18:26:28 +02004727 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4728 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4729 ECDHE_DEFAULT_CURVE);
Emeric Brun2b58d042012-09-20 17:10:03 +02004730
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004731 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004732 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004733 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 +01004734 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004735 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004736 }
4737 else {
4738 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4739 EC_KEY_free(ecdh);
4740 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004741#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
4742#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Emeric Brun2b58d042012-09-20 17:10:03 +02004743 }
Emeric Brun2b58d042012-09-20 17:10:03 +02004744
Emeric Brunfc0421f2012-09-07 17:30:07 +02004745 return cfgerr;
4746}
4747
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004748
4749/*
4750 * Prepare the SSL_CTX based on the bind line configuration.
4751 * Since the CA file loading is made depending on the verify option of the bind
4752 * line, the link between the SSL_CTX and the CA file tree entry is made here.
4753 * If we want to create a link between the CA file entry and the corresponding
4754 * ckch instance (for CA file hot update), it needs to be done after
4755 * ssl_sock_prepare_ctx.
4756 * Returns 0 in case of success.
4757 */
4758int ssl_sock_prep_ctx_and_inst(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
4759 SSL_CTX *ctx, struct ckch_inst *ckch_inst, char **err)
4760{
4761 int errcode = 0;
4762
4763 errcode |= ssl_sock_prepare_ctx(bind_conf, ssl_conf, ctx, err);
4764 if (!errcode && ckch_inst)
4765 ckch_inst_add_cafile_link(ckch_inst, bind_conf, ssl_conf, NULL);
4766
4767 return errcode;
4768}
4769
Evan Broderbe554312013-06-27 00:05:25 -07004770static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4771{
4772 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4773 size_t prefixlen, suffixlen;
4774
4775 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004776 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004777 return 1;
4778
Evan Broderbe554312013-06-27 00:05:25 -07004779 /* The rest of this logic is based on RFC 6125, section 6.4.3
4780 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4781
Emeric Bruna848dae2013-10-08 11:27:28 +02004782 pattern_wildcard = NULL;
4783 pattern_left_label_end = pattern;
4784 while (*pattern_left_label_end != '.') {
4785 switch (*pattern_left_label_end) {
4786 case 0:
4787 /* End of label not found */
4788 return 0;
4789 case '*':
4790 /* If there is more than one wildcards */
4791 if (pattern_wildcard)
4792 return 0;
4793 pattern_wildcard = pattern_left_label_end;
4794 break;
4795 }
4796 pattern_left_label_end++;
4797 }
4798
4799 /* If it's not trivial and there is no wildcard, it can't
4800 * match */
4801 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004802 return 0;
4803
4804 /* Make sure all labels match except the leftmost */
4805 hostname_left_label_end = strchr(hostname, '.');
4806 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004807 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004808 return 0;
4809
4810 /* Make sure the leftmost label of the hostname is long enough
4811 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004812 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004813 return 0;
4814
4815 /* Finally compare the string on either side of the
4816 * wildcard */
4817 prefixlen = pattern_wildcard - pattern;
4818 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004819 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4820 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004821 return 0;
4822
4823 return 1;
4824}
4825
4826static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4827{
4828 SSL *ssl;
4829 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004830 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004831 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004832 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004833
4834 int depth;
4835 X509 *cert;
4836 STACK_OF(GENERAL_NAME) *alt_names;
4837 int i;
4838 X509_NAME *cert_subject;
4839 char *str;
4840
4841 if (ok == 0)
4842 return ok;
4843
4844 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004845 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02004846 ssl_ctx = __conn_get_ssl_sock_ctx(conn);
Evan Broderbe554312013-06-27 00:05:25 -07004847
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004848 /* We're checking if the provided hostnames match the desired one. The
4849 * desired hostname comes from the SNI we presented if any, or if not
4850 * provided then it may have been explicitly stated using a "verifyhost"
4851 * directive. If neither is set, we don't care about the name so the
4852 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004853 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004854 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004855 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004856 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004857 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004858 if (!servername)
4859 return ok;
4860 }
Evan Broderbe554312013-06-27 00:05:25 -07004861
4862 /* We only need to verify the CN on the actual server cert,
4863 * not the indirect CAs */
4864 depth = X509_STORE_CTX_get_error_depth(ctx);
4865 if (depth != 0)
4866 return ok;
4867
4868 /* At this point, the cert is *not* OK unless we can find a
4869 * hostname match */
4870 ok = 0;
4871
4872 cert = X509_STORE_CTX_get_current_cert(ctx);
4873 /* It seems like this might happen if verify peer isn't set */
4874 if (!cert)
4875 return ok;
4876
4877 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4878 if (alt_names) {
4879 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4880 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4881 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004882#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004883 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4884#else
Evan Broderbe554312013-06-27 00:05:25 -07004885 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004886#endif
Evan Broderbe554312013-06-27 00:05:25 -07004887 ok = ssl_sock_srv_hostcheck(str, servername);
4888 OPENSSL_free(str);
4889 }
4890 }
4891 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004892 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004893 }
4894
4895 cert_subject = X509_get_subject_name(cert);
4896 i = -1;
4897 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4898 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004899 ASN1_STRING *value;
4900 value = X509_NAME_ENTRY_get_data(entry);
4901 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004902 ok = ssl_sock_srv_hostcheck(str, servername);
4903 OPENSSL_free(str);
4904 }
4905 }
4906
Willy Tarreau71d058c2017-07-26 20:09:56 +02004907 /* report the mismatch and indicate if SNI was used or not */
4908 if (!ok && !conn->err_code)
4909 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004910 return ok;
4911}
4912
Emeric Brun94324a42012-10-11 14:00:19 +02004913/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004914int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004915{
4916 int cfgerr = 0;
William Lallemand2c776f12021-12-28 18:47:17 +01004917 SSL_CTX *ctx;
William Lallemand0adafb32022-12-13 18:17:44 +01004918 /* Automatic memory computations need to know we use SSL there
4919 * If this is an internal proxy, don't use it for the computation */
William Lallemand04007cb2022-12-14 10:34:36 +01004920 if (!(srv->proxy->cap & PR_CAP_INT))
William Lallemand0adafb32022-12-13 18:17:44 +01004921 global.ssl_used_backend = 1;
Willy Tarreaufce03112015-01-15 21:32:40 +01004922
4923 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004924 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004925 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004926 ha_alert("out of memory.\n");
Emeric Brun821bb9b2017-06-15 16:37:39 +02004927 cfgerr++;
4928 return cfgerr;
4929 }
4930 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004931 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004932 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004933
William Lallemand2c776f12021-12-28 18:47:17 +01004934 if (srv->ssl_ctx.client_crt) {
4935 const int create_if_none = srv->flags & SRV_F_DYNAMIC ? 0 : 1;
4936 char *err = NULL;
4937 int err_code = 0;
4938
4939 /* If there is a crt keyword there, the SSL_CTX will be created here. */
4940 err_code = ssl_sock_load_srv_cert(srv->ssl_ctx.client_crt, srv, create_if_none, &err);
4941 if (err_code != ERR_NONE) {
4942 if ((err_code & ERR_WARN) && !(err_code & ERR_ALERT))
4943 ha_warning("%s", err);
4944 else
4945 ha_alert("%s", err);
4946
4947 if (err_code & (ERR_FATAL|ERR_ABORT))
4948 cfgerr++;
4949 }
4950 ha_free(&err);
4951 }
4952
4953 ctx = srv->ssl_ctx.ctx;
4954
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004955 /* The context will be uninitialized if there wasn't any "cert" option
4956 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004957 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004958 ctx = SSL_CTX_new(SSLv23_client_method());
4959 if (!ctx) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004960 ha_alert("unable to allocate ssl context.\n");
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004961 cfgerr++;
4962 return cfgerr;
4963 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004964
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004965 srv->ssl_ctx.ctx = ctx;
4966 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004967
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004968 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 +01004969
4970 return cfgerr;
4971}
4972
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004973/* Initialize an SSL context that will be used on the backend side.
4974 * Returns an error count.
4975 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004976static int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004977{
4978 struct proxy *curproxy = srv->proxy;
4979 int cfgerr = 0;
4980 long options =
4981 SSL_OP_ALL | /* all known workarounds for bugs */
4982 SSL_OP_NO_SSLv2 |
4983 SSL_OP_NO_COMPRESSION;
4984 long mode =
4985 SSL_MODE_ENABLE_PARTIAL_WRITE |
4986 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
4987 SSL_MODE_RELEASE_BUFFERS |
4988 SSL_MODE_SMALL_BUFFERS;
4989 int verify = SSL_VERIFY_NONE;
4990 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
4991 int i, min, max, hole;
4992 int flags = MC_SSL_O_ALL;
4993
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004994 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02004995 ha_warning("no-sslv3/no-tlsv1x are ignored for this server. "
4996 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n");
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004997 else
4998 flags = conf_ssl_methods->flags;
4999
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005000 /* Real min and max should be determinate with configuration and openssl's capabilities */
5001 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005002 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005003 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005004 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005005
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005006 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005007 min = max = CONF_TLSV_NONE;
5008 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005009 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005010 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005011 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005012 if (min) {
5013 if (hole) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005014 ha_warning("%s '%s': SSL/TLS versions range not contiguous for server '%s'. "
Christopher Faulet767a84b2017-11-24 16:50:31 +01005015 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
5016 proxy_type_str(curproxy), curproxy->id, srv->id,
5017 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005018 hole = 0;
5019 }
5020 max = i;
5021 }
5022 else {
5023 min = max = i;
5024 }
5025 }
5026 else {
5027 if (min)
5028 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005029 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005030 if (!min) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005031 ha_alert("%s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01005032 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005033 cfgerr += 1;
5034 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005035
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005036#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005037 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08005038 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005039 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005040 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005041 else
5042 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
5043 if (flags & methodVersions[i].flag)
5044 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005045#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005046 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005047 methodVersions[min].ctx_set_version(ctx, SET_MIN);
5048 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005049#endif
5050
5051 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
5052 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005053 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005054
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005055#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005056 if (global_ssl.async)
5057 mode |= SSL_MODE_ASYNC;
5058#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005059 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005060
Emeric Brun850efd52014-01-29 12:24:34 +01005061 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
5062 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01005063 switch (srv->ssl_ctx.verify) {
5064 case SSL_SOCK_VERIFY_NONE:
5065 verify = SSL_VERIFY_NONE;
5066 break;
5067 case SSL_SOCK_VERIFY_REQUIRED:
5068 verify = SSL_VERIFY_PEER;
5069 break;
5070 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005071 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02005072 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01005073 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02005074 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02005075 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005076 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005077 ha_alert("unable to set CA file '%s'.\n",
5078 srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005079 cfgerr++;
5080 }
5081 }
Emeric Brun850efd52014-01-29 12:24:34 +01005082 else {
5083 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005084 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 +01005085 else
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005086 ha_alert("verify is enabled but no CA file specified.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01005087 cfgerr++;
5088 }
Emeric Brunef42d922012-10-11 16:11:36 +02005089#ifdef X509_V_FLAG_CRL_CHECK
5090 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005091 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02005092
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01005093 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005094 ha_alert("unable to configure CRL file '%s'.\n",
5095 srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005096 cfgerr++;
5097 }
5098 else {
5099 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5100 }
5101 }
5102#endif
5103 }
5104
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005105 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5106 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02005107 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005108 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005109 ha_alert("unable to set SSL cipher list to '%s'.\n",
5110 srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02005111 cfgerr++;
5112 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005113
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05005114#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005115 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005116 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005117 ha_alert("unable to set TLS 1.3 cipher suites to '%s'.\n",
5118 srv->ssl_ctx.ciphersuites);
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005119 cfgerr++;
5120 }
5121#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01005122#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
5123 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005124 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01005125#endif
5126#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5127 if (srv->ssl_ctx.alpn_str)
5128 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
5129#endif
5130
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005131
5132 return cfgerr;
5133}
5134
5135/*
5136 * Prepare the frontend's SSL_CTX based on the server line configuration.
5137 * Since the CA file loading is made depending on the verify option of the
5138 * server line, the link between the SSL_CTX and the CA file tree entry is
5139 * made here.
5140 * If we want to create a link between the CA file entry and the corresponding
5141 * ckch instance (for CA file hot update), it needs to be done after
5142 * ssl_sock_prepare_srv_ssl_ctx.
5143 * Returns an error count.
5144 */
5145int ssl_sock_prep_srv_ctx_and_inst(const struct server *srv, SSL_CTX *ctx,
5146 struct ckch_inst *ckch_inst)
5147{
5148 int cfgerr = 0;
5149
5150 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, ctx);
5151 if (!cfgerr && ckch_inst)
5152 ckch_inst_add_cafile_link(ckch_inst, NULL, NULL, srv);
Emeric Brun94324a42012-10-11 14:00:19 +02005153
5154 return cfgerr;
5155}
5156
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005157
Frédéric Lécailleec216522020-11-23 14:33:30 +01005158/*
5159 * Create an initial CTX used to start the SSL connections.
5160 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
5161 * Returns 0 if succeeded, or something >0 if not.
5162 */
5163#ifdef USE_QUIC
5164static int ssl_initial_ctx(struct bind_conf *bind_conf)
5165{
5166 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
5167 return ssl_quic_initial_ctx(bind_conf);
5168 else
5169 return ssl_sock_initial_ctx(bind_conf);
5170}
5171#else
5172static int ssl_initial_ctx(struct bind_conf *bind_conf)
5173{
5174 return ssl_sock_initial_ctx(bind_conf);
5175}
5176#endif
5177
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005178/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005179 * be NULL, in which case nothing is done. Returns the number of errors
5180 * encountered.
5181 */
Willy Tarreau03209342016-12-22 17:08:28 +01005182int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005183{
5184 struct ebmb_node *node;
5185 struct sni_ctx *sni;
5186 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01005187 int errcode = 0;
5188 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02005189
Willy Tarreaufce03112015-01-15 21:32:40 +01005190 /* Automatic memory computations need to know we use SSL there */
5191 global.ssl_used_frontend = 1;
5192
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005193 /* Create initial_ctx used to start the ssl connection before do switchctx */
5194 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01005195 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005196 /* It should not be necessary to call this function, but it's
5197 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01005198 to initial_ctx in ssl_initial_ctx. */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005199 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, NULL, bind_conf->initial_ctx, NULL, &errmsg);
5200 }
5201 if (bind_conf->default_ctx) {
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005202 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 +01005203 }
Emeric Brun0bed9942014-10-30 19:25:24 +01005204
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005205 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005206 while (node) {
5207 sni = ebmb_entry(node, struct sni_ctx, name);
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005208 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005209 /* only initialize the CTX on its first occurrence and
5210 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005211 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
5212 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005213 node = ebmb_next(node);
5214 }
5215
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005216 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005217 while (node) {
5218 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01005219 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005220 /* only initialize the CTX on its first occurrence and
5221 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005222 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005223 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005224 node = ebmb_next(node);
5225 }
William Lallemand8b453912019-11-21 15:48:10 +01005226
5227 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005228 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005229 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005230 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005231 err++;
5232 }
5233
5234 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005235 return err;
5236}
5237
Willy Tarreau55d37912016-12-21 23:38:39 +01005238/* Prepares all the contexts for a bind_conf and allocates the shared SSL
5239 * context if needed. Returns < 0 on error, 0 on success. The warnings and
5240 * alerts are directly emitted since the rest of the stack does it below.
5241 */
5242int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
5243{
5244 struct proxy *px = bind_conf->frontend;
5245 int alloc_ctx;
5246 int err;
5247
Willy Tarreau11ba4042022-05-20 15:56:32 +02005248 if (!(bind_conf->options & BC_O_USE_SSL)) {
Willy Tarreau55d37912016-12-21 23:38:39 +01005249 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005250 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
5251 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01005252 }
5253 return 0;
5254 }
5255 if (!bind_conf->default_ctx) {
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005256 if (bind_conf->strict_sni && !(bind_conf->options & BC_O_GENERATE_CERTS)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005257 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5258 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005259 }
5260 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005261 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5262 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005263 return -1;
5264 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005265 }
William Lallemandc61c0b32017-12-04 18:46:39 +01005266 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005267 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02005268 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
Willy Tarreau91358592021-06-15 08:08:04 +02005269 sizeof(*sh_ssl_sess_tree), (global.nbthread > 1));
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02005270 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005271 if (alloc_ctx == SHCTX_E_INIT_LOCK)
5272 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");
5273 else
5274 ha_alert("Unable to allocate SSL session cache.\n");
5275 return -1;
5276 }
5277 /* free block callback */
5278 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5279 /* init the root tree within the extra space */
5280 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5281 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01005282 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005283 err = 0;
5284 /* initialize all certificate contexts */
5285 err += ssl_sock_prepare_all_ctx(bind_conf);
5286
5287 /* initialize CA variables if the certificates generation is enabled */
5288 err += ssl_sock_load_ca(bind_conf);
5289
5290 return -err;
5291}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005292
William Lallemand231610a2021-12-30 11:25:43 +01005293/* release ssl context allocated for servers. Most of the field free here
5294 * must also be allocated in srv_ssl_settings_cpy() */
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005295void ssl_sock_free_srv_ctx(struct server *srv)
5296{
Olivier Houchardc7566002018-11-20 23:33:50 +01005297#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
William Lallemand231610a2021-12-30 11:25:43 +01005298 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005299#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005300#ifdef OPENSSL_NPN_NEGOTIATED
William Lallemand231610a2021-12-30 11:25:43 +01005301 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005302#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005303 if (srv->ssl_ctx.reused_sess) {
5304 int i;
5305
William Lallemande18d4e82021-11-17 02:59:21 +01005306 for (i = 0; i < global.nbthread; i++) {
Willy Tarreaue709e822021-02-26 21:06:32 +01005307 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
William Lallemande18d4e82021-11-17 02:59:21 +01005308 ha_free(&srv->ssl_ctx.reused_sess[i].sni);
5309 }
Willy Tarreaue709e822021-02-26 21:06:32 +01005310 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005311 }
5312
Willy Tarreaue709e822021-02-26 21:06:32 +01005313 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005314 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005315 srv->ssl_ctx.ctx = NULL;
5316 }
William Lallemand231610a2021-12-30 11:25:43 +01005317
5318 ha_free(&srv->ssl_ctx.ca_file);
5319 ha_free(&srv->ssl_ctx.crl_file);
5320 ha_free(&srv->ssl_ctx.client_crt);
5321 ha_free(&srv->ssl_ctx.verify_host);
5322#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5323 ha_free(&srv->sni_expr);
William Lallemand43c2ce42022-03-16 17:48:19 +01005324 release_sample_expr(srv->ssl_ctx.sni);
5325 srv->ssl_ctx.sni = NULL;
William Lallemand231610a2021-12-30 11:25:43 +01005326#endif
5327 ha_free(&srv->ssl_ctx.ciphers);
5328#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
5329 ha_free(&srv->ssl_ctx.ciphersuites);
5330#endif
William Lallemande69563f2021-12-30 14:45:19 +01005331 /* If there is a certificate we must unlink the ckch instance */
5332 ckch_inst_free(srv->ssl_ctx.inst);
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005333}
5334
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005335/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005336 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5337 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005338void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005339{
5340 struct ebmb_node *node, *back;
5341 struct sni_ctx *sni;
5342
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005343 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005344 while (node) {
5345 sni = ebmb_entry(node, struct sni_ctx, name);
5346 back = ebmb_next(node);
5347 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005348 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005349 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005350 free(sni);
5351 node = back;
5352 }
5353
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005354 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005355 while (node) {
5356 sni = ebmb_entry(node, struct sni_ctx, name);
5357 back = ebmb_next(node);
5358 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005359 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005360 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005361 free(sni);
5362 node = back;
5363 }
William Lallemandb2408692020-06-24 09:54:29 +02005364
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005365 SSL_CTX_free(bind_conf->initial_ctx);
5366 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005367 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005368 bind_conf->default_ctx = NULL;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005369 bind_conf->default_inst = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005370 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005371}
William Lallemandb2408692020-06-24 09:54:29 +02005372
5373
5374void ssl_sock_deinit()
5375{
5376 crtlist_deinit(); /* must be free'd before the ckchs */
5377 ckch_deinit();
5378}
5379REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005380
Willy Tarreau795cdab2016-12-22 17:30:54 +01005381/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5382void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5383{
5384 ssl_sock_free_ca(bind_conf);
5385 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005386 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005387 free(bind_conf->ca_sign_file);
5388 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005389 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005390 free(bind_conf->keys_ref->filename);
5391 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005392 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005393 free(bind_conf->keys_ref);
5394 }
5395 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005396 bind_conf->ca_sign_pass = NULL;
5397 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005398}
5399
Christopher Faulet31af49d2015-06-09 17:29:50 +02005400/* Load CA cert file and private key used to generate certificates */
5401int
Willy Tarreau03209342016-12-22 17:08:28 +01005402ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005403{
Willy Tarreau03209342016-12-22 17:08:28 +01005404 struct proxy *px = bind_conf->frontend;
William Lallemand52ddd992022-11-22 11:51:53 +01005405 struct ckch_data *data = NULL;
Shimi Gersner5846c492020-08-23 13:58:12 +03005406 int ret = 0;
5407 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005408
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005409 if (!(bind_conf->options & BC_O_GENERATE_CERTS))
Shimi Gersner5846c492020-08-23 13:58:12 +03005410 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005411
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005412#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005413 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005414 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005415 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005416 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005417 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005418#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005419
Christopher Faulet31af49d2015-06-09 17:29:50 +02005420 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005421 ha_alert("Proxy '%s': cannot enable certificate generation, "
5422 "no CA certificate File configured at [%s:%d].\n",
5423 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005424 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005425 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005426
Shimi Gersner5846c492020-08-23 13:58:12 +03005427 /* Allocate cert structure */
William Lallemand52ddd992022-11-22 11:51:53 +01005428 data = calloc(1, sizeof(*data));
5429 if (!data) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005430 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5431 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5432 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005433 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005434
5435 /* Try to parse file */
William Lallemand52ddd992022-11-22 11:51:53 +01005436 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, data, &err)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005437 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5438 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005439 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005440 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005441 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005442
5443 /* Fail if missing cert or pkey */
William Lallemand52ddd992022-11-22 11:51:53 +01005444 if ((!data->cert) || (!data->key)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005445 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5446 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5447 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005448 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005449
Shimi Gersner5846c492020-08-23 13:58:12 +03005450 /* Final assignment to bind */
William Lallemand52ddd992022-11-22 11:51:53 +01005451 bind_conf->ca_sign_ckch = data;
Shimi Gersner5846c492020-08-23 13:58:12 +03005452 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005453
Shimi Gersner5846c492020-08-23 13:58:12 +03005454 failed:
William Lallemand52ddd992022-11-22 11:51:53 +01005455 if (data) {
5456 ssl_sock_free_cert_key_and_chain_contents(data);
5457 free(data);
Shimi Gersner5846c492020-08-23 13:58:12 +03005458 }
5459
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005460 bind_conf->options &= ~BC_O_GENERATE_CERTS;
Shimi Gersner5846c492020-08-23 13:58:12 +03005461 ret++;
5462 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005463}
5464
5465/* Release CA cert and private key used to generate certificated */
5466void
5467ssl_sock_free_ca(struct bind_conf *bind_conf)
5468{
Shimi Gersner5846c492020-08-23 13:58:12 +03005469 if (bind_conf->ca_sign_ckch) {
5470 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005471 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005472 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005473}
5474
Emeric Brun46591952012-05-18 15:47:34 +02005475/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005476 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5477 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5478 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5479 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005480 * 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 +01005481 * as parameters to this function.
5482 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5483 * CO_ER_SSL_NO_MEM.
5484 */
5485int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5486 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5487{
5488 int retry = 1;
5489
5490 retry:
5491 /* Alloc a new SSL session. */
5492 *ssl = SSL_new(ssl_ctx);
5493 if (!*ssl) {
5494 if (!retry--)
5495 goto err;
5496
5497 pool_gc(NULL);
5498 goto retry;
5499 }
5500
5501 *bio = BIO_new(bio_meth);
5502 if (!*bio) {
5503 SSL_free(*ssl);
5504 *ssl = NULL;
5505 if (!retry--)
5506 goto err;
5507
5508 pool_gc(NULL);
5509 goto retry;
5510 }
5511
5512 BIO_set_data(*bio, ctx);
5513 SSL_set_bio(*ssl, *bio, *bio);
5514
5515 /* set connection pointer. */
5516 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5517 SSL_free(*ssl);
5518 *ssl = NULL;
5519 if (!retry--)
5520 goto err;
5521
5522 pool_gc(NULL);
5523 goto retry;
5524 }
5525
5526 return 0;
5527
5528 err:
5529 conn->err_code = CO_ER_SSL_NO_MEM;
5530 return -1;
5531}
5532
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005533/* This function is called when all the XPRT have been initialized. We can
5534 * now attempt to start the SSL handshake.
5535 */
5536static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5537{
5538 struct ssl_sock_ctx *ctx = xprt_ctx;
5539
5540 if (ctx->xprt->start) {
5541 int ret;
5542
5543 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5544 if (ret < 0)
5545 return ret;
5546 }
5547 tasklet_wakeup(ctx->wait_event.tasklet);
5548
5549 return 0;
5550}
5551
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005552/*
Emeric Brun46591952012-05-18 15:47:34 +02005553 * This function is called if SSL * context is not yet allocated. The function
5554 * is designed to be called before any other data-layer operation and sets the
5555 * handshake flag on the connection. It is safe to call it multiple times.
5556 * It returns 0 on success and -1 in error case.
5557 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005558static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005559{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005560 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005561 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005562 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005563 return 0;
5564
Olivier Houchard66ab4982019-02-26 18:37:15 +01005565 ctx = pool_alloc(ssl_sock_ctx_pool);
5566 if (!ctx) {
5567 conn->err_code = CO_ER_SSL_NO_MEM;
5568 return -1;
5569 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005570 ctx->wait_event.tasklet = tasklet_new();
5571 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005572 conn->err_code = CO_ER_SSL_NO_MEM;
5573 pool_free(ssl_sock_ctx_pool, ctx);
5574 return -1;
5575 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005576 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5577 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005578 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005579 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005580 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005581 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005582 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005583 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005584 ctx->xprt_st = 0;
5585 ctx->xprt_ctx = NULL;
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005586 ctx->error_code = 0;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005587
5588 /* Only work with sockets for now, this should be adapted when we'll
5589 * add QUIC support.
5590 */
5591 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005592 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005593 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5594 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005595 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005596
Willy Tarreau82531f62021-10-06 12:15:18 +02005597 if (global.maxsslconn && global.sslconns >= global.maxsslconn) {
Willy Tarreau20879a02012-12-03 16:32:10 +01005598 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005599 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005600 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005601
Emeric Brun46591952012-05-18 15:47:34 +02005602 /* If it is in client mode initiate SSL session
5603 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005604 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005605 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5606 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005607 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005608
Olivier Houchard66ab4982019-02-26 18:37:15 +01005609 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005610 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005611 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5612 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5613 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 +01005614 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005615 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005616 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005617 } else if (sess) {
5618 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005619 }
5620 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005621 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005622
Emeric Brun46591952012-05-18 15:47:34 +02005623 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005624 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005625
Willy Tarreau82531f62021-10-06 12:15:18 +02005626 _HA_ATOMIC_INC(&global.sslconns);
5627 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005628 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005629 return 0;
5630 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005631 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005632 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005633
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005634 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5635 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005636 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005637
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005638#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005639 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005640 b_alloc(&ctx->early_buf);
5641 SSL_set_max_early_data(ctx->ssl,
5642 /* Only allow early data if we managed to allocate
5643 * a buffer.
5644 */
5645 (!b_is_null(&ctx->early_buf)) ?
5646 global.tune.bufsize - global.tune.maxrewrite : 0);
5647 }
5648#endif
5649
Olivier Houchard66ab4982019-02-26 18:37:15 +01005650 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005651
Emeric Brun46591952012-05-18 15:47:34 +02005652 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005653 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005654#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005655 if (bc->ssl_conf.early_data)
5656 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005657#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005658
Willy Tarreau82531f62021-10-06 12:15:18 +02005659 _HA_ATOMIC_INC(&global.sslconns);
5660 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005661 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005662 return 0;
5663 }
5664 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005665 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005666err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005667 if (ctx && ctx->wait_event.tasklet)
5668 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005669 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005670 return -1;
5671}
5672
5673
5674/* This is the callback which is used when an SSL handshake is pending. It
5675 * updates the FD status if it wants some polling before being called again.
5676 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5677 * otherwise it returns non-zero and removes itself from the connection's
5678 * flags (the bit is provided in <flag> by the caller).
5679 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005680static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005681{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005682 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Emeric Brun46591952012-05-18 15:47:34 +02005683 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005684 struct ssl_counters *counters = NULL;
5685 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005686 struct listener *li;
5687 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005688 socklen_t lskerr;
5689 int skerr;
5690
Emeric Brun46591952012-05-18 15:47:34 +02005691
Willy Tarreau3c728722014-01-23 13:50:42 +01005692 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005693 return 0;
5694
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005695 /* get counters */
5696 switch (obj_type(conn->target)) {
5697 case OBJ_TYPE_LISTENER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005698 li = __objt_listener(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005699 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5700 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5701 &ssl_stats_module);
5702 break;
5703
5704 case OBJ_TYPE_SERVER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005705 srv = __objt_server(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005706 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5707 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5708 &ssl_stats_module);
5709 break;
5710
5711 default:
5712 break;
5713 }
5714
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005715 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005716 goto out_error;
5717
Willy Tarreau06300382021-02-02 15:42:25 +01005718 /* don't start calculating a handshake on a dead connection */
5719 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5720 goto out_error;
5721
5722 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5723 * status from the lower layers, so let's check the FD directly. Ideally
5724 * the xprt layers should provide some status indicating their knowledge
5725 * of shutdowns or error.
5726 */
Willy Tarreau07ecfc52022-04-11 18:07:03 +02005727 BUG_ON(conn->flags & CO_FL_FDLESS);
5728
Willy Tarreau06300382021-02-02 15:42:25 +01005729 skerr = 0;
5730 lskerr = sizeof(skerr);
5731 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5732 skerr != 0)
5733 goto out_error;
5734
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005735#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005736 /*
5737 * Check if we have early data. If we do, we have to read them
5738 * before SSL_do_handshake() is called, And there's no way to
5739 * detect early data, except to try to read them
5740 */
5741 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005742 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005743
Olivier Houchard54907bb2019-12-19 15:02:39 +01005744 while (1) {
5745 ret = SSL_read_early_data(ctx->ssl,
5746 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5747 &read_data);
5748 if (ret == SSL_READ_EARLY_DATA_ERROR)
5749 goto check_error;
5750 if (read_data > 0) {
5751 conn->flags |= CO_FL_EARLY_DATA;
5752 b_add(&ctx->early_buf, read_data);
5753 }
5754 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5755 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5756 if (!b_data(&ctx->early_buf))
5757 b_free(&ctx->early_buf);
5758 break;
5759 }
5760 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005761 }
5762#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005763 /* If we use SSL_do_handshake to process a reneg initiated by
5764 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5765 * Usually SSL_write and SSL_read are used and process implicitly
5766 * the reneg handshake.
5767 * Here we use SSL_peek as a workaround for reneg.
5768 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005769 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005770 char c;
5771
Olivier Houchard66ab4982019-02-26 18:37:15 +01005772 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005773 if (ret <= 0) {
5774 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005775 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005776
Emeric Brun674b7432012-11-08 19:21:55 +01005777 if (ret == SSL_ERROR_WANT_WRITE) {
5778 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005779 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005780 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005781 return 0;
5782 }
5783 else if (ret == SSL_ERROR_WANT_READ) {
5784 /* handshake may have been completed but we have
5785 * no more data to read.
5786 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005787 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005788 ret = 1;
5789 goto reneg_ok;
5790 }
5791 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005792 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005793 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005794 return 0;
5795 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005796#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005797 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005798 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005799 return 0;
5800 }
5801#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005802 else if (ret == SSL_ERROR_SYSCALL) {
5803 /* if errno is null, then connection was successfully established */
5804 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5805 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005806 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005807#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5808 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005809 conn->err_code = CO_ER_SSL_HANDSHAKE;
5810#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005811 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005812#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005813 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005814 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005815 empty_handshake = state == TLS_ST_BEFORE;
5816#else
Lukas Tribus49799162019-07-08 14:29:15 +02005817 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5818 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005819#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005820 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005821 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005822 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005823 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5824 else
5825 conn->err_code = CO_ER_SSL_EMPTY;
5826 }
5827 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005828 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005829 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5830 else
5831 conn->err_code = CO_ER_SSL_ABORT;
5832 }
5833 }
5834 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005835 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005836 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005837 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005838 conn->err_code = CO_ER_SSL_HANDSHAKE;
5839 }
Lukas Tribus49799162019-07-08 14:29:15 +02005840#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005841 }
Emeric Brun674b7432012-11-08 19:21:55 +01005842 goto out_error;
5843 }
5844 else {
5845 /* Fail on all other handshake errors */
5846 /* Note: OpenSSL may leave unread bytes in the socket's
5847 * buffer, causing an RST to be emitted upon close() on
5848 * TCP sockets. We first try to drain possibly pending
5849 * data to avoid this as much as possible.
5850 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005851 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005852 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005853 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005854 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005855 goto out_error;
5856 }
5857 }
5858 /* read some data: consider handshake completed */
5859 goto reneg_ok;
5860 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005861 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005862check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005863 if (ret != 1) {
5864 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005865 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005866
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005867 if (!ctx->error_code)
5868 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton7c6898e2021-07-29 09:45:51 +02005869
Emeric Brun46591952012-05-18 15:47:34 +02005870 if (ret == SSL_ERROR_WANT_WRITE) {
5871 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005872 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005873 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005874 return 0;
5875 }
5876 else if (ret == SSL_ERROR_WANT_READ) {
5877 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005878 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005879 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5880 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005881 return 0;
5882 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005883#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005884 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005885 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005886 return 0;
5887 }
5888#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005889 else if (ret == SSL_ERROR_SYSCALL) {
5890 /* if errno is null, then connection was successfully established */
5891 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5892 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005893 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005894#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5895 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005896 conn->err_code = CO_ER_SSL_HANDSHAKE;
5897#else
5898 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005899#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005900 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005901 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005902 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005903#else
Lukas Tribus49799162019-07-08 14:29:15 +02005904 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5905 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005906#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005907 if (empty_handshake) {
5908 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005909 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005910 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5911 else
5912 conn->err_code = CO_ER_SSL_EMPTY;
5913 }
5914 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005915 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005916 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5917 else
5918 conn->err_code = CO_ER_SSL_ABORT;
5919 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005920 }
5921 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005922 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005923 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5924 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005925 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005926 }
Lukas Tribus49799162019-07-08 14:29:15 +02005927#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005928 }
Willy Tarreau89230192012-09-28 20:22:13 +02005929 goto out_error;
5930 }
Emeric Brun46591952012-05-18 15:47:34 +02005931 else {
5932 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005933 /* Note: OpenSSL may leave unread bytes in the socket's
5934 * buffer, causing an RST to be emitted upon close() on
5935 * TCP sockets. We first try to drain possibly pending
5936 * data to avoid this as much as possible.
5937 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005938 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005939 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005940 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005941 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005942 goto out_error;
5943 }
5944 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005945#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005946 else {
5947 /*
5948 * If the server refused the early data, we have to send a
5949 * 425 to the client, as we no longer have the data to sent
5950 * them again.
5951 */
5952 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005953 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005954 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5955 goto out_error;
5956 }
5957 }
5958 }
5959#endif
5960
Emeric Brun46591952012-05-18 15:47:34 +02005961
Emeric Brun674b7432012-11-08 19:21:55 +01005962reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005963
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005964#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00005965 /* ASYNC engine API doesn't support moving read/write
5966 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005967 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005968 */
5969 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005970 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005971#endif
Emeric Brun46591952012-05-18 15:47:34 +02005972 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005973 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005974 if (objt_server(conn->target)) {
5975 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5976 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5977 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005978 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005979 else {
5980 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5981 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5982 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5983 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005984
Willy Tarreau42995282020-11-06 13:19:18 +01005985 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01005986 HA_ATOMIC_INC(&counters->sess);
5987 HA_ATOMIC_INC(&counters_px->sess);
Willy Tarreau42995282020-11-06 13:19:18 +01005988 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005989 }
Willy Tarreau42995282020-11-06 13:19:18 +01005990 else if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01005991 HA_ATOMIC_INC(&counters->reused_sess);
5992 HA_ATOMIC_INC(&counters_px->reused_sess);
Emeric Brun46591952012-05-18 15:47:34 +02005993 }
5994
5995 /* The connection is now established at both layers, it's time to leave */
5996 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5997 return 1;
5998
5999 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006000 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006001 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006002 ERR_clear_error();
6003
Emeric Brun9fa89732012-10-04 17:09:56 +02006004 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01006005 if (objt_server(conn->target)) {
6006 struct server *s = __objt_server(conn->target);
6007 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
6008 * one cache per thread, it only prevents to flush it from the CLI in
6009 * another thread */
6010
6011 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01006012 if (s->ssl_ctx.reused_sess[tid].ptr)
6013 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01006014 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02006015 }
6016
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006017 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006018 HA_ATOMIC_INC(&counters->failed_handshake);
6019 HA_ATOMIC_INC(&counters_px->failed_handshake);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006020 }
6021
Emeric Brun46591952012-05-18 15:47:34 +02006022 /* Fail on all other handshake errors */
6023 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01006024 if (!conn->err_code)
6025 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006026 return 0;
6027}
6028
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006029/* Called from the upper layer, to subscribe <es> to events <event_type>. The
6030 * event subscriber <es> is not allowed to change from a previous call as long
6031 * as at least one event is still subscribed. The <event_type> must only be a
6032 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
6033 * unless the transport layer was already released.
6034 */
6035static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006036{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006037 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006038
Olivier Houchard0ff28652019-06-24 18:57:39 +02006039 if (!ctx)
6040 return -1;
6041
Willy Tarreau113d52b2020-01-10 09:20:26 +01006042 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006043 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006044
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006045 ctx->subs = es;
6046 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006047
6048 /* we may have to subscribe to lower layers for new events */
6049 event_type &= ~ctx->wait_event.events;
6050 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
6051 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006052 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006053}
6054
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006055/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
6056 * The <es> pointer is not allowed to differ from the one passed to the
6057 * subscribe() call. It always returns zero.
6058 */
6059static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006060{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006061 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006062
Willy Tarreau113d52b2020-01-10 09:20:26 +01006063 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006064 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006065
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006066 es->events &= ~event_type;
6067 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01006068 ctx->subs = NULL;
6069
6070 /* If we subscribed, and we're not doing the handshake,
6071 * then we subscribed because the upper layer asked for it,
6072 * as the upper layer is no longer interested, we can
6073 * unsubscribe too.
6074 */
6075 event_type &= ctx->wait_event.events;
6076 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
6077 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006078
6079 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006080}
6081
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006082/* The connection has been taken over, so destroy the old tasklet and create
6083 * a new one. The original thread ID must be passed into orig_tid
6084 * It should be called with the takeover lock for the old thread held.
6085 * Returns 0 on success, and -1 on failure
6086 */
6087static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
6088{
6089 struct ssl_sock_ctx *ctx = xprt_ctx;
6090 struct tasklet *tl = tasklet_new();
6091
6092 if (!tl)
6093 return -1;
6094
6095 ctx->wait_event.tasklet->context = NULL;
6096 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
6097 ctx->wait_event.tasklet = tl;
6098 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
6099 ctx->wait_event.tasklet->context = ctx;
6100 return 0;
6101}
6102
Willy Tarreau41491682021-03-02 17:29:56 +01006103/* notify the next xprt that the connection is about to become idle and that it
6104 * may be stolen at any time after the function returns and that any tasklet in
6105 * the chain must be careful before dereferencing its context.
6106 */
6107static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
6108{
6109 struct ssl_sock_ctx *ctx = xprt_ctx;
6110
6111 if (!ctx || !ctx->wait_event.tasklet)
6112 return;
6113
6114 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6115 if (ctx->xprt)
6116 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
6117}
6118
6119/* notify the next xprt that the connection is not idle anymore and that it may
6120 * not be stolen before the next xprt_set_idle().
6121 */
6122static void ssl_set_used(struct connection *conn, void *xprt_ctx)
6123{
6124 struct ssl_sock_ctx *ctx = xprt_ctx;
6125
6126 if (!ctx || !ctx->wait_event.tasklet)
6127 return;
6128
6129 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6130 if (ctx->xprt)
6131 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
6132}
6133
Olivier Houchard2e055482019-05-27 19:50:12 +02006134/* Use the provided XPRT as an underlying XPRT, and provide the old one.
6135 * Returns 0 on success, and non-zero on failure.
6136 */
6137static 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)
6138{
6139 struct ssl_sock_ctx *ctx = xprt_ctx;
6140
6141 if (oldxprt_ops != NULL)
6142 *oldxprt_ops = ctx->xprt;
6143 if (oldxprt_ctx != NULL)
6144 *oldxprt_ctx = ctx->xprt_ctx;
6145 ctx->xprt = toadd_ops;
6146 ctx->xprt_ctx = toadd_ctx;
6147 return 0;
6148}
6149
Olivier Houchard5149b592019-05-23 17:47:36 +02006150/* Remove the specified xprt. If if it our underlying XPRT, remove it and
6151 * return 0, otherwise just call the remove_xprt method from the underlying
6152 * XPRT.
6153 */
6154static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
6155{
6156 struct ssl_sock_ctx *ctx = xprt_ctx;
6157
6158 if (ctx->xprt_ctx == toremove_ctx) {
6159 ctx->xprt_ctx = newctx;
6160 ctx->xprt = newops;
6161 return 0;
6162 }
6163 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
6164}
6165
Willy Tarreau144f84a2021-03-02 16:09:26 +01006166struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02006167{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006168 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006169 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006170 struct connection *conn;
6171 int conn_in_list;
6172 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006173
Willy Tarreau41491682021-03-02 17:29:56 +01006174 if (state & TASK_F_USR1) {
6175 /* the tasklet was idling on an idle connection, it might have
6176 * been stolen, let's be careful!
6177 */
6178 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6179 if (tl->context == NULL) {
6180 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6181 tasklet_free(tl);
6182 return NULL;
6183 }
6184 conn = ctx->conn;
6185 conn_in_list = conn->flags & CO_FL_LIST_MASK;
6186 if (conn_in_list)
6187 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006188 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01006189 } else {
6190 conn = ctx->conn;
6191 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006192 }
Willy Tarreau41491682021-03-02 17:29:56 +01006193
Olivier Houchardea8dd942019-05-20 14:02:16 +02006194 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01006195 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006196 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006197 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
6198 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01006199 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006200 }
6201 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006202 /* If we had an error, or the handshake is done and I/O is available,
6203 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01006204 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02006205 * we can't be sure conn_fd_handler() will be called again.
6206 */
6207 if ((ctx->conn->flags & CO_FL_ERROR) ||
6208 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006209 int woke = 0;
6210
6211 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006212 if (ctx->subs) {
6213 tasklet_wakeup(ctx->subs->tasklet);
6214 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006215 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006216 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006217 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006218
Olivier Houchardea8dd942019-05-20 14:02:16 +02006219 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01006220 * upper layers know. If we have no mux, create it,
6221 * and once we have a mux, call its wake method if we didn't
6222 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02006223 */
6224 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01006225 if (!ctx->conn->mux)
6226 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006227 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006228 ret = ctx->conn->mux->wake(ctx->conn);
6229 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006230 }
6231 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006232#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006233 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006234 else if (b_data(&ctx->early_buf) && ctx->subs &&
6235 ctx->subs->events & SUB_RETRY_RECV) {
6236 tasklet_wakeup(ctx->subs->tasklet);
6237 ctx->subs->events &= ~SUB_RETRY_RECV;
6238 if (!ctx->subs->events)
6239 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01006240 }
6241#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006242leave:
6243 if (!ret && conn_in_list) {
6244 struct server *srv = objt_server(conn->target);
6245
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006246 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006247 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau85223482022-09-29 20:32:43 +02006248 eb64_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006249 else
Willy Tarreau85223482022-09-29 20:32:43 +02006250 eb64_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006251 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006252 }
Willy Tarreau74163142021-03-13 11:30:19 +01006253 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006254}
6255
Emeric Brun46591952012-05-18 15:47:34 +02006256/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01006257 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02006258 * buffer wraps, in which case a second call may be performed. The connection's
6259 * flags are updated with whatever special event is detected (error, read0,
6260 * empty). The caller is responsible for taking care of those events and
6261 * avoiding the call if inappropriate. The function does not call the
6262 * connection's polling update function, so the caller is responsible for this.
6263 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006264static 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 +02006265{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006266 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02006267 ssize_t ret;
6268 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02006269
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006270 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006271 goto out_error;
6272
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006273#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006274 if (b_data(&ctx->early_buf)) {
6275 try = b_contig_space(buf);
6276 if (try > b_data(&ctx->early_buf))
6277 try = b_data(&ctx->early_buf);
6278 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
6279 b_add(buf, try);
6280 b_del(&ctx->early_buf, try);
6281 if (b_data(&ctx->early_buf) == 0)
6282 b_free(&ctx->early_buf);
6283 return try;
6284 }
6285#endif
6286
Willy Tarreau911db9b2020-01-23 16:27:54 +01006287 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006288 /* a handshake was requested */
6289 return 0;
6290
Emeric Brun46591952012-05-18 15:47:34 +02006291 /* read the largest possible block. For this, we perform only one call
6292 * to recv() unless the buffer wraps and we exactly fill the first hunk,
6293 * in which case we accept to do it once again. A new attempt is made on
6294 * EINTR too.
6295 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01006296 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006297
Willy Tarreau591d4452018-06-15 17:21:00 +02006298 try = b_contig_space(buf);
6299 if (!try)
6300 break;
6301
Willy Tarreauabf08d92014-01-14 11:31:27 +01006302 if (try > count)
6303 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02006304
Olivier Houchard66ab4982019-02-26 18:37:15 +01006305 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02006306
Emeric Brune1f38db2012-09-03 20:36:47 +02006307 if (conn->flags & CO_FL_ERROR) {
6308 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006309 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006310 }
Emeric Brun46591952012-05-18 15:47:34 +02006311 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006312 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006313 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006314 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006315 }
Emeric Brun46591952012-05-18 15:47:34 +02006316 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006317 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006318 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006319 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006320 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006321 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006322#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006323 /* Async mode can be re-enabled, because we're leaving data state.*/
6324 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006325 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006326#endif
Emeric Brun46591952012-05-18 15:47:34 +02006327 break;
6328 }
6329 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006330 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006331 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6332 SUB_RETRY_RECV,
6333 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006334 /* handshake is running, and it may need to re-enable read */
6335 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006336#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006337 /* Async mode can be re-enabled, because we're leaving data state.*/
6338 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006339 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006340#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006341 break;
6342 }
Emeric Brun46591952012-05-18 15:47:34 +02006343 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006344 } else if (ret == SSL_ERROR_ZERO_RETURN)
6345 goto read0;
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006346 else if (ret == SSL_ERROR_SSL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006347 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6348 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006349 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006350 conn->err_code = CO_ERR_SSL_FATAL;
6351 }
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006352 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6353 * stack before shutting down the connection for
6354 * reading. */
Willy Tarreauacef5e22022-04-25 20:32:15 +02006355 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN || errno == EWOULDBLOCK))
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006356 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006357 /* otherwise it's a real error */
6358 goto out_error;
6359 }
6360 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006361 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006362 return done;
6363
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006364 clear_ssl_error:
6365 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006366 ssl_sock_dump_errors(conn, NULL);
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006367 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006368 read0:
6369 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006370 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006371
Emeric Brun46591952012-05-18 15:47:34 +02006372 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006373 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006374 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006375 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006376 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006377 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006378}
6379
6380
Willy Tarreau787db9a2018-06-14 18:31:46 +02006381/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6382 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6383 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006384 * Only one call to send() is performed, unless the buffer wraps, in which case
6385 * a second call may be performed. The connection's flags are updated with
6386 * whatever special event is detected (error, empty). The caller is responsible
6387 * for taking care of those events and avoiding the call if inappropriate. The
6388 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006389 * is responsible for this. The buffer's output is not adjusted, it's up to the
6390 * caller to take care of this. It's up to the caller to update the buffer's
6391 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006392 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006393static 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 +02006394{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006395 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006396 ssize_t ret;
6397 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006398
6399 done = 0;
6400
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006401 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006402 goto out_error;
6403
Willy Tarreau911db9b2020-01-23 16:27:54 +01006404 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006405 /* a handshake was requested */
6406 return 0;
6407
6408 /* send the largest possible block. For this we perform only one call
6409 * to send() unless the buffer wraps and we exactly fill the first hunk,
6410 * in which case we accept to do it once again.
6411 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006412 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006413#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006414 size_t written_data;
6415#endif
6416
Willy Tarreau787db9a2018-06-14 18:31:46 +02006417 try = b_contig_data(buf, done);
6418 if (try > count)
6419 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006420
Thomas Prückl10243932022-04-27 13:04:54 +02006421 if (global_ssl.hard_max_record && try > global_ssl.hard_max_record)
6422 try = global_ssl.hard_max_record;
6423
Willy Tarreau7bed9452014-02-02 02:00:24 +01006424 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006425 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006426 global_ssl.max_record && try > global_ssl.max_record) {
6427 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006428 }
6429 else {
6430 /* we need to keep the information about the fact that
6431 * we're not limiting the upcoming send(), because if it
6432 * fails, we'll have to retry with at least as many data.
6433 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006434 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006435 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006436
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006437#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006438 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006439 unsigned int max_early;
6440
Olivier Houchard522eea72017-11-03 16:27:47 +01006441 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006442 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006443 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006444 if (SSL_get0_session(ctx->ssl))
6445 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006446 else
6447 max_early = 0;
6448 }
6449
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006450 if (try + ctx->sent_early_data > max_early) {
6451 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006452 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006453 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006454 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006455 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006456 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006457 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006458 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006459 if (ret == 1) {
6460 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006461 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006462 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006463 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006464 /* Initiate the handshake, now */
6465 tasklet_wakeup(ctx->wait_event.tasklet);
6466 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006467
Olivier Houchardc2aae742017-09-22 18:26:28 +02006468 }
6469
6470 } else
6471#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006472 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006473
Emeric Brune1f38db2012-09-03 20:36:47 +02006474 if (conn->flags & CO_FL_ERROR) {
6475 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006476 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006477 }
Emeric Brun46591952012-05-18 15:47:34 +02006478 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006479 /* A send succeeded, so we can consider ourself connected */
6480 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006481 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006482 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006483 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006484 }
6485 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006486 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006487
Emeric Brun46591952012-05-18 15:47:34 +02006488 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006489 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006490 /* handshake is running, and it may need to re-enable write */
6491 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006492 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006493#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006494 /* Async mode can be re-enabled, because we're leaving data state.*/
6495 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006496 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006497#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006498 break;
6499 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006500
Emeric Brun46591952012-05-18 15:47:34 +02006501 break;
6502 }
6503 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006504 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006505 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006506 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6507 SUB_RETRY_RECV,
6508 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006509#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006510 /* Async mode can be re-enabled, because we're leaving data state.*/
6511 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006512 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006513#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006514 break;
6515 }
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006516 else if (ret == SSL_ERROR_SSL || ret == SSL_ERROR_SYSCALL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006517 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6518
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02006519 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006520 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006521 conn->err_code = CO_ERR_SSL_FATAL;
6522 }
Emeric Brun46591952012-05-18 15:47:34 +02006523 goto out_error;
6524 }
6525 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006526 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006527 return done;
6528
6529 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006530 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006531 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006532 ERR_clear_error();
6533
Emeric Brun46591952012-05-18 15:47:34 +02006534 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006535 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006536}
6537
Willy Tarreau832e2422021-05-13 10:11:03 +02006538void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006539
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006540 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006541
Olivier Houchardea8dd942019-05-20 14:02:16 +02006542
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006543 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006544 if (ctx->wait_event.events != 0)
6545 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6546 ctx->wait_event.events,
6547 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006548 if (ctx->subs) {
6549 ctx->subs->events = 0;
6550 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006551 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006552
Olivier Houchard692c1d02019-05-23 18:41:47 +02006553 if (ctx->xprt->close)
6554 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006555#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006556 if (global_ssl.async) {
6557 OSSL_ASYNC_FD all_fd[32], afd;
6558 size_t num_all_fds = 0;
6559 int i;
6560
Olivier Houchard66ab4982019-02-26 18:37:15 +01006561 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006562 if (num_all_fds > 32) {
6563 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6564 return;
6565 }
6566
Olivier Houchard66ab4982019-02-26 18:37:15 +01006567 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006568
6569 /* If an async job is pending, we must try to
6570 to catch the end using polling before calling
6571 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006572 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006573 for (i=0 ; i < num_all_fds ; i++) {
6574 /* switch on an handler designed to
6575 * handle the SSL_free
6576 */
6577 afd = all_fd[i];
6578 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006579 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006580 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006581 /* To ensure that the fd cache won't be used
6582 * and we'll catch a real RD event.
6583 */
6584 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006585 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006586 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006587 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006588 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006589 return;
6590 }
Emeric Brun3854e012017-05-17 20:42:48 +02006591 /* Else we can remove the fds from the fdtab
6592 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006593 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006594 * because the fd is owned by the engine.
6595 * the engine is responsible to close
6596 */
Emeric Brun7d392a52022-07-01 17:36:50 +02006597 for (i=0 ; i < num_all_fds ; i++) {
6598 /* We want to remove the fd from the fdtab
6599 * but we flag it to disown because the
6600 * close is performed by the engine itself
6601 */
6602 fdtab[all_fd[i]].state |= FD_DISOWN;
6603 fd_delete(all_fd[i]);
6604 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006605 }
6606#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006607 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006608 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006609 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006610 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau82531f62021-10-06 12:15:18 +02006611 _HA_ATOMIC_DEC(&global.sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006612 }
Emeric Brun46591952012-05-18 15:47:34 +02006613}
6614
6615/* This function tries to perform a clean shutdown on an SSL connection, and in
6616 * any case, flags the connection as reusable if no handshake was in progress.
6617 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006618static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006619{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006620 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006621
Willy Tarreau911db9b2020-01-23 16:27:54 +01006622 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006623 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006624 if (!clean)
6625 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006626 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006627 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006628 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006629 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006630 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006631 ERR_clear_error();
6632 }
Emeric Brun46591952012-05-18 15:47:34 +02006633}
6634
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006635
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006636/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006637int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6638{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006639 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemandd4f946c2019-12-05 10:26:40 +01006640 X509 *crt;
6641
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006642 if (!ctx)
William Lallemandd4f946c2019-12-05 10:26:40 +01006643 return 0;
William Lallemandd4f946c2019-12-05 10:26:40 +01006644 crt = SSL_get_certificate(ctx->ssl);
6645 if (!crt)
6646 return 0;
6647
6648 return cert_get_pkey_algo(crt, out);
6649}
6650
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006651/* used for ppv2 cert signature (can be used for logging) */
6652const char *ssl_sock_get_cert_sig(struct connection *conn)
6653{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006654 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006655
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006656 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6657 X509 *crt;
6658
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006659 if (!ctx)
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006660 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006661 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006662 if (!crt)
6663 return NULL;
6664 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6665 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6666}
6667
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006668/* used for ppv2 authority */
6669const char *ssl_sock_get_sni(struct connection *conn)
6670{
6671#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006672 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006673
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006674 if (!ctx)
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006675 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006676 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006677#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006678 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006679#endif
6680}
6681
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006682/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006683const char *ssl_sock_get_cipher_name(struct connection *conn)
6684{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006685 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006686
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006687 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006688 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006689 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006690}
6691
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006692/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006693const char *ssl_sock_get_proto_version(struct connection *conn)
6694{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006695 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006696
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006697 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006698 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006699 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006700}
6701
Olivier Houchardab28a322018-12-21 19:45:40 +01006702void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6703{
6704#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006705 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006706
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006707 if (!ctx)
Olivier Houcharde488ea82019-06-28 14:10:33 +02006708 return;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006709 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006710#endif
6711}
6712
Willy Tarreau119a4082016-12-22 21:58:38 +01006713/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6714 * to disable SNI.
6715 */
Willy Tarreau63076412015-07-10 11:33:32 +02006716void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6717{
6718#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006719 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemande18d4e82021-11-17 02:59:21 +01006720 struct server *s;
Willy Tarreau119a4082016-12-22 21:58:38 +01006721 char *prev_name;
6722
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006723 if (!ctx)
Willy Tarreau63076412015-07-10 11:33:32 +02006724 return;
Willy Tarreau77bfa662021-12-23 11:12:13 +01006725
6726 BUG_ON(!(conn->flags & CO_FL_WAIT_L6_CONN));
6727 BUG_ON(!(conn->flags & CO_FL_SSL_WAIT_HS));
6728
William Lallemande18d4e82021-11-17 02:59:21 +01006729 s = __objt_server(conn->target);
Willy Tarreau63076412015-07-10 11:33:32 +02006730
Willy Tarreau119a4082016-12-22 21:58:38 +01006731 /* if the SNI changes, we must destroy the reusable context so that a
William Lallemande18d4e82021-11-17 02:59:21 +01006732 * new connection will present a new SNI. compare with the SNI
6733 * previously stored in the reused_sess */
6734 /* the RWLOCK is used to ensure that we are not trying to flush the
6735 * cache from the CLI */
6736
6737 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
6738 prev_name = s->ssl_ctx.reused_sess[tid].sni;
Willy Tarreau119a4082016-12-22 21:58:38 +01006739 if ((!prev_name && hostname) ||
6740 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006741 SSL_set_session(ctx->ssl, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01006742 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau119a4082016-12-22 21:58:38 +01006743
Olivier Houchard66ab4982019-02-26 18:37:15 +01006744 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006745#endif
6746}
6747
Emeric Brun0abf8362014-06-24 18:26:41 +02006748/* Extract peer certificate's common name into the chunk dest
6749 * Returns
6750 * the len of the extracted common name
6751 * or 0 if no CN found in DN
6752 * or -1 on error case (i.e. no peer certificate)
6753 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006754int ssl_sock_get_remote_common_name(struct connection *conn,
6755 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006756{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006757 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
David Safb76832014-05-08 23:42:08 -04006758 X509 *crt = NULL;
6759 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006760 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006761 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006762 .area = (char *)&find_cn,
6763 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006764 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006765 int result = -1;
David Safb76832014-05-08 23:42:08 -04006766
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006767 if (!ctx)
Emeric Brun0abf8362014-06-24 18:26:41 +02006768 goto out;
David Safb76832014-05-08 23:42:08 -04006769
6770 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006771 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006772 if (!crt)
6773 goto out;
6774
6775 name = X509_get_subject_name(crt);
6776 if (!name)
6777 goto out;
David Safb76832014-05-08 23:42:08 -04006778
Emeric Brun0abf8362014-06-24 18:26:41 +02006779 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6780out:
David Safb76832014-05-08 23:42:08 -04006781 if (crt)
6782 X509_free(crt);
6783
6784 return result;
6785}
6786
Dave McCowan328fb582014-07-30 10:39:13 -04006787/* returns 1 if client passed a certificate for this session, 0 if not */
6788int ssl_sock_get_cert_used_sess(struct connection *conn)
6789{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006790 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dave McCowan328fb582014-07-30 10:39:13 -04006791 X509 *crt = NULL;
6792
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006793 if (!ctx)
Dave McCowan328fb582014-07-30 10:39:13 -04006794 return 0;
6795
6796 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006797 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006798 if (!crt)
6799 return 0;
6800
6801 X509_free(crt);
6802 return 1;
6803}
6804
6805/* returns 1 if client passed a certificate for this connection, 0 if not */
6806int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006807{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006808 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006809
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006810 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006811 return 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006812 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006813}
6814
6815/* returns result from SSL verify */
6816unsigned int ssl_sock_get_verify_result(struct connection *conn)
6817{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006818 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006819
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006820 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006821 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006822 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006823}
6824
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006825/* Returns the application layer protocol name in <str> and <len> when known.
6826 * Zero is returned if the protocol name was not found, otherwise non-zero is
6827 * returned. The string is allocated in the SSL context and doesn't have to be
6828 * freed by the caller. NPN is also checked if available since older versions
6829 * of openssl (1.0.1) which are more common in field only support this one.
6830 */
Amaury Denoyelle71e588c2021-11-12 11:23:29 +01006831int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006832{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006833#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6834 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006835 struct ssl_sock_ctx *ctx = xprt_ctx;
6836 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006837 return 0;
6838
6839 *str = NULL;
6840
6841#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006842 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006843 if (*str)
6844 return 1;
6845#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006846#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006847 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006848 if (*str)
6849 return 1;
6850#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006851#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006852 return 0;
6853}
6854
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006855/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006856int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006857{
6858 X509 *ca;
6859 X509_NAME *name = NULL;
6860 ASN1_OCTET_STRING *skid = NULL;
6861 STACK_OF(X509) *chain = NULL;
6862 struct issuer_chain *issuer;
6863 struct eb64_node *node;
6864 char *path;
6865 u64 key;
6866 int ret = 0;
6867
6868 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6869 if (chain == NULL) {
6870 chain = sk_X509_new_null();
6871 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6872 name = X509_get_subject_name(ca);
6873 }
6874 if (!sk_X509_push(chain, ca)) {
6875 X509_free(ca);
6876 goto end;
6877 }
6878 }
6879 if (!chain) {
6880 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6881 goto end;
6882 }
6883 if (!skid) {
6884 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6885 goto end;
6886 }
6887 if (!name) {
6888 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6889 goto end;
6890 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01006891 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006892 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006893 issuer = container_of(node, typeof(*issuer), node);
6894 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6895 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6896 goto end;
6897 }
6898 }
6899 issuer = calloc(1, sizeof *issuer);
6900 path = strdup(fp);
6901 if (!issuer || !path) {
6902 free(issuer);
6903 free(path);
6904 goto end;
6905 }
6906 issuer->node.key = key;
6907 issuer->path = path;
6908 issuer->chain = chain;
6909 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006910 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006911 ret = 1;
6912 end:
6913 if (skid)
6914 ASN1_OCTET_STRING_free(skid);
6915 if (chain)
6916 sk_X509_pop_free(chain, X509_free);
6917 return ret;
6918}
6919
William Lallemandda8584c2020-05-14 10:14:37 +02006920 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006921{
6922 AUTHORITY_KEYID *akid;
6923 struct issuer_chain *issuer = NULL;
6924
6925 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01006926 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006927 struct eb64_node *node;
6928 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01006929 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006930 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6931 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6932 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6933 issuer = ti;
6934 break;
6935 }
6936 }
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006937 }
Remi Tricot-Le Breton1621dc12022-11-03 15:16:48 +01006938 AUTHORITY_KEYID_free(akid);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006939 return issuer;
6940}
6941
William Lallemanddad31052020-05-14 17:47:32 +02006942void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006943{
6944 struct eb64_node *node, *back;
6945 struct issuer_chain *issuer;
6946
William Lallemande0f3fd52020-02-25 14:53:06 +01006947 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006948 while (node) {
6949 issuer = container_of(node, typeof(*issuer), node);
6950 back = eb64_next(node);
6951 eb64_delete(node);
6952 free(issuer->path);
6953 sk_X509_pop_free(issuer->chain, X509_free);
6954 free(issuer);
6955 node = back;
6956 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006957}
6958
William Lallemandd7bfbe22022-04-11 18:41:24 +02006959#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006960static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01006961 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006962
Emeric Brun3854e012017-05-17 20:42:48 +02006963 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006964 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006965 err_code = ERR_ABORT;
6966 }
6967 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006968}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006969#endif
6970
Willy Tarreaude5675a2021-01-20 14:41:29 +01006971/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006972 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01006973 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01006974static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01006975{
6976 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006977 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006978
6979 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006980 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006981
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006982 if (sctx->conn != conn) {
6983 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
6984 ret = 1;
6985 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01006986 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
6987
6988 if (sctx->xprt) {
6989 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
6990 if (sctx->xprt_ctx)
6991 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
6992 }
6993
6994 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006995
6996 /* as soon as a shutdown is reported the lower layer unregisters its
6997 * subscriber, so the situations below are transient and rare enough to
6998 * be reported as suspicious. In any case they shouldn't last.
6999 */
7000 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
7001 ret = 1;
7002 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
7003 ret = 1;
7004
Willy Tarreaude5675a2021-01-20 14:41:29 +01007005 chunk_appendf(&trash, " .subs=%p", sctx->subs);
7006 if (sctx->subs) {
7007 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007008 if (sctx->subs->tasklet->calls >= 1000000)
7009 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007010 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
7011 sctx->subs->tasklet->calls,
7012 sctx->subs->tasklet->context);
7013 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
7014 chunk_appendf(&trash, ")");
7015 }
7016 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
7017 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007018 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007019}
7020
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007021#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02007022/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007023 * each reference. The variable <ref> must point to the current node's list
7024 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02007025 */
William Lallemand32af2032016-10-29 18:09:35 +02007026static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007027struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02007028{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007029 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007030 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02007031
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007032 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007033 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007034 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02007035
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007036 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02007037}
7038
7039static inline
7040struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
7041{
7042 int id;
7043 char *error;
7044
7045 /* If the reference starts by a '#', this is numeric id. */
7046 if (reference[0] == '#') {
7047 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
7048 id = strtol(reference + 1, &error, 10);
7049 if (*error != '\0')
7050 return NULL;
7051
7052 /* Perform the unique id lookup. */
7053 return tlskeys_ref_lookupid(id);
7054 }
7055
7056 /* Perform the string lookup. */
7057 return tlskeys_ref_lookup(reference);
7058}
7059#endif
7060
7061
7062#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7063
Willy Tarreaua9380522022-05-05 08:50:17 +02007064/* dumps all tls keys. Relies on the show_keys_ctx context from the appctx. */
Willy Tarreaubd338642022-05-05 08:59:17 +02007065static int cli_io_handler_tlskeys_files(struct appctx *appctx)
7066{
Willy Tarreaua9380522022-05-05 08:50:17 +02007067 struct show_keys_ctx *ctx = appctx->svcctx;
William Lallemand32af2032016-10-29 18:09:35 +02007068
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007069 switch (ctx->state) {
7070 case SHOW_KEYS_INIT:
William Lallemand32af2032016-10-29 18:09:35 +02007071 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08007072 * quit the function with returning 0. The function is called
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007073 * later and restart at the state "SHOW_KEYS_INIT".
William Lallemand32af2032016-10-29 18:09:35 +02007074 */
7075 chunk_reset(&trash);
7076
Willy Tarreaubd338642022-05-05 08:59:17 +02007077 if (ctx->dump_entries)
William Lallemand32af2032016-10-29 18:09:35 +02007078 chunk_appendf(&trash, "# id secret\n");
7079 else
7080 chunk_appendf(&trash, "# id (file)\n");
7081
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007082 if (applet_putchk(appctx, &trash) == -1)
William Lallemand32af2032016-10-29 18:09:35 +02007083 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007084
William Lallemand32af2032016-10-29 18:09:35 +02007085 /* Now, we start the browsing of the references lists.
7086 * Note that the following call to LIST_ELEM return bad pointer. The only
7087 * available field of this pointer is <list>. It is used with the function
7088 * tlskeys_list_get_next() for retruning the first available entry
7089 */
Willy Tarreaua9380522022-05-05 08:50:17 +02007090 if (ctx->next_ref == NULL)
7091 ctx->next_ref = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007092
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007093 ctx->state = SHOW_KEYS_LIST;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007094 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007095
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007096 case SHOW_KEYS_LIST:
Willy Tarreaua9380522022-05-05 08:50:17 +02007097 while (ctx->next_ref) {
7098 struct tls_keys_ref *ref = ctx->next_ref;
William Lallemand32af2032016-10-29 18:09:35 +02007099
7100 chunk_reset(&trash);
Willy Tarreaubd338642022-05-05 08:59:17 +02007101 if (ctx->dump_entries && ctx->next_index == 0)
William Lallemand32af2032016-10-29 18:09:35 +02007102 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007103
Willy Tarreaua9380522022-05-05 08:50:17 +02007104 if (ctx->next_index == 0)
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007105 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
7106
Willy Tarreaubd338642022-05-05 08:59:17 +02007107 if (ctx->dump_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01007108 int head;
7109
7110 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
7111 head = ref->tls_ticket_enc_index;
Willy Tarreaua9380522022-05-05 08:50:17 +02007112 while (ctx->next_index < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02007113 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02007114
7115 chunk_reset(t2);
7116 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01007117 if (ref->key_size_bits == 128) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007118 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007119 sizeof(struct tls_sess_key_128),
7120 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007121 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007122 t2->area);
7123 }
7124 else if (ref->key_size_bits == 256) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007125 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007126 sizeof(struct tls_sess_key_256),
7127 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007128 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007129 t2->area);
7130 }
7131 else {
7132 /* This case should never happen */
Willy Tarreaua9380522022-05-05 08:50:17 +02007133 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, ctx->next_index);
Emeric Brun9e754772019-01-10 17:51:55 +01007134 }
William Lallemand32af2032016-10-29 18:09:35 +02007135
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007136 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007137 /* let's try again later from this stream. We add ourselves into
7138 * this stream's users so that it can remove us upon termination.
7139 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01007140 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
William Lallemand32af2032016-10-29 18:09:35 +02007141 return 0;
7142 }
Willy Tarreaua9380522022-05-05 08:50:17 +02007143 ctx->next_index++;
William Lallemand32af2032016-10-29 18:09:35 +02007144 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01007145 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaua9380522022-05-05 08:50:17 +02007146 ctx->next_index = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007147 }
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007148 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007149 /* let's try again later from this stream. We add ourselves into
7150 * this stream's users so that it can remove us upon termination.
7151 */
William Lallemand32af2032016-10-29 18:09:35 +02007152 return 0;
7153 }
7154
Willy Tarreaua9380522022-05-05 08:50:17 +02007155 if (ctx->names_only == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02007156 break;
7157
7158 /* get next list entry and check the end of the list */
Willy Tarreaua9380522022-05-05 08:50:17 +02007159 ctx->next_ref = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007160 }
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007161 ctx->state = SHOW_KEYS_DONE;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007162 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007163
7164 default:
William Lallemand32af2032016-10-29 18:09:35 +02007165 return 1;
7166 }
7167 return 0;
7168}
7169
Willy Tarreaua9380522022-05-05 08:50:17 +02007170/* Prepares a "show_keys_ctx" and sets the appropriate io_handler if needed */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007171static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007172{
Willy Tarreaua9380522022-05-05 08:50:17 +02007173 struct show_keys_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
7174
William Lallemand32af2032016-10-29 18:09:35 +02007175 /* no parameter, shows only file list */
7176 if (!*args[2]) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007177 ctx->names_only = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007178 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007179 }
7180
7181 if (args[2][0] == '*') {
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007182 /* list every TLS ticket keys */
7183 ctx->names_only = 1;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007184 } else {
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007185 ctx->next_ref = tlskeys_ref_lookup_ref(args[2]);
7186 if (!ctx->next_ref)
7187 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007188 }
7189
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007190 ctx->dump_entries = 1;
7191 return 0;
7192}
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007193
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007194static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
7195{
7196 struct tls_keys_ref *ref;
7197 int ret;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007198
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007199 /* Expect two parameters: the filename and the new new TLS key in encoding */
7200 if (!*args[3] || !*args[4])
7201 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 +02007202
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007203 ref = tlskeys_ref_lookup_ref(args[3]);
7204 if (!ref)
7205 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007206
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007207 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
7208 if (ret < 0)
7209 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007210
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007211 trash.data = ret;
7212 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
7213 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007214
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007215 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007216}
Remi Tricot-Le Bretonc8d814e2022-12-20 11:11:17 +01007217#endif
7218
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007219
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007220#ifdef HAVE_SSL_PROVIDERS
7221struct provider_name {
7222 const char *name;
7223 struct list list;
7224};
7225
7226
7227static int ssl_provider_get_name_cb(OSSL_PROVIDER *provider, void *cbdata)
7228{
7229 struct list *provider_names = cbdata;
7230 struct provider_name *item = NULL;
7231 const char *name = OSSL_PROVIDER_get0_name(provider);
7232
7233 if (!provider_names)
7234 return 0;
7235
7236 item = calloc(1, sizeof(*item));
7237
7238 if (!item)
7239 return 0;
7240
7241 item->name = name;
7242 LIST_APPEND(provider_names, &item->list);
7243
7244 return 1;
7245}
7246
7247static void ssl_provider_get_name_list(struct list *provider_names)
7248{
7249 if (!provider_names)
7250 return;
7251
7252 OSSL_PROVIDER_do_all(NULL, ssl_provider_get_name_cb, provider_names);
7253}
7254
7255static void ssl_provider_clear_name_list(struct list *provider_names)
7256{
7257 struct provider_name *item = NULL, *item_s = NULL;
7258
7259 if (provider_names) {
7260 list_for_each_entry_safe(item, item_s, provider_names, list) {
7261 LIST_DELETE(&item->list);
7262 free(item);
7263 }
7264 }
7265}
7266
7267static int cli_io_handler_show_providers(struct appctx *appctx)
7268{
7269 struct buffer *trash = get_trash_chunk();
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007270 struct list provider_names;
7271 struct provider_name *name;
7272
7273 LIST_INIT(&provider_names);
7274
7275 chunk_appendf(trash, "Loaded providers : \n");
7276
7277 ssl_provider_get_name_list(&provider_names);
7278
7279 list_for_each_entry(name, &provider_names, list) {
7280 chunk_appendf(trash, "\t- %s\n", name->name);
7281 }
7282
7283 ssl_provider_clear_name_list(&provider_names);
7284
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007285 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007286 goto yield;
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007287
7288 return 1;
7289
7290yield:
7291 return 0;
7292}
7293#endif
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01007294
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007295
William Lallemand32af2032016-10-29 18:09:35 +02007296/* register cli keywords */
7297static struct cli_kw_list cli_kws = {{ },{
7298#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01007299 { { "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 },
7300 { { "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 +02007301#endif
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007302#ifdef HAVE_SSL_PROVIDERS
7303 { { "show", "ssl", "providers", NULL }, "show ssl providers : show loaded SSL providers", NULL, cli_io_handler_show_providers },
7304#endif
William Lallemand32af2032016-10-29 18:09:35 +02007305 { { NULL }, NULL, NULL, NULL }
7306}};
7307
Willy Tarreau0108d902018-11-25 19:14:37 +01007308INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02007309
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02007310/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02007311struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02007312 .snd_buf = ssl_sock_from_buf,
7313 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01007314 .subscribe = ssl_subscribe,
7315 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02007316 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02007317 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02007318 .rcv_pipe = NULL,
7319 .snd_pipe = NULL,
7320 .shutr = NULL,
7321 .shutw = ssl_sock_shutw,
7322 .close = ssl_sock_close,
7323 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01007324 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01007325 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01007326 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01007327 .prepare_srv = ssl_sock_prepare_srv_ctx,
7328 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007329 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02007330 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01007331 .set_idle = ssl_set_idle,
7332 .set_used = ssl_set_used,
Willy Tarreaude827952022-04-11 10:43:28 +02007333 .get_ssl_sock_ctx = ssl_sock_get_ctx,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01007334 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01007335 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02007336};
7337
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007338enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
7339 struct session *sess, struct stream *s, int flags)
7340{
7341 struct connection *conn;
7342
7343 conn = objt_conn(sess->origin);
7344
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007345 if (conn) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007346 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007347 sc_ep_set(s->scf, SE_FL_WAIT_FOR_HS);
Christopher Faulet6e1bbc42022-12-12 08:08:15 +01007348 s->req.flags |= CF_READ_EVENT;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007349 return ACT_RET_YIELD;
7350 }
7351 }
7352 return (ACT_RET_CONT);
7353}
7354
7355static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
7356{
7357 rule->action_ptr = ssl_action_wait_for_hs;
7358
7359 return ACT_RET_PRS_OK;
7360}
7361
7362static struct action_kw_list http_req_actions = {ILH, {
7363 { "wait-for-handshake", ssl_parse_wait_for_hs },
7364 { /* END */ }
7365}};
7366
Willy Tarreau0108d902018-11-25 19:14:37 +01007367INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
7368
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007369#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007370
7371static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7372{
7373 if (ptr) {
7374 chunk_destroy(ptr);
7375 free(ptr);
7376 }
7377}
7378
7379#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007380
William Lallemand76b4a122020-08-04 17:41:39 +02007381
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007382static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7383{
Willy Tarreaubafbe012017-11-24 17:34:44 +01007384 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007385}
William Lallemand7d42ef52020-07-06 11:41:30 +02007386
William Lallemand722180a2021-06-09 16:46:12 +02007387#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007388static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7389{
7390 struct ssl_keylog *keylog;
7391
7392 if (!ptr)
7393 return;
7394
7395 keylog = ptr;
7396
7397 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7398 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7399 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7400 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7401 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7402 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7403 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7404 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7405
7406 pool_free(pool_head_ssl_keylog, ptr);
7407}
7408#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007409
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007410static void ssl_sock_clt_crt_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7411{
7412 if (!ptr)
7413 return;
7414
7415 X509_free((X509*)ptr);
7416}
7417
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01007418static void ssl_sock_clt_sni_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7419{
7420 pool_free(ssl_sock_client_sni_pool, ptr);
7421}
7422
Willy Tarreau92faadf2012-10-10 23:04:25 +02007423static void __ssl_sock_init(void)
7424{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007425#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007426 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007427 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007428#endif
Emeric Brun46591952012-05-18 15:47:34 +02007429
Willy Tarreauef934602016-12-22 23:12:01 +01007430 if (global_ssl.listen_default_ciphers)
7431 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7432 if (global_ssl.connect_default_ciphers)
7433 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007434#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007435 if (global_ssl.listen_default_ciphersuites)
7436 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7437 if (global_ssl.connect_default_ciphersuites)
7438 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7439#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007440
Willy Tarreau13e14102016-12-22 20:25:26 +01007441 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007442#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007443 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007444#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007445#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007446 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007447 n = sk_SSL_COMP_num(cm);
7448 while (n--) {
7449 (void) sk_SSL_COMP_pop(cm);
7450 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007451#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007452
Willy Tarreau5db847a2019-05-09 14:13:35 +02007453#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007454 ssl_locking_init();
7455#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007456#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007457 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
7458#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007459
7460#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7461 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
7462#endif
7463
Thierry FOURNIER28962c92018-06-17 21:37:05 +02007464 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02007465 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 +01007466#ifdef USE_QUIC
7467 ssl_qc_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7468#endif /* USE_QUIC */
William Lallemand722180a2021-06-09 16:46:12 +02007469#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007470 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
7471#endif
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007472 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 +01007473 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 +02007474#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00007475 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007476 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007477#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01007478#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7479 hap_register_post_check(tlskeys_finalize_config);
7480#endif
Willy Tarreau80713382018-11-26 10:19:54 +01007481
7482 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
7483 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
7484
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007485 hap_register_post_deinit(ssl_free_global_issuers);
7486
Willy Tarreau80713382018-11-26 10:19:54 +01007487#ifndef OPENSSL_NO_DH
7488 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7489 hap_register_post_deinit(ssl_free_dh);
7490#endif
William Lallemandd7bfbe22022-04-11 18:41:24 +02007491#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Willy Tarreau80713382018-11-26 10:19:54 +01007492 hap_register_post_deinit(ssl_free_engines);
7493#endif
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02007494#ifdef HAVE_SSL_PROVIDERS
7495 hap_register_post_deinit(ssl_unload_providers);
7496#endif
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01007497#if HA_OPENSSL_VERSION_NUMBER < 0x3000000fL
Willy Tarreau80713382018-11-26 10:19:54 +01007498 /* Load SSL string for the verbose & debug mode. */
7499 ERR_load_SSL_strings();
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01007500#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007501 ha_meth = BIO_meth_new(0x666, "ha methods");
7502 BIO_meth_set_write(ha_meth, ha_ssl_write);
7503 BIO_meth_set_read(ha_meth, ha_ssl_read);
7504 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
7505 BIO_meth_set_create(ha_meth, ha_ssl_new);
7506 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
7507 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
7508 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02007509
7510 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007511
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01007512 HA_SPIN_INIT(&ocsp_tree_lock);
7513
Dragan Dosen9ac98092020-05-11 15:51:45 +02007514 /* Try to register dedicated SSL/TLS protocol message callbacks for
7515 * heartbleed attack (CVE-2014-0160) and clienthello.
7516 */
7517 hap_register_post_check(ssl_sock_register_msg_callbacks);
7518
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007519 /* Try to free all callbacks that were registered by using
7520 * ssl_sock_register_msg_callback().
7521 */
7522 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01007523}
Willy Tarreau79367f92022-04-25 19:18:24 +02007524INITCALL0(STG_REGISTER, __ssl_sock_init);
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01007525
Willy Tarreau80713382018-11-26 10:19:54 +01007526/* Compute and register the version string */
7527static void ssl_register_build_options()
7528{
7529 char *ptr = NULL;
7530 int i;
7531
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007532 memprintf(&ptr, "Built with OpenSSL version : "
7533#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007534 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007535#else /* OPENSSL_IS_BORINGSSL */
7536 OPENSSL_VERSION_TEXT
7537 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08007538 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02007539 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007540#endif
7541 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007542#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007543 "no (library version too old)"
7544#elif defined(OPENSSL_NO_TLSEXT)
7545 "no (disabled via OPENSSL_NO_TLSEXT)"
7546#else
7547 "yes"
7548#endif
7549 "", ptr);
7550
7551 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
7552#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
7553 "yes"
7554#else
7555#ifdef OPENSSL_NO_TLSEXT
7556 "no (because of OPENSSL_NO_TLSEXT)"
7557#else
7558 "no (version might be too old, 0.9.8f min needed)"
7559#endif
7560#endif
7561 "", ptr);
7562
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02007563 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
7564 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
7565 if (methodVersions[i].option)
7566 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007567
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007568#ifdef HAVE_SSL_PROVIDERS
7569 {
7570 struct list provider_names;
7571 struct provider_name *name;
7572 LIST_INIT(&provider_names);
7573 ssl_provider_get_name_list(&provider_names);
7574
7575 memprintf(&ptr, "%s\nOpenSSL providers loaded :", ptr);
7576
7577 list_for_each_entry(name, &provider_names, list) {
7578 memprintf(&ptr, "%s %s", ptr, name->name);
7579 }
7580
7581 ssl_provider_clear_name_list(&provider_names);
7582 }
7583#endif
7584
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007585 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01007586}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007587
Willy Tarreau80713382018-11-26 10:19:54 +01007588INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02007589
William Lallemandd7bfbe22022-04-11 18:41:24 +02007590#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00007591void ssl_free_engines(void) {
7592 struct ssl_engine_list *wl, *wlb;
7593 /* free up engine list */
7594 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
7595 ENGINE_finish(wl->e);
7596 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02007597 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00007598 free(wl);
7599 }
7600}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007601#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02007602
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02007603#ifdef HAVE_SSL_PROVIDERS
7604void ssl_unload_providers(void) {
7605 struct ssl_provider_list *prov, *provb;
7606 list_for_each_entry_safe(prov, provb, &openssl_providers, list) {
7607 OSSL_PROVIDER_unload(prov->provider);
7608 LIST_DELETE(&prov->list);
7609 free(prov);
7610 }
7611}
7612#endif
7613
Remi Gacogned3a23c32015-05-28 16:39:47 +02007614#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00007615void ssl_free_dh(void) {
7616 if (local_dh_1024) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007617 HASSL_DH_free(local_dh_1024);
Grant Zhang872f9c22017-01-21 01:10:18 +00007618 local_dh_1024 = NULL;
7619 }
7620 if (local_dh_2048) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007621 HASSL_DH_free(local_dh_2048);
Grant Zhang872f9c22017-01-21 01:10:18 +00007622 local_dh_2048 = NULL;
7623 }
7624 if (local_dh_4096) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007625 HASSL_DH_free(local_dh_4096);
Grant Zhang872f9c22017-01-21 01:10:18 +00007626 local_dh_4096 = NULL;
7627 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02007628 if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01007629 HASSL_DH_free(global_dh);
Remi Gacogne47783ef2015-05-29 15:53:22 +02007630 global_dh = NULL;
7631 }
Grant Zhang872f9c22017-01-21 01:10:18 +00007632}
7633#endif
7634
Grant Zhang872f9c22017-01-21 01:10:18 +00007635static void __ssl_sock_deinit(void)
7636{
7637#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007638 if (ssl_ctx_lru_tree) {
7639 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007640 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02007641 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02007642#endif
7643
Willy Tarreau5db847a2019-05-09 14:13:35 +02007644#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007645 ERR_remove_state(0);
7646 ERR_free_strings();
7647
7648 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08007649#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007650
Willy Tarreau5db847a2019-05-09 14:13:35 +02007651#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007652 CRYPTO_cleanup_all_ex_data();
7653#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007654 BIO_meth_free(ha_meth);
Remi Tricot-Le Breton6477bbd2022-12-20 11:11:13 +01007655
7656#if !defined OPENSSL_NO_OCSP
7657 ssl_destroy_ocsp_update_task();
7658#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007659}
Willy Tarreau79367f92022-04-25 19:18:24 +02007660REGISTER_POST_DEINIT(__ssl_sock_deinit);
Remi Gacogned3a23c32015-05-28 16:39:47 +02007661
William Dauchyf6370442020-11-14 19:25:33 +01007662
Emeric Brun46591952012-05-18 15:47:34 +02007663/*
7664 * Local variables:
7665 * c-indent-level: 8
7666 * c-basic-offset: 8
7667 * End:
7668 */