blob: a36616289c58370837444421514405fab577b391 [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>
Emeric Brun46591952012-05-18 15:47:34 +020086
Emeric Brun46591952012-05-18 15:47:34 +020087
Willy Tarreau9356dac2019-05-10 09:22:53 +020088/* ***** READ THIS before adding code here! *****
89 *
90 * Due to API incompatibilities between multiple OpenSSL versions and their
91 * derivatives, it's often tempting to add macros to (re-)define certain
92 * symbols. Please do not do this here, and do it in common/openssl-compat.h
93 * exclusively so that the whole code consistently uses the same macros.
94 *
95 * Whenever possible if a macro is missing in certain versions, it's better
96 * to conditionally define it in openssl-compat.h than using lots of ifdefs.
97 */
98
Emeric Brunece0c332017-12-06 13:51:49 +010099int nb_engines = 0;
Emeric Brune1f38db2012-09-03 20:36:47 +0200100
William Lallemande0f3fd52020-02-25 14:53:06 +0100101static struct eb_root cert_issuer_tree = EB_ROOT; /* issuers tree from "issuers-chain-path" */
102
William Lallemand7fd8b452020-05-07 15:20:43 +0200103struct global_ssl global_ssl = {
Willy Tarreauef934602016-12-22 23:12:01 +0100104#ifdef LISTEN_DEFAULT_CIPHERS
105 .listen_default_ciphers = LISTEN_DEFAULT_CIPHERS,
106#endif
107#ifdef CONNECT_DEFAULT_CIPHERS
108 .connect_default_ciphers = CONNECT_DEFAULT_CIPHERS,
109#endif
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +0500110#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200111 .listen_default_ciphersuites = LISTEN_DEFAULT_CIPHERSUITES,
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200112 .connect_default_ciphersuites = CONNECT_DEFAULT_CIPHERSUITES,
113#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100114 .listen_default_ssloptions = BC_SSL_O_NONE,
115 .connect_default_ssloptions = SRV_SSL_O_NONE,
116
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +0200117 .listen_default_sslmethods.flags = MC_SSL_O_ALL,
118 .listen_default_sslmethods.min = CONF_TLSV_NONE,
119 .listen_default_sslmethods.max = CONF_TLSV_NONE,
120 .connect_default_sslmethods.flags = MC_SSL_O_ALL,
121 .connect_default_sslmethods.min = CONF_TLSV_NONE,
122 .connect_default_sslmethods.max = CONF_TLSV_NONE,
123
Willy Tarreauef934602016-12-22 23:12:01 +0100124#ifdef DEFAULT_SSL_MAX_RECORD
125 .max_record = DEFAULT_SSL_MAX_RECORD,
126#endif
Thomas Prückl10243932022-04-27 13:04:54 +0200127 .hard_max_record = 0,
Willy Tarreauef934602016-12-22 23:12:01 +0100128 .default_dh_param = SSL_DEFAULT_DH_PARAM,
129 .ctx_cache = DEFAULT_SSL_CTX_CACHE,
Marcin Deranek310a2602021-07-13 19:04:24 +0200130 .capture_buffer_size = 0,
William Lallemand3af48e72020-02-03 17:15:52 +0100131 .extra_files = SSL_GF_ALL,
William Lallemand8e8581e2020-10-20 17:36:46 +0200132 .extra_files_noext = 0,
William Lallemand722180a2021-06-09 16:46:12 +0200133#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200134 .keylog = 0
135#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100136};
137
Olivier Houcharda8955d52019-04-07 22:00:38 +0200138static BIO_METHOD *ha_meth;
139
Willy Tarreaub8dec4a2022-06-23 11:02:08 +0200140DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx", sizeof(struct ssl_sock_ctx));
Olivier Houchard66ab4982019-02-26 18:37:15 +0100141
Willy Tarreaub8dec4a2022-06-23 11:02:08 +0200142DECLARE_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 +0100143
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100144/* ssl stats module */
145enum {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100146 SSL_ST_SESS,
147 SSL_ST_REUSED_SESS,
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100148 SSL_ST_FAILED_HANDSHAKE,
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100149
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100150 SSL_ST_STATS_COUNT /* must be the last member of the enum */
151};
152
153static struct name_desc ssl_stats[] = {
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100154 [SSL_ST_SESS] = { .name = "ssl_sess",
155 .desc = "Total number of ssl sessions established" },
156 [SSL_ST_REUSED_SESS] = { .name = "ssl_reused_sess",
157 .desc = "Total number of ssl sessions reused" },
158 [SSL_ST_FAILED_HANDSHAKE] = { .name = "ssl_failed_handshake",
159 .desc = "Total number of failed handshake" },
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100160};
161
162static struct ssl_counters {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100163 long long sess;
164 long long reused_sess;
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100165 long long failed_handshake;
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100166} ssl_counters;
167
168static void ssl_fill_stats(void *data, struct field *stats)
169{
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100170 struct ssl_counters *counters = data;
171
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100172 stats[SSL_ST_SESS] = mkf_u64(FN_COUNTER, counters->sess);
173 stats[SSL_ST_REUSED_SESS] = mkf_u64(FN_COUNTER, counters->reused_sess);
174 stats[SSL_ST_FAILED_HANDSHAKE] = mkf_u64(FN_COUNTER, counters->failed_handshake);
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100175}
176
177static struct stats_module ssl_stats_module = {
178 .name = "ssl",
179 .fill_stats = ssl_fill_stats,
180 .stats = ssl_stats,
181 .stats_count = SSL_ST_STATS_COUNT,
182 .counters = &ssl_counters,
183 .counters_size = sizeof(ssl_counters),
184 .domain_flags = MK_STATS_PROXY_DOMAIN(STATS_PX_CAP_FE|STATS_PX_CAP_LI|STATS_PX_CAP_BE|STATS_PX_CAP_SRV),
185 .clearable = 1,
186};
187
188INITCALL1(STG_REGISTER, stats_register_module, &ssl_stats_module);
189
Willy Tarreaua9380522022-05-05 08:50:17 +0200190/* CLI context for "show tls-keys" */
191struct show_keys_ctx {
192 struct tls_keys_ref *next_ref; /* next reference to be dumped */
193 int names_only; /* non-zero = only show file names */
194 int next_index; /* next index to be dumped */
Willy Tarreaubd338642022-05-05 08:59:17 +0200195 int dump_entries; /* dump entries also */
Willy Tarreau9c5a38c2022-05-05 09:03:44 +0200196 enum {
197 SHOW_KEYS_INIT = 0,
198 SHOW_KEYS_LIST,
199 SHOW_KEYS_DONE,
200 } state; /* phase of the current dump */
Willy Tarreaua9380522022-05-05 08:50:17 +0200201};
202
Willy Tarreau691d5032021-01-20 14:55:01 +0100203/* ssl_sock_io_cb is exported to see it resolved in "show fd" */
Willy Tarreau144f84a2021-03-02 16:09:26 +0100204struct task *ssl_sock_io_cb(struct task *, void *, unsigned int);
Olivier Houchard000694c2019-05-23 14:45:12 +0200205static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
Olivier Houchardea8dd942019-05-20 14:02:16 +0200206
Olivier Houcharda8955d52019-04-07 22:00:38 +0200207/* Methods to implement OpenSSL BIO */
208static int ha_ssl_write(BIO *h, const char *buf, int num)
209{
210 struct buffer tmpbuf;
211 struct ssl_sock_ctx *ctx;
212 int ret;
213
214 ctx = BIO_get_data(h);
215 tmpbuf.size = num;
216 tmpbuf.area = (void *)(uintptr_t)buf;
217 tmpbuf.data = num;
218 tmpbuf.head = 0;
219 ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200220 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200221 BIO_set_retry_write(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200222 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200223 } else if (ret == 0)
224 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200225 return ret;
226}
227
228static int ha_ssl_gets(BIO *h, char *buf, int size)
229{
230
231 return 0;
232}
233
234static int ha_ssl_puts(BIO *h, const char *str)
235{
236
237 return ha_ssl_write(h, str, strlen(str));
238}
239
240static int ha_ssl_read(BIO *h, char *buf, int size)
241{
242 struct buffer tmpbuf;
243 struct ssl_sock_ctx *ctx;
244 int ret;
245
246 ctx = BIO_get_data(h);
247 tmpbuf.size = size;
248 tmpbuf.area = buf;
249 tmpbuf.data = 0;
250 tmpbuf.head = 0;
251 ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200252 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200253 BIO_set_retry_read(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200254 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200255 } else if (ret == 0)
256 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200257
258 return ret;
259}
260
261static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
262{
263 int ret = 0;
264 switch (cmd) {
265 case BIO_CTRL_DUP:
266 case BIO_CTRL_FLUSH:
267 ret = 1;
268 break;
269 }
270 return ret;
271}
272
273static int ha_ssl_new(BIO *h)
274{
275 BIO_set_init(h, 1);
276 BIO_set_data(h, NULL);
277 BIO_clear_flags(h, ~0);
278 return 1;
279}
280
281static int ha_ssl_free(BIO *data)
282{
283
284 return 1;
285}
286
287
Willy Tarreau5db847a2019-05-09 14:13:35 +0200288#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100289
Emeric Brun821bb9b2017-06-15 16:37:39 +0200290static HA_RWLOCK_T *ssl_rwlocks;
291
292
293unsigned long ssl_id_function(void)
294{
295 return (unsigned long)tid;
296}
297
298void ssl_locking_function(int mode, int n, const char * file, int line)
299{
300 if (mode & CRYPTO_LOCK) {
301 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100302 HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200303 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100304 HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200305 }
306 else {
307 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100308 HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200309 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100310 HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200311 }
312}
313
314static int ssl_locking_init(void)
315{
316 int i;
317
318 ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
319 if (!ssl_rwlocks)
320 return -1;
321
322 for (i = 0 ; i < CRYPTO_num_locks() ; i++)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100323 HA_RWLOCK_INIT(&ssl_rwlocks[i]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200324
325 CRYPTO_set_id_callback(ssl_id_function);
326 CRYPTO_set_locking_callback(ssl_locking_function);
327
328 return 0;
329}
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100330
Emeric Brun821bb9b2017-06-15 16:37:39 +0200331#endif
332
Willy Tarreauaf613e82020-06-05 08:40:51 +0200333__decl_thread(HA_SPINLOCK_T ckch_lock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200334
William Lallemandbc6ca7c2019-10-29 23:48:19 +0100335
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200336
337/* mimic what X509_STORE_load_locations do with store_ctx */
338static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
339{
Remi Tricot-Le Bretond75b99e2021-05-17 11:45:55 +0200340 X509_STORE *store = NULL;
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +0100341 struct cafile_entry *ca_e = ssl_store_get_cafile_entry(path, 0);
342 if (ca_e)
343 store = ca_e->ca_store;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200344 if (store_ctx && store) {
345 int i;
346 X509_OBJECT *obj;
347 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
348 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
349 obj = sk_X509_OBJECT_value(objs, i);
350 switch (X509_OBJECT_get_type(obj)) {
351 case X509_LU_X509:
352 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
353 break;
354 case X509_LU_CRL:
355 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
356 break;
357 default:
358 break;
359 }
360 }
361 return 1;
362 }
363 return 0;
364}
365
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500366/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200367static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
368{
369 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
370 return ssl_set_cert_crl_file(store_ctx, path);
371}
372
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200373/*
374 Extract CA_list from CA_file already in tree.
375 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
376 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
377*/
378static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
379{
380 struct ebmb_node *eb;
381 struct cafile_entry *ca_e;
382
383 eb = ebst_lookup(&cafile_tree, path);
384 if (!eb)
385 return NULL;
386 ca_e = ebmb_entry(eb, struct cafile_entry, node);
387
388 if (ca_e->ca_list == NULL) {
389 int i;
390 unsigned long key;
391 struct eb_root ca_name_tree = EB_ROOT;
392 struct eb64_node *node, *back;
393 struct {
394 struct eb64_node node;
395 X509_NAME *xname;
396 } *ca_name;
397 STACK_OF(X509_OBJECT) *objs;
398 STACK_OF(X509_NAME) *skn;
399 X509 *x;
400 X509_NAME *xn;
401
402 skn = sk_X509_NAME_new_null();
403 /* take x509 from cafile_tree */
404 objs = X509_STORE_get0_objects(ca_e->ca_store);
405 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
406 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
407 if (!x)
408 continue;
409 xn = X509_get_subject_name(x);
410 if (!xn)
411 continue;
412 /* Check for duplicates. */
413 key = X509_NAME_hash(xn);
414 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
415 node && ca_name == NULL;
416 node = eb64_next(node)) {
417 ca_name = container_of(node, typeof(*ca_name), node);
418 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
419 ca_name = NULL;
420 }
421 /* find a duplicate */
422 if (ca_name)
423 continue;
424 ca_name = calloc(1, sizeof *ca_name);
425 xn = X509_NAME_dup(xn);
426 if (!ca_name ||
427 !xn ||
428 !sk_X509_NAME_push(skn, xn)) {
429 free(ca_name);
430 X509_NAME_free(xn);
431 sk_X509_NAME_pop_free(skn, X509_NAME_free);
432 sk_X509_NAME_free(skn);
433 skn = NULL;
434 break;
435 }
436 ca_name->node.key = key;
437 ca_name->xname = xn;
438 eb64_insert(&ca_name_tree, &ca_name->node);
439 }
440 ca_e->ca_list = skn;
441 /* remove temporary ca_name tree */
442 node = eb64_first(&ca_name_tree);
443 while (node) {
444 ca_name = container_of(node, typeof(*ca_name), node);
445 back = eb64_next(node);
446 eb64_delete(node);
447 free(ca_name);
448 node = back;
449 }
450 }
451 return ca_e->ca_list;
452}
453
Willy Tarreauff882702021-04-10 17:23:00 +0200454struct pool_head *pool_head_ssl_capture __read_mostly = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200455int ssl_capture_ptr_index = -1;
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +0100456int ssl_app_data_index = -1;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +0100457#ifdef USE_QUIC
458int ssl_qc_app_data_index = -1;
459#endif /* USE_QUIC */
Willy Tarreauef934602016-12-22 23:12:01 +0100460
William Lallemand722180a2021-06-09 16:46:12 +0200461#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200462int ssl_keylog_index = -1;
Willy Tarreauff882702021-04-10 17:23:00 +0200463struct pool_head *pool_head_ssl_keylog __read_mostly = NULL;
464struct pool_head *pool_head_ssl_keylog_str __read_mostly = NULL;
William Lallemand7d42ef52020-07-06 11:41:30 +0200465#endif
466
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +0200467int ssl_client_crt_ref_index = -1;
468
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100469/* Used to store the client's SNI in case of ClientHello callback error */
470int ssl_client_sni_index = -1;
471
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200472#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
473struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
474#endif
475
William Lallemandd7bfbe22022-04-11 18:41:24 +0200476#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200477unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000478struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
479struct ssl_engine_list {
480 struct list list;
481 ENGINE *e;
482};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200483#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000484
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +0200485#ifdef HAVE_SSL_PROVIDERS
486struct list openssl_providers = LIST_HEAD_INIT(openssl_providers);
487struct ssl_provider_list {
488 struct list list;
489 OSSL_PROVIDER *provider;
490};
491#endif
492
Remi Gacogne8de54152014-07-15 11:36:40 +0200493#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200494static int ssl_dh_ptr_index = -1;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +0100495static HASSL_DH *global_dh = NULL;
496static HASSL_DH *local_dh_1024 = NULL;
497static HASSL_DH *local_dh_2048 = NULL;
498static HASSL_DH *local_dh_4096 = NULL;
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100499#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +0100500static DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100501#else
502static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey);
503#endif
Remi Gacogne8de54152014-07-15 11:36:40 +0200504#endif /* OPENSSL_NO_DH */
505
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100506#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200507/* X509V3 Extensions that will be added on generated certificates */
508#define X509V3_EXT_SIZE 5
509static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
510 "basicConstraints",
511 "nsComment",
512 "subjectKeyIdentifier",
513 "authorityKeyIdentifier",
514 "keyUsage",
515};
516static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
517 "CA:FALSE",
518 "\"OpenSSL Generated Certificate\"",
519 "hash",
520 "keyid,issuer:always",
521 "nonRepudiation,digitalSignature,keyEncipherment"
522};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200523/* LRU cache to store generated certificate */
524static struct lru64_head *ssl_ctx_lru_tree = NULL;
525static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200526static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100527__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200528
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200529#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
530
yanbzhube2774d2015-12-10 15:07:30 -0500531/* The order here matters for picking a default context,
532 * keep the most common keytype at the bottom of the list
533 */
534const char *SSL_SOCK_KEYTYPE_NAMES[] = {
535 "dsa",
536 "ecdsa",
537 "rsa"
538};
yanbzhube2774d2015-12-10 15:07:30 -0500539
William Lallemandc3cd35f2017-11-28 11:04:43 +0100540static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100541static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
542
Dragan Dosen9ac98092020-05-11 15:51:45 +0200543/* Dedicated callback functions for heartbeat and clienthello.
544 */
545#ifdef TLS1_RT_HEARTBEAT
546static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
547 int content_type, const void *buf, size_t len,
548 SSL *ssl);
549#endif
550static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
551 int content_type, const void *buf, size_t len,
552 SSL *ssl);
553
William Lallemand722180a2021-06-09 16:46:12 +0200554#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200555static void ssl_init_keylog(struct connection *conn, int write_p, int version,
556 int content_type, const void *buf, size_t len,
557 SSL *ssl);
558#endif
559
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200560/* List head of all registered SSL/TLS protocol message callbacks. */
561struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
562
563/* Registers the function <func> in order to be called on SSL/TLS protocol
564 * message processing. It will return 0 if the function <func> is not set
565 * or if it fails to allocate memory.
566 */
567int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
568{
569 struct ssl_sock_msg_callback *cbk;
570
571 if (!func)
572 return 0;
573
574 cbk = calloc(1, sizeof(*cbk));
575 if (!cbk) {
576 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
577 return 0;
578 }
579
580 cbk->func = func;
581
Willy Tarreau2b718102021-04-21 07:32:39 +0200582 LIST_APPEND(&ssl_sock_msg_callbacks, &cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200583
584 return 1;
585}
586
Dragan Dosen9ac98092020-05-11 15:51:45 +0200587/* Used to register dedicated SSL/TLS protocol message callbacks.
588 */
589static int ssl_sock_register_msg_callbacks(void)
590{
591#ifdef TLS1_RT_HEARTBEAT
592 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
593 return ERR_ABORT;
594#endif
Marcin Deranek310a2602021-07-13 19:04:24 +0200595 if (global_ssl.capture_buffer_size > 0) {
Dragan Dosen9ac98092020-05-11 15:51:45 +0200596 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
597 return ERR_ABORT;
598 }
William Lallemand722180a2021-06-09 16:46:12 +0200599#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200600 if (global_ssl.keylog > 0) {
601 if (!ssl_sock_register_msg_callback(ssl_init_keylog))
602 return ERR_ABORT;
603 }
604#endif
605
Christopher Fauletfc633b62020-11-06 15:24:23 +0100606 return ERR_NONE;
Dragan Dosen9ac98092020-05-11 15:51:45 +0200607}
608
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200609/* Used to free all SSL/TLS protocol message callbacks that were
610 * registered by using ssl_sock_register_msg_callback().
611 */
612static void ssl_sock_unregister_msg_callbacks(void)
613{
614 struct ssl_sock_msg_callback *cbk, *cbkback;
615
616 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +0200617 LIST_DELETE(&cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200618 free(cbk);
619 }
620}
621
Willy Tarreaude827952022-04-11 10:43:28 +0200622static struct ssl_sock_ctx *ssl_sock_get_ctx(struct connection *conn)
623{
624 if (!conn || conn->xprt != xprt_get(XPRT_SSL) || !conn->xprt_ctx)
625 return NULL;
626
627 return (struct ssl_sock_ctx *)conn->xprt_ctx;
628}
629
Dragan Doseneb607fe2020-05-11 17:17:06 +0200630SSL *ssl_sock_get_ssl_object(struct connection *conn)
631{
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200632 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dragan Doseneb607fe2020-05-11 17:17:06 +0200633
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200634 return ctx ? ctx->ssl : NULL;
Dragan Doseneb607fe2020-05-11 17:17:06 +0200635}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100636/*
637 * This function gives the detail of the SSL error. It is used only
638 * if the debug mode and the verbose mode are activated. It dump all
639 * the SSL error until the stack was empty.
640 */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +0200641static forceinline void ssl_sock_dump_errors(struct connection *conn,
642 struct quic_conn *qc)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100643{
644 unsigned long ret;
645
646 if (unlikely(global.mode & MODE_DEBUG)) {
647 while(1) {
Remi Tricot-Le Breton1effd9a2022-02-11 12:04:44 +0100648 const char *func = NULL;
649 ERR_peek_error_func(&func);
650
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100651 ret = ERR_get_error();
652 if (ret == 0)
653 return;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +0200654 if (conn) {
655 fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
656 conn_fd(conn), ret,
657 func, ERR_reason_error_string(ret));
658 }
659#ifdef USE_QUIC
660 else {
661 /* TODO: we are not sure <conn> is always initialized for QUIC connections */
662 fprintf(stderr, "qc @%p OpenSSL error[0x%lx] %s: %s\n", qc, ret,
663 func, ERR_reason_error_string(ret));
664 }
665#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100666 }
667 }
668}
669
yanbzhube2774d2015-12-10 15:07:30 -0500670
William Lallemandd7bfbe22022-04-11 18:41:24 +0200671#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200672int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000673{
674 int err_code = ERR_ABORT;
675 ENGINE *engine;
676 struct ssl_engine_list *el;
677
678 /* grab the structural reference to the engine */
679 engine = ENGINE_by_id(engine_id);
680 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100681 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000682 goto fail_get;
683 }
684
685 if (!ENGINE_init(engine)) {
686 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100687 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000688 goto fail_init;
689 }
690
691 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100692 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000693 goto fail_set_method;
694 }
695
696 el = calloc(1, sizeof(*el));
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200697 if (!el)
698 goto fail_alloc;
Grant Zhang872f9c22017-01-21 01:10:18 +0000699 el->e = engine;
Willy Tarreau2b718102021-04-21 07:32:39 +0200700 LIST_INSERT(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100701 nb_engines++;
702 if (global_ssl.async)
703 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000704 return 0;
705
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200706fail_alloc:
Grant Zhang872f9c22017-01-21 01:10:18 +0000707fail_set_method:
708 /* release the functional reference from ENGINE_init() */
709 ENGINE_finish(engine);
710
711fail_init:
712 /* release the structural reference from ENGINE_by_id() */
713 ENGINE_free(engine);
714
715fail_get:
716 return err_code;
717}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200718#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000719
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +0200720#ifdef HAVE_SSL_PROVIDERS
721int ssl_init_provider(const char *provider_name)
722{
723 int err_code = ERR_ABORT;
724 struct ssl_provider_list *prov = NULL;
725
726 prov = calloc(1, sizeof(*prov));
727 if (!prov) {
728 ha_alert("ssl-provider %s: memory allocation failure\n", provider_name);
729 goto error;
730 }
731
732 if ((prov->provider = OSSL_PROVIDER_load(NULL, provider_name)) == NULL) {
733 ha_alert("ssl-provider %s: unknown provider\n", provider_name);
734 goto error;
735 }
736
737 LIST_INSERT(&openssl_providers, &prov->list);
738
739 return 0;
740
741error:
742 ha_free(&prov);
743 return err_code;
744}
745#endif /* HAVE_SSL_PROVIDERS */
746
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +0500747#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +0200748/*
749 * openssl async fd handler
750 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200751void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000752{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200753 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000754
Emeric Brun3854e012017-05-17 20:42:48 +0200755 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000756 * to poll this fd until it is requested
757 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000758 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000759 fd_cant_recv(fd);
760
761 /* crypto engine is available, let's notify the associated
762 * connection that it can pursue its processing.
763 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200764 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000765}
766
Emeric Brun3854e012017-05-17 20:42:48 +0200767/*
768 * openssl async delayed SSL_free handler
769 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200770void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000771{
772 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200773 OSSL_ASYNC_FD all_fd[32];
774 size_t num_all_fds = 0;
775 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000776
Emeric Brun3854e012017-05-17 20:42:48 +0200777 /* We suppose that the async job for a same SSL *
778 * are serialized. So if we are awake it is
779 * because the running job has just finished
780 * and we can remove all async fds safely
781 */
782 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
783 if (num_all_fds > 32) {
784 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
785 return;
786 }
787
788 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
Emeric Brun7d392a52022-07-01 17:36:50 +0200789 for (i=0 ; i < num_all_fds ; i++) {
790 /* We want to remove the fd from the fdtab
791 * but we flag it to disown because the
792 * close is performed by the engine itself
793 */
794 fdtab[all_fd[i]].state |= FD_DISOWN;
795 fd_delete(all_fd[i]);
796 }
Emeric Brun3854e012017-05-17 20:42:48 +0200797
798 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000799 SSL_free(ssl);
Willy Tarreau82531f62021-10-06 12:15:18 +0200800 _HA_ATOMIC_DEC(&global.sslconns);
Willy Tarreau4781b152021-04-06 13:53:36 +0200801 _HA_ATOMIC_DEC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000802}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000803/*
Emeric Brun3854e012017-05-17 20:42:48 +0200804 * function used to manage a returned SSL_ERROR_WANT_ASYNC
805 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000806 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200807static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000808{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100809 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200810 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200811 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000812 size_t num_add_fds = 0;
813 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200814 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000815
816 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
817 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200818 if (num_add_fds > 32 || num_del_fds > 32) {
819 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 +0000820 return;
821 }
822
Emeric Brun3854e012017-05-17 20:42:48 +0200823 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000824
Emeric Brun3854e012017-05-17 20:42:48 +0200825 /* We remove unused fds from the fdtab */
Emeric Brun7d392a52022-07-01 17:36:50 +0200826 for (i=0 ; i < num_del_fds ; i++) {
827 /* We want to remove the fd from the fdtab
828 * but we flag it to disown because the
829 * close is performed by the engine itself
830 */
831 fdtab[del_fd[i]].state |= FD_DISOWN;
832 fd_delete(del_fd[i]);
833 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000834
Emeric Brun3854e012017-05-17 20:42:48 +0200835 /* We add new fds to the fdtab */
836 for (i=0 ; i < num_add_fds ; i++) {
Willy Tarreau27a32452022-07-07 08:29:00 +0200837 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tgid, ti->ltid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000838 }
839
Emeric Brun3854e012017-05-17 20:42:48 +0200840 num_add_fds = 0;
841 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
842 if (num_add_fds > 32) {
843 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
844 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000845 }
Emeric Brun3854e012017-05-17 20:42:48 +0200846
847 /* We activate the polling for all known async fds */
848 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000849 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200850 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000851 /* To ensure that the fd cache won't be used
852 * We'll prefer to catch a real RD event
853 * because handling an EAGAIN on this fd will
854 * result in a context switch and also
855 * some engines uses a fd in blocking mode.
856 */
857 fd_cant_recv(add_fd[i]);
858 }
Emeric Brun3854e012017-05-17 20:42:48 +0200859
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000860}
861#endif
862
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200863#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP && !defined HAVE_ASN1_TIME_TO_TM)
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200864/*
865 * This function returns the number of seconds elapsed
866 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
867 * date presented un ASN1_GENERALIZEDTIME.
868 *
869 * In parsing error case, it returns -1.
870 */
871static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
872{
873 long epoch;
874 char *p, *end;
875 const unsigned short month_offset[12] = {
876 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
877 };
Remi Tricot-Le Bretona3a0cce2021-06-09 17:16:18 +0200878 unsigned long year, month;
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200879
880 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
881
882 p = (char *)d->data;
883 end = p + d->length;
884
885 if (end - p < 4) return -1;
886 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
887 p += 4;
888 if (end - p < 2) return -1;
889 month = 10 * (p[0] - '0') + p[1] - '0';
890 if (month < 1 || month > 12) return -1;
891 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
892 We consider leap years and the current month (<marsh or not) */
893 epoch = ( ((year - 1970) * 365)
894 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
895 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
896 + month_offset[month-1]
897 ) * 24 * 60 * 60;
898 p += 2;
899 if (end - p < 2) return -1;
900 /* Add the number of seconds of completed days of current month */
901 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
902 p += 2;
903 if (end - p < 2) return -1;
904 /* Add the completed hours of the current day */
905 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
906 p += 2;
907 if (end - p < 2) return -1;
908 /* Add the completed minutes of the current hour */
909 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
910 p += 2;
911 if (p == end) return -1;
912 /* Test if there is available seconds */
913 if (p[0] < '0' || p[0] > '9')
914 goto nosec;
915 if (end - p < 2) return -1;
916 /* Add the seconds of the current minute */
917 epoch += 10 * (p[0] - '0') + p[1] - '0';
918 p += 2;
919 if (p == end) return -1;
920 /* Ignore seconds float part if present */
921 if (p[0] == '.') {
922 do {
923 if (++p == end) return -1;
924 } while (p[0] >= '0' && p[0] <= '9');
925 }
926
927nosec:
928 if (p[0] == 'Z') {
929 if (end - p != 1) return -1;
930 return epoch;
931 }
932 else if (p[0] == '+') {
933 if (end - p != 5) return -1;
934 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700935 return epoch - ((10 * (p[1] - '0') + p[2] - '0') * 60 * 60 + (10 * (p[3] - '0') + p[4] - '0')) * 60;
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200936 }
937 else if (p[0] == '-') {
938 if (end - p != 5) return -1;
939 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700940 return epoch + ((10 * (p[1] - '0') + p[2] - '0') * 60 * 60 + (10 * (p[3] - '0') + p[4] - '0')) * 60;
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200941 }
942
943 return -1;
944}
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200945#endif
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200946
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200947#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
William Lallemand104a7a62019-10-14 14:14:59 +0200948/*
949 * struct alignment works here such that the key.key is the same as key_data
950 * Do not change the placement of key_data
951 */
952struct certificate_ocsp {
953 struct ebmb_node key;
954 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
Remi Tricot-Le Breton5aa1dce2021-06-10 13:51:12 +0200955 unsigned int key_length;
William Lallemand104a7a62019-10-14 14:14:59 +0200956 struct buffer response;
William Lallemand76b4a122020-08-04 17:41:39 +0200957 int refcount;
William Lallemand104a7a62019-10-14 14:14:59 +0200958 long expire;
959};
960
961struct ocsp_cbk_arg {
962 int is_single;
963 int single_kt;
964 union {
965 struct certificate_ocsp *s_ocsp;
966 /*
967 * m_ocsp will have multiple entries dependent on key type
968 * Entry 0 - DSA
969 * Entry 1 - ECDSA
970 * Entry 2 - RSA
971 */
972 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
973 };
974};
975
Emeric Brun1d3865b2014-06-20 15:37:32 +0200976static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200977
978/* This function starts to check if the OCSP response (in DER format) contained
979 * in chunk 'ocsp_response' is valid (else exits on error).
980 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
981 * contained in the OCSP Response and exits on error if no match.
982 * If it's a valid OCSP Response:
983 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
984 * pointed by 'ocsp'.
985 * If 'ocsp' is NULL, the function looks up into the OCSP response's
986 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
987 * from the response) and exits on error if not found. Finally, If an OCSP response is
988 * already present in the container, it will be overwritten.
989 *
990 * Note: OCSP response containing more than one OCSP Single response is not
991 * considered valid.
992 *
993 * Returns 0 on success, 1 in error case.
994 */
Willy Tarreau83061a82018-07-13 11:56:34 +0200995static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
996 struct certificate_ocsp *ocsp,
997 OCSP_CERTID *cid, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +0200998{
999 OCSP_RESPONSE *resp;
1000 OCSP_BASICRESP *bs = NULL;
1001 OCSP_SINGLERESP *sr;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001002 OCSP_CERTID *id;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001003 unsigned char *p = (unsigned char *) ocsp_response->area;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001004 int rc , count_sr;
Emeric Brun13a6b482014-06-20 15:44:34 +02001005 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001006 int reason;
1007 int ret = 1;
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +02001008#ifdef HAVE_ASN1_TIME_TO_TM
1009 struct tm nextupd_tm = {0};
1010#endif
Emeric Brun4147b2e2014-06-16 18:36:30 +02001011
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001012 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
1013 ocsp_response->data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001014 if (!resp) {
1015 memprintf(err, "Unable to parse OCSP response");
1016 goto out;
1017 }
1018
1019 rc = OCSP_response_status(resp);
1020 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1021 memprintf(err, "OCSP response status not successful");
1022 goto out;
1023 }
1024
1025 bs = OCSP_response_get1_basic(resp);
1026 if (!bs) {
1027 memprintf(err, "Failed to get basic response from OCSP Response");
1028 goto out;
1029 }
1030
1031 count_sr = OCSP_resp_count(bs);
1032 if (count_sr > 1) {
1033 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
1034 goto out;
1035 }
1036
1037 sr = OCSP_resp_get0(bs, 0);
1038 if (!sr) {
1039 memprintf(err, "Failed to get OCSP single response");
1040 goto out;
1041 }
1042
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001043 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
1044
Emeric Brun4147b2e2014-06-16 18:36:30 +02001045 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
Emmanuel Hocdetef607052017-10-24 14:57:16 +02001046 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
Emmanuel Hocdet872085c2017-10-10 15:18:52 +02001047 memprintf(err, "OCSP single response: certificate status is unknown");
Emeric Brun4147b2e2014-06-16 18:36:30 +02001048 goto out;
1049 }
1050
Emeric Brun13a6b482014-06-20 15:44:34 +02001051 if (!nextupd) {
1052 memprintf(err, "OCSP single response: missing nextupdate");
1053 goto out;
1054 }
1055
Emeric Brunc8b27b62014-06-19 14:16:17 +02001056 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001057 if (!rc) {
1058 memprintf(err, "OCSP single response: no longer valid.");
1059 goto out;
1060 }
1061
1062 if (cid) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001063 if (OCSP_id_cmp(id, cid)) {
Emeric Brun4147b2e2014-06-16 18:36:30 +02001064 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
1065 goto out;
1066 }
1067 }
1068
1069 if (!ocsp) {
1070 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
1071 unsigned char *p;
1072
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001073 rc = i2d_OCSP_CERTID(id, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001074 if (!rc) {
1075 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
1076 goto out;
1077 }
1078
1079 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
1080 memprintf(err, "OCSP single response: Certificate ID too long");
1081 goto out;
1082 }
1083
1084 p = key;
1085 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001086 i2d_OCSP_CERTID(id, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001087 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
1088 if (!ocsp) {
1089 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
1090 goto out;
1091 }
1092 }
1093
1094 /* According to comments on "chunk_dup", the
1095 previous chunk buffer will be freed */
1096 if (!chunk_dup(&ocsp->response, ocsp_response)) {
1097 memprintf(err, "OCSP response: Memory allocation error");
1098 goto out;
1099 }
1100
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +02001101#ifdef HAVE_ASN1_TIME_TO_TM
1102 if (ASN1_TIME_to_tm(nextupd, &nextupd_tm) == 0) {
1103 memprintf(err, "OCSP single response: Invalid \"Next Update\" time");
1104 goto out;
1105 }
1106 ocsp->expire = my_timegm(&nextupd_tm) - OCSP_MAX_RESPONSE_TIME_SKEW;
1107#else
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001108 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
Remi Tricot-Le Bretona3a0cce2021-06-09 17:16:18 +02001109 if (ocsp->expire < 0) {
1110 memprintf(err, "OCSP single response: Invalid \"Next Update\" time");
1111 goto out;
1112 }
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +02001113#endif
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001114
Emeric Brun4147b2e2014-06-16 18:36:30 +02001115 ret = 0;
1116out:
Janusz Dziemidowicz8d710492017-03-08 16:59:41 +01001117 ERR_clear_error();
1118
Emeric Brun4147b2e2014-06-16 18:36:30 +02001119 if (bs)
1120 OCSP_BASICRESP_free(bs);
1121
1122 if (resp)
1123 OCSP_RESPONSE_free(resp);
1124
1125 return ret;
1126}
1127/*
1128 * External function use to update the OCSP response in the OCSP response's
1129 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
1130 * to update in DER format.
1131 *
1132 * Returns 0 on success, 1 in error case.
1133 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001134int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001135{
1136 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
1137}
1138
William Lallemand4a660132019-10-14 14:51:41 +02001139#endif
1140
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001141
1142/*
1143 * Initialize an HMAC context <hctx> using the <key> and <md> parameters.
1144 * Returns -1 in case of error, 1 otherwise.
1145 */
1146static int ssl_hmac_init(MAC_CTX *hctx, unsigned char *key, int key_len, const EVP_MD *md)
1147{
1148#ifdef HAVE_OSSL_PARAM
1149 OSSL_PARAM params[3];
1150
1151 params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, key, key_len);
1152 params[1] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, (char*)EVP_MD_name(md), 0);
1153 params[2] = OSSL_PARAM_construct_end();
1154 if (EVP_MAC_CTX_set_params(hctx, params) == 0)
1155 return -1; /* error in mac initialisation */
1156
1157#else
1158 HMAC_Init_ex(hctx, key, key_len, md, NULL);
1159#endif
1160 return 1;
1161}
1162
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001163#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +01001164
1165static 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 +01001166{
Frédéric Lécaille6aec1f32022-09-06 17:04:55 +02001167 struct tls_keys_ref *ref = NULL;
Emeric Brun9e754772019-01-10 17:51:55 +01001168 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001169 int head;
1170 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001171 int ret = -1; /* error by default */
Frédéric Lécaille6aec1f32022-09-06 17:04:55 +02001172 struct connection *conn = SSL_get_ex_data(s, ssl_app_data_index);
1173#ifdef USE_QUIC
1174 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
1175#endif
1176
1177 if (conn)
1178 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
1179#ifdef USE_QUIC
1180 else if (qc)
1181 ref = qc->li->bind_conf->keys_ref;
1182#endif
1183
1184 if (!ref) {
1185 /* must never happen */
1186 ABORT_NOW();
1187 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001188
Christopher Faulet16f45c82018-02-16 11:23:49 +01001189 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1190
1191 keys = ref->tlskeys;
1192 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001193
1194 if (enc) {
1195 memcpy(key_name, keys[head].name, 16);
1196
1197 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +01001198 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001199
Emeric Brun9e754772019-01-10 17:51:55 +01001200 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001201
Emeric Brun9e754772019-01-10 17:51:55 +01001202 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
1203 goto end;
1204
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001205 if (ssl_hmac_init(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
1206 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +01001207 ret = 1;
1208 }
1209 else if (ref->key_size_bits == 256 ) {
1210
1211 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
1212 goto end;
1213
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001214 if (ssl_hmac_init(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
1215 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +01001216 ret = 1;
1217 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001218 } else {
1219 for (i = 0; i < TLS_TICKETS_NO; i++) {
1220 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
1221 goto found;
1222 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01001223 ret = 0;
1224 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001225
Christopher Faulet16f45c82018-02-16 11:23:49 +01001226 found:
Emeric Brun9e754772019-01-10 17:51:55 +01001227 if (ref->key_size_bits == 128) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001228 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
1229 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +01001230 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
1231 goto end;
1232 /* 2 for key renewal, 1 if current key is still valid */
1233 ret = i ? 2 : 1;
1234 }
1235 else if (ref->key_size_bits == 256) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001236 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
1237 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +01001238 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
1239 goto end;
1240 /* 2 for key renewal, 1 if current key is still valid */
1241 ret = i ? 2 : 1;
1242 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001243 }
Emeric Brun9e754772019-01-10 17:51:55 +01001244
Christopher Faulet16f45c82018-02-16 11:23:49 +01001245 end:
1246 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1247 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001248}
1249
1250struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
1251{
1252 struct tls_keys_ref *ref;
1253
1254 list_for_each_entry(ref, &tlskeys_reference, list)
1255 if (ref->filename && strcmp(filename, ref->filename) == 0)
1256 return ref;
1257 return NULL;
1258}
1259
1260struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1261{
1262 struct tls_keys_ref *ref;
1263
1264 list_for_each_entry(ref, &tlskeys_reference, list)
1265 if (ref->unique_id == unique_id)
1266 return ref;
1267 return NULL;
1268}
1269
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001270/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001271 * match existing ones, this function returns -1
1272 * else it returns 0 on success.
1273 */
1274int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001275 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001276{
Emeric Brun9e754772019-01-10 17:51:55 +01001277 if (ref->key_size_bits == 128) {
1278 if (tlskey->data != sizeof(struct tls_sess_key_128))
1279 return -1;
1280 }
1281 else if (ref->key_size_bits == 256) {
1282 if (tlskey->data != sizeof(struct tls_sess_key_256))
1283 return -1;
1284 }
1285 else
1286 return -1;
1287
Christopher Faulet16f45c82018-02-16 11:23:49 +01001288 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001289 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1290 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001291 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1292 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001293
1294 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001295}
1296
Willy Tarreau83061a82018-07-13 11:56:34 +02001297int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001298{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001299 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1300
1301 if(!ref) {
1302 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1303 return 1;
1304 }
Emeric Brun9e754772019-01-10 17:51:55 +01001305 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1306 memprintf(err, "Invalid key size");
1307 return 1;
1308 }
1309
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001310 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001311}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001312
1313/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001314 * automatic ids. It's called just after the basic checks. It returns
1315 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001316 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001317static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001318{
1319 int i = 0;
1320 struct tls_keys_ref *ref, *ref2, *ref3;
1321 struct list tkr = LIST_HEAD_INIT(tkr);
1322
1323 list_for_each_entry(ref, &tlskeys_reference, list) {
1324 if (ref->unique_id == -1) {
1325 /* Look for the first free id. */
1326 while (1) {
1327 list_for_each_entry(ref2, &tlskeys_reference, list) {
1328 if (ref2->unique_id == i) {
1329 i++;
1330 break;
1331 }
1332 }
1333 if (&ref2->list == &tlskeys_reference)
1334 break;
1335 }
1336
1337 /* Uses the unique id and increment it for the next entry. */
1338 ref->unique_id = i;
1339 i++;
1340 }
1341 }
1342
1343 /* This sort the reference list by id. */
1344 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001345 LIST_DELETE(&ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001346 list_for_each_entry(ref3, &tkr, list) {
1347 if (ref->unique_id < ref3->unique_id) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001348 LIST_APPEND(&ref3->list, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001349 break;
1350 }
1351 }
1352 if (&ref3->list == &tkr)
Willy Tarreau2b718102021-04-21 07:32:39 +02001353 LIST_APPEND(&tkr, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001354 }
1355
1356 /* swap root */
Willy Tarreau2b718102021-04-21 07:32:39 +02001357 LIST_INSERT(&tkr, &tlskeys_reference);
1358 LIST_DELETE(&tkr);
Christopher Fauletfc633b62020-11-06 15:24:23 +01001359 return ERR_NONE;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001360}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001361#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1362
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001363#ifndef OPENSSL_NO_OCSP
William Lallemand76b4a122020-08-04 17:41:39 +02001364int ocsp_ex_index = -1;
1365
yanbzhube2774d2015-12-10 15:07:30 -05001366int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1367{
1368 switch (evp_keytype) {
1369 case EVP_PKEY_RSA:
1370 return 2;
1371 case EVP_PKEY_DSA:
1372 return 0;
1373 case EVP_PKEY_EC:
1374 return 1;
1375 }
1376
1377 return -1;
1378}
1379
Emeric Brun4147b2e2014-06-16 18:36:30 +02001380/*
1381 * Callback used to set OCSP status extension content in server hello.
1382 */
1383int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1384{
yanbzhube2774d2015-12-10 15:07:30 -05001385 struct certificate_ocsp *ocsp;
1386 struct ocsp_cbk_arg *ocsp_arg;
1387 char *ssl_buf;
William Lallemand76b4a122020-08-04 17:41:39 +02001388 SSL_CTX *ctx;
yanbzhube2774d2015-12-10 15:07:30 -05001389 EVP_PKEY *ssl_pkey;
1390 int key_type;
1391 int index;
1392
William Lallemand76b4a122020-08-04 17:41:39 +02001393 ctx = SSL_get_SSL_CTX(ssl);
1394 if (!ctx)
1395 return SSL_TLSEXT_ERR_NOACK;
1396
1397 ocsp_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
1398 if (!ocsp_arg)
1399 return SSL_TLSEXT_ERR_NOACK;
yanbzhube2774d2015-12-10 15:07:30 -05001400
1401 ssl_pkey = SSL_get_privatekey(ssl);
1402 if (!ssl_pkey)
1403 return SSL_TLSEXT_ERR_NOACK;
1404
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001405 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001406
1407 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1408 ocsp = ocsp_arg->s_ocsp;
1409 else {
1410 /* For multiple certs per context, we have to find the correct OCSP response based on
1411 * the certificate type
1412 */
1413 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1414
1415 if (index < 0)
1416 return SSL_TLSEXT_ERR_NOACK;
1417
1418 ocsp = ocsp_arg->m_ocsp[index];
1419
1420 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001421
1422 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001423 !ocsp->response.area ||
1424 !ocsp->response.data ||
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001425 (ocsp->expire < now.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001426 return SSL_TLSEXT_ERR_NOACK;
1427
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001428 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001429 if (!ssl_buf)
1430 return SSL_TLSEXT_ERR_NOACK;
1431
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001432 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01001433 SSL_set_tlsext_status_ocsp_resp(ssl, (unsigned char*)ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001434
1435 return SSL_TLSEXT_ERR_OK;
1436}
1437
William Lallemand4a660132019-10-14 14:51:41 +02001438#endif
1439
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001440#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
William Lallemand76b4a122020-08-04 17:41:39 +02001441
1442
1443/*
1444 * Decrease the refcount of the struct ocsp_response and frees it if it's not
1445 * used anymore. Also removes it from the tree if free'd.
1446 */
1447static void ssl_sock_free_ocsp(struct certificate_ocsp *ocsp)
1448{
1449 if (!ocsp)
1450 return;
1451
1452 ocsp->refcount--;
1453 if (ocsp->refcount <= 0) {
1454 ebmb_delete(&ocsp->key);
1455 chunk_destroy(&ocsp->response);
1456 free(ocsp);
1457 }
1458}
1459
1460
Emeric Brun4147b2e2014-06-16 18:36:30 +02001461/*
1462 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001463 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1464 * status extension, the issuer's certificate is mandatory. It should be
1465 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001466 *
William Lallemand246c0242019-10-11 08:59:13 +02001467 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1468 * OCSP response. If file is empty or content is not a valid OCSP response,
1469 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1470 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001471 *
1472 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001473 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001474 */
William Lallemand52ddd992022-11-22 11:51:53 +01001475static int ssl_sock_load_ocsp(SSL_CTX *ctx, const struct ckch_data *data, STACK_OF(X509) *chain)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001476{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001477 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001478 OCSP_CERTID *cid = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001479 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001480 struct certificate_ocsp *ocsp = NULL, *iocsp;
1481 char *warn = NULL;
1482 unsigned char *p;
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01001483#ifndef USE_OPENSSL_WOLFSSL
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001484 void (*callback) (void);
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01001485#else
1486 tlsextStatusCb callback;
1487#endif
Emeric Brun4147b2e2014-06-16 18:36:30 +02001488
Emeric Brun4147b2e2014-06-16 18:36:30 +02001489
William Lallemand52ddd992022-11-22 11:51:53 +01001490 x = data->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001491 if (!x)
1492 goto out;
1493
William Lallemand52ddd992022-11-22 11:51:53 +01001494 issuer = data->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001495 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1496 if (chain) {
1497 /* check if one of the certificate of the chain is the issuer */
1498 for (i = 0; i < sk_X509_num(chain); i++) {
1499 X509 *ti = sk_X509_value(chain, i);
1500 if (X509_check_issued(ti, x) == X509_V_OK) {
1501 issuer = ti;
1502 break;
1503 }
1504 }
1505 }
William Lallemand246c0242019-10-11 08:59:13 +02001506 if (!issuer)
1507 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001508
1509 cid = OCSP_cert_to_id(0, x, issuer);
1510 if (!cid)
1511 goto out;
1512
1513 i = i2d_OCSP_CERTID(cid, NULL);
1514 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1515 goto out;
1516
Vincent Bernat02779b62016-04-03 13:48:43 +02001517 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001518 if (!ocsp)
1519 goto out;
1520
1521 p = ocsp->key_data;
Remi Tricot-Le Breton5aa1dce2021-06-10 13:51:12 +02001522 ocsp->key_length = i2d_OCSP_CERTID(cid, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001523
1524 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1525 if (iocsp == ocsp)
1526 ocsp = NULL;
1527
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001528#ifndef SSL_CTX_get_tlsext_status_cb
1529# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1530 *cb = (void (*) (void))ctx->tlsext_status_cb;
1531#endif
1532 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1533
1534 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001535 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001536 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001537
William Lallemanda560c062020-07-31 11:43:20 +02001538 cb_arg = calloc(1, sizeof(*cb_arg));
1539 if (!cb_arg)
1540 goto out;
1541
yanbzhube2774d2015-12-10 15:07:30 -05001542 cb_arg->is_single = 1;
1543 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001544 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001545
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001546 pkey = X509_get_pubkey(x);
1547 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1548 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001549
1550 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001551 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 */
1552
yanbzhube2774d2015-12-10 15:07:30 -05001553 } else {
1554 /*
1555 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1556 * Update that cb_arg with the new cert's staple
1557 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001558 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001559 struct certificate_ocsp *tmp_ocsp;
1560 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001561 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001562 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001563
William Lallemand76b4a122020-08-04 17:41:39 +02001564 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001565
1566 /*
1567 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1568 * the order of operations below matter, take care when changing it
1569 */
1570 tmp_ocsp = cb_arg->s_ocsp;
1571 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1572 cb_arg->s_ocsp = NULL;
1573 cb_arg->m_ocsp[index] = tmp_ocsp;
1574 cb_arg->is_single = 0;
1575 cb_arg->single_kt = 0;
1576
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001577 pkey = X509_get_pubkey(x);
1578 key_type = EVP_PKEY_base_id(pkey);
1579 EVP_PKEY_free(pkey);
1580
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001581 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001582 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001583 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001584 iocsp->refcount++;
1585 }
yanbzhube2774d2015-12-10 15:07:30 -05001586 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001587
1588 ret = 0;
1589
1590 warn = NULL;
William Lallemand52ddd992022-11-22 11:51:53 +01001591 if (ssl_sock_load_ocsp_response(data->ocsp_response, iocsp, cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001592 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001593 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001594 }
1595
1596out:
Emeric Brun4147b2e2014-06-16 18:36:30 +02001597 if (cid)
1598 OCSP_CERTID_free(cid);
1599
1600 if (ocsp)
Remi Tricot-Le Bretonaa529f72022-11-03 15:16:49 +01001601 ssl_sock_free_ocsp(ocsp);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001602
1603 if (warn)
1604 free(warn);
1605
Emeric Brun4147b2e2014-06-16 18:36:30 +02001606 return ret;
1607}
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001608#endif
1609
1610#ifdef OPENSSL_IS_BORINGSSL
William Lallemand52ddd992022-11-22 11:51:53 +01001611static int ssl_sock_load_ocsp(SSL_CTX *ctx, const struct ckch_data *data, STACK_OF(X509) *chain)
Emmanuel Hocdet2c32d8f2017-05-22 14:58:00 +02001612{
William Lallemand4a660132019-10-14 14:51:41 +02001613 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 +02001614}
1615#endif
1616
William Lallemand4a660132019-10-14 14:51:41 +02001617
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001618#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001619
1620#define CT_EXTENSION_TYPE 18
1621
William Lallemand03c331c2020-05-13 10:10:01 +02001622int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001623
1624int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1625{
Willy Tarreau83061a82018-07-13 11:56:34 +02001626 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001627
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001628 *out = (unsigned char *) sctl->area;
1629 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001630
1631 return 1;
1632}
1633
1634int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1635{
1636 return 1;
1637}
1638
William Lallemanda17f4112019-10-10 15:16:44 +02001639static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001640{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001641 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001642
William Lallemanda17f4112019-10-10 15:16:44 +02001643 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 +01001644 goto out;
1645
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001646 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1647
1648 ret = 0;
1649
1650out:
1651 return ret;
1652}
1653
1654#endif
1655
Emeric Brune1f38db2012-09-03 20:36:47 +02001656void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1657{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001658 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001659#ifdef USE_QUIC
1660 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1661#endif /* USE_QUIC */
1662 struct ssl_sock_ctx *ctx = NULL;
1663
Emeric Brund8b2bb52014-01-28 15:43:53 +01001664 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001665 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001666
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001667 if (conn)
Willy Tarreau939b0bf2022-04-11 11:29:11 +02001668 ctx = conn_get_ssl_sock_ctx(conn);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001669#ifdef USE_QUIC
1670 else if (qc)
1671 ctx = qc->xprt_ctx;
1672#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01001673
1674 if (!ctx) {
1675 /* must never happen */
1676 ABORT_NOW();
1677 return;
1678 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001679
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001680#ifndef SSL_OP_NO_RENEGOTIATION
1681 /* Please note that BoringSSL defines this macro to zero so don't
1682 * change this to #if and do not assign a default value to this macro!
1683 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001684 if (where & SSL_CB_HANDSHAKE_START) {
1685 /* Disable renegotiation (CVE-2009-3555) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001686 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 +02001687 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001688 conn->err_code = CO_ER_SSL_RENEG;
1689 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001690 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001691#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001692
1693 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001694 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001695 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001696 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001697 consider that the buffering was activated,
1698 so we rise the output buffer size from 4k
1699 to 16k */
1700 write_bio = SSL_get_wbio(ssl);
1701 if (write_bio != SSL_get_rbio(ssl)) {
1702 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001703 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001704 }
1705 }
1706 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001707}
1708
Emeric Brune64aef12012-09-21 13:15:06 +02001709/* Callback is called for each certificate of the chain during a verify
1710 ok is set to 1 if preverify detect no error on current certificate.
1711 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001712int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001713{
1714 SSL *ssl;
1715 struct connection *conn;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001716 struct ssl_sock_ctx *ctx = NULL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001717 int err, depth;
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001718 X509 *client_crt;
1719 STACK_OF(X509) *certs;
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001720 struct bind_conf *bind_conf = NULL;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001721 struct quic_conn *qc = NULL;
Emeric Brune64aef12012-09-21 13:15:06 +02001722
1723 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001724 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001725 client_crt = SSL_get_ex_data(ssl, ssl_client_crt_ref_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001726
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001727 if (conn) {
1728 bind_conf = __objt_listener(conn->target)->bind_conf;
1729 ctx = __conn_get_ssl_sock_ctx(conn);
1730 }
1731#ifdef USE_QUIC
1732 else {
1733 qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
Amaury Denoyelleba303de2022-10-17 18:46:49 +02001734 BUG_ON(!qc); /* Must never happen */
1735 bind_conf = qc->li->bind_conf;
1736 ctx = qc->xprt_ctx;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001737 }
1738#endif
1739
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001740 BUG_ON(!ctx || !bind_conf);
Christopher Faulet881cce92022-11-23 09:27:13 +01001741 ALREADY_CHECKED(ctx);
1742 ALREADY_CHECKED(bind_conf);
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001743
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001744 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001745
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001746 depth = X509_STORE_CTX_get_error_depth(x_store);
1747 err = X509_STORE_CTX_get_error(x_store);
1748
Emeric Brun81c00f02012-09-21 14:31:21 +02001749 if (ok) /* no errors */
1750 return ok;
1751
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001752 /* Keep a reference to the client's certificate in order to be able to
1753 * dump some fetches values in a log even when the verification process
1754 * fails. */
1755 if (depth == 0) {
1756 X509_free(client_crt);
1757 client_crt = X509_STORE_CTX_get0_cert(x_store);
1758 if (client_crt) {
1759 X509_up_ref(client_crt);
1760 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
1761 }
1762 }
1763 else {
1764 /* An error occurred on a CA certificate of the certificate
1765 * chain, we might never call this verify callback on the client
1766 * certificate's depth (which is 0) so we try to store the
1767 * reference right now. */
Remi Tricot-Le Bretonf95c2952021-08-20 09:51:23 +02001768 certs = X509_STORE_CTX_get1_chain(x_store);
1769 if (certs) {
1770 client_crt = sk_X509_value(certs, 0);
1771 if (client_crt) {
1772 X509_up_ref(client_crt);
1773 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001774 }
1775 sk_X509_pop_free(certs, X509_free);
1776 }
1777 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001778
1779 /* check if CA error needs to be ignored */
1780 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001781 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1782 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1783 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001784 }
1785
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01001786 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01001787 cert_ignerr_bitfield_get(bind_conf->ca_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001788 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02001789
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001790 /* TODO: for QUIC connection, this error code is lost */
1791 if (conn)
1792 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001793 return 0;
1794 }
1795
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001796 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1797 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001798
Emeric Brun81c00f02012-09-21 14:31:21 +02001799 /* check if certificate error needs to be ignored */
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01001800 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01001801 cert_ignerr_bitfield_get(bind_conf->crt_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001802 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02001803
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001804 /* TODO: for QUIC connection, this error code is lost */
1805 if (conn)
1806 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001807 return 0;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001808
1809 err_ignored:
1810 ssl_sock_dump_errors(conn, qc);
1811 ERR_clear_error();
1812 return 1;
Emeric Brune64aef12012-09-21 13:15:06 +02001813}
1814
Dragan Dosen9ac98092020-05-11 15:51:45 +02001815#ifdef TLS1_RT_HEARTBEAT
1816static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1817 int content_type, const void *buf, size_t len,
1818 SSL *ssl)
1819{
1820 /* test heartbeat received (write_p is set to 0
1821 for a received record) */
1822 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02001823 struct ssl_sock_ctx *ctx = __conn_get_ssl_sock_ctx(conn);
Dragan Dosen9ac98092020-05-11 15:51:45 +02001824 const unsigned char *p = buf;
1825 unsigned int payload;
1826
1827 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1828
1829 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1830 if (*p != TLS1_HB_REQUEST)
1831 return;
1832
1833 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1834 goto kill_it;
1835
1836 payload = (p[1] * 256) + p[2];
1837 if (3 + payload + 16 <= len)
1838 return; /* OK no problem */
1839 kill_it:
1840 /* We have a clear heartbleed attack (CVE-2014-0160), the
1841 * advertised payload is larger than the advertised packet
1842 * length, so we have garbage in the buffer between the
1843 * payload and the end of the buffer (p+len). We can't know
1844 * if the SSL stack is patched, and we don't know if we can
1845 * safely wipe out the area between p+3+len and payload.
1846 * So instead, we prevent the response from being sent by
1847 * setting the max_send_fragment to 0 and we report an SSL
1848 * error, which will kill this connection. It will be reported
1849 * above as SSL_ERROR_SSL while an other handshake failure with
1850 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1851 */
1852 ssl->max_send_fragment = 0;
1853 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1854 }
1855}
1856#endif
1857
1858static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1859 int content_type, const void *buf, size_t len,
1860 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001861{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001862 struct ssl_capture *capture;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001863 uchar *msg;
1864 uchar *end;
1865 uchar *extensions_end;
1866 uchar *ec_start = NULL;
1867 uchar *ec_formats_start = NULL;
1868 uchar *list_end;
1869 ushort protocol_version;
1870 ushort extension_id;
1871 ushort ec_len = 0;
1872 uchar ec_formats_len = 0;
1873 int offset = 0;
1874 int rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001875
1876 /* This function is called for "from client" and "to server"
1877 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001878 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001879 */
1880
1881 /* "write_p" is set to 0 is the bytes are received messages,
1882 * otherwise it is set to 1.
1883 */
1884 if (write_p != 0)
1885 return;
1886
1887 /* content_type contains the type of message received or sent
1888 * according with the SSL/TLS protocol spec. This message is
1889 * encoded with one byte. The value 256 (two bytes) is used
1890 * for designing the SSL/TLS record layer. According with the
1891 * rfc6101, the expected message (other than 256) are:
1892 * - change_cipher_spec(20)
1893 * - alert(21)
1894 * - handshake(22)
1895 * - application_data(23)
1896 * - (255)
1897 * We are interessed by the handshake and specially the client
1898 * hello.
1899 */
1900 if (content_type != 22)
1901 return;
1902
1903 /* The message length is at least 4 bytes, containing the
1904 * message type and the message length.
1905 */
1906 if (len < 4)
1907 return;
1908
1909 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001910 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001911 * - hello_request(0)
1912 * - client_hello(1)
1913 * - server_hello(2)
1914 * - certificate(11)
1915 * - server_key_exchange (12)
1916 * - certificate_request(13)
1917 * - server_hello_done(14)
1918 * We are interested by the client hello.
1919 */
1920 msg = (unsigned char *)buf;
1921 if (msg[0] != 1)
1922 return;
1923
1924 /* Next three bytes are the length of the message. The total length
1925 * must be this decoded length + 4. If the length given as argument
1926 * is not the same, we abort the protocol dissector.
1927 */
1928 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1929 if (len < rec_len + 4)
1930 return;
1931 msg += 4;
1932 end = msg + rec_len;
1933 if (end < msg)
1934 return;
1935
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001936 /* Expect 2 bytes for protocol version
1937 * (1 byte for major and 1 byte for minor)
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001938 */
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001939 if (msg + 2 > end)
1940 return;
1941 protocol_version = (msg[0] << 8) + msg[1];
1942 msg += 2;
1943
1944 /* Expect the random, composed by 4 bytes for the unix time and
1945 * 28 bytes for unix payload. So we jump 4 + 28.
1946 */
1947 msg += 4 + 28;
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001948 if (msg > end)
1949 return;
1950
1951 /* Next, is session id:
1952 * if present, we have to jump by length + 1 for the size information
1953 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001954 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001955 if (msg[0] > 0)
1956 msg += msg[0];
1957 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001958 if (msg > end)
1959 return;
1960
1961 /* Next two bytes are the ciphersuite length. */
1962 if (msg + 2 > end)
1963 return;
1964 rec_len = (msg[0] << 8) + msg[1];
1965 msg += 2;
1966 if (msg + rec_len > end || msg + rec_len < msg)
1967 return;
1968
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001969 capture = pool_zalloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001970 if (!capture)
1971 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001972 /* Compute the xxh64 of the ciphersuite. */
1973 capture->xxh64 = XXH64(msg, rec_len, 0);
1974
1975 /* Capture the ciphersuite. */
Marcin Deranek310a2602021-07-13 19:04:24 +02001976 capture->ciphersuite_len = MIN(global_ssl.capture_buffer_size, rec_len);
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001977 capture->ciphersuite_offset = 0;
1978 memcpy(capture->data, msg, capture->ciphersuite_len);
1979 msg += rec_len;
1980 offset += capture->ciphersuite_len;
1981
1982 /* Initialize other data */
1983 capture->protocol_version = protocol_version;
1984
1985 /* Next, compression methods:
1986 * if present, we have to jump by length + 1 for the size information
1987 * if not present, we have to jump by 1 only
1988 */
1989 if (msg[0] > 0)
1990 msg += msg[0];
1991 msg += 1;
1992 if (msg > end)
1993 goto store_capture;
1994
1995 /* We reached extensions */
1996 if (msg + 2 > end)
1997 goto store_capture;
1998 rec_len = (msg[0] << 8) + msg[1];
1999 msg += 2;
2000 if (msg + rec_len > end || msg + rec_len < msg)
2001 goto store_capture;
2002 extensions_end = msg + rec_len;
2003 capture->extensions_offset = offset;
2004
2005 /* Parse each extension */
2006 while (msg + 4 < extensions_end) {
2007 /* Add 2 bytes of extension_id */
Marcin Deranek310a2602021-07-13 19:04:24 +02002008 if (global_ssl.capture_buffer_size >= offset + 2) {
Marcin Deranek769fd2e2021-07-12 14:16:55 +02002009 capture->data[offset++] = msg[0];
2010 capture->data[offset++] = msg[1];
2011 capture->extensions_len += 2;
2012 }
2013 else
2014 break;
2015 extension_id = (msg[0] << 8) + msg[1];
2016 /* Length of the extension */
2017 rec_len = (msg[2] << 8) + msg[3];
2018
2019 /* Expect 2 bytes extension id + 2 bytes extension size */
2020 msg += 2 + 2;
2021 if (msg + rec_len > extensions_end || msg + rec_len < msg)
2022 goto store_capture;
2023 /* TLS Extensions
2024 * https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml */
2025 if (extension_id == 0x000a) {
2026 /* Elliptic Curves:
2027 * https://www.rfc-editor.org/rfc/rfc8422.html
2028 * https://www.rfc-editor.org/rfc/rfc7919.html */
2029 list_end = msg + rec_len;
2030 if (msg + 2 > list_end)
2031 goto store_capture;
2032 rec_len = (msg[0] << 8) + msg[1];
2033 msg += 2;
2034
2035 if (msg + rec_len > list_end || msg + rec_len < msg)
2036 goto store_capture;
2037 /* Store location/size of the list */
2038 ec_start = msg;
2039 ec_len = rec_len;
2040 }
2041 else if (extension_id == 0x000b) {
2042 /* Elliptic Curves Point Formats:
2043 * https://www.rfc-editor.org/rfc/rfc8422.html */
2044 list_end = msg + rec_len;
2045 if (msg + 1 > list_end)
2046 goto store_capture;
2047 rec_len = msg[0];
2048 msg += 1;
2049
2050 if (msg + rec_len > list_end || msg + rec_len < msg)
2051 goto store_capture;
2052 /* Store location/size of the list */
2053 ec_formats_start = msg;
2054 ec_formats_len = rec_len;
2055 }
2056 msg += rec_len;
2057 }
2058
2059 if (ec_start) {
2060 rec_len = ec_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02002061 if (offset + rec_len > global_ssl.capture_buffer_size)
2062 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02002063 memcpy(capture->data + offset, ec_start, rec_len);
2064 capture->ec_offset = offset;
2065 capture->ec_len = rec_len;
2066 offset += rec_len;
2067 }
2068 if (ec_formats_start) {
2069 rec_len = ec_formats_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02002070 if (offset + rec_len > global_ssl.capture_buffer_size)
2071 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02002072 memcpy(capture->data + offset, ec_formats_start, rec_len);
2073 capture->ec_formats_offset = offset;
2074 capture->ec_formats_len = rec_len;
2075 offset += rec_len;
2076 }
Emmanuel Hocdete3804742017-03-08 11:07:10 +01002077
Marcin Deranek769fd2e2021-07-12 14:16:55 +02002078 store_capture:
Emmanuel Hocdete3804742017-03-08 11:07:10 +01002079 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01002080}
William Lallemand7d42ef52020-07-06 11:41:30 +02002081
2082
William Lallemand722180a2021-06-09 16:46:12 +02002083#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02002084static void ssl_init_keylog(struct connection *conn, int write_p, int version,
2085 int content_type, const void *buf, size_t len,
2086 SSL *ssl)
2087{
2088 struct ssl_keylog *keylog;
2089
2090 if (SSL_get_ex_data(ssl, ssl_keylog_index))
2091 return;
2092
Willy Tarreauf208ac02021-03-22 21:10:12 +01002093 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02002094 if (!keylog)
2095 return;
2096
William Lallemand7d42ef52020-07-06 11:41:30 +02002097 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
2098 pool_free(pool_head_ssl_keylog, keylog);
2099 return;
2100 }
2101}
2102#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01002103
Emeric Brun29f037d2014-04-25 19:05:36 +02002104/* Callback is called for ssl protocol analyse */
2105void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
2106{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02002107 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2108 struct ssl_sock_msg_callback *cbk;
2109
Dragan Dosen1e7ed042020-05-08 18:30:00 +02002110 /* Try to call all callback functions that were registered by using
2111 * ssl_sock_register_msg_callback().
2112 */
2113 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
2114 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
2115 }
Emeric Brun29f037d2014-04-25 19:05:36 +02002116}
2117
Bernard Spil13c53f82018-02-15 13:34:58 +01002118#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01002119static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
2120 const unsigned char *in, unsigned int inlen,
2121 void *arg)
2122{
2123 struct server *srv = arg;
2124
2125 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
2126 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
2127 return SSL_TLSEXT_ERR_OK;
2128 return SSL_TLSEXT_ERR_NOACK;
2129}
2130#endif
2131
2132#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02002133/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002134 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02002135 */
2136static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
2137 unsigned int *len, void *arg)
2138{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002139 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02002140
2141 *data = (const unsigned char *)conf->npn_str;
2142 *len = conf->npn_len;
2143 return SSL_TLSEXT_ERR_OK;
2144}
2145#endif
2146
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002147#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02002148/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002149 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02002150 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002151static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
2152 unsigned char *outlen,
2153 const unsigned char *server,
2154 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02002155{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002156 struct ssl_bind_conf *conf = arg;
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002157#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002158 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002159#endif
Willy Tarreauab861d32013-04-02 02:30:41 +02002160
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002161 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
2162 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01002163#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002164 if (qc)
2165 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01002166#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002167 return SSL_TLSEXT_ERR_NOACK;
2168 }
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002169
2170#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002171 if (qc && !quic_set_app_ops(qc, *out, *outlen)) {
2172 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002173 return SSL_TLSEXT_ERR_NOACK;
2174 }
2175#endif
2176
Willy Tarreauab861d32013-04-02 02:30:41 +02002177 return SSL_TLSEXT_ERR_OK;
2178}
2179#endif
2180
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02002181#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002182#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002183
cui flitera94bedc2022-08-29 14:42:57 +08002184/* Configure a DNS SAN extension on a certificate. */
Shimi Gersneradabbfe2020-08-23 13:58:13 +03002185int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
2186 int failure = 0;
2187 X509_EXTENSION *san_ext = NULL;
2188 CONF *conf = NULL;
2189 struct buffer *san_name = get_trash_chunk();
2190
2191 conf = NCONF_new(NULL);
2192 if (!conf) {
2193 failure = 1;
2194 goto cleanup;
2195 }
2196
2197 /* Build an extension based on the DNS entry above */
2198 chunk_appendf(san_name, "DNS:%s", servername);
2199 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
2200 if (!san_ext) {
2201 failure = 1;
2202 goto cleanup;
2203 }
2204
2205 /* Add the extension */
2206 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
2207 failure = 1;
2208 goto cleanup;
2209 }
2210
2211 /* Success */
2212 failure = 0;
2213
2214cleanup:
2215 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
2216 if (NULL != conf) NCONF_free(conf);
2217
2218 return failure;
2219}
2220
Christopher Faulet30548802015-06-11 13:39:32 +02002221/* Create a X509 certificate with the specified servername and serial. This
2222 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02002223static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002224ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002225{
Shimi Gersner5846c492020-08-23 13:58:12 +03002226 X509 *cacert = bind_conf->ca_sign_ckch->cert;
2227 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002228 SSL_CTX *ssl_ctx = NULL;
2229 X509 *newcrt = NULL;
2230 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002231 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002232 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002233 X509_NAME *name;
2234 const EVP_MD *digest;
2235 X509V3_CTX ctx;
2236 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002237 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002238
Christopher Faulet48a83322017-07-28 16:56:09 +02002239 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05002240#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002241 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
2242#else
2243 tmp_ssl = SSL_new(bind_conf->default_ctx);
2244 if (tmp_ssl)
2245 pkey = SSL_get_privatekey(tmp_ssl);
2246#endif
2247 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002248 goto mkcert_error;
2249
2250 /* Create the certificate */
2251 if (!(newcrt = X509_new()))
2252 goto mkcert_error;
2253
2254 /* Set version number for the certificate (X509v3) and the serial
2255 * number */
2256 if (X509_set_version(newcrt, 2L) != 1)
2257 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02002258 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002259
2260 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08002261 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
2262 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02002263 goto mkcert_error;
2264
2265 /* set public key in the certificate */
2266 if (X509_set_pubkey(newcrt, pkey) != 1)
2267 goto mkcert_error;
2268
2269 /* Set issuer name from the CA */
2270 if (!(name = X509_get_subject_name(cacert)))
2271 goto mkcert_error;
2272 if (X509_set_issuer_name(newcrt, name) != 1)
2273 goto mkcert_error;
2274
2275 /* Set the subject name using the same, but the CN */
2276 name = X509_NAME_dup(name);
2277 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
2278 (const unsigned char *)servername,
2279 -1, -1, 0) != 1) {
2280 X509_NAME_free(name);
2281 goto mkcert_error;
2282 }
2283 if (X509_set_subject_name(newcrt, name) != 1) {
2284 X509_NAME_free(name);
2285 goto mkcert_error;
2286 }
2287 X509_NAME_free(name);
2288
2289 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002290 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002291 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
2292 for (i = 0; i < X509V3_EXT_SIZE; i++) {
2293 X509_EXTENSION *ext;
2294
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002295 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02002296 goto mkcert_error;
2297 if (!X509_add_ext(newcrt, ext, -1)) {
2298 X509_EXTENSION_free(ext);
2299 goto mkcert_error;
2300 }
2301 X509_EXTENSION_free(ext);
2302 }
2303
Shimi Gersneradabbfe2020-08-23 13:58:13 +03002304 /* Add SAN extension */
2305 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
2306 goto mkcert_error;
2307 }
2308
Christopher Faulet31af49d2015-06-09 17:29:50 +02002309 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002310
2311 key_type = EVP_PKEY_base_id(capkey);
2312
2313 if (key_type == EVP_PKEY_DSA)
2314 digest = EVP_sha1();
2315 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002316 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002317 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02002318 digest = EVP_sha256();
2319 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05002320#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02002321 int nid;
2322
2323 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
2324 goto mkcert_error;
2325 if (!(digest = EVP_get_digestbynid(nid)))
2326 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02002327#else
2328 goto mkcert_error;
2329#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02002330 }
2331
Christopher Faulet31af49d2015-06-09 17:29:50 +02002332 if (!(X509_sign(newcrt, capkey, digest)))
2333 goto mkcert_error;
2334
2335 /* Create and set the new SSL_CTX */
2336 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
2337 goto mkcert_error;
2338 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
2339 goto mkcert_error;
2340 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
2341 goto mkcert_error;
2342 if (!SSL_CTX_check_private_key(ssl_ctx))
2343 goto mkcert_error;
2344
Shimi Gersner5846c492020-08-23 13:58:12 +03002345 /* Build chaining the CA cert and the rest of the chain, keep these order */
2346#if defined(SSL_CTX_add1_chain_cert)
2347 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
2348 goto mkcert_error;
2349 }
2350
2351 if (bind_conf->ca_sign_ckch->chain) {
2352 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2353 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2354 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2355 goto mkcert_error;
2356 }
2357 }
2358 }
2359#endif
2360
Christopher Faulet31af49d2015-06-09 17:29:50 +02002361 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002362
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002363#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002364#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002365 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002366#else
2367 ssl_sock_set_tmp_dh_from_pkey(ssl_ctx, pkey);
2368#endif
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002369#endif
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002370
2371#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
2372#if defined(SSL_CTX_set1_curves_list)
2373 {
2374 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
2375 if (!SSL_CTX_set1_curves_list(ssl_ctx, ecdhe))
2376 goto end;
2377 }
2378#endif
2379#else
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002380#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2381 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002382 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002383 EC_KEY *ecc;
2384 int nid;
2385
2386 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2387 goto end;
2388 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2389 goto end;
2390 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2391 EC_KEY_free(ecc);
2392 }
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002393#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
2394#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002395 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002396 return ssl_ctx;
2397
2398 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002399 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002400 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002401 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2402 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002403 return NULL;
2404}
2405
Christopher Faulet7969a332015-10-09 11:15:03 +02002406
Christopher Faulet30548802015-06-11 13:39:32 +02002407/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002408 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002409SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002410ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002411{
2412 struct lru64 *lru = NULL;
2413
2414 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002415 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002416 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002417 if (lru && lru->domain) {
2418 if (ssl)
2419 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002420 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002421 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002422 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002423 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002424 }
2425 return NULL;
2426}
2427
Emeric Brun821bb9b2017-06-15 16:37:39 +02002428/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2429 * function is not thread-safe, it should only be used to check if a certificate
2430 * exists in the lru cache (with no warranty it will not be removed by another
2431 * thread). It is kept for backward compatibility. */
2432SSL_CTX *
2433ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2434{
2435 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2436}
2437
Christopher Fauletd2cab922015-07-28 16:03:47 +02002438/* Set a certificate int the LRU cache used to store generated
2439 * certificate. Return 0 on success, otherwise -1 */
2440int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002441ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002442{
2443 struct lru64 *lru = NULL;
2444
2445 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002446 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002447 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002448 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002449 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002450 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002451 }
Christopher Faulet30548802015-06-11 13:39:32 +02002452 if (lru->domain && lru->data)
2453 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002454 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002455 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002456 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002457 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002458 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002459}
2460
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002461/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002462unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002463ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002464{
2465 return XXH32(data, len, ssl_ctx_lru_seed);
2466}
2467
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002468/* Generate a cert and immediately assign it to the SSL session so that the cert's
2469 * refcount is maintained regardless of the cert's presence in the LRU cache.
2470 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002471static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002472ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002473{
Shimi Gersner5846c492020-08-23 13:58:12 +03002474 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002475 SSL_CTX *ssl_ctx = NULL;
2476 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002477 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002478
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002479 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002480 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002481 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002482 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002483 if (lru && lru->domain)
2484 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002485 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002486 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002487 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002488 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002489 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002490 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002491 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002492 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002493 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002494 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002495 SSL_set_SSL_CTX(ssl, ssl_ctx);
2496 /* No LRU cache, this CTX will be released as soon as the session dies */
2497 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002498 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002499 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002500 return 0;
2501}
2502static int
2503ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2504{
2505 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002506 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002507
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002508 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002509 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002510 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002511 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002512 }
2513 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002514}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002515#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002516
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002517#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002518
2519static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002520{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002521#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002522 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002523 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2524#endif
2525}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002526static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2527 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002528 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2529}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002530static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002531#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002532 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002533 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2534#endif
2535}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002536static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002537#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002538 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002539 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2540#endif
2541}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002542/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002543static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2544/* Unusable in this context. */
2545static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2546static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2547static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2548static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2549static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002550#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002551
2552static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2553 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002554 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2555}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002556static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2557 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2558 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2559}
2560static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2561 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002562 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2563}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002564static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2565 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2566 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2567}
2568static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2569 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002570 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2571}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002572static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2573 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2574 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2575}
2576static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2577 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002578 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2579}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002580static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2581 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2582 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2583}
2584static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002585#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002586 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002587 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2588#endif
2589}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002590static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002591#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002592 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2593 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002594#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002595}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002596#endif
2597static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2598static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002599
William Lallemand7fd8b452020-05-07 15:20:43 +02002600struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002601 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2602 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2603 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2604 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2605 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2606 {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 +02002607};
2608
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002609static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2610{
2611 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2612 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2613 SSL_set_SSL_CTX(ssl, ctx);
2614}
2615
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002616#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002617
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002618int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002619{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002620 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002621 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002622
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002623 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || (s->options & BC_O_GENERATE_CERTS))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002624 return SSL_TLSEXT_ERR_OK;
2625 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002626}
2627
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002628#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002629int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002630{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002631 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002632#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002633int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002634{
2635#endif
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002636 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2637#ifdef USE_QUIC
2638 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2639#endif /* USE_QUIC */
2640 struct bind_conf *s = NULL;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002641 const uint8_t *extension_data;
2642 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002643 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002644
2645 char *wildp = NULL;
2646 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002647 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002648 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002649 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002650 int i;
2651
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002652 if (conn)
2653 s = __objt_listener(conn->target)->bind_conf;
2654#ifdef USE_QUIC
2655 else if (qc)
2656 s = qc->li->bind_conf;
2657#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01002658
2659 if (!s) {
2660 /* must never happen */
2661 ABORT_NOW();
2662 return 0;
2663 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002664
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002665#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002666 if (qc) {
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002667 /* Look for the QUIC transport parameters. */
2668#ifdef OPENSSL_IS_BORINGSSL
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002669 if (!SSL_early_callback_ctx_extension_get(ctx, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002670 &extension_data, &extension_len))
2671#else
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002672 if (!SSL_client_hello_get0_ext(ssl, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002673 &extension_data, &extension_len))
2674#endif
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002675 {
2676 /* This is not redundant. It we only return 0 without setting
2677 * <*al>, this has as side effect to generate another TLS alert
2678 * which would be set after calling quic_set_tls_alert().
2679 */
2680 *al = SSL_AD_MISSING_EXTENSION;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002681 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002682 return 0;
2683 }
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002684
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002685 if (!quic_transport_params_store(qc, 0, extension_data,
Frédéric Lécaille301425b2022-06-14 17:40:39 +02002686 extension_data + extension_len) ||
2687 !qc_conn_finalize(qc, 0))
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002688 goto abort;
2689 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002690#endif /* USE_QUIC */
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002691
Olivier Houchard9679ac92017-10-27 14:58:08 +02002692 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002693 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002694#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002695 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2696 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002697#else
2698 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2699#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002700 /*
2701 * The server_name extension was given too much extensibility when it
2702 * was written, so parsing the normal case is a bit complex.
2703 */
2704 size_t len;
2705 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002706 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002707 /* Extract the length of the supplied list of names. */
2708 len = (*extension_data++) << 8;
2709 len |= *extension_data++;
2710 if (len + 2 != extension_len)
2711 goto abort;
2712 /*
2713 * The list in practice only has a single element, so we only consider
2714 * the first one.
2715 */
2716 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2717 goto abort;
2718 extension_len = len - 1;
2719 /* Now we can finally pull out the byte array with the actual hostname. */
2720 if (extension_len <= 2)
2721 goto abort;
2722 len = (*extension_data++) << 8;
2723 len |= *extension_data++;
2724 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2725 || memchr(extension_data, 0, len) != NULL)
2726 goto abort;
2727 servername = extension_data;
2728 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002729 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002730#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002731 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002732 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002733 }
2734#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002735 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002736 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002737 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002738 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002739 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002740 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002741 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002742 goto abort;
2743 }
2744
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002745 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002746#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002747 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002748#else
2749 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2750#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002751 uint8_t sign;
2752 size_t len;
2753 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002754 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002755 len = (*extension_data++) << 8;
2756 len |= *extension_data++;
2757 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002758 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002759 if (len % 2 != 0)
2760 goto abort;
2761 for (; len > 0; len -= 2) {
2762 extension_data++; /* hash */
2763 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002764 switch (sign) {
2765 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002766 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002767 break;
2768 case TLSEXT_signature_ecdsa:
2769 has_ecdsa_sig = 1;
2770 break;
2771 default:
2772 continue;
2773 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002774 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002775 break;
2776 }
2777 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002778 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002779 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002780 }
2781 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002782 const SSL_CIPHER *cipher;
2783 size_t len;
2784 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002785 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002786#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002787 len = ctx->cipher_suites_len;
2788 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002789#else
2790 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2791#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002792 if (len % 2 != 0)
2793 goto abort;
2794 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002795#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002796 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002797 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002798#else
2799 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2800#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002801 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002802 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002803 break;
2804 }
2805 }
2806 }
2807
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002808 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002809 trash.area[i] = tolower(servername[i]);
2810 if (!wildp && (trash.area[i] == '.'))
2811 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002812 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002813 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002814
William Lallemand150bfa82019-09-19 17:12:49 +02002815 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002816
William Lallemand94bd3192020-08-14 14:43:35 +02002817 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2818 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002819 for (i = 0; i < 2; i++) {
2820 if (i == 0) /* lookup in full qualified names */
2821 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002822 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002823 node = ebst_lookup(&s->sni_w_ctx, wildp);
2824 else
2825 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002826
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002827 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002828
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002829 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002830 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002831 struct sni_ctx *sni, *sni_tmp;
2832 int skip = 0;
2833
2834 if (i == 1 && wildp) { /* wildcard */
2835 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2836 sni = container_of(n, struct sni_ctx, name);
2837 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002838 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002839 skip = 1;
2840 break;
2841 }
2842 }
2843 if (skip)
2844 continue;
2845 }
2846
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002847 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002848 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002849 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002850 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002851 break;
2852 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002853 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002854 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002855 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002856 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002857 if (!node_anonymous)
2858 node_anonymous = n;
2859 break;
2860 }
2861 }
2862 }
William Lallemand94bd3192020-08-14 14:43:35 +02002863 }
2864 /* Once the certificates are found, select them depending on what is
2865 * supported in the client and by key_signature priority order: EDSA >
2866 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002867 if (has_ecdsa_sig && node_ecdsa)
2868 node = node_ecdsa;
2869 else if (has_rsa_sig && node_rsa)
2870 node = node_rsa;
2871 else if (node_anonymous)
2872 node = node_anonymous;
2873 else if (node_ecdsa)
2874 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2875 else
2876 node = node_rsa; /* no rsa signature case (far far away) */
2877
William Lallemand94bd3192020-08-14 14:43:35 +02002878 if (node) {
2879 /* switch ctx */
2880 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2881 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2882 if (conf) {
2883 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2884 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2885 if (conf->early_data)
2886 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002887 }
William Lallemand94bd3192020-08-14 14:43:35 +02002888 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2889 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002890 }
William Lallemand150bfa82019-09-19 17:12:49 +02002891
William Lallemand02010472019-10-18 11:02:19 +02002892 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002893#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002894 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002895 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002896 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002897 }
2898#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002899 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002900 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002901 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002902 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002903 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
William Lallemand7980dff2021-11-18 17:46:26 +01002904 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002905 }
William Lallemand7980dff2021-11-18 17:46:26 +01002906
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01002907 /* We are about to raise an handshake error so the servername extension
2908 * callback will never be called and the SNI will never be stored in the
2909 * SSL context. In order for the ssl_fc_sni sample fetch to still work
2910 * in such a case, we store the SNI ourselves as an ex_data information
2911 * in the SSL context.
2912 */
2913 {
2914 char *client_sni = pool_alloc(ssl_sock_client_sni_pool);
2915 if (client_sni) {
2916 strncpy(client_sni, trash.area, TLSEXT_MAXLEN_host_name);
2917 client_sni[TLSEXT_MAXLEN_host_name] = '\0';
2918 SSL_set_ex_data(ssl, ssl_client_sni_index, client_sni);
2919 }
2920 }
2921
William Lallemand7980dff2021-11-18 17:46:26 +01002922 /* other cases fallback on abort, if strict-sni is set but no node was found */
2923
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002924 abort:
2925 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002926 if (conn)
2927 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002928#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002929 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002930#else
2931 *al = SSL_AD_UNRECOGNIZED_NAME;
2932 return 0;
2933#endif
William Lallemand7980dff2021-11-18 17:46:26 +01002934
2935allow_early:
2936#ifdef OPENSSL_IS_BORINGSSL
2937 if (allow_early)
2938 SSL_set_early_data_enabled(ssl, 1);
2939#else
2940 if (!allow_early)
2941 SSL_set_max_early_data(ssl, 0);
2942#endif
2943 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002944}
2945
William Lallemand002e2062021-11-18 15:25:16 +01002946#else /* ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002947
Emeric Brunfc0421f2012-09-07 17:30:07 +02002948/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2949 * warning when no match is found, which implies the default (first) cert
2950 * will keep being used.
2951 */
William Lallemand844009d2022-09-02 15:27:32 +02002952int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002953{
2954 const char *servername;
2955 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002956 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002957 struct bind_conf *s = priv;
William Lallemand70a6e632022-09-07 11:21:34 +02002958#ifdef USE_QUIC
2959 const uint8_t *extension_data;
2960 size_t extension_len;
2961 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2962#endif /* USE_QUIC */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002963 int i;
2964 (void)al; /* shut gcc stupid warning */
2965
William Lallemand70a6e632022-09-07 11:21:34 +02002966#ifdef USE_QUIC
2967 if (qc) {
2968
2969 /* Look for the QUIC transport parameters. */
2970 SSL_get_peer_quic_transport_params(ssl, &extension_data, &extension_len);
2971 if (extension_len == 0) {
2972 /* This is not redundant. It we only return 0 without setting
2973 * <*al>, this has as side effect to generate another TLS alert
2974 * which would be set after calling quic_set_tls_alert().
2975 */
2976 *al = SSL_AD_MISSING_EXTENSION;
2977 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
2978 return SSL_TLSEXT_ERR_NOACK;
2979 }
2980
2981 if (!quic_transport_params_store(qc, 0, extension_data,
2982 extension_data + extension_len) ||
2983 !qc_conn_finalize(qc, 0)) {
2984 return SSL_TLSEXT_ERR_NOACK;
2985 }
2986 }
2987#endif /* USE_QUIC */
2988
Emeric Brunfc0421f2012-09-07 17:30:07 +02002989 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002990 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002991#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002992 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002993 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002994#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002995 if (s->strict_sni)
2996 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002997 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002998 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002999 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003000 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01003001 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003002
Willy Tarreau19d14ef2012-10-29 16:51:55 +01003003 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003004 if (!servername[i])
3005 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02003006 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003007 if (!wildp && (trash.area[i] == '.'))
3008 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02003009 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003010 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003011
William Lallemand150bfa82019-09-19 17:12:49 +02003012 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01003013 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003014 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01003015 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
3016 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003017 if (!container_of(n, struct sni_ctx, name)->neg) {
3018 node = n;
3019 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01003020 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003021 }
3022 if (!node && wildp) {
3023 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01003024 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
3025 /* lookup a not neg filter */
3026 if (!container_of(n, struct sni_ctx, name)->neg) {
3027 node = n;
3028 break;
3029 }
3030 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003031 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01003032 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01003033#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02003034 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(servername, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003035 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02003036 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02003037 return SSL_TLSEXT_ERR_OK;
3038 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01003039#endif
William Lallemand21724f02019-11-04 17:56:13 +01003040 if (s->strict_sni) {
3041 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003042 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01003043 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003044 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01003045 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003046 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003047 }
3048
3049 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01003050 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02003051 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003052 return SSL_TLSEXT_ERR_OK;
3053}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003054#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02003055#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
3056
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003057#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003058
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01003059static inline HASSL_DH *ssl_new_dh_fromdata(BIGNUM *p, BIGNUM *g)
3060{
3061#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3062 OSSL_PARAM_BLD *tmpl = NULL;
3063 OSSL_PARAM *params = NULL;
3064 EVP_PKEY_CTX *ctx = NULL;
3065 EVP_PKEY *pkey = NULL;
3066
3067 if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
3068 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
3069 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)
3070 || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
3071 goto end;
3072 }
3073 ctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
3074 if (ctx == NULL
3075 || !EVP_PKEY_fromdata_init(ctx)
3076 || !EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params)) {
3077 goto end;
3078 }
3079
3080end:
3081 EVP_PKEY_CTX_free(ctx);
3082 OSSL_PARAM_free(params);
3083 OSSL_PARAM_BLD_free(tmpl);
Remi Tricot-Le Bretona2c21db2022-11-03 15:16:47 +01003084 BN_free(p);
3085 BN_free(g);
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01003086 return pkey;
3087#else
3088
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003089 HASSL_DH *dh = DH_new();
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01003090
3091 if (!dh)
3092 return NULL;
3093
3094 DH_set0_pqg(dh, p, NULL, g);
3095
3096 return dh;
3097#endif
3098}
3099
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02003100#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003101static inline HASSL_DH *ssl_get_dh_by_nid(int nid)
3102{
3103#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3104 OSSL_PARAM params[2];
3105 EVP_PKEY *pkey = NULL;
3106 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
3107 const char *named_group = NULL;
3108
3109 if (!pctx)
3110 goto end;
3111
3112 named_group = OBJ_nid2ln(nid);
3113
3114 if (!named_group)
3115 goto end;
3116
3117 params[0] = OSSL_PARAM_construct_utf8_string("group", (char*)named_group, 0);
3118 params[1] = OSSL_PARAM_construct_end();
3119
3120 if (EVP_PKEY_keygen_init(pctx) && EVP_PKEY_CTX_set_params(pctx, params))
3121 EVP_PKEY_generate(pctx, &pkey);
3122
3123end:
3124 EVP_PKEY_CTX_free(pctx);
3125 return pkey;
3126#else
3127
3128 HASSL_DH *dh = NULL;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003129 dh = DH_new_by_nid(nid);
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003130 return dh;
3131#endif
3132}
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02003133#endif
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003134
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01003135
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003136static HASSL_DH * ssl_get_dh_1024(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003137{
Remi Gacogned3a341a2015-05-29 16:26:17 +02003138 static unsigned char dh1024_p[]={
3139 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
3140 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
3141 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
3142 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
3143 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
3144 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
3145 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
3146 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
3147 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
3148 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
3149 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
3150 };
3151 static unsigned char dh1024_g[]={
3152 0x02,
3153 };
3154
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003155 BIGNUM *p;
3156 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02003157
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003158 HASSL_DH *dh = NULL;
3159
3160 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
3161 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
3162
3163 if (p && g)
3164 dh = ssl_new_dh_fromdata(p, g);
3165
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003166 return dh;
3167}
3168
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003169static HASSL_DH *ssl_get_dh_2048(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003170{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003171#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02003172 static unsigned char dh2048_p[]={
3173 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
3174 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
3175 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
3176 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
3177 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
3178 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
3179 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
3180 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
3181 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
3182 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
3183 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
3184 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
3185 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
3186 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
3187 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
3188 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
3189 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
3190 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
3191 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
3192 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
3193 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
3194 0xB7,0x1F,0x77,0xF3,
3195 };
3196 static unsigned char dh2048_g[]={
3197 0x02,
3198 };
3199
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003200 BIGNUM *p;
3201 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02003202
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003203 HASSL_DH *dh = NULL;
3204
3205 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
3206 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
3207
3208 if (p && g)
3209 dh = ssl_new_dh_fromdata(p, g);
3210
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003211 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003212#else
3213 return ssl_get_dh_by_nid(NID_ffdhe2048);
3214#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003215}
3216
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003217static HASSL_DH *ssl_get_dh_4096(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003218{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003219#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02003220 static unsigned char dh4096_p[]={
3221 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
3222 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
3223 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
3224 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
3225 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
3226 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
3227 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
3228 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
3229 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
3230 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
3231 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
3232 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
3233 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
3234 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
3235 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
3236 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
3237 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
3238 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
3239 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
3240 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
3241 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
3242 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
3243 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
3244 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
3245 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
3246 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
3247 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
3248 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
3249 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
3250 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
3251 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
3252 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
3253 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
3254 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
3255 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
3256 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
3257 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
3258 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
3259 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
3260 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
3261 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
3262 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
3263 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003264 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02003265 static unsigned char dh4096_g[]={
3266 0x02,
3267 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003268
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003269 BIGNUM *p;
3270 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02003271
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003272 HASSL_DH *dh = NULL;
3273
3274 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
3275 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
3276
3277 if (p && g)
3278 dh = ssl_new_dh_fromdata(p, g);
3279
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003280 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003281#else
3282 return ssl_get_dh_by_nid(NID_ffdhe4096);
3283#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003284}
3285
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003286static HASSL_DH *ssl_get_tmp_dh(EVP_PKEY *pkey)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003287{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003288 HASSL_DH *dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003289 int type;
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003290 int keylen = 0;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003291
3292 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003293
Ilya Shipitsin52f2ff52022-07-23 23:55:19 +05003294 if (type == EVP_PKEY_EC) {
3295 keylen = global_ssl.default_dh_param;
3296 }
3297
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003298 /* The keylen supplied by OpenSSL can only be 512 or 1024.
3299 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
3300 */
3301 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
3302 keylen = EVP_PKEY_bits(pkey);
3303 }
3304
Willy Tarreauef934602016-12-22 23:12:01 +01003305 if (keylen > global_ssl.default_dh_param) {
3306 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003307 }
3308
Remi Gacogned3a341a2015-05-29 16:26:17 +02003309 if (keylen >= 4096) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003310 if (!local_dh_4096)
3311 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02003312 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003313 }
3314 else if (keylen >= 2048) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003315 if (!local_dh_2048)
3316 local_dh_2048 = ssl_get_dh_2048();
Remi Gacogne8de54152014-07-15 11:36:40 +02003317 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003318 }
3319 else {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003320 if (!local_dh_1024)
3321 local_dh_1024 = ssl_get_dh_1024();
Remi Gacogne8de54152014-07-15 11:36:40 +02003322 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003323 }
3324
3325 return dh;
3326}
3327
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003328#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003329/* Returns Diffie-Hellman parameters matching the private key length
3330 but not exceeding global_ssl.default_dh_param */
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003331static HASSL_DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003332{
3333 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
3334
3335 return ssl_get_tmp_dh(pkey);
3336}
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003337#endif
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003338
Remi Tricot-Le Breton846eda92022-02-11 12:04:50 +01003339static int ssl_sock_set_tmp_dh(SSL_CTX *ctx, HASSL_DH *dh)
3340{
3341#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
3342 return SSL_CTX_set_tmp_dh(ctx, dh);
3343#else
3344 int retval = 0;
3345 HASSL_DH_up_ref(dh);
3346
3347 retval = SSL_CTX_set0_tmp_dh_pkey(ctx, dh);
3348
3349 if (!retval)
3350 HASSL_DH_free(dh);
3351
3352 return retval;
3353#endif
3354}
3355
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003356#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3357static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey)
3358{
3359 HASSL_DH *dh = NULL;
3360 if (pkey && (dh = ssl_get_tmp_dh(pkey))) {
3361 HASSL_DH_up_ref(dh);
3362 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dh))
3363 HASSL_DH_free(dh);
3364 }
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003365}
3366#endif
3367
Remi Tricot-Le Breton09ebb332022-02-11 12:04:48 +01003368HASSL_DH *ssl_sock_get_dh_from_bio(BIO *bio)
3369{
3370#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3371 HASSL_DH *dh = NULL;
3372 OSSL_DECODER_CTX *dctx = NULL;
3373 const char *format = "PEM";
3374 const char *keytype = "DH";
3375
3376 dctx = OSSL_DECODER_CTX_new_for_pkey(&dh, format, NULL, keytype,
3377 OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
3378 NULL, NULL);
3379
3380 if (dctx == NULL || OSSL_DECODER_CTX_get_num_decoders(dctx) == 0)
3381 goto end;
3382
3383 /* The DH parameters might not be the first section found in the PEM
3384 * file so we need to iterate over all of them until we find the right
3385 * one.
3386 */
3387 while (!BIO_eof(bio) && !dh)
3388 OSSL_DECODER_from_bio(dctx, bio);
3389
3390end:
3391 OSSL_DECODER_CTX_free(dctx);
3392 return dh;
3393#else
3394 HASSL_DH *dh = NULL;
3395
3396 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3397
3398 return dh;
3399#endif
3400}
3401
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003402static HASSL_DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003403{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003404 HASSL_DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02003405 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003406
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003407 if (in == NULL)
3408 goto end;
3409
Remi Gacogne47783ef2015-05-29 15:53:22 +02003410 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003411 goto end;
3412
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003413 dh = ssl_sock_get_dh_from_bio(in);
Remi Gacogne47783ef2015-05-29 15:53:22 +02003414
3415end:
3416 if (in)
3417 BIO_free(in);
3418
Emeric Brune1b4ed42018-08-16 15:14:12 +02003419 ERR_clear_error();
3420
Remi Gacogne47783ef2015-05-29 15:53:22 +02003421 return dh;
3422}
3423
3424int ssl_sock_load_global_dh_param_from_file(const char *filename)
3425{
3426 global_dh = ssl_sock_get_dh_from_file(filename);
3427
3428 if (global_dh) {
3429 return 0;
3430 }
3431
3432 return -1;
3433}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003434#endif
3435
William Lallemand9117de92019-10-04 00:29:42 +02003436/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02003437static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02003438 struct bind_conf *s, struct ssl_bind_conf *conf,
3439 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003440{
3441 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003442 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003443
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003444 if (*name == '!') {
3445 neg = 1;
3446 name++;
3447 }
3448 if (*name == '*') {
3449 wild = 1;
3450 name++;
3451 }
3452 /* !* filter is a nop */
3453 if (neg && wild)
3454 return order;
3455 if (*name) {
3456 int j, len;
3457 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003458 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02003459 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003460 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02003461 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003462 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003463
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003464 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02003465 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02003466 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003467 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02003468 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003469 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003470 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003471 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003472 sc->order = order++;
3473 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02003474 sc->wild = wild;
3475 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01003476 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02003477 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003478 }
3479 return order;
3480}
3481
William Lallemand6af03992019-07-23 15:00:54 +02003482/*
William Lallemand1d29c742019-10-04 00:53:29 +02003483 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
3484 * This function can't return an error.
3485 *
3486 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
3487 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003488void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02003489{
3490
3491 struct sni_ctx *sc0, *sc0b, *sc1;
3492 struct ebmb_node *node;
3493
3494 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
3495
3496 /* ignore if sc0 was already inserted in a tree */
3497 if (sc0->name.node.leaf_p)
3498 continue;
3499
3500 /* Check for duplicates. */
3501 if (sc0->wild)
3502 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
3503 else
3504 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
3505
3506 for (; node; node = ebmb_next_dup(node)) {
3507 sc1 = ebmb_entry(node, struct sni_ctx, name);
3508 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
3509 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
3510 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02003511 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02003512 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003513 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02003514 break;
William Lallemand1d29c742019-10-04 00:53:29 +02003515 }
3516 }
3517
3518 /* if duplicate, ignore the insertion */
3519 if (!sc0)
3520 continue;
3521
3522 if (sc0->wild)
3523 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
3524 else
3525 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003526 }
William Lallemand21724f02019-11-04 17:56:13 +01003527
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003528 /* replace the default_ctx if required with the instance's ctx. */
3529 if (ckch_inst->is_default) {
3530 SSL_CTX_free(bind_conf->default_ctx);
3531 SSL_CTX_up_ref(ckch_inst->ctx);
3532 bind_conf->default_ctx = ckch_inst->ctx;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003533 bind_conf->default_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02003534 }
3535}
3536
3537/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003538 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02003539 */
William Lallemande3af8fb2019-10-08 11:36:53 +02003540struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02003541
William Lallemand2954c472020-03-06 21:54:13 +01003542/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02003543struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02003544
Emeric Brun7a883362019-10-17 13:27:40 +02003545/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003546 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02003547 * DH parameter is loaded into the SSL_CTX and if there is no
3548 * DH parameter available in ckchs nor in global, the default
3549 * DH parameters are applied on the SSL_CTX.
3550 * Returns a bitfield containing the flags:
3551 * ERR_FATAL in any fatal error case
3552 * ERR_ALERT if a reason of the error is availabine in err
3553 * ERR_WARN if a warning is available into err
3554 * The value 0 means there is no error nor warning and
3555 * the operation succeed.
3556 */
William Lallemandfa892222019-07-23 16:06:08 +02003557#ifndef OPENSSL_NO_DH
William Lallemand52ddd992022-11-22 11:51:53 +01003558static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct ckch_data *data,
Emeric Brun7a883362019-10-17 13:27:40 +02003559 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02003560{
Emeric Brun7a883362019-10-17 13:27:40 +02003561 int ret = 0;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003562 HASSL_DH *dh = NULL;
William Lallemandfa892222019-07-23 16:06:08 +02003563
William Lallemand52ddd992022-11-22 11:51:53 +01003564 if (data && data->dh) {
3565 dh = data->dh;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003566 if (!ssl_sock_set_tmp_dh(ctx, dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003567 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
3568 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003569 memprintf(err, "%s, DH ciphers won't be available.\n",
3570 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003571 ret |= ERR_WARN;
3572 goto end;
3573 }
William Lallemandfa892222019-07-23 16:06:08 +02003574
3575 if (ssl_dh_ptr_index >= 0) {
3576 /* store a pointer to the DH params to avoid complaining about
3577 ssl-default-dh-param not being set for this SSL_CTX */
3578 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
3579 }
3580 }
3581 else if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003582 if (!ssl_sock_set_tmp_dh(ctx, global_dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003583 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
3584 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003585 memprintf(err, "%s, DH ciphers won't be available.\n",
3586 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003587 ret |= ERR_WARN;
3588 goto end;
3589 }
William Lallemandfa892222019-07-23 16:06:08 +02003590 }
3591 else {
3592 /* Clear openssl global errors stack */
3593 ERR_clear_error();
3594
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003595 /* We do not want DHE ciphers to be added to the cipher list
3596 * unless there is an explicit global dh option in the conf.
3597 */
3598 if (global_ssl.default_dh_param) {
3599 if (global_ssl.default_dh_param <= 1024) {
3600 /* we are limited to DH parameter of 1024 bits anyway */
3601 if (local_dh_1024 == NULL)
3602 local_dh_1024 = ssl_get_dh_1024();
William Lallemandfa892222019-07-23 16:06:08 +02003603
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003604 if (local_dh_1024 == NULL) {
3605 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3606 err && *err ? *err : "", path);
3607 ret |= ERR_ALERT | ERR_FATAL;
3608 goto end;
3609 }
William Lallemandfa892222019-07-23 16:06:08 +02003610
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003611 if (!ssl_sock_set_tmp_dh(ctx, local_dh_1024)) {
3612 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3613 err && *err ? *err : "", path);
3614 memprintf(err, "%s, DH ciphers won't be available.\n",
3615 err && *err ? *err : "");
3616 ret |= ERR_WARN;
3617 goto end;
3618 }
Emeric Bruna9363eb2019-10-17 14:53:03 +02003619 }
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003620 else {
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003621#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003622 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003623#else
William Lallemand52ddd992022-11-22 11:51:53 +01003624 ssl_sock_set_tmp_dh_from_pkey(ctx, data ? data->key : NULL);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003625#endif
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003626 }
William Lallemandfa892222019-07-23 16:06:08 +02003627 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003628 }
3629
William Lallemandf9568fc2019-10-16 18:27:58 +02003630end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003631 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003632 return ret;
3633}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003634#endif
William Lallemandfa892222019-07-23 16:06:08 +02003635
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003636
3637/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003638 * Returns a bitfield containing the flags:
3639 * ERR_FATAL in any fatal error case
3640 * ERR_ALERT if the reason of the error is available in err
3641 * ERR_WARN if a warning is available into err
3642 * The value 0 means there is no error nor warning and
3643 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003644 */
William Lallemand52ddd992022-11-22 11:51:53 +01003645static int ssl_sock_load_cert_chain(const char *path, const struct ckch_data *data,
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003646 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003647{
Emeric Bruna96b5822019-10-17 13:25:14 +02003648 int errcode = 0;
William Lallemand45fed2c2022-11-15 16:56:03 +01003649 int ret;
3650
3651 ERR_clear_error();
Emeric Bruna96b5822019-10-17 13:25:14 +02003652
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003653 if (find_chain == NULL) {
3654 errcode |= ERR_FATAL;
3655 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003656 }
3657
William Lallemand52ddd992022-11-22 11:51:53 +01003658 if (!SSL_CTX_use_certificate(ctx, data->cert)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003659 ret = ERR_get_error();
3660 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s': %s.\n",
3661 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Emeric Bruna96b5822019-10-17 13:25:14 +02003662 errcode |= ERR_ALERT | ERR_FATAL;
3663 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003664 }
3665
William Lallemand52ddd992022-11-22 11:51:53 +01003666 if (data->chain) {
3667 *find_chain = data->chain;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003668 } else {
3669 /* Find Certificate Chain in global */
3670 struct issuer_chain *issuer;
William Lallemand52ddd992022-11-22 11:51:53 +01003671 issuer = ssl_get0_issuer_chain(data->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003672 if (issuer)
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003673 *find_chain = issuer->chain;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003674 }
William Lallemand85888572020-02-27 14:48:35 +01003675
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003676 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003677 /* always put a null chain stack in the SSL_CTX so it does not
3678 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003679 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003680 }
3681
William Lallemand52ddd992022-11-22 11:51:53 +01003682 /* Load all certs in the data into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003683#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003684 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003685 ret = ERR_get_error();
3686 memprintf(err, "%sunable to load chain certificate into SSL Context '%s': %s. Make sure you are linking against Openssl >= 1.0.2.\n",
3687 err && *err ? *err : "", path, ERR_reason_error_string(ret));
William Lallemand935d8292020-08-12 20:02:10 +02003688 errcode |= ERR_ALERT | ERR_FATAL;
3689 goto end;
3690 }
William Lallemandf187ce62020-06-02 18:27:20 +02003691#else
3692 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003693 X509 *ca;
William Lallemandf187ce62020-06-02 18:27:20 +02003694 STACK_OF(X509) *chain;
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003695 chain = X509_chain_up_ref(*find_chain);
William Lallemandf187ce62020-06-02 18:27:20 +02003696 while ((ca = sk_X509_shift(chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003697 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003698 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3699 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003700 X509_free(ca);
3701 sk_X509_pop_free(chain, X509_free);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003702 errcode |= ERR_ALERT | ERR_FATAL;
3703 goto end;
3704 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003705 }
William Lallemandf187ce62020-06-02 18:27:20 +02003706#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003707
William Lallemand9a1d8392020-08-10 17:28:23 +02003708#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003709 /* remove the Root CA from the SSL_CTX if the option is activated */
3710 if (global_ssl.skip_self_issued_ca) {
3711 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3712 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3713 err && *err ? *err : "", path);
3714 errcode |= ERR_ALERT | ERR_FATAL;
3715 goto end;
3716 }
3717 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003718#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003719
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003720end:
3721 return errcode;
3722}
3723
3724
3725/* Loads the info in ckch into ctx
3726 * Returns a bitfield containing the flags:
3727 * ERR_FATAL in any fatal error case
3728 * ERR_ALERT if the reason of the error is available in err
3729 * ERR_WARN if a warning is available into err
3730 * The value 0 means there is no error nor warning and
3731 * the operation succeed.
3732 */
William Lallemand52ddd992022-11-22 11:51:53 +01003733static int ssl_sock_put_ckch_into_ctx(const char *path, const struct ckch_data *data, SSL_CTX *ctx, char **err)
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003734{
3735 int errcode = 0;
3736 STACK_OF(X509) *find_chain = NULL;
3737
William Lallemand5de49512022-10-27 14:41:07 +02003738 ERR_clear_error();
3739
William Lallemand52ddd992022-11-22 11:51:53 +01003740 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
William Lallemand5de49512022-10-27 14:41:07 +02003741 int ret;
3742
3743 ret = ERR_get_error();
3744 memprintf(err, "%sunable to load SSL private key into SSL Context '%s': %s.\n",
3745 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003746 errcode |= ERR_ALERT | ERR_FATAL;
3747 return errcode;
3748 }
3749
3750 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01003751 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003752 if (errcode & ERR_CODE)
3753 goto end;
3754
William Lallemandfa892222019-07-23 16:06:08 +02003755#ifndef OPENSSL_NO_DH
3756 /* store a NULL pointer to indicate we have not yet loaded
3757 a custom DH param file */
3758 if (ssl_dh_ptr_index >= 0) {
3759 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3760 }
3761
William Lallemand52ddd992022-11-22 11:51:53 +01003762 errcode |= ssl_sock_load_dh_params(ctx, data, path, err);
Emeric Brun7a883362019-10-17 13:27:40 +02003763 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003764 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3765 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003766 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003767 }
3768#endif
3769
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003770#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemand52ddd992022-11-22 11:51:53 +01003771 if (sctl_ex_index >= 0 && data->sctl) {
3772 if (ssl_sock_load_sctl(ctx, data->sctl) < 0) {
William Lallemanda17f4112019-10-10 15:16:44 +02003773 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003774 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003775 errcode |= ERR_ALERT | ERR_FATAL;
3776 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003777 }
3778 }
3779#endif
3780
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003781#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
William Lallemand246c0242019-10-11 08:59:13 +02003782 /* Load OCSP Info into context */
William Lallemand52ddd992022-11-22 11:51:53 +01003783 if (data->ocsp_response) {
3784 if (ssl_sock_load_ocsp(ctx, data, find_chain) < 0) {
Tim Duesterhus93128532019-11-23 23:45:10 +01003785 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",
3786 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003787 errcode |= ERR_ALERT | ERR_FATAL;
3788 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003789 }
3790 }
William Lallemand246c0242019-10-11 08:59:13 +02003791#endif
3792
Emeric Bruna96b5822019-10-17 13:25:14 +02003793 end:
3794 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003795}
3796
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003797
3798/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
3799 * Returns a bitfield containing the flags:
3800 * ERR_FATAL in any fatal error case
3801 * ERR_ALERT if the reason of the error is available in err
3802 * ERR_WARN if a warning is available into err
3803 * The value 0 means there is no error nor warning and
3804 * the operation succeed.
3805 */
William Lallemand52ddd992022-11-22 11:51:53 +01003806static 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 +01003807 SSL_CTX *ctx, char **err)
3808{
3809 int errcode = 0;
3810 STACK_OF(X509) *find_chain = NULL;
3811
3812 /* Load the private key */
William Lallemand52ddd992022-11-22 11:51:53 +01003813 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003814 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3815 err && *err ? *err : "", path);
3816 errcode |= ERR_ALERT | ERR_FATAL;
3817 }
3818
3819 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01003820 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003821 if (errcode & ERR_CODE)
3822 goto end;
3823
3824 if (SSL_CTX_check_private_key(ctx) <= 0) {
3825 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3826 err && *err ? *err : "", path);
3827 errcode |= ERR_ALERT | ERR_FATAL;
3828 }
3829
3830end:
3831 return errcode;
3832}
3833
3834
William Lallemand614ca0d2019-10-07 13:52:11 +02003835/*
3836 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003837 *
3838 * Returns a bitfield containing the flags:
3839 * ERR_FATAL in any fatal error case
3840 * ERR_ALERT if the reason of the error is available in err
3841 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003842 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003843int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003844 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003845{
William Lallemandc9402072019-05-15 15:33:54 +02003846 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003847 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003848 int order = 0;
3849 X509_NAME *xname;
3850 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003851 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003852 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003853#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3854 STACK_OF(GENERAL_NAME) *names;
3855#endif
William Lallemand52ddd992022-11-22 11:51:53 +01003856 struct ckch_data *data;
William Lallemand614ca0d2019-10-07 13:52:11 +02003857 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003858 int errcode = 0;
3859
3860 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003861
William Lallemand52ddd992022-11-22 11:51:53 +01003862 if (!ckchs || !ckchs->data)
Emeric Brun054563d2019-10-17 13:16:58 +02003863 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003864
William Lallemand52ddd992022-11-22 11:51:53 +01003865 data = ckchs->data;
William Lallemand36b84632019-07-18 19:28:17 +02003866
William Lallemandc9402072019-05-15 15:33:54 +02003867 ctx = SSL_CTX_new(SSLv23_server_method());
3868 if (!ctx) {
3869 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3870 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003871 errcode |= ERR_ALERT | ERR_FATAL;
3872 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003873 }
3874
William Lallemand52ddd992022-11-22 11:51:53 +01003875 errcode |= ssl_sock_put_ckch_into_ctx(path, data, ctx, err);
Emeric Bruna96b5822019-10-17 13:25:14 +02003876 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003877 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003878
3879 ckch_inst = ckch_inst_new();
3880 if (!ckch_inst) {
3881 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3882 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003883 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003884 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003885 }
3886
William Lallemand52ddd992022-11-22 11:51:53 +01003887 pkey = X509_get_pubkey(data->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003888 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003889 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003890 switch(EVP_PKEY_base_id(pkey)) {
3891 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003892 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003893 break;
3894 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003895 kinfo.sig = TLSEXT_signature_ecdsa;
3896 break;
3897 case EVP_PKEY_DSA:
3898 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003899 break;
3900 }
3901 EVP_PKEY_free(pkey);
3902 }
3903
Emeric Brun50bcecc2013-04-22 13:05:23 +02003904 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003905 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003906 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 +02003907 if (order < 0) {
3908 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003909 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003910 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003911 }
3912 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003913 }
3914 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003915#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand52ddd992022-11-22 11:51:53 +01003916 names = X509_get_ext_d2i(data->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003917 if (names) {
3918 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3919 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3920 if (name->type == GEN_DNS) {
3921 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003922 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003923 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003924 if (order < 0) {
3925 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003926 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003927 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003928 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003929 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003930 }
3931 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003932 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003933 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003934#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand52ddd992022-11-22 11:51:53 +01003935 xname = X509_get_subject_name(data->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003936 i = -1;
3937 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3938 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003939 ASN1_STRING *value;
3940
3941 value = X509_NAME_ENTRY_get_data(entry);
3942 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003943 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003944 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003945 if (order < 0) {
3946 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003947 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003948 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003949 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003950 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003951 }
3952 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003953 /* we must not free the SSL_CTX anymore below, since it's already in
3954 * the tree, so it will be discovered and cleaned in time.
3955 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003956
Emeric Brunfc0421f2012-09-07 17:30:07 +02003957#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003958 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003959 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3960 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003961 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003962 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003963 }
3964#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003965 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003966 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003967 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003968 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003969 SSL_CTX_up_ref(ctx);
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003970 bind_conf->default_inst = ckch_inst;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003971 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003972
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003973 /* Always keep a reference to the newly constructed SSL_CTX in the
3974 * instance. This way if the instance has no SNIs, the SSL_CTX will
3975 * still be linked. */
3976 SSL_CTX_up_ref(ctx);
3977 ckch_inst->ctx = ctx;
3978
William Lallemand9117de92019-10-04 00:29:42 +02003979 /* everything succeed, the ckch instance can be used */
3980 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003981 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003982 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003983
William Lallemand02e19a52020-04-08 16:11:26 +02003984 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3985
Emeric Brun054563d2019-10-17 13:16:58 +02003986 *ckchi = ckch_inst;
3987 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003988
3989error:
3990 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003991 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003992 if (ckch_inst->is_default)
3993 SSL_CTX_free(ctx);
3994
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003995 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003996 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003997 }
William Lallemandd9199372019-10-04 15:37:05 +02003998 SSL_CTX_free(ctx);
3999
Emeric Brun054563d2019-10-17 13:16:58 +02004000 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004001}
4002
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004003
4004/*
4005 * This function allocate a ckch_inst that will be used on the backend side
4006 * (server line)
4007 *
4008 * Returns a bitfield containing the flags:
4009 * ERR_FATAL in any fatal error case
4010 * ERR_ALERT if the reason of the error is available in err
4011 * ERR_WARN if a warning is available into err
4012 */
4013int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01004014 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004015{
4016 SSL_CTX *ctx;
William Lallemand52ddd992022-11-22 11:51:53 +01004017 struct ckch_data *data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004018 struct ckch_inst *ckch_inst = NULL;
4019 int errcode = 0;
4020
4021 *ckchi = NULL;
4022
William Lallemand52ddd992022-11-22 11:51:53 +01004023 if (!ckchs || !ckchs->data)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004024 return ERR_FATAL;
4025
William Lallemand52ddd992022-11-22 11:51:53 +01004026 data = ckchs->data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004027
4028 ctx = SSL_CTX_new(SSLv23_client_method());
4029 if (!ctx) {
4030 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
4031 err && *err ? *err : "", path);
4032 errcode |= ERR_ALERT | ERR_FATAL;
4033 goto error;
4034 }
4035
William Lallemand52ddd992022-11-22 11:51:53 +01004036 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, data, ctx, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004037 if (errcode & ERR_CODE)
4038 goto error;
4039
4040 ckch_inst = ckch_inst_new();
4041 if (!ckch_inst) {
4042 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
4043 err && *err ? *err : "", path);
4044 errcode |= ERR_ALERT | ERR_FATAL;
4045 goto error;
4046 }
4047
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004048 /* everything succeed, the ckch instance can be used */
4049 ckch_inst->bind_conf = NULL;
4050 ckch_inst->ssl_conf = NULL;
4051 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01004052 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01004053 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004054
4055 *ckchi = ckch_inst;
4056 return errcode;
4057
4058error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004059 SSL_CTX_free(ctx);
4060
4061 return errcode;
4062}
4063
Willy Tarreau8c5414a2019-10-16 17:06:25 +02004064/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02004065static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
4066 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01004067 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02004068{
Emeric Brun054563d2019-10-17 13:16:58 +02004069 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02004070
4071 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02004072 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 +02004073
Emeric Brun054563d2019-10-17 13:16:58 +02004074 if (errcode & ERR_CODE)
4075 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02004076
William Lallemand24bde432020-03-09 16:48:43 +01004077 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02004078
4079 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02004080 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02004081 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02004082}
4083
William Lallemanddb26e2b2021-01-26 12:01:46 +01004084/* This function generates a <struct ckch_inst *> for a <struct server *>, and
4085 * fill the SSL_CTX of the server.
4086 *
4087 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004088static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01004089 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004090{
4091 int errcode = 0;
4092
4093 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01004094 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004095
4096 if (errcode & ERR_CODE)
4097 return errcode;
4098
William Lallemanddb26e2b2021-01-26 12:01:46 +01004099 (*ckch_inst)->server = server;
4100 /* Keep the reference to the SSL_CTX in the server. */
4101 SSL_CTX_up_ref((*ckch_inst)->ctx);
4102 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004103 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02004104 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004105 return errcode;
4106}
4107
William Lallemand6be66ec2020-03-06 22:26:32 +01004108
William Lallemand4c68bba2020-03-30 18:45:10 +02004109
4110
4111/* Make sure openssl opens /dev/urandom before the chroot. The work is only
4112 * done once. Zero is returned if the operation fails. No error is returned
4113 * if the random is said as not implemented, because we expect that openssl
4114 * will use another method once needed.
4115 */
Amaury Denoyellec593bcd2021-05-19 15:35:29 +02004116int ssl_initialize_random(void)
William Lallemand4c68bba2020-03-30 18:45:10 +02004117{
4118 unsigned char random;
4119 static int random_initialized = 0;
4120
4121 if (!random_initialized && RAND_bytes(&random, 1) != 0)
4122 random_initialized = 1;
4123
4124 return random_initialized;
4125}
4126
William Lallemand2954c472020-03-06 21:54:13 +01004127/* Load a crt-list file, this is done in 2 parts:
4128 * - store the content of the file in a crtlist structure with crtlist_entry structures
4129 * - generate the instances by iterating on entries in the crtlist struct
4130 *
4131 * Nothing is locked there, this function is used in the configuration parser.
4132 *
4133 * Returns a set of ERR_* flags possibly with an error in <err>.
4134 */
William Lallemand6be66ec2020-03-06 22:26:32 +01004135int 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 +01004136{
4137 struct crtlist *crtlist = NULL;
4138 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02004139 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01004140 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01004141 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02004142 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01004143
William Lallemand79d31ec2020-03-25 15:10:49 +01004144 bind_conf_node = malloc(sizeof(*bind_conf_node));
4145 if (!bind_conf_node) {
4146 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
4147 cfgerr |= ERR_FATAL | ERR_ALERT;
4148 goto error;
4149 }
4150 bind_conf_node->next = NULL;
4151 bind_conf_node->bind_conf = bind_conf;
4152
William Lallemand41ca9302020-04-08 13:15:18 +02004153 /* strip trailing slashes, including first one */
4154 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
4155 *end = 0;
4156
William Lallemand2954c472020-03-06 21:54:13 +01004157 /* look for an existing crtlist or create one */
4158 eb = ebst_lookup(&crtlists_tree, file);
4159 if (eb) {
4160 crtlist = ebmb_entry(eb, struct crtlist, node);
4161 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01004162 /* load a crt-list OR a directory */
4163 if (dir)
4164 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
4165 else
4166 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
4167
William Lallemand2954c472020-03-06 21:54:13 +01004168 if (!(cfgerr & ERR_CODE))
4169 ebst_insert(&crtlists_tree, &crtlist->node);
4170 }
4171
4172 if (cfgerr & ERR_CODE) {
4173 cfgerr |= ERR_FATAL | ERR_ALERT;
4174 goto error;
4175 }
4176
4177 /* generates ckch instance from the crtlist_entry */
4178 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
4179 struct ckch_store *store;
4180 struct ckch_inst *ckch_inst = NULL;
4181
4182 store = entry->node.key;
4183 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
4184 if (cfgerr & ERR_CODE) {
4185 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
4186 goto error;
4187 }
Willy Tarreau2b718102021-04-21 07:32:39 +02004188 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02004189 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01004190 }
William Lallemand2954c472020-03-06 21:54:13 +01004191
William Lallemand79d31ec2020-03-25 15:10:49 +01004192 /* add the bind_conf to the list */
4193 bind_conf_node->next = crtlist->bind_conf;
4194 crtlist->bind_conf = bind_conf_node;
4195
William Lallemand2954c472020-03-06 21:54:13 +01004196 return cfgerr;
4197error:
4198 {
William Lallemand49398312020-03-30 17:01:33 +02004199 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01004200 struct ckch_inst *inst, *s_inst;
4201
William Lallemand49398312020-03-30 17:01:33 +02004202 lastentry = entry; /* which entry we tried to generate last */
4203 if (lastentry) {
4204 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
4205 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
4206 break;
4207
4208 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01004209
William Lallemand49398312020-03-30 17:01:33 +02004210 /* this was not generated for this bind_conf, skip */
4211 if (inst->bind_conf != bind_conf)
4212 continue;
4213
William Lallemandd9d5d1b2020-04-09 16:31:05 +02004214 /* free the sni_ctx and instance */
4215 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02004216 }
William Lallemand2954c472020-03-06 21:54:13 +01004217 }
William Lallemand2954c472020-03-06 21:54:13 +01004218 }
William Lallemand79d31ec2020-03-25 15:10:49 +01004219 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01004220 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01004221 return cfgerr;
4222}
4223
William Lallemand06b22a82020-03-16 14:45:55 +01004224/* Returns a set of ERR_* flags possibly with an error in <err>. */
4225int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
4226{
4227 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01004228 int cfgerr = 0;
4229 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01004230 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01004231 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01004232
4233 if ((ckchs = ckchs_lookup(path))) {
4234 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01004235 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
4236 found++;
4237 } else if (stat(path, &buf) == 0) {
4238 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01004239 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02004240 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01004241 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01004242 cfgerr |= ERR_ALERT | ERR_FATAL;
4243 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01004244 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01004245 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01004246 }
4247 } else {
4248 /* stat failed, could be a bundle */
4249 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02004250 char fp[MAXPATHLEN+1] = {0};
4251 int n = 0;
4252
4253 /* Load all possible certs and keys in separate ckch_store */
4254 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
4255 struct stat buf;
4256 int ret;
4257
4258 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
4259 if (ret > sizeof(fp))
4260 continue;
4261
4262 if ((ckchs = ckchs_lookup(fp))) {
4263 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01004264 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02004265 } else {
4266 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01004267 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02004268 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02004269 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01004270 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02004271 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
4272 }
4273 }
4274 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01004275#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
4276 if (found) {
4277 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
4278 err && *err ? *err : "", path);
4279 cfgerr |= ERR_ALERT | ERR_FATAL;
4280 }
4281#endif
William Lallemand06b22a82020-03-16 14:45:55 +01004282 }
4283 }
William Lallemand06ce84a2020-11-20 15:36:13 +01004284 if (!found) {
4285 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
4286 err && *err ? *err : "", path, strerror(errno));
4287 cfgerr |= ERR_ALERT | ERR_FATAL;
4288 }
William Lallemand06b22a82020-03-16 14:45:55 +01004289
4290 return cfgerr;
4291}
4292
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004293
4294/* Create a full ssl context and ckch instance that will be used for a specific
4295 * backend server (server configuration line).
4296 * Returns a set of ERR_* flags possibly with an error in <err>.
4297 */
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004298int 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 +01004299{
4300 struct stat buf;
4301 int cfgerr = 0;
4302 struct ckch_store *ckchs;
4303 int found = 0; /* did we found a file to load ? */
4304
4305 if ((ckchs = ckchs_lookup(path))) {
4306 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01004307 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004308 found++;
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004309 } else {
4310 if (!create_if_none) {
4311 memprintf(err, "%sunable to stat SSL certificate '%s'.\n",
4312 err && *err ? *err : "", path);
4313 cfgerr |= ERR_ALERT | ERR_FATAL;
4314 goto out;
4315 }
4316
4317 if (stat(path, &buf) == 0) {
4318 /* We do not manage directories on backend side. */
4319 if (S_ISDIR(buf.st_mode) == 0) {
4320 ++found;
4321 ckchs = ckchs_load_cert_file(path, err);
4322 if (!ckchs)
4323 cfgerr |= ERR_ALERT | ERR_FATAL;
4324 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
4325 }
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004326 }
4327 }
4328 if (!found) {
4329 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
4330 err && *err ? *err : "", path, strerror(errno));
4331 cfgerr |= ERR_ALERT | ERR_FATAL;
4332 }
4333
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004334out:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004335 return cfgerr;
4336}
4337
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004338/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004339static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004340ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004341{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004342 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004343 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004344 SSL_OP_ALL | /* all known workarounds for bugs */
4345 SSL_OP_NO_SSLv2 |
4346 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02004347 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02004348 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004349 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02004350 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004351 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004352 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004353 SSL_MODE_ENABLE_PARTIAL_WRITE |
4354 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004355 SSL_MODE_RELEASE_BUFFERS |
4356 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004357 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004358 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004359 int flags = MC_SSL_O_ALL;
4360 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02004361 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004362
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004363 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004364 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004365
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004366 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004367 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
4368 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4369 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004370 else
4371 flags = conf_ssl_methods->flags;
4372
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004373 min = conf_ssl_methods->min;
4374 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02004375
4376 /* default minimum is TLSV12, */
4377 if (!min) {
4378 if (!max || (max >= default_min_ver)) {
4379 min = default_min_ver;
4380 } else {
4381 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). "
4382 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
4383 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
4384 min = max;
4385 }
4386 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004387 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004388 if (min)
4389 flags |= (methodVersions[min].flag - 1);
4390 if (max)
4391 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004392 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004393 min = max = CONF_TLSV_NONE;
4394 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004395 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004396 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004397 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004398 if (min) {
4399 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004400 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
4401 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4402 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
4403 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004404 hole = 0;
4405 }
4406 max = i;
4407 }
4408 else {
4409 min = max = i;
4410 }
4411 }
4412 else {
4413 if (min)
4414 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004415 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004416 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004417 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4418 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004419 cfgerr += 1;
4420 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004421 /* save real min/max in bind_conf */
4422 conf_ssl_methods->min = min;
4423 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004424
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004425#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004426 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004427 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004428 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004429 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004430 else
William Lallemandd0712f32020-06-11 17:34:00 +02004431 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
4432 /* clear every version flags in case SSL_CTX_new()
4433 * returns an SSL_CTX with disabled versions */
4434 SSL_CTX_clear_options(ctx, methodVersions[i].option);
4435
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004436 if (flags & methodVersions[i].flag)
4437 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02004438
4439 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004440#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004441 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004442 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4443 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02004444#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004445
4446 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
4447 options |= SSL_OP_NO_TICKET;
4448 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
4449 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08004450
4451#ifdef SSL_OP_NO_RENEGOTIATION
4452 options |= SSL_OP_NO_RENEGOTIATION;
4453#endif
4454
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004455 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004456
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004457#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004458 if (global_ssl.async)
4459 mode |= SSL_MODE_ASYNC;
4460#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004461 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004462 if (global_ssl.life_time)
4463 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004464
4465#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand4b7938d2022-09-07 10:54:17 +02004466# ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004467 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
4468 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004469# elif defined(HAVE_SSL_CLIENT_HELLO_CB)
4470# if defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01004471 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01004472 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
William Lallemand4b7938d2022-09-07 10:54:17 +02004473# endif /* ! SSL_OP_NO_ANTI_REPLAY */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02004474 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
4475 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004476# else /* ! OPENSSL_IS_BORINGSSL && ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004477 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004478# endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02004479 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
William Lallemand4b7938d2022-09-07 10:54:17 +02004480#endif /* ! SSL_CTRL_SET_TLSEXT_HOSTNAME */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004481 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004482}
4483
William Lallemand4f45bb92017-10-30 20:08:51 +01004484
4485static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
4486{
4487 if (first == block) {
4488 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4489 if (first->len > 0)
4490 sh_ssl_sess_tree_delete(sh_ssl_sess);
4491 }
4492}
4493
4494/* return first block from sh_ssl_sess */
4495static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
4496{
4497 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
4498
4499}
4500
4501/* store a session into the cache
4502 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
4503 * data: asn1 encoded session
4504 * data_len: asn1 encoded session length
4505 * Returns 1 id session was stored (else 0)
4506 */
4507static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
4508{
4509 struct shared_block *first;
4510 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
4511
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004512 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01004513 if (!first) {
4514 /* Could not retrieve enough free blocks to store that session */
4515 return 0;
4516 }
4517
4518 /* STORE the key in the first elem */
4519 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4520 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
4521 first->len = sizeof(struct sh_ssl_sess_hdr);
4522
4523 /* it returns the already existing node
4524 or current node if none, never returns null */
4525 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
4526 if (oldsh_ssl_sess != sh_ssl_sess) {
4527 /* NOTE: Row couldn't be in use because we lock read & write function */
4528 /* release the reserved row */
4529 shctx_row_dec_hot(ssl_shctx, first);
4530 /* replace the previous session already in the tree */
4531 sh_ssl_sess = oldsh_ssl_sess;
4532 /* ignore the previous session data, only use the header */
4533 first = sh_ssl_sess_first_block(sh_ssl_sess);
4534 shctx_row_inc_hot(ssl_shctx, first);
4535 first->len = sizeof(struct sh_ssl_sess_hdr);
4536 }
4537
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004538 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01004539 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004540 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01004541 }
4542
4543 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004544
4545 return 1;
4546}
William Lallemanded0b5ad2017-10-30 19:36:36 +01004547
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004548/* SSL callback used when a new session is created while connecting to a server */
4549static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4550{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004551 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004552 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004553
Willy Tarreau07d94e42018-09-20 10:57:52 +02004554 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004555
William Lallemand3ce6eed2021-02-08 10:43:44 +01004556 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4557 * one cache per thread, it only prevents to flush it from the CLI in
4558 * another thread */
4559
Olivier Houcharde6060c52017-11-16 17:42:52 +01004560 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4561 int len;
4562 unsigned char *ptr;
William Lallemande18d4e82021-11-17 02:59:21 +01004563 const char *sni;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004564
Olivier Houcharde6060c52017-11-16 17:42:52 +01004565 len = i2d_SSL_SESSION(sess, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01004566 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004567 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004568 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4569 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4570 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004571 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
4572 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004573 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4574 }
4575 if (s->ssl_ctx.reused_sess[tid].ptr) {
4576 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4577 &ptr);
4578 }
William Lallemande18d4e82021-11-17 02:59:21 +01004579
4580 if (s->ssl_ctx.reused_sess[tid].sni) {
4581 /* if the new sni is empty or isn' t the same as the old one */
4582 if ((!sni) || strcmp(s->ssl_ctx.reused_sess[tid].sni, sni) != 0) {
4583 ha_free(&s->ssl_ctx.reused_sess[tid].sni);
4584 if (sni)
4585 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4586 }
4587 } else if (sni) {
4588 /* if there wasn't an old sni but there is a new one */
4589 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4590 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004591 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004592 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004593 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004594 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004595 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004596 }
4597
4598 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004599}
4600
Olivier Houcharde6060c52017-11-16 17:42:52 +01004601
William Lallemanded0b5ad2017-10-30 19:36:36 +01004602/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004603int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004604{
4605 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4606 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4607 unsigned char *p;
4608 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004609 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004610 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004611
4612 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004613 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004614 * note: SSL_SESSION_set1_id is using
4615 * a memcpy so we need to use a different pointer
4616 * than sid_data or sid_ctx_data to avoid valgrind
4617 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004618 */
4619
4620 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004621
4622 /* copy value in an other buffer */
4623 memcpy(encid, sid_data, sid_length);
4624
4625 /* pad with 0 */
4626 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4627 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4628
4629 /* force length to zero to avoid ASN1 encoding */
4630 SSL_SESSION_set1_id(sess, encid, 0);
4631
4632 /* force length to zero to avoid ASN1 encoding */
4633 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004634
4635 /* check if buffer is large enough for the ASN1 encoded session */
4636 data_len = i2d_SSL_SESSION(sess, NULL);
4637 if (data_len > SHSESS_MAX_DATA_LEN)
4638 goto err;
4639
4640 p = encsess;
4641
4642 /* process ASN1 session encoding before the lock */
4643 i2d_SSL_SESSION(sess, &p);
4644
William Lallemanded0b5ad2017-10-30 19:36:36 +01004645
William Lallemanda3c77cf2017-10-30 23:44:40 +01004646 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004647 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004648 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004649 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004650err:
4651 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004652 SSL_SESSION_set1_id(sess, encid, sid_length);
4653 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004654
4655 return 0; /* do not increment session reference count */
4656}
4657
4658/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004659SSL_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 +01004660{
William Lallemand4f45bb92017-10-30 20:08:51 +01004661 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004662 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4663 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004664 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004665 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004666
Willy Tarreau4c19e992021-06-15 16:39:22 +02004667 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004668
4669 /* allow the session to be freed automatically by openssl */
4670 *do_copy = 0;
4671
4672 /* tree key is zeros padded sessionid */
4673 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4674 memcpy(tmpkey, key, key_len);
4675 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4676 key = tmpkey;
4677 }
4678
4679 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004680 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004681
4682 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004683 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4684 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004685 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004686 shctx_unlock(ssl_shctx);
Willy Tarreau4c19e992021-06-15 16:39:22 +02004687 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004688 return NULL;
4689 }
4690
William Lallemand4f45bb92017-10-30 20:08:51 +01004691 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4692 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004693
William Lallemand4f45bb92017-10-30 20:08:51 +01004694 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 +01004695
William Lallemanda3c77cf2017-10-30 23:44:40 +01004696 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004697
4698 /* decode ASN1 session */
4699 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004700 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004701 /* Reset session id and session id contenxt */
4702 if (sess) {
4703 SSL_SESSION_set1_id(sess, key, key_len);
4704 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4705 }
4706
4707 return sess;
4708}
4709
William Lallemand4f45bb92017-10-30 20:08:51 +01004710
William Lallemanded0b5ad2017-10-30 19:36:36 +01004711/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004712void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004713{
William Lallemand4f45bb92017-10-30 20:08:51 +01004714 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004715 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4716 unsigned int sid_length;
4717 const unsigned char *sid_data;
4718 (void)ctx;
4719
4720 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4721 /* tree key is zeros padded sessionid */
4722 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4723 memcpy(tmpkey, sid_data, sid_length);
4724 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4725 sid_data = tmpkey;
4726 }
4727
William Lallemanda3c77cf2017-10-30 23:44:40 +01004728 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004729
4730 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004731 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4732 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004733 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004734 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004735 }
4736
4737 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004738 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004739}
4740
4741/* Set session cache mode to server and disable openssl internal cache.
4742 * Set shared cache callbacks on an ssl context.
4743 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004744void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004745{
4746 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4747
4748 if (!ssl_shctx) {
4749 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4750 return;
4751 }
4752
4753 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4754 SSL_SESS_CACHE_NO_INTERNAL |
4755 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4756
4757 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004758 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4759 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4760 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004761}
William Lallemand7d42ef52020-07-06 11:41:30 +02004762
4763/*
4764 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4765 *
4766 * The format is:
4767 * * <Label> <space> <ClientRandom> <space> <Secret>
4768 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4769 */
4770
William Lallemand722180a2021-06-09 16:46:12 +02004771#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004772void SSL_CTX_keylog(const SSL *ssl, const char *line)
4773{
4774 struct ssl_keylog *keylog;
4775 char *lastarg = NULL;
4776 char *dst = NULL;
4777
4778 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4779 if (!keylog)
4780 return;
4781
4782 lastarg = strrchr(line, ' ');
4783 if (lastarg == NULL || ++lastarg == NULL)
4784 return;
4785
4786 dst = pool_alloc(pool_head_ssl_keylog_str);
4787 if (!dst)
4788 return;
4789
4790 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4791 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4792
4793 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4794 if (keylog->client_random)
4795 goto error;
4796 keylog->client_random = dst;
4797
4798 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4799 if (keylog->client_early_traffic_secret)
4800 goto error;
4801 keylog->client_early_traffic_secret = dst;
4802
4803 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4804 if(keylog->client_handshake_traffic_secret)
4805 goto error;
4806 keylog->client_handshake_traffic_secret = dst;
4807
4808 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4809 if (keylog->server_handshake_traffic_secret)
4810 goto error;
4811 keylog->server_handshake_traffic_secret = dst;
4812
4813 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4814 if (keylog->client_traffic_secret_0)
4815 goto error;
4816 keylog->client_traffic_secret_0 = dst;
4817
4818 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4819 if (keylog->server_traffic_secret_0)
4820 goto error;
4821 keylog->server_traffic_secret_0 = dst;
4822
4823 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4824 if (keylog->early_exporter_secret)
4825 goto error;
4826 keylog->early_exporter_secret = dst;
4827
4828 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4829 if (keylog->exporter_secret)
4830 goto error;
4831 keylog->exporter_secret = dst;
4832 } else {
4833 goto error;
4834 }
4835
4836 return;
4837
4838error:
4839 pool_free(pool_head_ssl_keylog_str, dst);
4840
4841 return;
4842}
4843#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004844
William Lallemand8b453912019-11-21 15:48:10 +01004845/*
4846 * This function applies the SSL configuration on a SSL_CTX
4847 * It returns an error code and fills the <err> buffer
4848 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004849static 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 +01004850{
4851 struct proxy *curproxy = bind_conf->frontend;
4852 int cfgerr = 0;
4853 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004854 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004855 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004856#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004857 const char *conf_ciphersuites;
4858#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004859 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004860
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004861 if (ssl_conf) {
4862 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4863 int i, min, max;
4864 int flags = MC_SSL_O_ALL;
4865
4866 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004867 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4868 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004869 if (min)
4870 flags |= (methodVersions[min].flag - 1);
4871 if (max)
4872 flags |= ~((methodVersions[max].flag << 1) - 1);
4873 min = max = CONF_TLSV_NONE;
4874 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4875 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4876 if (min)
4877 max = i;
4878 else
4879 min = max = i;
4880 }
4881 /* save real min/max */
4882 conf_ssl_methods->min = min;
4883 conf_ssl_methods->max = max;
4884 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004885 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4886 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004887 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004888 }
4889 }
4890
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004891 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004892 case SSL_SOCK_VERIFY_NONE:
4893 verify = SSL_VERIFY_NONE;
4894 break;
4895 case SSL_SOCK_VERIFY_OPTIONAL:
4896 verify = SSL_VERIFY_PEER;
4897 break;
4898 case SSL_SOCK_VERIFY_REQUIRED:
4899 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4900 break;
4901 }
4902 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4903 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004904 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 +01004905 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 +01004906 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 +01004907 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004908 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004909 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004910 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004911 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004912 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004913 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004914 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4915 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4916 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4917 cfgerr |= ERR_ALERT | ERR_FATAL;
4918 }
4919 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004920 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004921 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 +02004922 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004923 }
Emeric Brun850efd52014-01-29 12:24:34 +01004924 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004925 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4926 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004927 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004928 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004929#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004930 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004931 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4932
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004933 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004934 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4935 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004936 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004937 }
Emeric Brun561e5742012-10-02 15:20:55 +02004938 else {
4939 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4940 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004941 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004942#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004943 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004944 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004945#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004946 if(bind_conf->keys_ref) {
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +01004947 if (!SSL_CTX_set_tlsext_ticket_key_evp_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004948 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4949 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004950 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004951 }
4952 }
4953#endif
4954
William Lallemand4f45bb92017-10-30 20:08:51 +01004955 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004956 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4957 if (conf_ciphers &&
4958 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004959 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4960 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004961 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004962 }
4963
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004964#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004965 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4966 if (conf_ciphersuites &&
4967 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004968 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4969 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004970 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004971 }
4972#endif
4973
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004974#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02004975 if (!local_dh_1024)
4976 local_dh_1024 = ssl_get_dh_1024();
4977 if (!local_dh_2048)
4978 local_dh_2048 = ssl_get_dh_2048();
4979 if (!local_dh_4096)
4980 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02004981#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004982
Emeric Brunfc0421f2012-09-07 17:30:07 +02004983 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004984#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004985 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004986#endif
William Lallemand722180a2021-06-09 16:46:12 +02004987#ifdef HAVE_SSL_KEYLOG
William Lallemandb60a77b2022-11-18 15:00:15 +01004988 /* only activate the keylog callback if it was required to prevent performance loss */
4989 if (global_ssl.keylog > 0)
4990 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02004991#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004992
Bernard Spil13c53f82018-02-15 13:34:58 +01004993#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004994 ssl_conf_cur = NULL;
4995 if (ssl_conf && ssl_conf->npn_str)
4996 ssl_conf_cur = ssl_conf;
4997 else if (bind_conf->ssl_conf.npn_str)
4998 ssl_conf_cur = &bind_conf->ssl_conf;
4999 if (ssl_conf_cur)
5000 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02005001#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01005002#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005003 ssl_conf_cur = NULL;
5004 if (ssl_conf && ssl_conf->alpn_str)
5005 ssl_conf_cur = ssl_conf;
5006 else if (bind_conf->ssl_conf.alpn_str)
5007 ssl_conf_cur = &bind_conf->ssl_conf;
5008 if (ssl_conf_cur)
5009 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02005010#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05005011#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01005012 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
5013 if (conf_curves) {
5014 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01005015 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
5016 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01005017 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01005018 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01005019 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01005020 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01005021#endif /* defined(SSL_CTX_set1_curves_list) */
5022
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01005023 if (!conf_curves) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005024#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01005025#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005026 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02005027 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
5028 NULL);
5029
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01005030 if (ecdhe && SSL_CTX_set1_curves_list(ctx, ecdhe) == 0) {
5031 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
5032 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
5033 cfgerr |= ERR_ALERT | ERR_FATAL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005034 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01005035#endif /* defined(SSL_CTX_set1_curves_list) */
Olivier Houchardc2aae742017-09-22 18:26:28 +02005036#else
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01005037#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
5038 int i;
5039 EC_KEY *ecdh;
5040
Olivier Houchardc2aae742017-09-22 18:26:28 +02005041 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
5042 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
5043 ECDHE_DEFAULT_CURVE);
Emeric Brun2b58d042012-09-20 17:10:03 +02005044
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005045 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02005046 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01005047 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 +01005048 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01005049 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02005050 }
5051 else {
5052 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
5053 EC_KEY_free(ecdh);
5054 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01005055#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
5056#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Emeric Brun2b58d042012-09-20 17:10:03 +02005057 }
Emeric Brun2b58d042012-09-20 17:10:03 +02005058
Emeric Brunfc0421f2012-09-07 17:30:07 +02005059 return cfgerr;
5060}
5061
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005062
5063/*
5064 * Prepare the SSL_CTX based on the bind line configuration.
5065 * Since the CA file loading is made depending on the verify option of the bind
5066 * line, the link between the SSL_CTX and the CA file tree entry is made here.
5067 * If we want to create a link between the CA file entry and the corresponding
5068 * ckch instance (for CA file hot update), it needs to be done after
5069 * ssl_sock_prepare_ctx.
5070 * Returns 0 in case of success.
5071 */
5072int ssl_sock_prep_ctx_and_inst(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
5073 SSL_CTX *ctx, struct ckch_inst *ckch_inst, char **err)
5074{
5075 int errcode = 0;
5076
5077 errcode |= ssl_sock_prepare_ctx(bind_conf, ssl_conf, ctx, err);
5078 if (!errcode && ckch_inst)
5079 ckch_inst_add_cafile_link(ckch_inst, bind_conf, ssl_conf, NULL);
5080
5081 return errcode;
5082}
5083
Evan Broderbe554312013-06-27 00:05:25 -07005084static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
5085{
5086 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
5087 size_t prefixlen, suffixlen;
5088
5089 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02005090 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07005091 return 1;
5092
Evan Broderbe554312013-06-27 00:05:25 -07005093 /* The rest of this logic is based on RFC 6125, section 6.4.3
5094 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
5095
Emeric Bruna848dae2013-10-08 11:27:28 +02005096 pattern_wildcard = NULL;
5097 pattern_left_label_end = pattern;
5098 while (*pattern_left_label_end != '.') {
5099 switch (*pattern_left_label_end) {
5100 case 0:
5101 /* End of label not found */
5102 return 0;
5103 case '*':
5104 /* If there is more than one wildcards */
5105 if (pattern_wildcard)
5106 return 0;
5107 pattern_wildcard = pattern_left_label_end;
5108 break;
5109 }
5110 pattern_left_label_end++;
5111 }
5112
5113 /* If it's not trivial and there is no wildcard, it can't
5114 * match */
5115 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07005116 return 0;
5117
5118 /* Make sure all labels match except the leftmost */
5119 hostname_left_label_end = strchr(hostname, '.');
5120 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02005121 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07005122 return 0;
5123
5124 /* Make sure the leftmost label of the hostname is long enough
5125 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02005126 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07005127 return 0;
5128
5129 /* Finally compare the string on either side of the
5130 * wildcard */
5131 prefixlen = pattern_wildcard - pattern;
5132 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02005133 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
5134 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07005135 return 0;
5136
5137 return 1;
5138}
5139
5140static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
5141{
5142 SSL *ssl;
5143 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005144 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02005145 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02005146 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07005147
5148 int depth;
5149 X509 *cert;
5150 STACK_OF(GENERAL_NAME) *alt_names;
5151 int i;
5152 X509_NAME *cert_subject;
5153 char *str;
5154
5155 if (ok == 0)
5156 return ok;
5157
5158 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02005159 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02005160 ssl_ctx = __conn_get_ssl_sock_ctx(conn);
Evan Broderbe554312013-06-27 00:05:25 -07005161
Willy Tarreauad92a9a2017-07-28 11:38:41 +02005162 /* We're checking if the provided hostnames match the desired one. The
5163 * desired hostname comes from the SNI we presented if any, or if not
5164 * provided then it may have been explicitly stated using a "verifyhost"
5165 * directive. If neither is set, we don't care about the name so the
5166 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02005167 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005168 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02005169 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02005170 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02005171 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02005172 if (!servername)
5173 return ok;
5174 }
Evan Broderbe554312013-06-27 00:05:25 -07005175
5176 /* We only need to verify the CN on the actual server cert,
5177 * not the indirect CAs */
5178 depth = X509_STORE_CTX_get_error_depth(ctx);
5179 if (depth != 0)
5180 return ok;
5181
5182 /* At this point, the cert is *not* OK unless we can find a
5183 * hostname match */
5184 ok = 0;
5185
5186 cert = X509_STORE_CTX_get_current_cert(ctx);
5187 /* It seems like this might happen if verify peer isn't set */
5188 if (!cert)
5189 return ok;
5190
5191 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
5192 if (alt_names) {
5193 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
5194 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
5195 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005196#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02005197 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
5198#else
Evan Broderbe554312013-06-27 00:05:25 -07005199 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02005200#endif
Evan Broderbe554312013-06-27 00:05:25 -07005201 ok = ssl_sock_srv_hostcheck(str, servername);
5202 OPENSSL_free(str);
5203 }
5204 }
5205 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02005206 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07005207 }
5208
5209 cert_subject = X509_get_subject_name(cert);
5210 i = -1;
5211 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
5212 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005213 ASN1_STRING *value;
5214 value = X509_NAME_ENTRY_get_data(entry);
5215 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07005216 ok = ssl_sock_srv_hostcheck(str, servername);
5217 OPENSSL_free(str);
5218 }
5219 }
5220
Willy Tarreau71d058c2017-07-26 20:09:56 +02005221 /* report the mismatch and indicate if SNI was used or not */
5222 if (!ok && !conn->err_code)
5223 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07005224 return ok;
5225}
5226
Emeric Brun94324a42012-10-11 14:00:19 +02005227/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01005228int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02005229{
5230 int cfgerr = 0;
William Lallemand2c776f12021-12-28 18:47:17 +01005231 SSL_CTX *ctx;
William Lallemand0adafb32022-12-13 18:17:44 +01005232 /* Automatic memory computations need to know we use SSL there
5233 * If this is an internal proxy, don't use it for the computation */
William Lallemand04007cb2022-12-14 10:34:36 +01005234 if (!(srv->proxy->cap & PR_CAP_INT))
William Lallemand0adafb32022-12-13 18:17:44 +01005235 global.ssl_used_backend = 1;
Willy Tarreaufce03112015-01-15 21:32:40 +01005236
5237 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02005238 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005239 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005240 ha_alert("out of memory.\n");
Emeric Brun821bb9b2017-06-15 16:37:39 +02005241 cfgerr++;
5242 return cfgerr;
5243 }
5244 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01005245 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02005246 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02005247
William Lallemand2c776f12021-12-28 18:47:17 +01005248 if (srv->ssl_ctx.client_crt) {
5249 const int create_if_none = srv->flags & SRV_F_DYNAMIC ? 0 : 1;
5250 char *err = NULL;
5251 int err_code = 0;
5252
5253 /* If there is a crt keyword there, the SSL_CTX will be created here. */
5254 err_code = ssl_sock_load_srv_cert(srv->ssl_ctx.client_crt, srv, create_if_none, &err);
5255 if (err_code != ERR_NONE) {
5256 if ((err_code & ERR_WARN) && !(err_code & ERR_ALERT))
5257 ha_warning("%s", err);
5258 else
5259 ha_alert("%s", err);
5260
5261 if (err_code & (ERR_FATAL|ERR_ABORT))
5262 cfgerr++;
5263 }
5264 ha_free(&err);
5265 }
5266
5267 ctx = srv->ssl_ctx.ctx;
5268
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005269 /* The context will be uninitialized if there wasn't any "cert" option
5270 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005271 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005272 ctx = SSL_CTX_new(SSLv23_client_method());
5273 if (!ctx) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005274 ha_alert("unable to allocate ssl context.\n");
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005275 cfgerr++;
5276 return cfgerr;
5277 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005278
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005279 srv->ssl_ctx.ctx = ctx;
5280 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005281
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005282 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 +01005283
5284 return cfgerr;
5285}
5286
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005287/* Initialize an SSL context that will be used on the backend side.
5288 * Returns an error count.
5289 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005290static int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005291{
5292 struct proxy *curproxy = srv->proxy;
5293 int cfgerr = 0;
5294 long options =
5295 SSL_OP_ALL | /* all known workarounds for bugs */
5296 SSL_OP_NO_SSLv2 |
5297 SSL_OP_NO_COMPRESSION;
5298 long mode =
5299 SSL_MODE_ENABLE_PARTIAL_WRITE |
5300 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
5301 SSL_MODE_RELEASE_BUFFERS |
5302 SSL_MODE_SMALL_BUFFERS;
5303 int verify = SSL_VERIFY_NONE;
5304 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
5305 int i, min, max, hole;
5306 int flags = MC_SSL_O_ALL;
5307
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005308 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005309 ha_warning("no-sslv3/no-tlsv1x are ignored for this server. "
5310 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n");
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005311 else
5312 flags = conf_ssl_methods->flags;
5313
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005314 /* Real min and max should be determinate with configuration and openssl's capabilities */
5315 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005316 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005317 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005318 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005319
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005320 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005321 min = max = CONF_TLSV_NONE;
5322 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005323 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005324 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005325 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005326 if (min) {
5327 if (hole) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005328 ha_warning("%s '%s': SSL/TLS versions range not contiguous for server '%s'. "
Christopher Faulet767a84b2017-11-24 16:50:31 +01005329 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
5330 proxy_type_str(curproxy), curproxy->id, srv->id,
5331 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005332 hole = 0;
5333 }
5334 max = i;
5335 }
5336 else {
5337 min = max = i;
5338 }
5339 }
5340 else {
5341 if (min)
5342 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005343 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005344 if (!min) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005345 ha_alert("%s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01005346 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005347 cfgerr += 1;
5348 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005349
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005350#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005351 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08005352 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005353 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005354 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005355 else
5356 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
5357 if (flags & methodVersions[i].flag)
5358 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005359#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005360 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005361 methodVersions[min].ctx_set_version(ctx, SET_MIN);
5362 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005363#endif
5364
5365 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
5366 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005367 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005368
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005369#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005370 if (global_ssl.async)
5371 mode |= SSL_MODE_ASYNC;
5372#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005373 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005374
Emeric Brun850efd52014-01-29 12:24:34 +01005375 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
5376 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01005377 switch (srv->ssl_ctx.verify) {
5378 case SSL_SOCK_VERIFY_NONE:
5379 verify = SSL_VERIFY_NONE;
5380 break;
5381 case SSL_SOCK_VERIFY_REQUIRED:
5382 verify = SSL_VERIFY_PEER;
5383 break;
5384 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005385 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02005386 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01005387 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02005388 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02005389 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005390 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005391 ha_alert("unable to set CA file '%s'.\n",
5392 srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005393 cfgerr++;
5394 }
5395 }
Emeric Brun850efd52014-01-29 12:24:34 +01005396 else {
5397 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005398 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 +01005399 else
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005400 ha_alert("verify is enabled but no CA file specified.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01005401 cfgerr++;
5402 }
Emeric Brunef42d922012-10-11 16:11:36 +02005403#ifdef X509_V_FLAG_CRL_CHECK
5404 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005405 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02005406
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01005407 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005408 ha_alert("unable to configure CRL file '%s'.\n",
5409 srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005410 cfgerr++;
5411 }
5412 else {
5413 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5414 }
5415 }
5416#endif
5417 }
5418
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005419 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5420 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02005421 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005422 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005423 ha_alert("unable to set SSL cipher list to '%s'.\n",
5424 srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02005425 cfgerr++;
5426 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005427
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05005428#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005429 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005430 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005431 ha_alert("unable to set TLS 1.3 cipher suites to '%s'.\n",
5432 srv->ssl_ctx.ciphersuites);
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005433 cfgerr++;
5434 }
5435#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01005436#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
5437 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005438 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01005439#endif
5440#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5441 if (srv->ssl_ctx.alpn_str)
5442 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
5443#endif
5444
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005445
5446 return cfgerr;
5447}
5448
5449/*
5450 * Prepare the frontend's SSL_CTX based on the server line configuration.
5451 * Since the CA file loading is made depending on the verify option of the
5452 * server line, the link between the SSL_CTX and the CA file tree entry is
5453 * made here.
5454 * If we want to create a link between the CA file entry and the corresponding
5455 * ckch instance (for CA file hot update), it needs to be done after
5456 * ssl_sock_prepare_srv_ssl_ctx.
5457 * Returns an error count.
5458 */
5459int ssl_sock_prep_srv_ctx_and_inst(const struct server *srv, SSL_CTX *ctx,
5460 struct ckch_inst *ckch_inst)
5461{
5462 int cfgerr = 0;
5463
5464 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, ctx);
5465 if (!cfgerr && ckch_inst)
5466 ckch_inst_add_cafile_link(ckch_inst, NULL, NULL, srv);
Emeric Brun94324a42012-10-11 14:00:19 +02005467
5468 return cfgerr;
5469}
5470
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005471
Frédéric Lécailleec216522020-11-23 14:33:30 +01005472/*
5473 * Create an initial CTX used to start the SSL connections.
5474 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
5475 * Returns 0 if succeeded, or something >0 if not.
5476 */
5477#ifdef USE_QUIC
5478static int ssl_initial_ctx(struct bind_conf *bind_conf)
5479{
5480 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
5481 return ssl_quic_initial_ctx(bind_conf);
5482 else
5483 return ssl_sock_initial_ctx(bind_conf);
5484}
5485#else
5486static int ssl_initial_ctx(struct bind_conf *bind_conf)
5487{
5488 return ssl_sock_initial_ctx(bind_conf);
5489}
5490#endif
5491
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005492/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005493 * be NULL, in which case nothing is done. Returns the number of errors
5494 * encountered.
5495 */
Willy Tarreau03209342016-12-22 17:08:28 +01005496int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005497{
5498 struct ebmb_node *node;
5499 struct sni_ctx *sni;
5500 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01005501 int errcode = 0;
5502 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02005503
Willy Tarreaufce03112015-01-15 21:32:40 +01005504 /* Automatic memory computations need to know we use SSL there */
5505 global.ssl_used_frontend = 1;
5506
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005507 /* Create initial_ctx used to start the ssl connection before do switchctx */
5508 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01005509 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005510 /* It should not be necessary to call this function, but it's
5511 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01005512 to initial_ctx in ssl_initial_ctx. */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005513 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, NULL, bind_conf->initial_ctx, NULL, &errmsg);
5514 }
5515 if (bind_conf->default_ctx) {
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005516 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 +01005517 }
Emeric Brun0bed9942014-10-30 19:25:24 +01005518
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005519 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005520 while (node) {
5521 sni = ebmb_entry(node, struct sni_ctx, name);
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005522 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005523 /* only initialize the CTX on its first occurrence and
5524 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005525 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
5526 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005527 node = ebmb_next(node);
5528 }
5529
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005530 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005531 while (node) {
5532 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01005533 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005534 /* only initialize the CTX on its first occurrence and
5535 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005536 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005537 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005538 node = ebmb_next(node);
5539 }
William Lallemand8b453912019-11-21 15:48:10 +01005540
5541 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005542 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005543 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005544 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005545 err++;
5546 }
5547
5548 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005549 return err;
5550}
5551
Willy Tarreau55d37912016-12-21 23:38:39 +01005552/* Prepares all the contexts for a bind_conf and allocates the shared SSL
5553 * context if needed. Returns < 0 on error, 0 on success. The warnings and
5554 * alerts are directly emitted since the rest of the stack does it below.
5555 */
5556int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
5557{
5558 struct proxy *px = bind_conf->frontend;
5559 int alloc_ctx;
5560 int err;
5561
Willy Tarreau11ba4042022-05-20 15:56:32 +02005562 if (!(bind_conf->options & BC_O_USE_SSL)) {
Willy Tarreau55d37912016-12-21 23:38:39 +01005563 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005564 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
5565 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01005566 }
5567 return 0;
5568 }
5569 if (!bind_conf->default_ctx) {
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005570 if (bind_conf->strict_sni && !(bind_conf->options & BC_O_GENERATE_CERTS)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005571 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5572 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005573 }
5574 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005575 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5576 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005577 return -1;
5578 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005579 }
William Lallemandc61c0b32017-12-04 18:46:39 +01005580 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005581 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02005582 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
Willy Tarreau91358592021-06-15 08:08:04 +02005583 sizeof(*sh_ssl_sess_tree), (global.nbthread > 1));
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02005584 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005585 if (alloc_ctx == SHCTX_E_INIT_LOCK)
5586 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");
5587 else
5588 ha_alert("Unable to allocate SSL session cache.\n");
5589 return -1;
5590 }
5591 /* free block callback */
5592 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5593 /* init the root tree within the extra space */
5594 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5595 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01005596 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005597 err = 0;
5598 /* initialize all certificate contexts */
5599 err += ssl_sock_prepare_all_ctx(bind_conf);
5600
5601 /* initialize CA variables if the certificates generation is enabled */
5602 err += ssl_sock_load_ca(bind_conf);
5603
5604 return -err;
5605}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005606
William Lallemand231610a2021-12-30 11:25:43 +01005607/* release ssl context allocated for servers. Most of the field free here
5608 * must also be allocated in srv_ssl_settings_cpy() */
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005609void ssl_sock_free_srv_ctx(struct server *srv)
5610{
Olivier Houchardc7566002018-11-20 23:33:50 +01005611#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
William Lallemand231610a2021-12-30 11:25:43 +01005612 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005613#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005614#ifdef OPENSSL_NPN_NEGOTIATED
William Lallemand231610a2021-12-30 11:25:43 +01005615 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005616#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005617 if (srv->ssl_ctx.reused_sess) {
5618 int i;
5619
William Lallemande18d4e82021-11-17 02:59:21 +01005620 for (i = 0; i < global.nbthread; i++) {
Willy Tarreaue709e822021-02-26 21:06:32 +01005621 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
William Lallemande18d4e82021-11-17 02:59:21 +01005622 ha_free(&srv->ssl_ctx.reused_sess[i].sni);
5623 }
Willy Tarreaue709e822021-02-26 21:06:32 +01005624 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005625 }
5626
Willy Tarreaue709e822021-02-26 21:06:32 +01005627 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005628 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005629 srv->ssl_ctx.ctx = NULL;
5630 }
William Lallemand231610a2021-12-30 11:25:43 +01005631
5632 ha_free(&srv->ssl_ctx.ca_file);
5633 ha_free(&srv->ssl_ctx.crl_file);
5634 ha_free(&srv->ssl_ctx.client_crt);
5635 ha_free(&srv->ssl_ctx.verify_host);
5636#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5637 ha_free(&srv->sni_expr);
William Lallemand43c2ce42022-03-16 17:48:19 +01005638 release_sample_expr(srv->ssl_ctx.sni);
5639 srv->ssl_ctx.sni = NULL;
William Lallemand231610a2021-12-30 11:25:43 +01005640#endif
5641 ha_free(&srv->ssl_ctx.ciphers);
5642#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
5643 ha_free(&srv->ssl_ctx.ciphersuites);
5644#endif
William Lallemande69563f2021-12-30 14:45:19 +01005645 /* If there is a certificate we must unlink the ckch instance */
5646 ckch_inst_free(srv->ssl_ctx.inst);
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005647}
5648
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005649/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005650 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5651 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005652void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005653{
5654 struct ebmb_node *node, *back;
5655 struct sni_ctx *sni;
5656
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005657 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005658 while (node) {
5659 sni = ebmb_entry(node, struct sni_ctx, name);
5660 back = ebmb_next(node);
5661 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005662 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005663 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005664 free(sni);
5665 node = back;
5666 }
5667
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005668 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005669 while (node) {
5670 sni = ebmb_entry(node, struct sni_ctx, name);
5671 back = ebmb_next(node);
5672 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005673 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005674 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005675 free(sni);
5676 node = back;
5677 }
William Lallemandb2408692020-06-24 09:54:29 +02005678
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005679 SSL_CTX_free(bind_conf->initial_ctx);
5680 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005681 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005682 bind_conf->default_ctx = NULL;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005683 bind_conf->default_inst = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005684 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005685}
William Lallemandb2408692020-06-24 09:54:29 +02005686
5687
5688void ssl_sock_deinit()
5689{
5690 crtlist_deinit(); /* must be free'd before the ckchs */
5691 ckch_deinit();
5692}
5693REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005694
Willy Tarreau795cdab2016-12-22 17:30:54 +01005695/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5696void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5697{
5698 ssl_sock_free_ca(bind_conf);
5699 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005700 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005701 free(bind_conf->ca_sign_file);
5702 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005703 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005704 free(bind_conf->keys_ref->filename);
5705 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005706 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005707 free(bind_conf->keys_ref);
5708 }
5709 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005710 bind_conf->ca_sign_pass = NULL;
5711 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005712}
5713
Christopher Faulet31af49d2015-06-09 17:29:50 +02005714/* Load CA cert file and private key used to generate certificates */
5715int
Willy Tarreau03209342016-12-22 17:08:28 +01005716ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005717{
Willy Tarreau03209342016-12-22 17:08:28 +01005718 struct proxy *px = bind_conf->frontend;
William Lallemand52ddd992022-11-22 11:51:53 +01005719 struct ckch_data *data = NULL;
Shimi Gersner5846c492020-08-23 13:58:12 +03005720 int ret = 0;
5721 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005722
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005723 if (!(bind_conf->options & BC_O_GENERATE_CERTS))
Shimi Gersner5846c492020-08-23 13:58:12 +03005724 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005725
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005726#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005727 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005728 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005729 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005730 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005731 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005732#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005733
Christopher Faulet31af49d2015-06-09 17:29:50 +02005734 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005735 ha_alert("Proxy '%s': cannot enable certificate generation, "
5736 "no CA certificate File configured at [%s:%d].\n",
5737 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005738 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005739 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005740
Shimi Gersner5846c492020-08-23 13:58:12 +03005741 /* Allocate cert structure */
William Lallemand52ddd992022-11-22 11:51:53 +01005742 data = calloc(1, sizeof(*data));
5743 if (!data) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005744 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5745 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5746 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005747 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005748
5749 /* Try to parse file */
William Lallemand52ddd992022-11-22 11:51:53 +01005750 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, data, &err)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005751 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5752 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005753 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005754 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005755 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005756
5757 /* Fail if missing cert or pkey */
William Lallemand52ddd992022-11-22 11:51:53 +01005758 if ((!data->cert) || (!data->key)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005759 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5760 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5761 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005762 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005763
Shimi Gersner5846c492020-08-23 13:58:12 +03005764 /* Final assignment to bind */
William Lallemand52ddd992022-11-22 11:51:53 +01005765 bind_conf->ca_sign_ckch = data;
Shimi Gersner5846c492020-08-23 13:58:12 +03005766 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005767
Shimi Gersner5846c492020-08-23 13:58:12 +03005768 failed:
William Lallemand52ddd992022-11-22 11:51:53 +01005769 if (data) {
5770 ssl_sock_free_cert_key_and_chain_contents(data);
5771 free(data);
Shimi Gersner5846c492020-08-23 13:58:12 +03005772 }
5773
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005774 bind_conf->options &= ~BC_O_GENERATE_CERTS;
Shimi Gersner5846c492020-08-23 13:58:12 +03005775 ret++;
5776 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005777}
5778
5779/* Release CA cert and private key used to generate certificated */
5780void
5781ssl_sock_free_ca(struct bind_conf *bind_conf)
5782{
Shimi Gersner5846c492020-08-23 13:58:12 +03005783 if (bind_conf->ca_sign_ckch) {
5784 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005785 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005786 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005787}
5788
Emeric Brun46591952012-05-18 15:47:34 +02005789/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005790 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5791 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5792 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5793 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005794 * 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 +01005795 * as parameters to this function.
5796 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5797 * CO_ER_SSL_NO_MEM.
5798 */
5799int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5800 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5801{
5802 int retry = 1;
5803
5804 retry:
5805 /* Alloc a new SSL session. */
5806 *ssl = SSL_new(ssl_ctx);
5807 if (!*ssl) {
5808 if (!retry--)
5809 goto err;
5810
5811 pool_gc(NULL);
5812 goto retry;
5813 }
5814
5815 *bio = BIO_new(bio_meth);
5816 if (!*bio) {
5817 SSL_free(*ssl);
5818 *ssl = NULL;
5819 if (!retry--)
5820 goto err;
5821
5822 pool_gc(NULL);
5823 goto retry;
5824 }
5825
5826 BIO_set_data(*bio, ctx);
5827 SSL_set_bio(*ssl, *bio, *bio);
5828
5829 /* set connection pointer. */
5830 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5831 SSL_free(*ssl);
5832 *ssl = NULL;
5833 if (!retry--)
5834 goto err;
5835
5836 pool_gc(NULL);
5837 goto retry;
5838 }
5839
5840 return 0;
5841
5842 err:
5843 conn->err_code = CO_ER_SSL_NO_MEM;
5844 return -1;
5845}
5846
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005847/* This function is called when all the XPRT have been initialized. We can
5848 * now attempt to start the SSL handshake.
5849 */
5850static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5851{
5852 struct ssl_sock_ctx *ctx = xprt_ctx;
5853
5854 if (ctx->xprt->start) {
5855 int ret;
5856
5857 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5858 if (ret < 0)
5859 return ret;
5860 }
5861 tasklet_wakeup(ctx->wait_event.tasklet);
5862
5863 return 0;
5864}
5865
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005866/*
Emeric Brun46591952012-05-18 15:47:34 +02005867 * This function is called if SSL * context is not yet allocated. The function
5868 * is designed to be called before any other data-layer operation and sets the
5869 * handshake flag on the connection. It is safe to call it multiple times.
5870 * It returns 0 on success and -1 in error case.
5871 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005872static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005873{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005874 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005875 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005876 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005877 return 0;
5878
Olivier Houchard66ab4982019-02-26 18:37:15 +01005879 ctx = pool_alloc(ssl_sock_ctx_pool);
5880 if (!ctx) {
5881 conn->err_code = CO_ER_SSL_NO_MEM;
5882 return -1;
5883 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005884 ctx->wait_event.tasklet = tasklet_new();
5885 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005886 conn->err_code = CO_ER_SSL_NO_MEM;
5887 pool_free(ssl_sock_ctx_pool, ctx);
5888 return -1;
5889 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005890 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5891 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005892 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005893 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005894 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005895 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005896 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005897 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005898 ctx->xprt_st = 0;
5899 ctx->xprt_ctx = NULL;
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005900 ctx->error_code = 0;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005901
5902 /* Only work with sockets for now, this should be adapted when we'll
5903 * add QUIC support.
5904 */
5905 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005906 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005907 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5908 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005909 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005910
Willy Tarreau82531f62021-10-06 12:15:18 +02005911 if (global.maxsslconn && global.sslconns >= global.maxsslconn) {
Willy Tarreau20879a02012-12-03 16:32:10 +01005912 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005913 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005914 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005915
Emeric Brun46591952012-05-18 15:47:34 +02005916 /* If it is in client mode initiate SSL session
5917 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005918 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005919 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5920 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005921 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005922
Olivier Houchard66ab4982019-02-26 18:37:15 +01005923 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005924 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005925 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5926 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5927 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 +01005928 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005929 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005930 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005931 } else if (sess) {
5932 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005933 }
5934 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005935 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005936
Emeric Brun46591952012-05-18 15:47:34 +02005937 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005938 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005939
Willy Tarreau82531f62021-10-06 12:15:18 +02005940 _HA_ATOMIC_INC(&global.sslconns);
5941 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005942 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005943 return 0;
5944 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005945 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005946 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005947
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005948 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5949 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005950 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005951
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005952#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005953 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005954 b_alloc(&ctx->early_buf);
5955 SSL_set_max_early_data(ctx->ssl,
5956 /* Only allow early data if we managed to allocate
5957 * a buffer.
5958 */
5959 (!b_is_null(&ctx->early_buf)) ?
5960 global.tune.bufsize - global.tune.maxrewrite : 0);
5961 }
5962#endif
5963
Olivier Houchard66ab4982019-02-26 18:37:15 +01005964 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005965
Emeric Brun46591952012-05-18 15:47:34 +02005966 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005967 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005968#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005969 if (bc->ssl_conf.early_data)
5970 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005971#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005972
Willy Tarreau82531f62021-10-06 12:15:18 +02005973 _HA_ATOMIC_INC(&global.sslconns);
5974 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005975 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005976 return 0;
5977 }
5978 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005979 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005980err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005981 if (ctx && ctx->wait_event.tasklet)
5982 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005983 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005984 return -1;
5985}
5986
5987
5988/* This is the callback which is used when an SSL handshake is pending. It
5989 * updates the FD status if it wants some polling before being called again.
5990 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5991 * otherwise it returns non-zero and removes itself from the connection's
5992 * flags (the bit is provided in <flag> by the caller).
5993 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005994static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005995{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005996 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Emeric Brun46591952012-05-18 15:47:34 +02005997 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005998 struct ssl_counters *counters = NULL;
5999 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006000 struct listener *li;
6001 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01006002 socklen_t lskerr;
6003 int skerr;
6004
Emeric Brun46591952012-05-18 15:47:34 +02006005
Willy Tarreau3c728722014-01-23 13:50:42 +01006006 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02006007 return 0;
6008
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006009 /* get counters */
6010 switch (obj_type(conn->target)) {
6011 case OBJ_TYPE_LISTENER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02006012 li = __objt_listener(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006013 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
6014 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
6015 &ssl_stats_module);
6016 break;
6017
6018 case OBJ_TYPE_SERVER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02006019 srv = __objt_server(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006020 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
6021 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
6022 &ssl_stats_module);
6023 break;
6024
6025 default:
6026 break;
6027 }
6028
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006029 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006030 goto out_error;
6031
Willy Tarreau06300382021-02-02 15:42:25 +01006032 /* don't start calculating a handshake on a dead connection */
6033 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
6034 goto out_error;
6035
6036 /* FIXME/WT: for now we don't have a clear way to inspect the connection
6037 * status from the lower layers, so let's check the FD directly. Ideally
6038 * the xprt layers should provide some status indicating their knowledge
6039 * of shutdowns or error.
6040 */
Willy Tarreau07ecfc52022-04-11 18:07:03 +02006041 BUG_ON(conn->flags & CO_FL_FDLESS);
6042
Willy Tarreau06300382021-02-02 15:42:25 +01006043 skerr = 0;
6044 lskerr = sizeof(skerr);
6045 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
6046 skerr != 0)
6047 goto out_error;
6048
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006049#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006050 /*
6051 * Check if we have early data. If we do, we have to read them
6052 * before SSL_do_handshake() is called, And there's no way to
6053 * detect early data, except to try to read them
6054 */
6055 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01006056 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006057
Olivier Houchard54907bb2019-12-19 15:02:39 +01006058 while (1) {
6059 ret = SSL_read_early_data(ctx->ssl,
6060 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
6061 &read_data);
6062 if (ret == SSL_READ_EARLY_DATA_ERROR)
6063 goto check_error;
6064 if (read_data > 0) {
6065 conn->flags |= CO_FL_EARLY_DATA;
6066 b_add(&ctx->early_buf, read_data);
6067 }
6068 if (ret == SSL_READ_EARLY_DATA_FINISH) {
6069 conn->flags &= ~CO_FL_EARLY_SSL_HS;
6070 if (!b_data(&ctx->early_buf))
6071 b_free(&ctx->early_buf);
6072 break;
6073 }
6074 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006075 }
6076#endif
Emeric Brun674b7432012-11-08 19:21:55 +01006077 /* If we use SSL_do_handshake to process a reneg initiated by
6078 * the remote peer, it sometimes returns SSL_ERROR_SSL.
6079 * Usually SSL_write and SSL_read are used and process implicitly
6080 * the reneg handshake.
6081 * Here we use SSL_peek as a workaround for reneg.
6082 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006083 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01006084 char c;
6085
Olivier Houchard66ab4982019-02-26 18:37:15 +01006086 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01006087 if (ret <= 0) {
6088 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006089 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006090
Emeric Brun674b7432012-11-08 19:21:55 +01006091 if (ret == SSL_ERROR_WANT_WRITE) {
6092 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02006093 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02006094 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01006095 return 0;
6096 }
6097 else if (ret == SSL_ERROR_WANT_READ) {
6098 /* handshake may have been completed but we have
6099 * no more data to read.
6100 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006101 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01006102 ret = 1;
6103 goto reneg_ok;
6104 }
6105 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02006106 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02006107 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01006108 return 0;
6109 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006110#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006111 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006112 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006113 return 0;
6114 }
6115#endif
Emeric Brun674b7432012-11-08 19:21:55 +01006116 else if (ret == SSL_ERROR_SYSCALL) {
6117 /* if errno is null, then connection was successfully established */
6118 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
6119 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01006120 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02006121#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
6122 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006123 conn->err_code = CO_ER_SSL_HANDSHAKE;
6124#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006125 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02006126#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02006127 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006128 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006129 empty_handshake = state == TLS_ST_BEFORE;
6130#else
Lukas Tribus49799162019-07-08 14:29:15 +02006131 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
6132 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006133#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006134 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02006135 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006136 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006137 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6138 else
6139 conn->err_code = CO_ER_SSL_EMPTY;
6140 }
6141 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006142 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006143 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6144 else
6145 conn->err_code = CO_ER_SSL_ABORT;
6146 }
6147 }
6148 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006149 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006150 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01006151 else
Emeric Brun29f037d2014-04-25 19:05:36 +02006152 conn->err_code = CO_ER_SSL_HANDSHAKE;
6153 }
Lukas Tribus49799162019-07-08 14:29:15 +02006154#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01006155 }
Emeric Brun674b7432012-11-08 19:21:55 +01006156 goto out_error;
6157 }
6158 else {
6159 /* Fail on all other handshake errors */
6160 /* Note: OpenSSL may leave unread bytes in the socket's
6161 * buffer, causing an RST to be emitted upon close() on
6162 * TCP sockets. We first try to drain possibly pending
6163 * data to avoid this as much as possible.
6164 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01006165 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01006166 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006167 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02006168 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01006169 goto out_error;
6170 }
6171 }
6172 /* read some data: consider handshake completed */
6173 goto reneg_ok;
6174 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006175 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006176check_error:
Emeric Brun46591952012-05-18 15:47:34 +02006177 if (ret != 1) {
6178 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006179 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006180
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02006181 if (!ctx->error_code)
6182 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton7c6898e2021-07-29 09:45:51 +02006183
Emeric Brun46591952012-05-18 15:47:34 +02006184 if (ret == SSL_ERROR_WANT_WRITE) {
6185 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02006186 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02006187 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02006188 return 0;
6189 }
6190 else if (ret == SSL_ERROR_WANT_READ) {
6191 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02006192 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02006193 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6194 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02006195 return 0;
6196 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006197#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006198 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006199 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006200 return 0;
6201 }
6202#endif
Willy Tarreau89230192012-09-28 20:22:13 +02006203 else if (ret == SSL_ERROR_SYSCALL) {
6204 /* if errno is null, then connection was successfully established */
6205 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
6206 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006207 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02006208#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
6209 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006210 conn->err_code = CO_ER_SSL_HANDSHAKE;
6211#else
6212 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02006213#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02006214 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006215 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006216 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006217#else
Lukas Tribus49799162019-07-08 14:29:15 +02006218 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
6219 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006220#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006221 if (empty_handshake) {
6222 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006223 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006224 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6225 else
6226 conn->err_code = CO_ER_SSL_EMPTY;
6227 }
6228 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006229 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006230 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6231 else
6232 conn->err_code = CO_ER_SSL_ABORT;
6233 }
Emeric Brun29f037d2014-04-25 19:05:36 +02006234 }
6235 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006236 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006237 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6238 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006239 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02006240 }
Lukas Tribus49799162019-07-08 14:29:15 +02006241#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02006242 }
Willy Tarreau89230192012-09-28 20:22:13 +02006243 goto out_error;
6244 }
Emeric Brun46591952012-05-18 15:47:34 +02006245 else {
6246 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02006247 /* Note: OpenSSL may leave unread bytes in the socket's
6248 * buffer, causing an RST to be emitted upon close() on
6249 * TCP sockets. We first try to drain possibly pending
6250 * data to avoid this as much as possible.
6251 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01006252 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01006253 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006254 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02006255 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006256 goto out_error;
6257 }
6258 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006259#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01006260 else {
6261 /*
6262 * If the server refused the early data, we have to send a
6263 * 425 to the client, as we no longer have the data to sent
6264 * them again.
6265 */
6266 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006267 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006268 conn->err_code = CO_ER_SSL_EARLY_FAILED;
6269 goto out_error;
6270 }
6271 }
6272 }
6273#endif
6274
Emeric Brun46591952012-05-18 15:47:34 +02006275
Emeric Brun674b7432012-11-08 19:21:55 +01006276reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00006277
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006278#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006279 /* ASYNC engine API doesn't support moving read/write
6280 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006281 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00006282 */
6283 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006284 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006285#endif
Emeric Brun46591952012-05-18 15:47:34 +02006286 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006287 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02006288 if (objt_server(conn->target)) {
6289 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
6290 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
6291 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02006292 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02006293 else {
6294 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
6295 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
6296 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
6297 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006298
Willy Tarreau42995282020-11-06 13:19:18 +01006299 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006300 HA_ATOMIC_INC(&counters->sess);
6301 HA_ATOMIC_INC(&counters_px->sess);
Willy Tarreau42995282020-11-06 13:19:18 +01006302 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006303 }
Willy Tarreau42995282020-11-06 13:19:18 +01006304 else if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006305 HA_ATOMIC_INC(&counters->reused_sess);
6306 HA_ATOMIC_INC(&counters_px->reused_sess);
Emeric Brun46591952012-05-18 15:47:34 +02006307 }
6308
6309 /* The connection is now established at both layers, it's time to leave */
6310 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
6311 return 1;
6312
6313 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006314 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006315 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006316 ERR_clear_error();
6317
Emeric Brun9fa89732012-10-04 17:09:56 +02006318 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01006319 if (objt_server(conn->target)) {
6320 struct server *s = __objt_server(conn->target);
6321 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
6322 * one cache per thread, it only prevents to flush it from the CLI in
6323 * another thread */
6324
6325 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01006326 if (s->ssl_ctx.reused_sess[tid].ptr)
6327 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01006328 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02006329 }
6330
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006331 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006332 HA_ATOMIC_INC(&counters->failed_handshake);
6333 HA_ATOMIC_INC(&counters_px->failed_handshake);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006334 }
6335
Emeric Brun46591952012-05-18 15:47:34 +02006336 /* Fail on all other handshake errors */
6337 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01006338 if (!conn->err_code)
6339 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006340 return 0;
6341}
6342
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006343/* Called from the upper layer, to subscribe <es> to events <event_type>. The
6344 * event subscriber <es> is not allowed to change from a previous call as long
6345 * as at least one event is still subscribed. The <event_type> must only be a
6346 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
6347 * unless the transport layer was already released.
6348 */
6349static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006350{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006351 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006352
Olivier Houchard0ff28652019-06-24 18:57:39 +02006353 if (!ctx)
6354 return -1;
6355
Willy Tarreau113d52b2020-01-10 09:20:26 +01006356 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006357 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006358
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006359 ctx->subs = es;
6360 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006361
6362 /* we may have to subscribe to lower layers for new events */
6363 event_type &= ~ctx->wait_event.events;
6364 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
6365 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006366 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006367}
6368
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006369/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
6370 * The <es> pointer is not allowed to differ from the one passed to the
6371 * subscribe() call. It always returns zero.
6372 */
6373static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006374{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006375 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006376
Willy Tarreau113d52b2020-01-10 09:20:26 +01006377 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006378 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006379
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006380 es->events &= ~event_type;
6381 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01006382 ctx->subs = NULL;
6383
6384 /* If we subscribed, and we're not doing the handshake,
6385 * then we subscribed because the upper layer asked for it,
6386 * as the upper layer is no longer interested, we can
6387 * unsubscribe too.
6388 */
6389 event_type &= ctx->wait_event.events;
6390 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
6391 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006392
6393 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006394}
6395
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006396/* The connection has been taken over, so destroy the old tasklet and create
6397 * a new one. The original thread ID must be passed into orig_tid
6398 * It should be called with the takeover lock for the old thread held.
6399 * Returns 0 on success, and -1 on failure
6400 */
6401static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
6402{
6403 struct ssl_sock_ctx *ctx = xprt_ctx;
6404 struct tasklet *tl = tasklet_new();
6405
6406 if (!tl)
6407 return -1;
6408
6409 ctx->wait_event.tasklet->context = NULL;
6410 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
6411 ctx->wait_event.tasklet = tl;
6412 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
6413 ctx->wait_event.tasklet->context = ctx;
6414 return 0;
6415}
6416
Willy Tarreau41491682021-03-02 17:29:56 +01006417/* notify the next xprt that the connection is about to become idle and that it
6418 * may be stolen at any time after the function returns and that any tasklet in
6419 * the chain must be careful before dereferencing its context.
6420 */
6421static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
6422{
6423 struct ssl_sock_ctx *ctx = xprt_ctx;
6424
6425 if (!ctx || !ctx->wait_event.tasklet)
6426 return;
6427
6428 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6429 if (ctx->xprt)
6430 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
6431}
6432
6433/* notify the next xprt that the connection is not idle anymore and that it may
6434 * not be stolen before the next xprt_set_idle().
6435 */
6436static void ssl_set_used(struct connection *conn, void *xprt_ctx)
6437{
6438 struct ssl_sock_ctx *ctx = xprt_ctx;
6439
6440 if (!ctx || !ctx->wait_event.tasklet)
6441 return;
6442
6443 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6444 if (ctx->xprt)
6445 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
6446}
6447
Olivier Houchard2e055482019-05-27 19:50:12 +02006448/* Use the provided XPRT as an underlying XPRT, and provide the old one.
6449 * Returns 0 on success, and non-zero on failure.
6450 */
6451static 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)
6452{
6453 struct ssl_sock_ctx *ctx = xprt_ctx;
6454
6455 if (oldxprt_ops != NULL)
6456 *oldxprt_ops = ctx->xprt;
6457 if (oldxprt_ctx != NULL)
6458 *oldxprt_ctx = ctx->xprt_ctx;
6459 ctx->xprt = toadd_ops;
6460 ctx->xprt_ctx = toadd_ctx;
6461 return 0;
6462}
6463
Olivier Houchard5149b592019-05-23 17:47:36 +02006464/* Remove the specified xprt. If if it our underlying XPRT, remove it and
6465 * return 0, otherwise just call the remove_xprt method from the underlying
6466 * XPRT.
6467 */
6468static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
6469{
6470 struct ssl_sock_ctx *ctx = xprt_ctx;
6471
6472 if (ctx->xprt_ctx == toremove_ctx) {
6473 ctx->xprt_ctx = newctx;
6474 ctx->xprt = newops;
6475 return 0;
6476 }
6477 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
6478}
6479
Willy Tarreau144f84a2021-03-02 16:09:26 +01006480struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02006481{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006482 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006483 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006484 struct connection *conn;
6485 int conn_in_list;
6486 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006487
Willy Tarreau41491682021-03-02 17:29:56 +01006488 if (state & TASK_F_USR1) {
6489 /* the tasklet was idling on an idle connection, it might have
6490 * been stolen, let's be careful!
6491 */
6492 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6493 if (tl->context == NULL) {
6494 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6495 tasklet_free(tl);
6496 return NULL;
6497 }
6498 conn = ctx->conn;
6499 conn_in_list = conn->flags & CO_FL_LIST_MASK;
6500 if (conn_in_list)
6501 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006502 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01006503 } else {
6504 conn = ctx->conn;
6505 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006506 }
Willy Tarreau41491682021-03-02 17:29:56 +01006507
Olivier Houchardea8dd942019-05-20 14:02:16 +02006508 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01006509 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006510 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006511 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
6512 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01006513 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006514 }
6515 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006516 /* If we had an error, or the handshake is done and I/O is available,
6517 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01006518 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02006519 * we can't be sure conn_fd_handler() will be called again.
6520 */
6521 if ((ctx->conn->flags & CO_FL_ERROR) ||
6522 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006523 int woke = 0;
6524
6525 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006526 if (ctx->subs) {
6527 tasklet_wakeup(ctx->subs->tasklet);
6528 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006529 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006530 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006531 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006532
Olivier Houchardea8dd942019-05-20 14:02:16 +02006533 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01006534 * upper layers know. If we have no mux, create it,
6535 * and once we have a mux, call its wake method if we didn't
6536 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02006537 */
6538 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01006539 if (!ctx->conn->mux)
6540 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006541 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006542 ret = ctx->conn->mux->wake(ctx->conn);
6543 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006544 }
6545 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006546#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006547 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006548 else if (b_data(&ctx->early_buf) && ctx->subs &&
6549 ctx->subs->events & SUB_RETRY_RECV) {
6550 tasklet_wakeup(ctx->subs->tasklet);
6551 ctx->subs->events &= ~SUB_RETRY_RECV;
6552 if (!ctx->subs->events)
6553 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01006554 }
6555#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006556leave:
6557 if (!ret && conn_in_list) {
6558 struct server *srv = objt_server(conn->target);
6559
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006560 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006561 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau85223482022-09-29 20:32:43 +02006562 eb64_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006563 else
Willy Tarreau85223482022-09-29 20:32:43 +02006564 eb64_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006565 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006566 }
Willy Tarreau74163142021-03-13 11:30:19 +01006567 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006568}
6569
Emeric Brun46591952012-05-18 15:47:34 +02006570/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01006571 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02006572 * buffer wraps, in which case a second call may be performed. The connection's
6573 * flags are updated with whatever special event is detected (error, read0,
6574 * empty). The caller is responsible for taking care of those events and
6575 * avoiding the call if inappropriate. The function does not call the
6576 * connection's polling update function, so the caller is responsible for this.
6577 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006578static 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 +02006579{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006580 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02006581 ssize_t ret;
6582 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02006583
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006584 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006585 goto out_error;
6586
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006587#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006588 if (b_data(&ctx->early_buf)) {
6589 try = b_contig_space(buf);
6590 if (try > b_data(&ctx->early_buf))
6591 try = b_data(&ctx->early_buf);
6592 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
6593 b_add(buf, try);
6594 b_del(&ctx->early_buf, try);
6595 if (b_data(&ctx->early_buf) == 0)
6596 b_free(&ctx->early_buf);
6597 return try;
6598 }
6599#endif
6600
Willy Tarreau911db9b2020-01-23 16:27:54 +01006601 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006602 /* a handshake was requested */
6603 return 0;
6604
Emeric Brun46591952012-05-18 15:47:34 +02006605 /* read the largest possible block. For this, we perform only one call
6606 * to recv() unless the buffer wraps and we exactly fill the first hunk,
6607 * in which case we accept to do it once again. A new attempt is made on
6608 * EINTR too.
6609 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01006610 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006611
Willy Tarreau591d4452018-06-15 17:21:00 +02006612 try = b_contig_space(buf);
6613 if (!try)
6614 break;
6615
Willy Tarreauabf08d92014-01-14 11:31:27 +01006616 if (try > count)
6617 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02006618
Olivier Houchard66ab4982019-02-26 18:37:15 +01006619 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02006620
Emeric Brune1f38db2012-09-03 20:36:47 +02006621 if (conn->flags & CO_FL_ERROR) {
6622 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006623 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006624 }
Emeric Brun46591952012-05-18 15:47:34 +02006625 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006626 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006627 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006628 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006629 }
Emeric Brun46591952012-05-18 15:47:34 +02006630 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006631 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006632 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006633 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006634 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006635 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006636#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006637 /* Async mode can be re-enabled, because we're leaving data state.*/
6638 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006639 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006640#endif
Emeric Brun46591952012-05-18 15:47:34 +02006641 break;
6642 }
6643 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006644 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006645 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6646 SUB_RETRY_RECV,
6647 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006648 /* handshake is running, and it may need to re-enable read */
6649 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006650#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006651 /* Async mode can be re-enabled, because we're leaving data state.*/
6652 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006653 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006654#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006655 break;
6656 }
Emeric Brun46591952012-05-18 15:47:34 +02006657 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006658 } else if (ret == SSL_ERROR_ZERO_RETURN)
6659 goto read0;
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006660 else if (ret == SSL_ERROR_SSL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006661 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6662 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006663 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006664 conn->err_code = CO_ERR_SSL_FATAL;
6665 }
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006666 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6667 * stack before shutting down the connection for
6668 * reading. */
Willy Tarreauacef5e22022-04-25 20:32:15 +02006669 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN || errno == EWOULDBLOCK))
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006670 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006671 /* otherwise it's a real error */
6672 goto out_error;
6673 }
6674 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006675 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006676 return done;
6677
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006678 clear_ssl_error:
6679 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006680 ssl_sock_dump_errors(conn, NULL);
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006681 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006682 read0:
6683 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006684 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006685
Emeric Brun46591952012-05-18 15:47:34 +02006686 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006687 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006688 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006689 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006690 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006691 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006692}
6693
6694
Willy Tarreau787db9a2018-06-14 18:31:46 +02006695/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6696 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6697 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006698 * Only one call to send() is performed, unless the buffer wraps, in which case
6699 * a second call may be performed. The connection's flags are updated with
6700 * whatever special event is detected (error, empty). The caller is responsible
6701 * for taking care of those events and avoiding the call if inappropriate. The
6702 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006703 * is responsible for this. The buffer's output is not adjusted, it's up to the
6704 * caller to take care of this. It's up to the caller to update the buffer's
6705 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006706 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006707static 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 +02006708{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006709 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006710 ssize_t ret;
6711 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006712
6713 done = 0;
6714
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006715 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006716 goto out_error;
6717
Willy Tarreau911db9b2020-01-23 16:27:54 +01006718 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006719 /* a handshake was requested */
6720 return 0;
6721
6722 /* send the largest possible block. For this we perform only one call
6723 * to send() unless the buffer wraps and we exactly fill the first hunk,
6724 * in which case we accept to do it once again.
6725 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006726 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006727#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006728 size_t written_data;
6729#endif
6730
Willy Tarreau787db9a2018-06-14 18:31:46 +02006731 try = b_contig_data(buf, done);
6732 if (try > count)
6733 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006734
Thomas Prückl10243932022-04-27 13:04:54 +02006735 if (global_ssl.hard_max_record && try > global_ssl.hard_max_record)
6736 try = global_ssl.hard_max_record;
6737
Willy Tarreau7bed9452014-02-02 02:00:24 +01006738 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006739 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006740 global_ssl.max_record && try > global_ssl.max_record) {
6741 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006742 }
6743 else {
6744 /* we need to keep the information about the fact that
6745 * we're not limiting the upcoming send(), because if it
6746 * fails, we'll have to retry with at least as many data.
6747 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006748 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006749 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006750
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006751#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006752 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006753 unsigned int max_early;
6754
Olivier Houchard522eea72017-11-03 16:27:47 +01006755 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006756 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006757 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006758 if (SSL_get0_session(ctx->ssl))
6759 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006760 else
6761 max_early = 0;
6762 }
6763
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006764 if (try + ctx->sent_early_data > max_early) {
6765 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006766 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006767 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006768 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006769 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006770 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006771 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006772 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006773 if (ret == 1) {
6774 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006775 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006776 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006777 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006778 /* Initiate the handshake, now */
6779 tasklet_wakeup(ctx->wait_event.tasklet);
6780 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006781
Olivier Houchardc2aae742017-09-22 18:26:28 +02006782 }
6783
6784 } else
6785#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006786 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006787
Emeric Brune1f38db2012-09-03 20:36:47 +02006788 if (conn->flags & CO_FL_ERROR) {
6789 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006790 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006791 }
Emeric Brun46591952012-05-18 15:47:34 +02006792 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006793 /* A send succeeded, so we can consider ourself connected */
6794 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006795 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006796 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006797 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006798 }
6799 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006800 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006801
Emeric Brun46591952012-05-18 15:47:34 +02006802 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006803 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006804 /* handshake is running, and it may need to re-enable write */
6805 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006806 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006807#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006808 /* Async mode can be re-enabled, because we're leaving data state.*/
6809 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006810 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006811#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006812 break;
6813 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006814
Emeric Brun46591952012-05-18 15:47:34 +02006815 break;
6816 }
6817 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006818 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006819 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006820 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6821 SUB_RETRY_RECV,
6822 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006823#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006824 /* Async mode can be re-enabled, because we're leaving data state.*/
6825 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006826 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006827#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006828 break;
6829 }
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006830 else if (ret == SSL_ERROR_SSL || ret == SSL_ERROR_SYSCALL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006831 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6832
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02006833 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006834 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006835 conn->err_code = CO_ERR_SSL_FATAL;
6836 }
Emeric Brun46591952012-05-18 15:47:34 +02006837 goto out_error;
6838 }
6839 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006840 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006841 return done;
6842
6843 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006844 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006845 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006846 ERR_clear_error();
6847
Emeric Brun46591952012-05-18 15:47:34 +02006848 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006849 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006850}
6851
Willy Tarreau832e2422021-05-13 10:11:03 +02006852void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006853
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006854 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006855
Olivier Houchardea8dd942019-05-20 14:02:16 +02006856
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006857 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006858 if (ctx->wait_event.events != 0)
6859 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6860 ctx->wait_event.events,
6861 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006862 if (ctx->subs) {
6863 ctx->subs->events = 0;
6864 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006865 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006866
Olivier Houchard692c1d02019-05-23 18:41:47 +02006867 if (ctx->xprt->close)
6868 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006869#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006870 if (global_ssl.async) {
6871 OSSL_ASYNC_FD all_fd[32], afd;
6872 size_t num_all_fds = 0;
6873 int i;
6874
Olivier Houchard66ab4982019-02-26 18:37:15 +01006875 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006876 if (num_all_fds > 32) {
6877 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6878 return;
6879 }
6880
Olivier Houchard66ab4982019-02-26 18:37:15 +01006881 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006882
6883 /* If an async job is pending, we must try to
6884 to catch the end using polling before calling
6885 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006886 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006887 for (i=0 ; i < num_all_fds ; i++) {
6888 /* switch on an handler designed to
6889 * handle the SSL_free
6890 */
6891 afd = all_fd[i];
6892 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006893 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006894 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006895 /* To ensure that the fd cache won't be used
6896 * and we'll catch a real RD event.
6897 */
6898 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006899 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006900 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006901 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006902 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006903 return;
6904 }
Emeric Brun3854e012017-05-17 20:42:48 +02006905 /* Else we can remove the fds from the fdtab
6906 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006907 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006908 * because the fd is owned by the engine.
6909 * the engine is responsible to close
6910 */
Emeric Brun7d392a52022-07-01 17:36:50 +02006911 for (i=0 ; i < num_all_fds ; i++) {
6912 /* We want to remove the fd from the fdtab
6913 * but we flag it to disown because the
6914 * close is performed by the engine itself
6915 */
6916 fdtab[all_fd[i]].state |= FD_DISOWN;
6917 fd_delete(all_fd[i]);
6918 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006919 }
6920#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006921 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006922 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006923 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006924 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau82531f62021-10-06 12:15:18 +02006925 _HA_ATOMIC_DEC(&global.sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006926 }
Emeric Brun46591952012-05-18 15:47:34 +02006927}
6928
6929/* This function tries to perform a clean shutdown on an SSL connection, and in
6930 * any case, flags the connection as reusable if no handshake was in progress.
6931 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006932static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006933{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006934 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006935
Willy Tarreau911db9b2020-01-23 16:27:54 +01006936 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006937 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006938 if (!clean)
6939 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006940 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006941 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006942 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006943 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006944 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006945 ERR_clear_error();
6946 }
Emeric Brun46591952012-05-18 15:47:34 +02006947}
6948
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006949
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006950/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006951int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6952{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006953 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemandd4f946c2019-12-05 10:26:40 +01006954 X509 *crt;
6955
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006956 if (!ctx)
William Lallemandd4f946c2019-12-05 10:26:40 +01006957 return 0;
William Lallemandd4f946c2019-12-05 10:26:40 +01006958 crt = SSL_get_certificate(ctx->ssl);
6959 if (!crt)
6960 return 0;
6961
6962 return cert_get_pkey_algo(crt, out);
6963}
6964
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006965/* used for ppv2 cert signature (can be used for logging) */
6966const char *ssl_sock_get_cert_sig(struct connection *conn)
6967{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006968 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006969
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006970 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6971 X509 *crt;
6972
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006973 if (!ctx)
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006974 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006975 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006976 if (!crt)
6977 return NULL;
6978 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6979 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6980}
6981
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006982/* used for ppv2 authority */
6983const char *ssl_sock_get_sni(struct connection *conn)
6984{
6985#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006986 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006987
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006988 if (!ctx)
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006989 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006990 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006991#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006992 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006993#endif
6994}
6995
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006996/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006997const char *ssl_sock_get_cipher_name(struct connection *conn)
6998{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006999 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01007000
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007001 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02007002 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01007003 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02007004}
7005
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02007006/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02007007const char *ssl_sock_get_proto_version(struct connection *conn)
7008{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007009 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01007010
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007011 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02007012 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01007013 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02007014}
7015
Olivier Houchardab28a322018-12-21 19:45:40 +01007016void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
7017{
7018#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007019 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01007020
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007021 if (!ctx)
Olivier Houcharde488ea82019-06-28 14:10:33 +02007022 return;
Olivier Houchard66ab4982019-02-26 18:37:15 +01007023 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01007024#endif
7025}
7026
Willy Tarreau119a4082016-12-22 21:58:38 +01007027/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
7028 * to disable SNI.
7029 */
Willy Tarreau63076412015-07-10 11:33:32 +02007030void ssl_sock_set_servername(struct connection *conn, const char *hostname)
7031{
7032#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007033 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemande18d4e82021-11-17 02:59:21 +01007034 struct server *s;
Willy Tarreau119a4082016-12-22 21:58:38 +01007035 char *prev_name;
7036
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007037 if (!ctx)
Willy Tarreau63076412015-07-10 11:33:32 +02007038 return;
Willy Tarreau77bfa662021-12-23 11:12:13 +01007039
7040 BUG_ON(!(conn->flags & CO_FL_WAIT_L6_CONN));
7041 BUG_ON(!(conn->flags & CO_FL_SSL_WAIT_HS));
7042
William Lallemande18d4e82021-11-17 02:59:21 +01007043 s = __objt_server(conn->target);
Willy Tarreau63076412015-07-10 11:33:32 +02007044
Willy Tarreau119a4082016-12-22 21:58:38 +01007045 /* if the SNI changes, we must destroy the reusable context so that a
William Lallemande18d4e82021-11-17 02:59:21 +01007046 * new connection will present a new SNI. compare with the SNI
7047 * previously stored in the reused_sess */
7048 /* the RWLOCK is used to ensure that we are not trying to flush the
7049 * cache from the CLI */
7050
7051 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
7052 prev_name = s->ssl_ctx.reused_sess[tid].sni;
Willy Tarreau119a4082016-12-22 21:58:38 +01007053 if ((!prev_name && hostname) ||
7054 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01007055 SSL_set_session(ctx->ssl, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01007056 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau119a4082016-12-22 21:58:38 +01007057
Olivier Houchard66ab4982019-02-26 18:37:15 +01007058 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02007059#endif
7060}
7061
Emeric Brun0abf8362014-06-24 18:26:41 +02007062/* Extract peer certificate's common name into the chunk dest
7063 * Returns
7064 * the len of the extracted common name
7065 * or 0 if no CN found in DN
7066 * or -1 on error case (i.e. no peer certificate)
7067 */
Willy Tarreau83061a82018-07-13 11:56:34 +02007068int ssl_sock_get_remote_common_name(struct connection *conn,
7069 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04007070{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007071 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
David Safb76832014-05-08 23:42:08 -04007072 X509 *crt = NULL;
7073 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04007074 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02007075 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007076 .area = (char *)&find_cn,
7077 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04007078 };
Emeric Brun0abf8362014-06-24 18:26:41 +02007079 int result = -1;
David Safb76832014-05-08 23:42:08 -04007080
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007081 if (!ctx)
Emeric Brun0abf8362014-06-24 18:26:41 +02007082 goto out;
David Safb76832014-05-08 23:42:08 -04007083
7084 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01007085 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04007086 if (!crt)
7087 goto out;
7088
7089 name = X509_get_subject_name(crt);
7090 if (!name)
7091 goto out;
David Safb76832014-05-08 23:42:08 -04007092
Emeric Brun0abf8362014-06-24 18:26:41 +02007093 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
7094out:
David Safb76832014-05-08 23:42:08 -04007095 if (crt)
7096 X509_free(crt);
7097
7098 return result;
7099}
7100
Dave McCowan328fb582014-07-30 10:39:13 -04007101/* returns 1 if client passed a certificate for this session, 0 if not */
7102int ssl_sock_get_cert_used_sess(struct connection *conn)
7103{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007104 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dave McCowan328fb582014-07-30 10:39:13 -04007105 X509 *crt = NULL;
7106
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007107 if (!ctx)
Dave McCowan328fb582014-07-30 10:39:13 -04007108 return 0;
7109
7110 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01007111 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04007112 if (!crt)
7113 return 0;
7114
7115 X509_free(crt);
7116 return 1;
7117}
7118
7119/* returns 1 if client passed a certificate for this connection, 0 if not */
7120int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04007121{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007122 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01007123
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007124 if (!ctx)
David Safb76832014-05-08 23:42:08 -04007125 return 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01007126 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04007127}
7128
7129/* returns result from SSL verify */
7130unsigned int ssl_sock_get_verify_result(struct connection *conn)
7131{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007132 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01007133
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007134 if (!ctx)
David Safb76832014-05-08 23:42:08 -04007135 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Olivier Houchard66ab4982019-02-26 18:37:15 +01007136 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04007137}
7138
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007139/* Returns the application layer protocol name in <str> and <len> when known.
7140 * Zero is returned if the protocol name was not found, otherwise non-zero is
7141 * returned. The string is allocated in the SSL context and doesn't have to be
7142 * freed by the caller. NPN is also checked if available since older versions
7143 * of openssl (1.0.1) which are more common in field only support this one.
7144 */
Amaury Denoyelle71e588c2021-11-12 11:23:29 +01007145int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007146{
Olivier Houchard66ab4982019-02-26 18:37:15 +01007147#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
7148 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01007149 struct ssl_sock_ctx *ctx = xprt_ctx;
7150 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007151 return 0;
7152
7153 *str = NULL;
7154
7155#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01007156 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007157 if (*str)
7158 return 1;
7159#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01007160#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01007161 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007162 if (*str)
7163 return 1;
7164#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01007165#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007166 return 0;
7167}
7168
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007169/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02007170int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007171{
7172 X509 *ca;
7173 X509_NAME *name = NULL;
7174 ASN1_OCTET_STRING *skid = NULL;
7175 STACK_OF(X509) *chain = NULL;
7176 struct issuer_chain *issuer;
7177 struct eb64_node *node;
7178 char *path;
7179 u64 key;
7180 int ret = 0;
7181
7182 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
7183 if (chain == NULL) {
7184 chain = sk_X509_new_null();
7185 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
7186 name = X509_get_subject_name(ca);
7187 }
7188 if (!sk_X509_push(chain, ca)) {
7189 X509_free(ca);
7190 goto end;
7191 }
7192 }
7193 if (!chain) {
7194 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
7195 goto end;
7196 }
7197 if (!skid) {
7198 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
7199 goto end;
7200 }
7201 if (!name) {
7202 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
7203 goto end;
7204 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01007205 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01007206 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007207 issuer = container_of(node, typeof(*issuer), node);
7208 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
7209 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
7210 goto end;
7211 }
7212 }
7213 issuer = calloc(1, sizeof *issuer);
7214 path = strdup(fp);
7215 if (!issuer || !path) {
7216 free(issuer);
7217 free(path);
7218 goto end;
7219 }
7220 issuer->node.key = key;
7221 issuer->path = path;
7222 issuer->chain = chain;
7223 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01007224 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007225 ret = 1;
7226 end:
7227 if (skid)
7228 ASN1_OCTET_STRING_free(skid);
7229 if (chain)
7230 sk_X509_pop_free(chain, X509_free);
7231 return ret;
7232}
7233
William Lallemandda8584c2020-05-14 10:14:37 +02007234 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007235{
7236 AUTHORITY_KEYID *akid;
7237 struct issuer_chain *issuer = NULL;
7238
7239 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01007240 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007241 struct eb64_node *node;
7242 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01007243 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007244 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
7245 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
7246 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
7247 issuer = ti;
7248 break;
7249 }
7250 }
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007251 }
Remi Tricot-Le Breton1621dc12022-11-03 15:16:48 +01007252 AUTHORITY_KEYID_free(akid);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007253 return issuer;
7254}
7255
William Lallemanddad31052020-05-14 17:47:32 +02007256void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007257{
7258 struct eb64_node *node, *back;
7259 struct issuer_chain *issuer;
7260
William Lallemande0f3fd52020-02-25 14:53:06 +01007261 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007262 while (node) {
7263 issuer = container_of(node, typeof(*issuer), node);
7264 back = eb64_next(node);
7265 eb64_delete(node);
7266 free(issuer->path);
7267 sk_X509_pop_free(issuer->chain, X509_free);
7268 free(issuer);
7269 node = back;
7270 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007271}
7272
William Lallemandd7bfbe22022-04-11 18:41:24 +02007273#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007274static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01007275 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007276
Emeric Brun3854e012017-05-17 20:42:48 +02007277 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01007278 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007279 err_code = ERR_ABORT;
7280 }
7281 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01007282}
Willy Tarreau9ceda382016-12-21 23:13:03 +01007283#endif
7284
Willy Tarreaude5675a2021-01-20 14:41:29 +01007285/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007286 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01007287 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01007288static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01007289{
7290 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007291 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007292
7293 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007294 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007295
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007296 if (sctx->conn != conn) {
7297 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
7298 ret = 1;
7299 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01007300 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
7301
7302 if (sctx->xprt) {
7303 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
7304 if (sctx->xprt_ctx)
7305 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
7306 }
7307
7308 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007309
7310 /* as soon as a shutdown is reported the lower layer unregisters its
7311 * subscriber, so the situations below are transient and rare enough to
7312 * be reported as suspicious. In any case they shouldn't last.
7313 */
7314 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
7315 ret = 1;
7316 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
7317 ret = 1;
7318
Willy Tarreaude5675a2021-01-20 14:41:29 +01007319 chunk_appendf(&trash, " .subs=%p", sctx->subs);
7320 if (sctx->subs) {
7321 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007322 if (sctx->subs->tasklet->calls >= 1000000)
7323 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007324 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
7325 sctx->subs->tasklet->calls,
7326 sctx->subs->tasklet->context);
7327 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
7328 chunk_appendf(&trash, ")");
7329 }
7330 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
7331 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007332 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007333}
7334
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007335#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02007336/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007337 * each reference. The variable <ref> must point to the current node's list
7338 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02007339 */
William Lallemand32af2032016-10-29 18:09:35 +02007340static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007341struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02007342{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007343 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007344 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02007345
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007346 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007347 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007348 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02007349
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007350 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02007351}
7352
7353static inline
7354struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
7355{
7356 int id;
7357 char *error;
7358
7359 /* If the reference starts by a '#', this is numeric id. */
7360 if (reference[0] == '#') {
7361 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
7362 id = strtol(reference + 1, &error, 10);
7363 if (*error != '\0')
7364 return NULL;
7365
7366 /* Perform the unique id lookup. */
7367 return tlskeys_ref_lookupid(id);
7368 }
7369
7370 /* Perform the string lookup. */
7371 return tlskeys_ref_lookup(reference);
7372}
7373#endif
7374
7375
7376#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7377
Willy Tarreaua9380522022-05-05 08:50:17 +02007378/* dumps all tls keys. Relies on the show_keys_ctx context from the appctx. */
Willy Tarreaubd338642022-05-05 08:59:17 +02007379static int cli_io_handler_tlskeys_files(struct appctx *appctx)
7380{
Willy Tarreaua9380522022-05-05 08:50:17 +02007381 struct show_keys_ctx *ctx = appctx->svcctx;
William Lallemand32af2032016-10-29 18:09:35 +02007382
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007383 switch (ctx->state) {
7384 case SHOW_KEYS_INIT:
William Lallemand32af2032016-10-29 18:09:35 +02007385 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08007386 * quit the function with returning 0. The function is called
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007387 * later and restart at the state "SHOW_KEYS_INIT".
William Lallemand32af2032016-10-29 18:09:35 +02007388 */
7389 chunk_reset(&trash);
7390
Willy Tarreaubd338642022-05-05 08:59:17 +02007391 if (ctx->dump_entries)
William Lallemand32af2032016-10-29 18:09:35 +02007392 chunk_appendf(&trash, "# id secret\n");
7393 else
7394 chunk_appendf(&trash, "# id (file)\n");
7395
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007396 if (applet_putchk(appctx, &trash) == -1)
William Lallemand32af2032016-10-29 18:09:35 +02007397 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007398
William Lallemand32af2032016-10-29 18:09:35 +02007399 /* Now, we start the browsing of the references lists.
7400 * Note that the following call to LIST_ELEM return bad pointer. The only
7401 * available field of this pointer is <list>. It is used with the function
7402 * tlskeys_list_get_next() for retruning the first available entry
7403 */
Willy Tarreaua9380522022-05-05 08:50:17 +02007404 if (ctx->next_ref == NULL)
7405 ctx->next_ref = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007406
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007407 ctx->state = SHOW_KEYS_LIST;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007408 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007409
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007410 case SHOW_KEYS_LIST:
Willy Tarreaua9380522022-05-05 08:50:17 +02007411 while (ctx->next_ref) {
7412 struct tls_keys_ref *ref = ctx->next_ref;
William Lallemand32af2032016-10-29 18:09:35 +02007413
7414 chunk_reset(&trash);
Willy Tarreaubd338642022-05-05 08:59:17 +02007415 if (ctx->dump_entries && ctx->next_index == 0)
William Lallemand32af2032016-10-29 18:09:35 +02007416 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007417
Willy Tarreaua9380522022-05-05 08:50:17 +02007418 if (ctx->next_index == 0)
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007419 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
7420
Willy Tarreaubd338642022-05-05 08:59:17 +02007421 if (ctx->dump_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01007422 int head;
7423
7424 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
7425 head = ref->tls_ticket_enc_index;
Willy Tarreaua9380522022-05-05 08:50:17 +02007426 while (ctx->next_index < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02007427 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02007428
7429 chunk_reset(t2);
7430 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01007431 if (ref->key_size_bits == 128) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007432 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007433 sizeof(struct tls_sess_key_128),
7434 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007435 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007436 t2->area);
7437 }
7438 else if (ref->key_size_bits == 256) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007439 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007440 sizeof(struct tls_sess_key_256),
7441 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007442 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007443 t2->area);
7444 }
7445 else {
7446 /* This case should never happen */
Willy Tarreaua9380522022-05-05 08:50:17 +02007447 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, ctx->next_index);
Emeric Brun9e754772019-01-10 17:51:55 +01007448 }
William Lallemand32af2032016-10-29 18:09:35 +02007449
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007450 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007451 /* let's try again later from this stream. We add ourselves into
7452 * this stream's users so that it can remove us upon termination.
7453 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01007454 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
William Lallemand32af2032016-10-29 18:09:35 +02007455 return 0;
7456 }
Willy Tarreaua9380522022-05-05 08:50:17 +02007457 ctx->next_index++;
William Lallemand32af2032016-10-29 18:09:35 +02007458 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01007459 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaua9380522022-05-05 08:50:17 +02007460 ctx->next_index = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007461 }
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007462 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007463 /* let's try again later from this stream. We add ourselves into
7464 * this stream's users so that it can remove us upon termination.
7465 */
William Lallemand32af2032016-10-29 18:09:35 +02007466 return 0;
7467 }
7468
Willy Tarreaua9380522022-05-05 08:50:17 +02007469 if (ctx->names_only == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02007470 break;
7471
7472 /* get next list entry and check the end of the list */
Willy Tarreaua9380522022-05-05 08:50:17 +02007473 ctx->next_ref = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007474 }
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007475 ctx->state = SHOW_KEYS_DONE;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007476 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007477
7478 default:
William Lallemand32af2032016-10-29 18:09:35 +02007479 return 1;
7480 }
7481 return 0;
7482}
7483
Willy Tarreaua9380522022-05-05 08:50:17 +02007484/* Prepares a "show_keys_ctx" and sets the appropriate io_handler if needed */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007485static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007486{
Willy Tarreaua9380522022-05-05 08:50:17 +02007487 struct show_keys_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
7488
William Lallemand32af2032016-10-29 18:09:35 +02007489 /* no parameter, shows only file list */
7490 if (!*args[2]) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007491 ctx->names_only = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007492 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007493 }
7494
7495 if (args[2][0] == '*') {
7496 /* list every TLS ticket keys */
Willy Tarreaua9380522022-05-05 08:50:17 +02007497 ctx->names_only = 1;
William Lallemand32af2032016-10-29 18:09:35 +02007498 } else {
Willy Tarreaua9380522022-05-05 08:50:17 +02007499 ctx->next_ref = tlskeys_ref_lookup_ref(args[2]);
7500 if (!ctx->next_ref)
Willy Tarreau9d008692019-08-09 11:21:01 +02007501 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02007502 }
Willy Tarreaubd338642022-05-05 08:59:17 +02007503
7504 ctx->dump_entries = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007505 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007506}
7507
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007508static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007509{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007510 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02007511 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007512
William Lallemand32af2032016-10-29 18:09:35 +02007513 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02007514 if (!*args[3] || !*args[4])
7515 return cli_err(appctx, "'set ssl tls-key' expects a filename and the new TLS key in base64 encoding.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007516
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007517 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02007518 if (!ref)
7519 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02007520
Willy Tarreau1c913e42018-08-22 05:26:57 +02007521 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02007522 if (ret < 0)
7523 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01007524
Willy Tarreau1c913e42018-08-22 05:26:57 +02007525 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02007526 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
7527 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007528
Willy Tarreau9d008692019-08-09 11:21:01 +02007529 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02007530}
William Lallemandd4f946c2019-12-05 10:26:40 +01007531#endif
William Lallemand419e6342020-04-08 12:05:39 +02007532
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007533static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007534{
7535#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
7536 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02007537 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02007538
7539 if (!payload)
7540 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02007541
7542 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02007543 if (!*payload)
7544 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02007545
7546 /* remove \r and \n from the payload */
7547 for (i = 0, j = 0; payload[i]; i++) {
7548 if (payload[i] == '\r' || payload[i] == '\n')
7549 continue;
7550 payload[j++] = payload[i];
7551 }
7552 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007553
Willy Tarreau1c913e42018-08-22 05:26:57 +02007554 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02007555 if (ret < 0)
7556 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007557
Willy Tarreau1c913e42018-08-22 05:26:57 +02007558 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02007559 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02007560 if (err)
7561 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
7562 else
7563 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007564 }
Willy Tarreau9d008692019-08-09 11:21:01 +02007565
7566 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02007567#else
Willy Tarreau9d008692019-08-09 11:21:01 +02007568 return cli_err(appctx, "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007569#endif
7570
Elliot Otchet71f82972020-01-15 08:12:14 -05007571}
7572
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007573
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007574#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007575static int cli_io_handler_show_ocspresponse_detail(struct appctx *appctx);
7576#endif
7577
Willy Tarreau170b35b2022-05-05 09:09:15 +02007578/* parsing function for 'show ssl ocsp-response [id]'. If an entry is forced,
7579 * it's set into appctx->svcctx.
7580 */
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007581static int cli_parse_show_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
7582{
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007583#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007584 if (*args[3]) {
7585 struct certificate_ocsp *ocsp = NULL;
7586 char *key = NULL;
7587 int key_length = 0;
7588
7589 if (strlen(args[3]) > OCSP_MAX_CERTID_ASN1_LENGTH*2) {
7590 return cli_err(appctx, "'show ssl ocsp-response' received a too big key.\n");
7591 }
7592
7593 if (parse_binary(args[3], &key, &key_length, NULL)) {
7594
7595 char full_key[OCSP_MAX_CERTID_ASN1_LENGTH] = {};
7596 memcpy(full_key, key, key_length);
7597
7598 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, full_key, OCSP_MAX_CERTID_ASN1_LENGTH);
7599 }
7600 if (key)
7601 ha_free(&key);
7602
7603 if (!ocsp) {
7604 return cli_err(appctx, "Certificate ID does not match any certificate.\n");
7605 }
7606
Willy Tarreau170b35b2022-05-05 09:09:15 +02007607 appctx->svcctx = ocsp;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007608 appctx->io_handler = cli_io_handler_show_ocspresponse_detail;
7609 }
7610
7611 return 0;
7612
7613#else
7614 return cli_err(appctx, "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n");
7615#endif
7616}
7617
7618
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007619#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007620/*
7621 * This function dumps the details of an OCSP_CERTID. It is based on
7622 * ocsp_certid_print in OpenSSL.
7623 */
7624static inline int ocsp_certid_print(BIO *bp, OCSP_CERTID *certid, int indent)
7625{
7626 ASN1_OCTET_STRING *piNameHash = NULL;
7627 ASN1_OCTET_STRING *piKeyHash = NULL;
7628 ASN1_INTEGER *pSerial = NULL;
7629
7630 if (OCSP_id_get0_info(&piNameHash, NULL, &piKeyHash, &pSerial, certid)) {
7631
7632 BIO_printf(bp, "%*sCertificate ID:\n", indent, "");
7633 indent += 2;
Remi Tricot-Le Bretoncc750ef2021-12-17 18:53:23 +01007634 BIO_printf(bp, "%*sIssuer Name Hash: ", indent, "");
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01007635#ifndef USE_OPENSSL_WOLFSSL
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007636 i2a_ASN1_STRING(bp, piNameHash, 0);
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01007637#else
7638 wolfSSL_ASN1_STRING_print(bp, piNameHash);
7639#endif
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007640 BIO_printf(bp, "\n%*sIssuer Key Hash: ", indent, "");
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01007641#ifndef USE_OPENSSL_WOLFSSL
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007642 i2a_ASN1_STRING(bp, piKeyHash, 0);
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01007643#else
7644 wolfSSL_ASN1_STRING_print(bp, piNameHash);
7645#endif
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007646 BIO_printf(bp, "\n%*sSerial Number: ", indent, "");
7647 i2a_ASN1_INTEGER(bp, pSerial);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007648 }
7649 return 1;
7650}
7651#endif
7652
7653/*
7654 * IO handler of "show ssl ocsp-response". The command taking a specific ID
7655 * is managed in cli_io_handler_show_ocspresponse_detail.
Willy Tarreau170b35b2022-05-05 09:09:15 +02007656 * The current entry is taken from appctx->svcctx.
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007657 */
7658static int cli_io_handler_show_ocspresponse(struct appctx *appctx)
7659{
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007660#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007661 struct buffer *trash = alloc_trash_chunk();
7662 struct buffer *tmp = NULL;
7663 struct ebmb_node *node;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007664 struct certificate_ocsp *ocsp = NULL;
7665 BIO *bio = NULL;
7666 int write = -1;
7667
7668 if (trash == NULL)
7669 return 1;
7670
7671 tmp = alloc_trash_chunk();
7672 if (!tmp)
7673 goto end;
7674
7675 if ((bio = BIO_new(BIO_s_mem())) == NULL)
7676 goto end;
7677
Willy Tarreau170b35b2022-05-05 09:09:15 +02007678 if (!appctx->svcctx) {
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007679 chunk_appendf(trash, "# Certificate IDs\n");
7680 node = ebmb_first(&cert_ocsp_tree);
7681 } else {
Willy Tarreau170b35b2022-05-05 09:09:15 +02007682 node = &((struct certificate_ocsp *)appctx->svcctx)->key;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007683 }
7684
7685 while (node) {
7686 OCSP_CERTID *certid = NULL;
7687 const unsigned char *p = NULL;
7688 int i;
7689
7690 ocsp = ebmb_entry(node, struct certificate_ocsp, key);
7691
7692 /* Dump the key in hexadecimal */
7693 chunk_appendf(trash, "Certificate ID key : ");
7694 for (i = 0; i < ocsp->key_length; ++i) {
7695 chunk_appendf(trash, "%02x", ocsp->key_data[i]);
7696 }
7697 chunk_appendf(trash, "\n");
7698
7699 p = ocsp->key_data;
7700
7701 /* Decode the certificate ID (serialized into the key). */
7702 d2i_OCSP_CERTID(&certid, &p, ocsp->key_length);
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007703 if (!certid)
7704 goto end;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007705
7706 /* Dump the CERTID info */
7707 ocsp_certid_print(bio, certid, 1);
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007708 OCSP_CERTID_free(certid);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007709 write = BIO_read(bio, tmp->area, tmp->size-1);
Remi Tricot-Le Bretoncc750ef2021-12-17 18:53:23 +01007710 /* strip trailing LFs */
7711 while (write > 0 && tmp->area[write-1] == '\n')
7712 write--;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007713 tmp->area[write] = '\0';
7714
7715 chunk_appendf(trash, "%s\n", tmp->area);
7716
7717 node = ebmb_next(node);
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007718 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007719 goto yield;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007720 }
7721
7722end:
Willy Tarreau170b35b2022-05-05 09:09:15 +02007723 appctx->svcctx = NULL;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007724 if (trash)
7725 free_trash_chunk(trash);
7726 if (tmp)
7727 free_trash_chunk(tmp);
7728 if (bio)
7729 BIO_free(bio);
7730 return 1;
7731
7732yield:
7733
7734 if (trash)
7735 free_trash_chunk(trash);
7736 if (tmp)
7737 free_trash_chunk(tmp);
7738 if (bio)
7739 BIO_free(bio);
Willy Tarreau170b35b2022-05-05 09:09:15 +02007740 appctx->svcctx = ocsp;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007741 return 0;
7742#else
7743 return cli_err(appctx, "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n");
7744#endif
7745}
7746
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007747#ifdef HAVE_SSL_PROVIDERS
7748struct provider_name {
7749 const char *name;
7750 struct list list;
7751};
7752
7753
7754static int ssl_provider_get_name_cb(OSSL_PROVIDER *provider, void *cbdata)
7755{
7756 struct list *provider_names = cbdata;
7757 struct provider_name *item = NULL;
7758 const char *name = OSSL_PROVIDER_get0_name(provider);
7759
7760 if (!provider_names)
7761 return 0;
7762
7763 item = calloc(1, sizeof(*item));
7764
7765 if (!item)
7766 return 0;
7767
7768 item->name = name;
7769 LIST_APPEND(provider_names, &item->list);
7770
7771 return 1;
7772}
7773
7774static void ssl_provider_get_name_list(struct list *provider_names)
7775{
7776 if (!provider_names)
7777 return;
7778
7779 OSSL_PROVIDER_do_all(NULL, ssl_provider_get_name_cb, provider_names);
7780}
7781
7782static void ssl_provider_clear_name_list(struct list *provider_names)
7783{
7784 struct provider_name *item = NULL, *item_s = NULL;
7785
7786 if (provider_names) {
7787 list_for_each_entry_safe(item, item_s, provider_names, list) {
7788 LIST_DELETE(&item->list);
7789 free(item);
7790 }
7791 }
7792}
7793
7794static int cli_io_handler_show_providers(struct appctx *appctx)
7795{
7796 struct buffer *trash = get_trash_chunk();
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007797 struct list provider_names;
7798 struct provider_name *name;
7799
7800 LIST_INIT(&provider_names);
7801
7802 chunk_appendf(trash, "Loaded providers : \n");
7803
7804 ssl_provider_get_name_list(&provider_names);
7805
7806 list_for_each_entry(name, &provider_names, list) {
7807 chunk_appendf(trash, "\t- %s\n", name->name);
7808 }
7809
7810 ssl_provider_clear_name_list(&provider_names);
7811
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007812 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007813 goto yield;
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007814
7815 return 1;
7816
7817yield:
7818 return 0;
7819}
7820#endif
7821
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007822
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007823#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007824/*
7825 * Dump the details about an OCSP response in DER format stored in
7826 * <ocsp_response> into buffer <out>.
7827 * Returns 0 in case of success.
7828 */
7829int ssl_ocsp_response_print(struct buffer *ocsp_response, struct buffer *out)
7830{
7831 BIO *bio = NULL;
7832 int write = -1;
7833 OCSP_RESPONSE *resp;
7834 const unsigned char *p;
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01007835 int retval = -1;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007836
7837 if (!ocsp_response)
7838 return -1;
7839
7840 if ((bio = BIO_new(BIO_s_mem())) == NULL)
7841 return -1;
7842
7843 p = (const unsigned char*)ocsp_response->area;
7844
7845 resp = d2i_OCSP_RESPONSE(NULL, &p, ocsp_response->data);
7846 if (!resp) {
7847 chunk_appendf(out, "Unable to parse OCSP response");
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007848 goto end;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007849 }
7850
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01007851#ifndef USE_OPENSSL_WOLFSSL
7852 if (OCSP_RESPONSE_print(bio, resp, 0) != 0) {
7853#else
7854 if (wolfSSL_d2i_OCSP_RESPONSE_bio(bio, &resp) != 0) {
7855#endif
Remi Tricot-Le Breton2e7d1eb2022-01-11 10:11:10 +01007856 struct buffer *trash = get_trash_chunk();
7857 struct ist ist_block = IST_NULL;
7858 struct ist ist_double_lf = IST_NULL;
7859 static struct ist double_lf = IST("\n\n");
7860
7861 write = BIO_read(bio, trash->area, trash->size - 1);
Remi Tricot-Le Breton1b01b7f2022-02-16 15:17:09 +01007862 if (write <= 0)
7863 goto end;
Remi Tricot-Le Breton2e7d1eb2022-01-11 10:11:10 +01007864 trash->data = write;
7865
7866 /* Look for empty lines in the 'trash' buffer and add a space to
7867 * the beginning to avoid having empty lines in the output
7868 * (without changing the appearance of the information
7869 * displayed).
7870 */
7871 ist_block = ist2(b_orig(trash), b_data(trash));
7872
7873 ist_double_lf = istist(ist_block, double_lf);
7874
7875 while (istlen(ist_double_lf)) {
7876 /* istptr(ist_double_lf) points to the first \n of a
7877 * \n\n pattern.
7878 */
7879 uint empty_line_offset = istptr(ist_double_lf) + 1 - istptr(ist_block);
7880
7881 /* Write up to the first '\n' of the "\n\n" pattern into
7882 * the output buffer.
7883 */
7884 b_putblk(out, istptr(ist_block), empty_line_offset);
7885 /* Add an extra space. */
7886 b_putchr(out, ' ');
7887
7888 /* Keep looking for empty lines in the rest of the data. */
7889 ist_block = istadv(ist_block, empty_line_offset);
7890
7891 ist_double_lf = istist(ist_block, double_lf);
7892 }
7893
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01007894 retval = (b_istput(out, ist_block) <= 0);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007895 }
7896
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007897end:
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007898 if (bio)
7899 BIO_free(bio);
7900
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007901 OCSP_RESPONSE_free(resp);
7902
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01007903 return retval;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007904}
7905
7906/*
7907 * Dump the details of the OCSP response of ID <ocsp_certid> into buffer <out>.
7908 * Returns 0 in case of success.
7909 */
7910int ssl_get_ocspresponse_detail(unsigned char *ocsp_certid, struct buffer *out)
7911{
7912 struct certificate_ocsp *ocsp;
7913
7914 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, ocsp_certid, OCSP_MAX_CERTID_ASN1_LENGTH);
7915 if (!ocsp)
7916 return -1;
7917
7918 return ssl_ocsp_response_print(&ocsp->response, out);
7919}
7920
7921
Willy Tarreau170b35b2022-05-05 09:09:15 +02007922/* IO handler of details "show ssl ocsp-response <id>".
7923 * The current entry is taken from appctx->svcctx.
7924 */
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007925static int cli_io_handler_show_ocspresponse_detail(struct appctx *appctx)
7926{
7927 struct buffer *trash = alloc_trash_chunk();
Willy Tarreau170b35b2022-05-05 09:09:15 +02007928 struct certificate_ocsp *ocsp = appctx->svcctx;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007929
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007930 if (trash == NULL)
7931 return 1;
7932
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01007933 if (ssl_ocsp_response_print(&ocsp->response, trash)) {
7934 free_trash_chunk(trash);
7935 return 1;
7936 }
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007937
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007938 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007939 goto yield;
Willy Tarreau170b35b2022-05-05 09:09:15 +02007940
7941 appctx->svcctx = NULL;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007942 if (trash)
7943 free_trash_chunk(trash);
7944 return 1;
7945
7946yield:
7947 if (trash)
7948 free_trash_chunk(trash);
7949
7950 return 0;
7951}
7952#endif
7953
William Lallemand32af2032016-10-29 18:09:35 +02007954/* register cli keywords */
7955static struct cli_kw_list cli_kws = {{ },{
7956#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Willy Tarreaubd338642022-05-05 08:59:17 +02007957 { { "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 },
Willy Tarreaub205bfd2021-05-07 11:38:37 +02007958 { { "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 +02007959#endif
Willy Tarreaub205bfd2021-05-07 11:38:37 +02007960 { { "set", "ssl", "ocsp-response", NULL }, "set ssl ocsp-response <resp|payload> : update a certificate's OCSP Response from a base64-encode DER", cli_parse_set_ocspresponse, NULL },
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007961
7962 { { "show", "ssl", "ocsp-response", NULL },"show ssl ocsp-response [id] : display the IDs of the OCSP responses used in memory, or the details of a single OCSP response", cli_parse_show_ocspresponse, cli_io_handler_show_ocspresponse, NULL },
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007963#ifdef HAVE_SSL_PROVIDERS
7964 { { "show", "ssl", "providers", NULL }, "show ssl providers : show loaded SSL providers", NULL, cli_io_handler_show_providers },
7965#endif
William Lallemand32af2032016-10-29 18:09:35 +02007966 { { NULL }, NULL, NULL, NULL }
7967}};
7968
Willy Tarreau0108d902018-11-25 19:14:37 +01007969INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02007970
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02007971/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02007972struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02007973 .snd_buf = ssl_sock_from_buf,
7974 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01007975 .subscribe = ssl_subscribe,
7976 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02007977 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02007978 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02007979 .rcv_pipe = NULL,
7980 .snd_pipe = NULL,
7981 .shutr = NULL,
7982 .shutw = ssl_sock_shutw,
7983 .close = ssl_sock_close,
7984 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01007985 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01007986 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01007987 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01007988 .prepare_srv = ssl_sock_prepare_srv_ctx,
7989 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007990 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02007991 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01007992 .set_idle = ssl_set_idle,
7993 .set_used = ssl_set_used,
Willy Tarreaude827952022-04-11 10:43:28 +02007994 .get_ssl_sock_ctx = ssl_sock_get_ctx,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01007995 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01007996 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02007997};
7998
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007999enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
8000 struct session *sess, struct stream *s, int flags)
8001{
8002 struct connection *conn;
8003
8004 conn = objt_conn(sess->origin);
8005
Willy Tarreaub52d4d22022-05-27 10:44:39 +02008006 if (conn) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02008007 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Willy Tarreaub52d4d22022-05-27 10:44:39 +02008008 sc_ep_set(s->scf, SE_FL_WAIT_FOR_HS);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02008009 s->req.flags |= CF_READ_NULL;
8010 return ACT_RET_YIELD;
8011 }
8012 }
8013 return (ACT_RET_CONT);
8014}
8015
8016static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
8017{
8018 rule->action_ptr = ssl_action_wait_for_hs;
8019
8020 return ACT_RET_PRS_OK;
8021}
8022
8023static struct action_kw_list http_req_actions = {ILH, {
8024 { "wait-for-handshake", ssl_parse_wait_for_hs },
8025 { /* END */ }
8026}};
8027
Willy Tarreau0108d902018-11-25 19:14:37 +01008028INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
8029
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05008030#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01008031
8032static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
8033{
8034 if (ptr) {
8035 chunk_destroy(ptr);
8036 free(ptr);
8037 }
8038}
8039
8040#endif
William Lallemand76b4a122020-08-04 17:41:39 +02008041
8042#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
8043static void ssl_sock_ocsp_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
8044{
8045 struct ocsp_cbk_arg *ocsp_arg;
8046
8047 if (ptr) {
8048 ocsp_arg = ptr;
8049
8050 if (ocsp_arg->is_single) {
8051 ssl_sock_free_ocsp(ocsp_arg->s_ocsp);
8052 ocsp_arg->s_ocsp = NULL;
8053 } else {
8054 int i;
8055
8056 for (i = 0; i < SSL_SOCK_NUM_KEYTYPES; i++) {
8057 ssl_sock_free_ocsp(ocsp_arg->m_ocsp[i]);
8058 ocsp_arg->m_ocsp[i] = NULL;
8059 }
8060 }
8061 free(ocsp_arg);
8062 }
8063}
8064#endif
8065
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01008066static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
8067{
Willy Tarreaubafbe012017-11-24 17:34:44 +01008068 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01008069}
William Lallemand7d42ef52020-07-06 11:41:30 +02008070
William Lallemand722180a2021-06-09 16:46:12 +02008071#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02008072static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
8073{
8074 struct ssl_keylog *keylog;
8075
8076 if (!ptr)
8077 return;
8078
8079 keylog = ptr;
8080
8081 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
8082 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
8083 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
8084 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
8085 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
8086 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
8087 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
8088 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
8089
8090 pool_free(pool_head_ssl_keylog, ptr);
8091}
8092#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01008093
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02008094static void ssl_sock_clt_crt_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
8095{
8096 if (!ptr)
8097 return;
8098
8099 X509_free((X509*)ptr);
8100}
8101
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01008102static void ssl_sock_clt_sni_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
8103{
8104 pool_free(ssl_sock_client_sni_pool, ptr);
8105}
8106
Willy Tarreau92faadf2012-10-10 23:04:25 +02008107static void __ssl_sock_init(void)
8108{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05008109#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02008110 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05008111 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05008112#endif
Emeric Brun46591952012-05-18 15:47:34 +02008113
Willy Tarreauef934602016-12-22 23:12:01 +01008114 if (global_ssl.listen_default_ciphers)
8115 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
8116 if (global_ssl.connect_default_ciphers)
8117 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05008118#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02008119 if (global_ssl.listen_default_ciphersuites)
8120 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
8121 if (global_ssl.connect_default_ciphersuites)
8122 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
8123#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01008124
Willy Tarreau13e14102016-12-22 20:25:26 +01008125 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02008126#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02008127 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08008128#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05008129#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02008130 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05008131 n = sk_SSL_COMP_num(cm);
8132 while (n--) {
8133 (void) sk_SSL_COMP_pop(cm);
8134 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05008135#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05008136
Willy Tarreau5db847a2019-05-09 14:13:35 +02008137#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02008138 ssl_locking_init();
8139#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05008140#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01008141 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
8142#endif
William Lallemand76b4a122020-08-04 17:41:39 +02008143
8144#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
8145 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
8146#endif
8147
Thierry FOURNIER28962c92018-06-17 21:37:05 +02008148 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02008149 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 +01008150#ifdef USE_QUIC
8151 ssl_qc_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
8152#endif /* USE_QUIC */
William Lallemand722180a2021-06-09 16:46:12 +02008153#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02008154 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
8155#endif
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02008156 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 +01008157 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 +02008158#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00008159 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00008160 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02008161#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01008162#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
8163 hap_register_post_check(tlskeys_finalize_config);
8164#endif
Willy Tarreau80713382018-11-26 10:19:54 +01008165
8166 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
8167 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
8168
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01008169 hap_register_post_deinit(ssl_free_global_issuers);
8170
Willy Tarreau80713382018-11-26 10:19:54 +01008171#ifndef OPENSSL_NO_DH
8172 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
8173 hap_register_post_deinit(ssl_free_dh);
8174#endif
William Lallemandd7bfbe22022-04-11 18:41:24 +02008175#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Willy Tarreau80713382018-11-26 10:19:54 +01008176 hap_register_post_deinit(ssl_free_engines);
8177#endif
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02008178#ifdef HAVE_SSL_PROVIDERS
8179 hap_register_post_deinit(ssl_unload_providers);
8180#endif
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01008181#if HA_OPENSSL_VERSION_NUMBER < 0x3000000fL
Willy Tarreau80713382018-11-26 10:19:54 +01008182 /* Load SSL string for the verbose & debug mode. */
8183 ERR_load_SSL_strings();
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01008184#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02008185 ha_meth = BIO_meth_new(0x666, "ha methods");
8186 BIO_meth_set_write(ha_meth, ha_ssl_write);
8187 BIO_meth_set_read(ha_meth, ha_ssl_read);
8188 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
8189 BIO_meth_set_create(ha_meth, ha_ssl_new);
8190 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
8191 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
8192 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02008193
8194 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02008195
Dragan Dosen9ac98092020-05-11 15:51:45 +02008196 /* Try to register dedicated SSL/TLS protocol message callbacks for
8197 * heartbleed attack (CVE-2014-0160) and clienthello.
8198 */
8199 hap_register_post_check(ssl_sock_register_msg_callbacks);
8200
Dragan Dosen1e7ed042020-05-08 18:30:00 +02008201 /* Try to free all callbacks that were registered by using
8202 * ssl_sock_register_msg_callback().
8203 */
8204 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01008205}
Willy Tarreau79367f92022-04-25 19:18:24 +02008206INITCALL0(STG_REGISTER, __ssl_sock_init);
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01008207
Willy Tarreau80713382018-11-26 10:19:54 +01008208/* Compute and register the version string */
8209static void ssl_register_build_options()
8210{
8211 char *ptr = NULL;
8212 int i;
8213
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008214 memprintf(&ptr, "Built with OpenSSL version : "
8215#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01008216 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008217#else /* OPENSSL_IS_BORINGSSL */
8218 OPENSSL_VERSION_TEXT
8219 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08008220 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02008221 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008222#endif
8223 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02008224#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008225 "no (library version too old)"
8226#elif defined(OPENSSL_NO_TLSEXT)
8227 "no (disabled via OPENSSL_NO_TLSEXT)"
8228#else
8229 "yes"
8230#endif
8231 "", ptr);
8232
8233 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
8234#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
8235 "yes"
8236#else
8237#ifdef OPENSSL_NO_TLSEXT
8238 "no (because of OPENSSL_NO_TLSEXT)"
8239#else
8240 "no (version might be too old, 0.9.8f min needed)"
8241#endif
8242#endif
8243 "", ptr);
8244
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02008245 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
8246 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
8247 if (methodVersions[i].option)
8248 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01008249
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02008250#ifdef HAVE_SSL_PROVIDERS
8251 {
8252 struct list provider_names;
8253 struct provider_name *name;
8254 LIST_INIT(&provider_names);
8255 ssl_provider_get_name_list(&provider_names);
8256
8257 memprintf(&ptr, "%s\nOpenSSL providers loaded :", ptr);
8258
8259 list_for_each_entry(name, &provider_names, list) {
8260 memprintf(&ptr, "%s %s", ptr, name->name);
8261 }
8262
8263 ssl_provider_clear_name_list(&provider_names);
8264 }
8265#endif
8266
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008267 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01008268}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008269
Willy Tarreau80713382018-11-26 10:19:54 +01008270INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02008271
William Lallemandd7bfbe22022-04-11 18:41:24 +02008272#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00008273void ssl_free_engines(void) {
8274 struct ssl_engine_list *wl, *wlb;
8275 /* free up engine list */
8276 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
8277 ENGINE_finish(wl->e);
8278 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02008279 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00008280 free(wl);
8281 }
8282}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02008283#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02008284
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02008285#ifdef HAVE_SSL_PROVIDERS
8286void ssl_unload_providers(void) {
8287 struct ssl_provider_list *prov, *provb;
8288 list_for_each_entry_safe(prov, provb, &openssl_providers, list) {
8289 OSSL_PROVIDER_unload(prov->provider);
8290 LIST_DELETE(&prov->list);
8291 free(prov);
8292 }
8293}
8294#endif
8295
Remi Gacogned3a23c32015-05-28 16:39:47 +02008296#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00008297void ssl_free_dh(void) {
8298 if (local_dh_1024) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008299 HASSL_DH_free(local_dh_1024);
Grant Zhang872f9c22017-01-21 01:10:18 +00008300 local_dh_1024 = NULL;
8301 }
8302 if (local_dh_2048) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008303 HASSL_DH_free(local_dh_2048);
Grant Zhang872f9c22017-01-21 01:10:18 +00008304 local_dh_2048 = NULL;
8305 }
8306 if (local_dh_4096) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008307 HASSL_DH_free(local_dh_4096);
Grant Zhang872f9c22017-01-21 01:10:18 +00008308 local_dh_4096 = NULL;
8309 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02008310 if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008311 HASSL_DH_free(global_dh);
Remi Gacogne47783ef2015-05-29 15:53:22 +02008312 global_dh = NULL;
8313 }
Grant Zhang872f9c22017-01-21 01:10:18 +00008314}
8315#endif
8316
Grant Zhang872f9c22017-01-21 01:10:18 +00008317static void __ssl_sock_deinit(void)
8318{
8319#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02008320 if (ssl_ctx_lru_tree) {
8321 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01008322 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02008323 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02008324#endif
8325
Willy Tarreau5db847a2019-05-09 14:13:35 +02008326#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02008327 ERR_remove_state(0);
8328 ERR_free_strings();
8329
8330 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08008331#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02008332
Willy Tarreau5db847a2019-05-09 14:13:35 +02008333#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02008334 CRYPTO_cleanup_all_ex_data();
8335#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02008336 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02008337}
Willy Tarreau79367f92022-04-25 19:18:24 +02008338REGISTER_POST_DEINIT(__ssl_sock_deinit);
Remi Gacogned3a23c32015-05-28 16:39:47 +02008339
William Dauchyf6370442020-11-14 19:25:33 +01008340
Emeric Brun46591952012-05-18 15:47:34 +02008341/*
8342 * Local variables:
8343 * c-indent-level: 8
8344 * c-basic-offset: 8
8345 * End:
8346 */