blob: cf918ae4ccf9450d02c5026ce202cf9ee34f230d [file] [log] [blame]
yanbzhu08ce6ab2015-12-02 13:01:29 -05001
Emeric Brun46591952012-05-18 15:47:34 +02002/*
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02003 * SSL/TLS transport layer over SOCK_STREAM sockets
Emeric Brun46591952012-05-18 15:47:34 +02004 *
5 * Copyright (C) 2012 EXCELIANCE, Emeric Brun <ebrun@exceliance.fr>
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version
10 * 2 of the License, or (at your option) any later version.
11 *
Willy Tarreau69845df2012-09-10 09:43:09 +020012 * Acknowledgement:
13 * We'd like to specially thank the Stud project authors for a very clean
14 * and well documented code which helped us understand how the OpenSSL API
15 * ought to be used in non-blocking mode. This is one difficult part which
16 * is not easy to get from the OpenSSL doc, and reading the Stud code made
17 * it much more obvious than the examples in the OpenSSL package. Keep up
18 * the good works, guys !
19 *
20 * Stud is an extremely efficient and scalable SSL/TLS proxy which combines
21 * particularly well with haproxy. For more info about this project, visit :
22 * https://github.com/bumptech/stud
23 *
Emeric Brun46591952012-05-18 15:47:34 +020024 */
25
Willy Tarreau8d164dc2019-05-10 09:35:00 +020026/* Note: do NOT include openssl/xxx.h here, do it in openssl-compat.h */
Emeric Brun46591952012-05-18 15:47:34 +020027#define _GNU_SOURCE
Emeric Brunfc0421f2012-09-07 17:30:07 +020028#include <ctype.h>
29#include <dirent.h>
Emeric Brun46591952012-05-18 15:47:34 +020030#include <errno.h>
Emeric Brun46591952012-05-18 15:47:34 +020031#include <stdio.h>
32#include <stdlib.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020033#include <string.h>
34#include <unistd.h>
Emeric Brun46591952012-05-18 15:47:34 +020035
36#include <sys/socket.h>
37#include <sys/stat.h>
38#include <sys/types.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020039#include <netdb.h>
Emeric Brun46591952012-05-18 15:47:34 +020040#include <netinet/tcp.h>
41
Willy Tarreaub2551052020-06-09 09:07:15 +020042#include <import/ebpttree.h>
43#include <import/ebsttree.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020044#include <import/lru.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020045
Willy Tarreaub2551052020-06-09 09:07:15 +020046#include <haproxy/api.h>
Willy Tarreaua9380522022-05-05 08:50:17 +020047#include <haproxy/applet.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020048#include <haproxy/arg.h>
49#include <haproxy/base64.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020050#include <haproxy/channel.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020051#include <haproxy/chunk.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020052#include <haproxy/cli.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020053#include <haproxy/connection.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020054#include <haproxy/dynbuf.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020055#include <haproxy/errors.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020056#include <haproxy/fd.h>
57#include <haproxy/freq_ctr.h>
Willy Tarreau762d7a52020-06-04 11:23:07 +020058#include <haproxy/frontend.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020059#include <haproxy/global.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020060#include <haproxy/http_rules.h>
Willy Tarreauaeed4a82020-06-04 22:01:04 +020061#include <haproxy/log.h>
Willy Tarreau6019fab2020-05-27 16:26:00 +020062#include <haproxy/openssl-compat.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020063#include <haproxy/pattern-t.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020064#include <haproxy/proto_tcp.h>
Willy Tarreaua264d962020-06-04 22:29:18 +020065#include <haproxy/proxy.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020066#include <haproxy/sample.h>
67#include <haproxy/sc_strm.h>
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020068#include <haproxy/quic_conn.h>
Frédéric Lécaille748ece62022-05-21 23:58:40 +020069#include <haproxy/quic_tp.h>
Willy Tarreau1e56f922020-06-04 23:20:13 +020070#include <haproxy/server.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020071#include <haproxy/shctx.h>
Willy Tarreau47d7f902020-06-04 14:25:47 +020072#include <haproxy/ssl_ckch.h>
Willy Tarreau52d88722020-06-04 14:29:23 +020073#include <haproxy/ssl_crtlist.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020074#include <haproxy/ssl_sock.h>
Willy Tarreaub2bd8652020-06-04 14:21:22 +020075#include <haproxy/ssl_utils.h>
Amaury Denoyelle9963fa72020-11-03 17:10:00 +010076#include <haproxy/stats.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020077#include <haproxy/stconn.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020078#include <haproxy/stream-t.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020079#include <haproxy/task.h>
Willy Tarreauc2f7c582020-06-02 18:15:32 +020080#include <haproxy/ticks.h>
Willy Tarreau92b4f132020-06-01 11:05:15 +020081#include <haproxy/time.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020082#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020083#include <haproxy/vars.h>
Tim Duesterhusd5fc8fc2021-09-11 17:51:13 +020084#include <haproxy/xxhash.h>
Remi Tricot-Le Breton2e7d1eb2022-01-11 10:11:10 +010085#include <haproxy/istbuf.h>
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +010086#include <haproxy/http_client.h>
Emeric Brun46591952012-05-18 15:47:34 +020087
Emeric Brun46591952012-05-18 15:47:34 +020088
Willy Tarreau9356dac2019-05-10 09:22:53 +020089/* ***** READ THIS before adding code here! *****
90 *
91 * Due to API incompatibilities between multiple OpenSSL versions and their
92 * derivatives, it's often tempting to add macros to (re-)define certain
93 * symbols. Please do not do this here, and do it in common/openssl-compat.h
94 * exclusively so that the whole code consistently uses the same macros.
95 *
96 * Whenever possible if a macro is missing in certain versions, it's better
97 * to conditionally define it in openssl-compat.h than using lots of ifdefs.
98 */
99
Emeric Brunece0c332017-12-06 13:51:49 +0100100int nb_engines = 0;
Emeric Brune1f38db2012-09-03 20:36:47 +0200101
William Lallemande0f3fd52020-02-25 14:53:06 +0100102static struct eb_root cert_issuer_tree = EB_ROOT; /* issuers tree from "issuers-chain-path" */
103
William Lallemand7fd8b452020-05-07 15:20:43 +0200104struct global_ssl global_ssl = {
Willy Tarreauef934602016-12-22 23:12:01 +0100105#ifdef LISTEN_DEFAULT_CIPHERS
106 .listen_default_ciphers = LISTEN_DEFAULT_CIPHERS,
107#endif
108#ifdef CONNECT_DEFAULT_CIPHERS
109 .connect_default_ciphers = CONNECT_DEFAULT_CIPHERS,
110#endif
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +0500111#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200112 .listen_default_ciphersuites = LISTEN_DEFAULT_CIPHERSUITES,
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200113 .connect_default_ciphersuites = CONNECT_DEFAULT_CIPHERSUITES,
114#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100115 .listen_default_ssloptions = BC_SSL_O_NONE,
116 .connect_default_ssloptions = SRV_SSL_O_NONE,
117
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +0200118 .listen_default_sslmethods.flags = MC_SSL_O_ALL,
119 .listen_default_sslmethods.min = CONF_TLSV_NONE,
120 .listen_default_sslmethods.max = CONF_TLSV_NONE,
121 .connect_default_sslmethods.flags = MC_SSL_O_ALL,
122 .connect_default_sslmethods.min = CONF_TLSV_NONE,
123 .connect_default_sslmethods.max = CONF_TLSV_NONE,
124
Willy Tarreauef934602016-12-22 23:12:01 +0100125#ifdef DEFAULT_SSL_MAX_RECORD
126 .max_record = DEFAULT_SSL_MAX_RECORD,
127#endif
Thomas Prückl10243932022-04-27 13:04:54 +0200128 .hard_max_record = 0,
Willy Tarreauef934602016-12-22 23:12:01 +0100129 .default_dh_param = SSL_DEFAULT_DH_PARAM,
130 .ctx_cache = DEFAULT_SSL_CTX_CACHE,
Marcin Deranek310a2602021-07-13 19:04:24 +0200131 .capture_buffer_size = 0,
William Lallemand3af48e72020-02-03 17:15:52 +0100132 .extra_files = SSL_GF_ALL,
William Lallemand8e8581e2020-10-20 17:36:46 +0200133 .extra_files_noext = 0,
William Lallemand722180a2021-06-09 16:46:12 +0200134#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200135 .keylog = 0
136#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100137};
138
Olivier Houcharda8955d52019-04-07 22:00:38 +0200139static BIO_METHOD *ha_meth;
140
Willy Tarreaub8dec4a2022-06-23 11:02:08 +0200141DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx", sizeof(struct ssl_sock_ctx));
Olivier Houchard66ab4982019-02-26 18:37:15 +0100142
Willy Tarreaub8dec4a2022-06-23 11:02:08 +0200143DECLARE_STATIC_POOL(ssl_sock_client_sni_pool, "ssl_sock_client_sni", TLSEXT_MAXLEN_host_name + 1);
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100144
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100145/* ssl stats module */
146enum {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100147 SSL_ST_SESS,
148 SSL_ST_REUSED_SESS,
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100149 SSL_ST_FAILED_HANDSHAKE,
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100150
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100151 SSL_ST_STATS_COUNT /* must be the last member of the enum */
152};
153
154static struct name_desc ssl_stats[] = {
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100155 [SSL_ST_SESS] = { .name = "ssl_sess",
156 .desc = "Total number of ssl sessions established" },
157 [SSL_ST_REUSED_SESS] = { .name = "ssl_reused_sess",
158 .desc = "Total number of ssl sessions reused" },
159 [SSL_ST_FAILED_HANDSHAKE] = { .name = "ssl_failed_handshake",
160 .desc = "Total number of failed handshake" },
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100161};
162
163static struct ssl_counters {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100164 long long sess;
165 long long reused_sess;
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100166 long long failed_handshake;
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100167} ssl_counters;
168
169static void ssl_fill_stats(void *data, struct field *stats)
170{
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100171 struct ssl_counters *counters = data;
172
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100173 stats[SSL_ST_SESS] = mkf_u64(FN_COUNTER, counters->sess);
174 stats[SSL_ST_REUSED_SESS] = mkf_u64(FN_COUNTER, counters->reused_sess);
175 stats[SSL_ST_FAILED_HANDSHAKE] = mkf_u64(FN_COUNTER, counters->failed_handshake);
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100176}
177
178static struct stats_module ssl_stats_module = {
179 .name = "ssl",
180 .fill_stats = ssl_fill_stats,
181 .stats = ssl_stats,
182 .stats_count = SSL_ST_STATS_COUNT,
183 .counters = &ssl_counters,
184 .counters_size = sizeof(ssl_counters),
185 .domain_flags = MK_STATS_PROXY_DOMAIN(STATS_PX_CAP_FE|STATS_PX_CAP_LI|STATS_PX_CAP_BE|STATS_PX_CAP_SRV),
186 .clearable = 1,
187};
188
189INITCALL1(STG_REGISTER, stats_register_module, &ssl_stats_module);
190
Willy Tarreaua9380522022-05-05 08:50:17 +0200191/* CLI context for "show tls-keys" */
192struct show_keys_ctx {
193 struct tls_keys_ref *next_ref; /* next reference to be dumped */
194 int names_only; /* non-zero = only show file names */
195 int next_index; /* next index to be dumped */
Willy Tarreaubd338642022-05-05 08:59:17 +0200196 int dump_entries; /* dump entries also */
Willy Tarreau9c5a38c2022-05-05 09:03:44 +0200197 enum {
198 SHOW_KEYS_INIT = 0,
199 SHOW_KEYS_LIST,
200 SHOW_KEYS_DONE,
201 } state; /* phase of the current dump */
Willy Tarreaua9380522022-05-05 08:50:17 +0200202};
203
Willy Tarreau691d5032021-01-20 14:55:01 +0100204/* ssl_sock_io_cb is exported to see it resolved in "show fd" */
Willy Tarreau144f84a2021-03-02 16:09:26 +0100205struct task *ssl_sock_io_cb(struct task *, void *, unsigned int);
Olivier Houchard000694c2019-05-23 14:45:12 +0200206static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
Olivier Houchardea8dd942019-05-20 14:02:16 +0200207
Olivier Houcharda8955d52019-04-07 22:00:38 +0200208/* Methods to implement OpenSSL BIO */
209static int ha_ssl_write(BIO *h, const char *buf, int num)
210{
211 struct buffer tmpbuf;
212 struct ssl_sock_ctx *ctx;
213 int ret;
214
215 ctx = BIO_get_data(h);
216 tmpbuf.size = num;
217 tmpbuf.area = (void *)(uintptr_t)buf;
218 tmpbuf.data = num;
219 tmpbuf.head = 0;
220 ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200221 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200222 BIO_set_retry_write(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200223 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200224 } else if (ret == 0)
225 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200226 return ret;
227}
228
229static int ha_ssl_gets(BIO *h, char *buf, int size)
230{
231
232 return 0;
233}
234
235static int ha_ssl_puts(BIO *h, const char *str)
236{
237
238 return ha_ssl_write(h, str, strlen(str));
239}
240
241static int ha_ssl_read(BIO *h, char *buf, int size)
242{
243 struct buffer tmpbuf;
244 struct ssl_sock_ctx *ctx;
245 int ret;
246
247 ctx = BIO_get_data(h);
248 tmpbuf.size = size;
249 tmpbuf.area = buf;
250 tmpbuf.data = 0;
251 tmpbuf.head = 0;
252 ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200253 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200254 BIO_set_retry_read(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200255 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200256 } else if (ret == 0)
257 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200258
259 return ret;
260}
261
262static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
263{
264 int ret = 0;
265 switch (cmd) {
266 case BIO_CTRL_DUP:
267 case BIO_CTRL_FLUSH:
268 ret = 1;
269 break;
270 }
271 return ret;
272}
273
274static int ha_ssl_new(BIO *h)
275{
276 BIO_set_init(h, 1);
277 BIO_set_data(h, NULL);
278 BIO_clear_flags(h, ~0);
279 return 1;
280}
281
282static int ha_ssl_free(BIO *data)
283{
284
285 return 1;
286}
287
288
Willy Tarreau5db847a2019-05-09 14:13:35 +0200289#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100290
Emeric Brun821bb9b2017-06-15 16:37:39 +0200291static HA_RWLOCK_T *ssl_rwlocks;
292
293
294unsigned long ssl_id_function(void)
295{
296 return (unsigned long)tid;
297}
298
299void ssl_locking_function(int mode, int n, const char * file, int line)
300{
301 if (mode & CRYPTO_LOCK) {
302 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100303 HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200304 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100305 HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200306 }
307 else {
308 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100309 HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200310 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100311 HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200312 }
313}
314
315static int ssl_locking_init(void)
316{
317 int i;
318
319 ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
320 if (!ssl_rwlocks)
321 return -1;
322
323 for (i = 0 ; i < CRYPTO_num_locks() ; i++)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100324 HA_RWLOCK_INIT(&ssl_rwlocks[i]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200325
326 CRYPTO_set_id_callback(ssl_id_function);
327 CRYPTO_set_locking_callback(ssl_locking_function);
328
329 return 0;
330}
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100331
Emeric Brun821bb9b2017-06-15 16:37:39 +0200332#endif
333
Willy Tarreauaf613e82020-06-05 08:40:51 +0200334__decl_thread(HA_SPINLOCK_T ckch_lock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200335
William Lallemandbc6ca7c2019-10-29 23:48:19 +0100336
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200337
338/* mimic what X509_STORE_load_locations do with store_ctx */
339static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
340{
Remi Tricot-Le Bretond75b99e2021-05-17 11:45:55 +0200341 X509_STORE *store = NULL;
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +0100342 struct cafile_entry *ca_e = ssl_store_get_cafile_entry(path, 0);
343 if (ca_e)
344 store = ca_e->ca_store;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200345 if (store_ctx && store) {
346 int i;
347 X509_OBJECT *obj;
348 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
349 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
350 obj = sk_X509_OBJECT_value(objs, i);
351 switch (X509_OBJECT_get_type(obj)) {
352 case X509_LU_X509:
353 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
354 break;
355 case X509_LU_CRL:
356 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
357 break;
358 default:
359 break;
360 }
361 }
362 return 1;
363 }
364 return 0;
365}
366
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500367/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200368static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
369{
370 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
371 return ssl_set_cert_crl_file(store_ctx, path);
372}
373
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200374/*
375 Extract CA_list from CA_file already in tree.
376 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
377 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
378*/
379static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
380{
381 struct ebmb_node *eb;
382 struct cafile_entry *ca_e;
383
384 eb = ebst_lookup(&cafile_tree, path);
385 if (!eb)
386 return NULL;
387 ca_e = ebmb_entry(eb, struct cafile_entry, node);
388
389 if (ca_e->ca_list == NULL) {
390 int i;
391 unsigned long key;
392 struct eb_root ca_name_tree = EB_ROOT;
393 struct eb64_node *node, *back;
394 struct {
395 struct eb64_node node;
396 X509_NAME *xname;
397 } *ca_name;
398 STACK_OF(X509_OBJECT) *objs;
399 STACK_OF(X509_NAME) *skn;
400 X509 *x;
401 X509_NAME *xn;
402
403 skn = sk_X509_NAME_new_null();
404 /* take x509 from cafile_tree */
405 objs = X509_STORE_get0_objects(ca_e->ca_store);
406 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
407 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
408 if (!x)
409 continue;
410 xn = X509_get_subject_name(x);
411 if (!xn)
412 continue;
413 /* Check for duplicates. */
414 key = X509_NAME_hash(xn);
415 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
416 node && ca_name == NULL;
417 node = eb64_next(node)) {
418 ca_name = container_of(node, typeof(*ca_name), node);
419 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
420 ca_name = NULL;
421 }
422 /* find a duplicate */
423 if (ca_name)
424 continue;
425 ca_name = calloc(1, sizeof *ca_name);
426 xn = X509_NAME_dup(xn);
427 if (!ca_name ||
428 !xn ||
429 !sk_X509_NAME_push(skn, xn)) {
430 free(ca_name);
431 X509_NAME_free(xn);
432 sk_X509_NAME_pop_free(skn, X509_NAME_free);
433 sk_X509_NAME_free(skn);
434 skn = NULL;
435 break;
436 }
437 ca_name->node.key = key;
438 ca_name->xname = xn;
439 eb64_insert(&ca_name_tree, &ca_name->node);
440 }
441 ca_e->ca_list = skn;
442 /* remove temporary ca_name tree */
443 node = eb64_first(&ca_name_tree);
444 while (node) {
445 ca_name = container_of(node, typeof(*ca_name), node);
446 back = eb64_next(node);
447 eb64_delete(node);
448 free(ca_name);
449 node = back;
450 }
451 }
452 return ca_e->ca_list;
453}
454
Willy Tarreauff882702021-04-10 17:23:00 +0200455struct pool_head *pool_head_ssl_capture __read_mostly = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200456int ssl_capture_ptr_index = -1;
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +0100457int ssl_app_data_index = -1;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +0100458#ifdef USE_QUIC
459int ssl_qc_app_data_index = -1;
460#endif /* USE_QUIC */
Willy Tarreauef934602016-12-22 23:12:01 +0100461
William Lallemand722180a2021-06-09 16:46:12 +0200462#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200463int ssl_keylog_index = -1;
Willy Tarreauff882702021-04-10 17:23:00 +0200464struct pool_head *pool_head_ssl_keylog __read_mostly = NULL;
465struct pool_head *pool_head_ssl_keylog_str __read_mostly = NULL;
William Lallemand7d42ef52020-07-06 11:41:30 +0200466#endif
467
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +0200468int ssl_client_crt_ref_index = -1;
469
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100470/* Used to store the client's SNI in case of ClientHello callback error */
471int ssl_client_sni_index = -1;
472
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200473#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
474struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
475#endif
476
William Lallemandd7bfbe22022-04-11 18:41:24 +0200477#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200478unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000479struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
480struct ssl_engine_list {
481 struct list list;
482 ENGINE *e;
483};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200484#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000485
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +0200486#ifdef HAVE_SSL_PROVIDERS
487struct list openssl_providers = LIST_HEAD_INIT(openssl_providers);
488struct ssl_provider_list {
489 struct list list;
490 OSSL_PROVIDER *provider;
491};
492#endif
493
Remi Gacogne8de54152014-07-15 11:36:40 +0200494#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200495static int ssl_dh_ptr_index = -1;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +0100496static HASSL_DH *global_dh = NULL;
497static HASSL_DH *local_dh_1024 = NULL;
498static HASSL_DH *local_dh_2048 = NULL;
499static HASSL_DH *local_dh_4096 = NULL;
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100500#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +0100501static DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100502#else
503static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey);
504#endif
Remi Gacogne8de54152014-07-15 11:36:40 +0200505#endif /* OPENSSL_NO_DH */
506
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100507#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200508/* X509V3 Extensions that will be added on generated certificates */
509#define X509V3_EXT_SIZE 5
510static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
511 "basicConstraints",
512 "nsComment",
513 "subjectKeyIdentifier",
514 "authorityKeyIdentifier",
515 "keyUsage",
516};
517static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
518 "CA:FALSE",
519 "\"OpenSSL Generated Certificate\"",
520 "hash",
521 "keyid,issuer:always",
522 "nonRepudiation,digitalSignature,keyEncipherment"
523};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200524/* LRU cache to store generated certificate */
525static struct lru64_head *ssl_ctx_lru_tree = NULL;
526static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200527static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100528__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200529
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200530#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
531
yanbzhube2774d2015-12-10 15:07:30 -0500532/* The order here matters for picking a default context,
533 * keep the most common keytype at the bottom of the list
534 */
535const char *SSL_SOCK_KEYTYPE_NAMES[] = {
536 "dsa",
537 "ecdsa",
538 "rsa"
539};
yanbzhube2774d2015-12-10 15:07:30 -0500540
William Lallemandc3cd35f2017-11-28 11:04:43 +0100541static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100542static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
543
Dragan Dosen9ac98092020-05-11 15:51:45 +0200544/* Dedicated callback functions for heartbeat and clienthello.
545 */
546#ifdef TLS1_RT_HEARTBEAT
547static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
548 int content_type, const void *buf, size_t len,
549 SSL *ssl);
550#endif
551static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
552 int content_type, const void *buf, size_t len,
553 SSL *ssl);
554
William Lallemand722180a2021-06-09 16:46:12 +0200555#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200556static void ssl_init_keylog(struct connection *conn, int write_p, int version,
557 int content_type, const void *buf, size_t len,
558 SSL *ssl);
559#endif
560
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200561/* List head of all registered SSL/TLS protocol message callbacks. */
562struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
563
564/* Registers the function <func> in order to be called on SSL/TLS protocol
565 * message processing. It will return 0 if the function <func> is not set
566 * or if it fails to allocate memory.
567 */
568int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
569{
570 struct ssl_sock_msg_callback *cbk;
571
572 if (!func)
573 return 0;
574
575 cbk = calloc(1, sizeof(*cbk));
576 if (!cbk) {
577 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
578 return 0;
579 }
580
581 cbk->func = func;
582
Willy Tarreau2b718102021-04-21 07:32:39 +0200583 LIST_APPEND(&ssl_sock_msg_callbacks, &cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200584
585 return 1;
586}
587
Dragan Dosen9ac98092020-05-11 15:51:45 +0200588/* Used to register dedicated SSL/TLS protocol message callbacks.
589 */
590static int ssl_sock_register_msg_callbacks(void)
591{
592#ifdef TLS1_RT_HEARTBEAT
593 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
594 return ERR_ABORT;
595#endif
Marcin Deranek310a2602021-07-13 19:04:24 +0200596 if (global_ssl.capture_buffer_size > 0) {
Dragan Dosen9ac98092020-05-11 15:51:45 +0200597 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
598 return ERR_ABORT;
599 }
William Lallemand722180a2021-06-09 16:46:12 +0200600#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200601 if (global_ssl.keylog > 0) {
602 if (!ssl_sock_register_msg_callback(ssl_init_keylog))
603 return ERR_ABORT;
604 }
605#endif
606
Christopher Fauletfc633b62020-11-06 15:24:23 +0100607 return ERR_NONE;
Dragan Dosen9ac98092020-05-11 15:51:45 +0200608}
609
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200610/* Used to free all SSL/TLS protocol message callbacks that were
611 * registered by using ssl_sock_register_msg_callback().
612 */
613static void ssl_sock_unregister_msg_callbacks(void)
614{
615 struct ssl_sock_msg_callback *cbk, *cbkback;
616
617 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +0200618 LIST_DELETE(&cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200619 free(cbk);
620 }
621}
622
Willy Tarreaude827952022-04-11 10:43:28 +0200623static struct ssl_sock_ctx *ssl_sock_get_ctx(struct connection *conn)
624{
625 if (!conn || conn->xprt != xprt_get(XPRT_SSL) || !conn->xprt_ctx)
626 return NULL;
627
628 return (struct ssl_sock_ctx *)conn->xprt_ctx;
629}
630
Dragan Doseneb607fe2020-05-11 17:17:06 +0200631SSL *ssl_sock_get_ssl_object(struct connection *conn)
632{
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200633 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dragan Doseneb607fe2020-05-11 17:17:06 +0200634
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200635 return ctx ? ctx->ssl : NULL;
Dragan Doseneb607fe2020-05-11 17:17:06 +0200636}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100637/*
638 * This function gives the detail of the SSL error. It is used only
639 * if the debug mode and the verbose mode are activated. It dump all
640 * the SSL error until the stack was empty.
641 */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +0200642static forceinline void ssl_sock_dump_errors(struct connection *conn,
643 struct quic_conn *qc)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100644{
645 unsigned long ret;
646
647 if (unlikely(global.mode & MODE_DEBUG)) {
648 while(1) {
Remi Tricot-Le Breton1effd9a2022-02-11 12:04:44 +0100649 const char *func = NULL;
650 ERR_peek_error_func(&func);
651
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100652 ret = ERR_get_error();
653 if (ret == 0)
654 return;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +0200655 if (conn) {
656 fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
657 conn_fd(conn), ret,
658 func, ERR_reason_error_string(ret));
659 }
660#ifdef USE_QUIC
661 else {
662 /* TODO: we are not sure <conn> is always initialized for QUIC connections */
663 fprintf(stderr, "qc @%p OpenSSL error[0x%lx] %s: %s\n", qc, ret,
664 func, ERR_reason_error_string(ret));
665 }
666#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100667 }
668 }
669}
670
yanbzhube2774d2015-12-10 15:07:30 -0500671
William Lallemandd7bfbe22022-04-11 18:41:24 +0200672#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200673int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000674{
675 int err_code = ERR_ABORT;
676 ENGINE *engine;
677 struct ssl_engine_list *el;
678
679 /* grab the structural reference to the engine */
680 engine = ENGINE_by_id(engine_id);
681 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100682 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000683 goto fail_get;
684 }
685
686 if (!ENGINE_init(engine)) {
687 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100688 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000689 goto fail_init;
690 }
691
692 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100693 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000694 goto fail_set_method;
695 }
696
697 el = calloc(1, sizeof(*el));
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200698 if (!el)
699 goto fail_alloc;
Grant Zhang872f9c22017-01-21 01:10:18 +0000700 el->e = engine;
Willy Tarreau2b718102021-04-21 07:32:39 +0200701 LIST_INSERT(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100702 nb_engines++;
703 if (global_ssl.async)
704 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000705 return 0;
706
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200707fail_alloc:
Grant Zhang872f9c22017-01-21 01:10:18 +0000708fail_set_method:
709 /* release the functional reference from ENGINE_init() */
710 ENGINE_finish(engine);
711
712fail_init:
713 /* release the structural reference from ENGINE_by_id() */
714 ENGINE_free(engine);
715
716fail_get:
717 return err_code;
718}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200719#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000720
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +0200721#ifdef HAVE_SSL_PROVIDERS
722int ssl_init_provider(const char *provider_name)
723{
724 int err_code = ERR_ABORT;
725 struct ssl_provider_list *prov = NULL;
726
727 prov = calloc(1, sizeof(*prov));
728 if (!prov) {
729 ha_alert("ssl-provider %s: memory allocation failure\n", provider_name);
730 goto error;
731 }
732
733 if ((prov->provider = OSSL_PROVIDER_load(NULL, provider_name)) == NULL) {
734 ha_alert("ssl-provider %s: unknown provider\n", provider_name);
735 goto error;
736 }
737
738 LIST_INSERT(&openssl_providers, &prov->list);
739
740 return 0;
741
742error:
743 ha_free(&prov);
744 return err_code;
745}
746#endif /* HAVE_SSL_PROVIDERS */
747
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +0500748#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +0200749/*
750 * openssl async fd handler
751 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200752void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000753{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200754 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000755
Emeric Brun3854e012017-05-17 20:42:48 +0200756 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000757 * to poll this fd until it is requested
758 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000759 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000760 fd_cant_recv(fd);
761
762 /* crypto engine is available, let's notify the associated
763 * connection that it can pursue its processing.
764 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200765 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000766}
767
Emeric Brun3854e012017-05-17 20:42:48 +0200768/*
769 * openssl async delayed SSL_free handler
770 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200771void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000772{
773 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200774 OSSL_ASYNC_FD all_fd[32];
775 size_t num_all_fds = 0;
776 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000777
Emeric Brun3854e012017-05-17 20:42:48 +0200778 /* We suppose that the async job for a same SSL *
779 * are serialized. So if we are awake it is
780 * because the running job has just finished
781 * and we can remove all async fds safely
782 */
783 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
784 if (num_all_fds > 32) {
785 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
786 return;
787 }
788
789 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
Emeric Brun7d392a52022-07-01 17:36:50 +0200790 for (i=0 ; i < num_all_fds ; i++) {
791 /* We want to remove the fd from the fdtab
792 * but we flag it to disown because the
793 * close is performed by the engine itself
794 */
795 fdtab[all_fd[i]].state |= FD_DISOWN;
796 fd_delete(all_fd[i]);
797 }
Emeric Brun3854e012017-05-17 20:42:48 +0200798
799 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000800 SSL_free(ssl);
Willy Tarreau82531f62021-10-06 12:15:18 +0200801 _HA_ATOMIC_DEC(&global.sslconns);
Willy Tarreau4781b152021-04-06 13:53:36 +0200802 _HA_ATOMIC_DEC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000803}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000804/*
Emeric Brun3854e012017-05-17 20:42:48 +0200805 * function used to manage a returned SSL_ERROR_WANT_ASYNC
806 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000807 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200808static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000809{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100810 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200811 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200812 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000813 size_t num_add_fds = 0;
814 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200815 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000816
817 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
818 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200819 if (num_add_fds > 32 || num_del_fds > 32) {
820 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000821 return;
822 }
823
Emeric Brun3854e012017-05-17 20:42:48 +0200824 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000825
Emeric Brun3854e012017-05-17 20:42:48 +0200826 /* We remove unused fds from the fdtab */
Emeric Brun7d392a52022-07-01 17:36:50 +0200827 for (i=0 ; i < num_del_fds ; i++) {
828 /* We want to remove the fd from the fdtab
829 * but we flag it to disown because the
830 * close is performed by the engine itself
831 */
832 fdtab[del_fd[i]].state |= FD_DISOWN;
833 fd_delete(del_fd[i]);
834 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000835
Emeric Brun3854e012017-05-17 20:42:48 +0200836 /* We add new fds to the fdtab */
837 for (i=0 ; i < num_add_fds ; i++) {
Willy Tarreau27a32452022-07-07 08:29:00 +0200838 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tgid, ti->ltid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000839 }
840
Emeric Brun3854e012017-05-17 20:42:48 +0200841 num_add_fds = 0;
842 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
843 if (num_add_fds > 32) {
844 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
845 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000846 }
Emeric Brun3854e012017-05-17 20:42:48 +0200847
848 /* We activate the polling for all known async fds */
849 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000850 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200851 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000852 /* To ensure that the fd cache won't be used
853 * We'll prefer to catch a real RD event
854 * because handling an EAGAIN on this fd will
855 * result in a context switch and also
856 * some engines uses a fd in blocking mode.
857 */
858 fd_cant_recv(add_fd[i]);
859 }
Emeric Brun3854e012017-05-17 20:42:48 +0200860
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000861}
862#endif
863
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200864#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 +0200865/*
866 * This function returns the number of seconds elapsed
867 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
868 * date presented un ASN1_GENERALIZEDTIME.
869 *
870 * In parsing error case, it returns -1.
871 */
872static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
873{
874 long epoch;
875 char *p, *end;
876 const unsigned short month_offset[12] = {
877 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
878 };
Remi Tricot-Le Bretona3a0cce2021-06-09 17:16:18 +0200879 unsigned long year, month;
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200880
881 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
882
883 p = (char *)d->data;
884 end = p + d->length;
885
886 if (end - p < 4) return -1;
887 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
888 p += 4;
889 if (end - p < 2) return -1;
890 month = 10 * (p[0] - '0') + p[1] - '0';
891 if (month < 1 || month > 12) return -1;
892 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
893 We consider leap years and the current month (<marsh or not) */
894 epoch = ( ((year - 1970) * 365)
895 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
896 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
897 + month_offset[month-1]
898 ) * 24 * 60 * 60;
899 p += 2;
900 if (end - p < 2) return -1;
901 /* Add the number of seconds of completed days of current month */
902 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
903 p += 2;
904 if (end - p < 2) return -1;
905 /* Add the completed hours of the current day */
906 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
907 p += 2;
908 if (end - p < 2) return -1;
909 /* Add the completed minutes of the current hour */
910 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
911 p += 2;
912 if (p == end) return -1;
913 /* Test if there is available seconds */
914 if (p[0] < '0' || p[0] > '9')
915 goto nosec;
916 if (end - p < 2) return -1;
917 /* Add the seconds of the current minute */
918 epoch += 10 * (p[0] - '0') + p[1] - '0';
919 p += 2;
920 if (p == end) return -1;
921 /* Ignore seconds float part if present */
922 if (p[0] == '.') {
923 do {
924 if (++p == end) return -1;
925 } while (p[0] >= '0' && p[0] <= '9');
926 }
927
928nosec:
929 if (p[0] == 'Z') {
930 if (end - p != 1) return -1;
931 return epoch;
932 }
933 else if (p[0] == '+') {
934 if (end - p != 5) return -1;
935 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700936 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 +0200937 }
938 else if (p[0] == '-') {
939 if (end - p != 5) return -1;
940 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700941 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 +0200942 }
943
944 return -1;
945}
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200946#endif
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200947
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200948#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
William Lallemand104a7a62019-10-14 14:14:59 +0200949/*
950 * struct alignment works here such that the key.key is the same as key_data
951 * Do not change the placement of key_data
952 */
953struct certificate_ocsp {
954 struct ebmb_node key;
955 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
Remi Tricot-Le Breton5aa1dce2021-06-10 13:51:12 +0200956 unsigned int key_length;
William Lallemand104a7a62019-10-14 14:14:59 +0200957 struct buffer response;
William Lallemand76b4a122020-08-04 17:41:39 +0200958 int refcount;
William Lallemand104a7a62019-10-14 14:14:59 +0200959 long expire;
Remi Tricot-Le Bretonbdd3c792022-12-20 11:11:09 +0100960 struct eb64_node next_update; /* Key of items inserted in ocsp_update_tree (sorted by absolute date) */
William Lallemand104a7a62019-10-14 14:14:59 +0200961};
962
963struct ocsp_cbk_arg {
964 int is_single;
965 int single_kt;
966 union {
967 struct certificate_ocsp *s_ocsp;
968 /*
969 * m_ocsp will have multiple entries dependent on key type
970 * Entry 0 - DSA
971 * Entry 1 - ECDSA
972 * Entry 2 - RSA
973 */
974 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
975 };
976};
977
Emeric Brun1d3865b2014-06-20 15:37:32 +0200978static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200979
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +0100980__decl_thread(HA_SPINLOCK_T ocsp_tree_lock);
981
Remi Tricot-Le Bretonbdd3c792022-12-20 11:11:09 +0100982static struct eb_root ocsp_update_tree = EB_ROOT; /* updatable ocsp responses sorted by next_update in absolute time */
983#define SSL_OCSP_UPDATE_DELAY_MAX 60*60 /* 1H */
984#define SSL_OCSP_UPDATE_DELAY_MIN 5*60 /* 5 minutes */
985#define SSL_OCSP_UPDATE_MARGIN 60 /* 1 minute */
986
Emeric Brun4147b2e2014-06-16 18:36:30 +0200987/* This function starts to check if the OCSP response (in DER format) contained
988 * in chunk 'ocsp_response' is valid (else exits on error).
989 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
990 * contained in the OCSP Response and exits on error if no match.
991 * If it's a valid OCSP Response:
992 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
993 * pointed by 'ocsp'.
994 * If 'ocsp' is NULL, the function looks up into the OCSP response's
995 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
996 * from the response) and exits on error if not found. Finally, If an OCSP response is
997 * already present in the container, it will be overwritten.
998 *
999 * Note: OCSP response containing more than one OCSP Single response is not
1000 * considered valid.
1001 *
1002 * Returns 0 on success, 1 in error case.
1003 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001004static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
1005 struct certificate_ocsp *ocsp,
1006 OCSP_CERTID *cid, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001007{
1008 OCSP_RESPONSE *resp;
1009 OCSP_BASICRESP *bs = NULL;
1010 OCSP_SINGLERESP *sr;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001011 OCSP_CERTID *id;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001012 unsigned char *p = (unsigned char *) ocsp_response->area;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001013 int rc , count_sr;
Emeric Brun13a6b482014-06-20 15:44:34 +02001014 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001015 int reason;
1016 int ret = 1;
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +02001017#ifdef HAVE_ASN1_TIME_TO_TM
1018 struct tm nextupd_tm = {0};
1019#endif
Emeric Brun4147b2e2014-06-16 18:36:30 +02001020
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001021 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
1022 ocsp_response->data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001023 if (!resp) {
1024 memprintf(err, "Unable to parse OCSP response");
1025 goto out;
1026 }
1027
1028 rc = OCSP_response_status(resp);
1029 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1030 memprintf(err, "OCSP response status not successful");
1031 goto out;
1032 }
1033
1034 bs = OCSP_response_get1_basic(resp);
1035 if (!bs) {
1036 memprintf(err, "Failed to get basic response from OCSP Response");
1037 goto out;
1038 }
1039
1040 count_sr = OCSP_resp_count(bs);
1041 if (count_sr > 1) {
1042 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
1043 goto out;
1044 }
1045
1046 sr = OCSP_resp_get0(bs, 0);
1047 if (!sr) {
1048 memprintf(err, "Failed to get OCSP single response");
1049 goto out;
1050 }
1051
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001052 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
1053
Emeric Brun4147b2e2014-06-16 18:36:30 +02001054 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
Emmanuel Hocdetef607052017-10-24 14:57:16 +02001055 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
Emmanuel Hocdet872085c2017-10-10 15:18:52 +02001056 memprintf(err, "OCSP single response: certificate status is unknown");
Emeric Brun4147b2e2014-06-16 18:36:30 +02001057 goto out;
1058 }
1059
Emeric Brun13a6b482014-06-20 15:44:34 +02001060 if (!nextupd) {
1061 memprintf(err, "OCSP single response: missing nextupdate");
1062 goto out;
1063 }
1064
Emeric Brunc8b27b62014-06-19 14:16:17 +02001065 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001066 if (!rc) {
1067 memprintf(err, "OCSP single response: no longer valid.");
1068 goto out;
1069 }
1070
1071 if (cid) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001072 if (OCSP_id_cmp(id, cid)) {
Emeric Brun4147b2e2014-06-16 18:36:30 +02001073 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
1074 goto out;
1075 }
1076 }
1077
1078 if (!ocsp) {
1079 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
1080 unsigned char *p;
1081
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001082 rc = i2d_OCSP_CERTID(id, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001083 if (!rc) {
1084 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
1085 goto out;
1086 }
1087
1088 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
1089 memprintf(err, "OCSP single response: Certificate ID too long");
1090 goto out;
1091 }
1092
1093 p = key;
1094 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001095 i2d_OCSP_CERTID(id, &p);
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001096 HA_SPIN_LOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001097 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
1098 if (!ocsp) {
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001099 HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001100 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
1101 goto out;
1102 }
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001103 HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001104 }
1105
1106 /* According to comments on "chunk_dup", the
1107 previous chunk buffer will be freed */
1108 if (!chunk_dup(&ocsp->response, ocsp_response)) {
1109 memprintf(err, "OCSP response: Memory allocation error");
1110 goto out;
1111 }
1112
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +02001113#ifdef HAVE_ASN1_TIME_TO_TM
1114 if (ASN1_TIME_to_tm(nextupd, &nextupd_tm) == 0) {
1115 memprintf(err, "OCSP single response: Invalid \"Next Update\" time");
1116 goto out;
1117 }
1118 ocsp->expire = my_timegm(&nextupd_tm) - OCSP_MAX_RESPONSE_TIME_SKEW;
1119#else
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001120 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
Remi Tricot-Le Bretona3a0cce2021-06-09 17:16:18 +02001121 if (ocsp->expire < 0) {
1122 memprintf(err, "OCSP single response: Invalid \"Next Update\" time");
1123 goto out;
1124 }
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +02001125#endif
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001126
Emeric Brun4147b2e2014-06-16 18:36:30 +02001127 ret = 0;
1128out:
Janusz Dziemidowicz8d710492017-03-08 16:59:41 +01001129 ERR_clear_error();
1130
Emeric Brun4147b2e2014-06-16 18:36:30 +02001131 if (bs)
1132 OCSP_BASICRESP_free(bs);
1133
1134 if (resp)
1135 OCSP_RESPONSE_free(resp);
1136
1137 return ret;
1138}
1139/*
1140 * External function use to update the OCSP response in the OCSP response's
1141 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
1142 * to update in DER format.
1143 *
1144 * Returns 0 on success, 1 in error case.
1145 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001146int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001147{
1148 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
1149}
1150
Remi Tricot-Le Breton47a4f122022-12-20 11:11:04 +01001151
1152/*
1153 * Extract the first OCSP URI (if any) contained in <cert> and write it into
1154 * <out>.
1155 * Returns 0 in case of success, 1 otherwise.
1156 */
1157int ssl_ocsp_get_uri_from_cert(X509 *cert, struct buffer *out, char **err)
1158{
1159 STACK_OF(OPENSSL_STRING) *ocsp_uri_stk = NULL;
1160 int ret = 1;
1161
1162 if (!cert || !out)
1163 goto end;
1164
1165 ocsp_uri_stk = X509_get1_ocsp(cert);
1166 if (ocsp_uri_stk == NULL) {
1167 memprintf(err, "%sNo OCSP URL stack!\n", *err ? *err : "");
1168 goto end;
1169 }
1170
1171 chunk_strcpy(out, sk_OPENSSL_STRING_value(ocsp_uri_stk, 0));
1172 if (b_data(out) == 0) {
1173 memprintf(err, "%sNo OCSP URL!\n", *err ? *err : "");
1174 goto end;
1175 }
1176
1177 ret = 0;
1178
1179end:
1180 X509_email_free(ocsp_uri_stk);
1181 return ret;
1182}
William Lallemand4a660132019-10-14 14:51:41 +02001183
Remi Tricot-Le Bretone09d2ae2022-12-20 11:11:05 +01001184/*
1185 * Create the url and request body that make a proper OCSP request for the
1186 * <certid>. The <req_url> parameter should already hold the OCSP URI that was
1187 * extracted from the corresponding certificate. Depending on the size of the
1188 * certid we will either append data to the <req_url> to create a proper URL
1189 * that will be sent with a GET command, or the <req_body> will be constructed
1190 * in case of a POST.
1191 * Returns 0 in case of success.
1192 */
1193int ssl_ocsp_create_request_details(const OCSP_CERTID *certid, struct buffer *req_url,
1194 struct buffer *req_body, char **err)
1195{
1196 int errcode = -1;
1197 OCSP_REQUEST *ocsp;
1198 struct buffer *bin_request = get_trash_chunk();
1199 unsigned char *outbuf = (unsigned char*)b_orig(bin_request);
1200
1201 ocsp = OCSP_REQUEST_new();
1202 if (ocsp == NULL) {
1203 memprintf(err, "%sCan't create OCSP_REQUEST\n", *err ? *err : "");
1204 goto end;
1205 }
1206
1207 if (OCSP_request_add0_id(ocsp, (OCSP_CERTID*)certid) == NULL) {
1208 memprintf(err, "%sOCSP_request_add0_id() error\n", *err ? *err : "");
1209 goto end;
1210 }
1211
1212 bin_request->data = i2d_OCSP_REQUEST(ocsp, &outbuf);
1213 if (b_data(bin_request) <= 0) {
1214 memprintf(err, "%si2d_OCSP_REQUEST() error\n", *err ? *err : "");
1215 goto end;
1216 }
1217
1218 errcode = 0;
1219
1220 /* HTTP based OCSP requests can use either the GET or the POST method to
1221 * submit their requests. To enable HTTP caching, small requests (that
1222 * after encoding are less than 255 bytes), MAY be submitted using GET.
1223 * If HTTP caching is not important, or the request is greater than 255
1224 * bytes, the request SHOULD be submitted using POST.
1225 */
1226 if (b_data(bin_request)+b_data(req_url) < 0xff) {
1227 struct buffer *b64buf = get_trash_chunk();
1228 char *ret = NULL;
1229 int base64_ret = 0;
1230
1231 chunk_strcat(req_url, "/");
1232
1233 base64_ret = a2base64(b_orig(bin_request), b_data(bin_request),
1234 b_orig(b64buf), b_size(b64buf));
1235
1236 if (base64_ret < 0) {
1237 memprintf(err, "%sa2base64() error\n", *err ? *err : "");
1238 }
1239
1240 b64buf->data = base64_ret;
1241
1242 ret = encode_chunk((char*)b_stop(req_url), b_orig(req_url)+b_size(req_url), '%',
1243 query_encode_map, b64buf);
1244 if (ret && *ret == '\0') {
1245 req_url->data = ret-b_orig(req_url);
1246 }
1247 }
1248 else {
1249 chunk_cpy(req_body, bin_request);
1250 }
1251
1252end:
1253 OCSP_REQUEST_free(ocsp);
1254
1255 return errcode;
1256}
1257
Remi Tricot-Le Bretonc0b40582022-12-20 11:11:06 +01001258/*
1259 * Parse an OCSP_RESPONSE contained in <respbuf> and check its validity in
1260 * regard to the contents of <ckch> or the <issuer> certificate.
1261 * Certificate_ocsp structure does not keep a reference to the corresponding
1262 * ckch_store so outside of a CLI context (see "send ssl ocsp-response"
1263 * command), we only have an easy access to the issuer's certificate whose
1264 * reference is held in the structure.
1265 * Return 0 in case of success, 1 otherwise.
1266 */
1267int ssl_ocsp_check_response(STACK_OF(X509) *chain, X509 *issuer,
1268 struct buffer *respbuf, char **err)
1269{
1270 int ret = 1;
1271 int n;
1272 OCSP_RESPONSE *response = NULL;
1273 OCSP_BASICRESP *basic = NULL;
1274 X509_STORE *store = NULL;
1275 const unsigned char *start = (const unsigned char*)b_orig(respbuf);
1276
1277 if (!chain && !issuer) {
1278 memprintf(err, "check_ocsp_response needs a certificate validation chain or an issuer certificate");
1279 goto end;
1280 }
1281
1282 response = d2i_OCSP_RESPONSE(NULL, &start, b_data(respbuf));
1283 if (!response) {
1284 memprintf(err, "d2i_OCSP_RESPONSE() failed");
1285 goto end;
1286 }
1287
1288 n = OCSP_response_status(response);
1289
1290 if (n != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1291 memprintf(err, "OCSP response not successful (%d: %s)",
1292 n, OCSP_response_status_str(n));
1293 goto end;
1294 }
1295
1296 basic = OCSP_response_get1_basic(response);
1297 if (basic == NULL) {
1298 memprintf(err, "OCSP_response_get1_basic() failed");
1299 goto end;
1300 }
1301
1302 /* Add ocsp issuer certificate to a store in order verify the ocsp
1303 * response. */
1304 store = X509_STORE_new();
1305 if (!store) {
1306 memprintf(err, "X509_STORE_new() failed");
1307 goto end;
1308 }
1309 X509_STORE_add_cert(store, issuer);
1310
1311 if (OCSP_basic_verify(basic, chain, store, 0) != 1) {
1312 memprintf(err, "OCSP_basic_verify() failed");
1313 goto end;
1314 }
1315
1316 ret = 0;
1317
1318end:
1319 X509_STORE_free(store);
1320 OCSP_RESPONSE_free(response);
1321 OCSP_BASICRESP_free(basic);
1322 return ret;
1323}
Remi Tricot-Le Bretonbdd3c792022-12-20 11:11:09 +01001324
1325/*
1326 * Insert a certificate_ocsp structure into the ocsp_update_tree tree, in which
1327 * entries are sorted by absolute date of the next update. The next_update key
1328 * will be the smallest out of the actual expire value of the response and
1329 * now+1H. This arbitrary 1H value ensures that ocsp responses are updated
1330 * periodically even when they have a long expire time, while not overloading
1331 * the system too much (in theory). Likewise, a minimum 5 minutes interval is
1332 * defined in order to avoid updating too often responses that have a really
1333 * short expire time or even no 'Next Update' at all.
1334 */
1335static int ssl_ocsp_update_insert(struct certificate_ocsp *ocsp)
1336{
1337 int update_margin = (ocsp->expire >= SSL_OCSP_UPDATE_MARGIN) ? SSL_OCSP_UPDATE_MARGIN : 0;
1338
1339 ocsp->next_update.key = MIN(now.tv_sec + SSL_OCSP_UPDATE_DELAY_MAX,
1340 ocsp->expire - update_margin);
1341
1342 /* An already existing valid OCSP response that expires within less than
1343 * SSL_OCSP_UPDATE_DELAY_MIN or has no 'Next Update' field should not be
1344 * updated more than once every 5 minutes in order to avoid continuous
1345 * update of the same response. */
1346 if (b_data(&ocsp->response))
1347 ocsp->next_update.key = MAX(ocsp->next_update.key, SSL_OCSP_UPDATE_DELAY_MIN);
1348
1349 HA_SPIN_LOCK(OCSP_LOCK, &ocsp_tree_lock);
1350 eb64_insert(&ocsp_update_tree, &ocsp->next_update);
1351 HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
1352
1353 return 0;
1354}
Remi Tricot-Le Breton47a4f122022-12-20 11:11:04 +01001355#endif /* defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP */
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001356
1357/*
1358 * Initialize an HMAC context <hctx> using the <key> and <md> parameters.
1359 * Returns -1 in case of error, 1 otherwise.
1360 */
1361static int ssl_hmac_init(MAC_CTX *hctx, unsigned char *key, int key_len, const EVP_MD *md)
1362{
1363#ifdef HAVE_OSSL_PARAM
1364 OSSL_PARAM params[3];
1365
1366 params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, key, key_len);
1367 params[1] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, (char*)EVP_MD_name(md), 0);
1368 params[2] = OSSL_PARAM_construct_end();
1369 if (EVP_MAC_CTX_set_params(hctx, params) == 0)
1370 return -1; /* error in mac initialisation */
1371
1372#else
1373 HMAC_Init_ex(hctx, key, key_len, md, NULL);
1374#endif
1375 return 1;
1376}
1377
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001378#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +01001379
1380static 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 +01001381{
Frédéric Lécaille6aec1f32022-09-06 17:04:55 +02001382 struct tls_keys_ref *ref = NULL;
Emeric Brun9e754772019-01-10 17:51:55 +01001383 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001384 int head;
1385 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001386 int ret = -1; /* error by default */
Frédéric Lécaille6aec1f32022-09-06 17:04:55 +02001387 struct connection *conn = SSL_get_ex_data(s, ssl_app_data_index);
1388#ifdef USE_QUIC
1389 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
1390#endif
1391
1392 if (conn)
1393 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
1394#ifdef USE_QUIC
1395 else if (qc)
1396 ref = qc->li->bind_conf->keys_ref;
1397#endif
1398
1399 if (!ref) {
1400 /* must never happen */
1401 ABORT_NOW();
1402 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001403
Christopher Faulet16f45c82018-02-16 11:23:49 +01001404 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1405
1406 keys = ref->tlskeys;
1407 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001408
1409 if (enc) {
1410 memcpy(key_name, keys[head].name, 16);
1411
1412 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +01001413 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001414
Emeric Brun9e754772019-01-10 17:51:55 +01001415 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001416
Emeric Brun9e754772019-01-10 17:51:55 +01001417 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
1418 goto end;
1419
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001420 if (ssl_hmac_init(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
1421 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +01001422 ret = 1;
1423 }
1424 else if (ref->key_size_bits == 256 ) {
1425
1426 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
1427 goto end;
1428
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001429 if (ssl_hmac_init(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
1430 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +01001431 ret = 1;
1432 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001433 } else {
1434 for (i = 0; i < TLS_TICKETS_NO; i++) {
1435 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
1436 goto found;
1437 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01001438 ret = 0;
1439 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001440
Christopher Faulet16f45c82018-02-16 11:23:49 +01001441 found:
Emeric Brun9e754772019-01-10 17:51:55 +01001442 if (ref->key_size_bits == 128) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001443 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
1444 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +01001445 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
1446 goto end;
1447 /* 2 for key renewal, 1 if current key is still valid */
1448 ret = i ? 2 : 1;
1449 }
1450 else if (ref->key_size_bits == 256) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001451 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
1452 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +01001453 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
1454 goto end;
1455 /* 2 for key renewal, 1 if current key is still valid */
1456 ret = i ? 2 : 1;
1457 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001458 }
Emeric Brun9e754772019-01-10 17:51:55 +01001459
Christopher Faulet16f45c82018-02-16 11:23:49 +01001460 end:
1461 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1462 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001463}
1464
1465struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
1466{
1467 struct tls_keys_ref *ref;
1468
1469 list_for_each_entry(ref, &tlskeys_reference, list)
1470 if (ref->filename && strcmp(filename, ref->filename) == 0)
1471 return ref;
1472 return NULL;
1473}
1474
1475struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1476{
1477 struct tls_keys_ref *ref;
1478
1479 list_for_each_entry(ref, &tlskeys_reference, list)
1480 if (ref->unique_id == unique_id)
1481 return ref;
1482 return NULL;
1483}
1484
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001485/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001486 * match existing ones, this function returns -1
1487 * else it returns 0 on success.
1488 */
1489int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001490 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001491{
Emeric Brun9e754772019-01-10 17:51:55 +01001492 if (ref->key_size_bits == 128) {
1493 if (tlskey->data != sizeof(struct tls_sess_key_128))
1494 return -1;
1495 }
1496 else if (ref->key_size_bits == 256) {
1497 if (tlskey->data != sizeof(struct tls_sess_key_256))
1498 return -1;
1499 }
1500 else
1501 return -1;
1502
Christopher Faulet16f45c82018-02-16 11:23:49 +01001503 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001504 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1505 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001506 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1507 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001508
1509 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001510}
1511
Willy Tarreau83061a82018-07-13 11:56:34 +02001512int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001513{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001514 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1515
1516 if(!ref) {
1517 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1518 return 1;
1519 }
Emeric Brun9e754772019-01-10 17:51:55 +01001520 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1521 memprintf(err, "Invalid key size");
1522 return 1;
1523 }
1524
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001525 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001526}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001527
1528/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001529 * automatic ids. It's called just after the basic checks. It returns
1530 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001531 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001532static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001533{
1534 int i = 0;
1535 struct tls_keys_ref *ref, *ref2, *ref3;
1536 struct list tkr = LIST_HEAD_INIT(tkr);
1537
1538 list_for_each_entry(ref, &tlskeys_reference, list) {
1539 if (ref->unique_id == -1) {
1540 /* Look for the first free id. */
1541 while (1) {
1542 list_for_each_entry(ref2, &tlskeys_reference, list) {
1543 if (ref2->unique_id == i) {
1544 i++;
1545 break;
1546 }
1547 }
1548 if (&ref2->list == &tlskeys_reference)
1549 break;
1550 }
1551
1552 /* Uses the unique id and increment it for the next entry. */
1553 ref->unique_id = i;
1554 i++;
1555 }
1556 }
1557
1558 /* This sort the reference list by id. */
1559 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001560 LIST_DELETE(&ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001561 list_for_each_entry(ref3, &tkr, list) {
1562 if (ref->unique_id < ref3->unique_id) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001563 LIST_APPEND(&ref3->list, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001564 break;
1565 }
1566 }
1567 if (&ref3->list == &tkr)
Willy Tarreau2b718102021-04-21 07:32:39 +02001568 LIST_APPEND(&tkr, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001569 }
1570
1571 /* swap root */
Willy Tarreau2b718102021-04-21 07:32:39 +02001572 LIST_INSERT(&tkr, &tlskeys_reference);
1573 LIST_DELETE(&tkr);
Christopher Fauletfc633b62020-11-06 15:24:23 +01001574 return ERR_NONE;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001575}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001576#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1577
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001578#ifndef OPENSSL_NO_OCSP
William Lallemand76b4a122020-08-04 17:41:39 +02001579int ocsp_ex_index = -1;
1580
yanbzhube2774d2015-12-10 15:07:30 -05001581int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1582{
1583 switch (evp_keytype) {
1584 case EVP_PKEY_RSA:
1585 return 2;
1586 case EVP_PKEY_DSA:
1587 return 0;
1588 case EVP_PKEY_EC:
1589 return 1;
1590 }
1591
1592 return -1;
1593}
1594
Emeric Brun4147b2e2014-06-16 18:36:30 +02001595/*
1596 * Callback used to set OCSP status extension content in server hello.
1597 */
1598int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1599{
yanbzhube2774d2015-12-10 15:07:30 -05001600 struct certificate_ocsp *ocsp;
1601 struct ocsp_cbk_arg *ocsp_arg;
1602 char *ssl_buf;
William Lallemand76b4a122020-08-04 17:41:39 +02001603 SSL_CTX *ctx;
yanbzhube2774d2015-12-10 15:07:30 -05001604 EVP_PKEY *ssl_pkey;
1605 int key_type;
1606 int index;
1607
William Lallemand76b4a122020-08-04 17:41:39 +02001608 ctx = SSL_get_SSL_CTX(ssl);
1609 if (!ctx)
1610 return SSL_TLSEXT_ERR_NOACK;
1611
1612 ocsp_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
1613 if (!ocsp_arg)
1614 return SSL_TLSEXT_ERR_NOACK;
yanbzhube2774d2015-12-10 15:07:30 -05001615
1616 ssl_pkey = SSL_get_privatekey(ssl);
1617 if (!ssl_pkey)
1618 return SSL_TLSEXT_ERR_NOACK;
1619
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001620 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001621
1622 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1623 ocsp = ocsp_arg->s_ocsp;
1624 else {
1625 /* For multiple certs per context, we have to find the correct OCSP response based on
1626 * the certificate type
1627 */
1628 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1629
1630 if (index < 0)
1631 return SSL_TLSEXT_ERR_NOACK;
1632
1633 ocsp = ocsp_arg->m_ocsp[index];
1634
1635 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001636
1637 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001638 !ocsp->response.area ||
1639 !ocsp->response.data ||
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001640 (ocsp->expire < now.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001641 return SSL_TLSEXT_ERR_NOACK;
1642
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001643 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001644 if (!ssl_buf)
1645 return SSL_TLSEXT_ERR_NOACK;
1646
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001647 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01001648 SSL_set_tlsext_status_ocsp_resp(ssl, (unsigned char*)ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001649
1650 return SSL_TLSEXT_ERR_OK;
1651}
1652
William Lallemand4a660132019-10-14 14:51:41 +02001653#endif
1654
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001655#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
William Lallemand76b4a122020-08-04 17:41:39 +02001656
1657
1658/*
1659 * Decrease the refcount of the struct ocsp_response and frees it if it's not
1660 * used anymore. Also removes it from the tree if free'd.
1661 */
1662static void ssl_sock_free_ocsp(struct certificate_ocsp *ocsp)
1663{
1664 if (!ocsp)
1665 return;
1666
1667 ocsp->refcount--;
1668 if (ocsp->refcount <= 0) {
1669 ebmb_delete(&ocsp->key);
Remi Tricot-Le Bretonbdd3c792022-12-20 11:11:09 +01001670 eb64_delete(&ocsp->next_update);
William Lallemand76b4a122020-08-04 17:41:39 +02001671 chunk_destroy(&ocsp->response);
Remi Tricot-Le Bretonbdd3c792022-12-20 11:11:09 +01001672
William Lallemand76b4a122020-08-04 17:41:39 +02001673 free(ocsp);
1674 }
1675}
1676
1677
Emeric Brun4147b2e2014-06-16 18:36:30 +02001678/*
1679 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001680 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1681 * status extension, the issuer's certificate is mandatory. It should be
1682 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001683 *
William Lallemand246c0242019-10-11 08:59:13 +02001684 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1685 * OCSP response. If file is empty or content is not a valid OCSP response,
1686 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1687 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001688 *
1689 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001690 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001691 */
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001692static int ssl_sock_load_ocsp(SSL_CTX *ctx, struct ckch_data *data, STACK_OF(X509) *chain)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001693{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001694 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001695 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001696 struct certificate_ocsp *ocsp = NULL, *iocsp;
1697 char *warn = NULL;
1698 unsigned char *p;
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01001699#ifndef USE_OPENSSL_WOLFSSL
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001700 void (*callback) (void);
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01001701#else
1702 tlsextStatusCb callback;
1703#endif
Emeric Brun4147b2e2014-06-16 18:36:30 +02001704
Emeric Brun4147b2e2014-06-16 18:36:30 +02001705
William Lallemand52ddd992022-11-22 11:51:53 +01001706 x = data->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001707 if (!x)
1708 goto out;
1709
William Lallemand52ddd992022-11-22 11:51:53 +01001710 issuer = data->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001711 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1712 if (chain) {
1713 /* check if one of the certificate of the chain is the issuer */
1714 for (i = 0; i < sk_X509_num(chain); i++) {
1715 X509 *ti = sk_X509_value(chain, i);
1716 if (X509_check_issued(ti, x) == X509_V_OK) {
1717 issuer = ti;
1718 break;
1719 }
1720 }
1721 }
William Lallemand246c0242019-10-11 08:59:13 +02001722 if (!issuer)
1723 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001724
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001725 data->ocsp_cid = OCSP_cert_to_id(0, x, issuer);
1726 if (!data->ocsp_cid)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001727 goto out;
1728
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001729 i = i2d_OCSP_CERTID(data->ocsp_cid, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001730 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1731 goto out;
1732
Vincent Bernat02779b62016-04-03 13:48:43 +02001733 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001734 if (!ocsp)
1735 goto out;
1736
1737 p = ocsp->key_data;
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001738 ocsp->key_length = i2d_OCSP_CERTID(data->ocsp_cid, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001739
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001740 HA_SPIN_LOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001741 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1742 if (iocsp == ocsp)
1743 ocsp = NULL;
1744
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001745#ifndef SSL_CTX_get_tlsext_status_cb
1746# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1747 *cb = (void (*) (void))ctx->tlsext_status_cb;
1748#endif
1749 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1750
1751 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001752 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001753 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001754
William Lallemanda560c062020-07-31 11:43:20 +02001755 cb_arg = calloc(1, sizeof(*cb_arg));
1756 if (!cb_arg)
1757 goto out;
1758
yanbzhube2774d2015-12-10 15:07:30 -05001759 cb_arg->is_single = 1;
1760 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001761 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001762
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001763 pkey = X509_get_pubkey(x);
1764 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1765 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001766
1767 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001768 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 */
1769
yanbzhube2774d2015-12-10 15:07:30 -05001770 } else {
1771 /*
1772 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1773 * Update that cb_arg with the new cert's staple
1774 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001775 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001776 struct certificate_ocsp *tmp_ocsp;
1777 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001778 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001779 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001780
William Lallemand76b4a122020-08-04 17:41:39 +02001781 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001782
1783 /*
1784 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1785 * the order of operations below matter, take care when changing it
1786 */
1787 tmp_ocsp = cb_arg->s_ocsp;
1788 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1789 cb_arg->s_ocsp = NULL;
1790 cb_arg->m_ocsp[index] = tmp_ocsp;
1791 cb_arg->is_single = 0;
1792 cb_arg->single_kt = 0;
1793
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001794 pkey = X509_get_pubkey(x);
1795 key_type = EVP_PKEY_base_id(pkey);
1796 EVP_PKEY_free(pkey);
1797
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001798 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001799 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001800 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001801 iocsp->refcount++;
1802 }
yanbzhube2774d2015-12-10 15:07:30 -05001803 }
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01001804 HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001805
1806 ret = 0;
1807
1808 warn = NULL;
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001809 if (ssl_sock_load_ocsp_response(data->ocsp_response, iocsp, data->ocsp_cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001810 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001811 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001812 }
1813
1814out:
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001815 if (ret && data->ocsp_cid)
1816 OCSP_CERTID_free(data->ocsp_cid);
1817
1818 if (!ret && data->ocsp_response) {
1819 ha_free(&data->ocsp_response->area);
1820 ha_free(&data->ocsp_response);
1821 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001822
1823 if (ocsp)
Remi Tricot-Le Bretonaa529f72022-11-03 15:16:49 +01001824 ssl_sock_free_ocsp(ocsp);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001825
1826 if (warn)
1827 free(warn);
1828
Emeric Brun4147b2e2014-06-16 18:36:30 +02001829 return ret;
1830}
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001831#endif
1832
1833#ifdef OPENSSL_IS_BORINGSSL
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01001834static int ssl_sock_load_ocsp(SSL_CTX *ctx, struct ckch_data *data, STACK_OF(X509) *chain)
Emmanuel Hocdet2c32d8f2017-05-22 14:58:00 +02001835{
William Lallemand4a660132019-10-14 14:51:41 +02001836 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 +02001837}
1838#endif
1839
William Lallemand4a660132019-10-14 14:51:41 +02001840
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001841#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001842
1843#define CT_EXTENSION_TYPE 18
1844
William Lallemand03c331c2020-05-13 10:10:01 +02001845int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001846
1847int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1848{
Willy Tarreau83061a82018-07-13 11:56:34 +02001849 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001850
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001851 *out = (unsigned char *) sctl->area;
1852 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001853
1854 return 1;
1855}
1856
1857int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1858{
1859 return 1;
1860}
1861
William Lallemanda17f4112019-10-10 15:16:44 +02001862static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001863{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001864 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001865
William Lallemanda17f4112019-10-10 15:16:44 +02001866 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 +01001867 goto out;
1868
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001869 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1870
1871 ret = 0;
1872
1873out:
1874 return ret;
1875}
1876
1877#endif
1878
Emeric Brune1f38db2012-09-03 20:36:47 +02001879void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1880{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001881 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001882#ifdef USE_QUIC
1883 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1884#endif /* USE_QUIC */
1885 struct ssl_sock_ctx *ctx = NULL;
1886
Emeric Brund8b2bb52014-01-28 15:43:53 +01001887 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001888 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001889
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001890 if (conn)
Willy Tarreau939b0bf2022-04-11 11:29:11 +02001891 ctx = conn_get_ssl_sock_ctx(conn);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001892#ifdef USE_QUIC
1893 else if (qc)
1894 ctx = qc->xprt_ctx;
1895#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01001896
1897 if (!ctx) {
1898 /* must never happen */
1899 ABORT_NOW();
1900 return;
1901 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001902
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001903#ifndef SSL_OP_NO_RENEGOTIATION
1904 /* Please note that BoringSSL defines this macro to zero so don't
1905 * change this to #if and do not assign a default value to this macro!
1906 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001907 if (where & SSL_CB_HANDSHAKE_START) {
1908 /* Disable renegotiation (CVE-2009-3555) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001909 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 +02001910 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001911 conn->err_code = CO_ER_SSL_RENEG;
1912 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001913 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001914#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001915
1916 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001917 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001918 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001919 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001920 consider that the buffering was activated,
1921 so we rise the output buffer size from 4k
1922 to 16k */
1923 write_bio = SSL_get_wbio(ssl);
1924 if (write_bio != SSL_get_rbio(ssl)) {
1925 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001926 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001927 }
1928 }
1929 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001930}
1931
Emeric Brune64aef12012-09-21 13:15:06 +02001932/* Callback is called for each certificate of the chain during a verify
1933 ok is set to 1 if preverify detect no error on current certificate.
1934 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001935int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001936{
1937 SSL *ssl;
1938 struct connection *conn;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001939 struct ssl_sock_ctx *ctx = NULL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001940 int err, depth;
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001941 X509 *client_crt;
1942 STACK_OF(X509) *certs;
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001943 struct bind_conf *bind_conf = NULL;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001944 struct quic_conn *qc = NULL;
Emeric Brune64aef12012-09-21 13:15:06 +02001945
1946 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001947 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001948 client_crt = SSL_get_ex_data(ssl, ssl_client_crt_ref_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001949
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001950 if (conn) {
1951 bind_conf = __objt_listener(conn->target)->bind_conf;
1952 ctx = __conn_get_ssl_sock_ctx(conn);
1953 }
1954#ifdef USE_QUIC
1955 else {
1956 qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
Amaury Denoyelleba303de2022-10-17 18:46:49 +02001957 BUG_ON(!qc); /* Must never happen */
1958 bind_conf = qc->li->bind_conf;
1959 ctx = qc->xprt_ctx;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001960 }
1961#endif
1962
Frédéric Lécaille48e46f92022-10-14 09:34:00 +02001963 BUG_ON(!ctx || !bind_conf);
Christopher Faulet881cce92022-11-23 09:27:13 +01001964 ALREADY_CHECKED(ctx);
1965 ALREADY_CHECKED(bind_conf);
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02001966
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001967 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001968
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001969 depth = X509_STORE_CTX_get_error_depth(x_store);
1970 err = X509_STORE_CTX_get_error(x_store);
1971
Emeric Brun81c00f02012-09-21 14:31:21 +02001972 if (ok) /* no errors */
1973 return ok;
1974
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001975 /* Keep a reference to the client's certificate in order to be able to
1976 * dump some fetches values in a log even when the verification process
1977 * fails. */
1978 if (depth == 0) {
1979 X509_free(client_crt);
1980 client_crt = X509_STORE_CTX_get0_cert(x_store);
1981 if (client_crt) {
1982 X509_up_ref(client_crt);
1983 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
1984 }
1985 }
1986 else {
1987 /* An error occurred on a CA certificate of the certificate
1988 * chain, we might never call this verify callback on the client
1989 * certificate's depth (which is 0) so we try to store the
1990 * reference right now. */
Remi Tricot-Le Bretonf95c2952021-08-20 09:51:23 +02001991 certs = X509_STORE_CTX_get1_chain(x_store);
1992 if (certs) {
1993 client_crt = sk_X509_value(certs, 0);
1994 if (client_crt) {
1995 X509_up_ref(client_crt);
1996 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001997 }
1998 sk_X509_pop_free(certs, X509_free);
1999 }
2000 }
Emeric Brun81c00f02012-09-21 14:31:21 +02002001
2002 /* check if CA error needs to be ignored */
2003 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01002004 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
2005 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
2006 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02002007 }
2008
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01002009 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01002010 cert_ignerr_bitfield_get(bind_conf->ca_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02002011 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02002012
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02002013 /* TODO: for QUIC connection, this error code is lost */
2014 if (conn)
2015 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02002016 return 0;
2017 }
2018
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01002019 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
2020 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02002021
Emeric Brun81c00f02012-09-21 14:31:21 +02002022 /* check if certificate error needs to be ignored */
Remi Tricot-Le Breton9b259822022-11-10 10:48:58 +01002023 if (err <= SSL_MAX_VFY_ERROR_CODE &&
William Lallemand46396892022-11-10 16:45:24 +01002024 cert_ignerr_bitfield_get(bind_conf->crt_ignerr_bitfield, err))
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02002025 goto err_ignored;
Emeric Brun81c00f02012-09-21 14:31:21 +02002026
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02002027 /* TODO: for QUIC connection, this error code is lost */
2028 if (conn)
2029 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02002030 return 0;
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02002031
2032 err_ignored:
2033 ssl_sock_dump_errors(conn, qc);
2034 ERR_clear_error();
2035 return 1;
Emeric Brune64aef12012-09-21 13:15:06 +02002036}
2037
Dragan Dosen9ac98092020-05-11 15:51:45 +02002038#ifdef TLS1_RT_HEARTBEAT
2039static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
2040 int content_type, const void *buf, size_t len,
2041 SSL *ssl)
2042{
2043 /* test heartbeat received (write_p is set to 0
2044 for a received record) */
2045 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02002046 struct ssl_sock_ctx *ctx = __conn_get_ssl_sock_ctx(conn);
Dragan Dosen9ac98092020-05-11 15:51:45 +02002047 const unsigned char *p = buf;
2048 unsigned int payload;
2049
2050 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
2051
2052 /* Check if this is a CVE-2014-0160 exploitation attempt. */
2053 if (*p != TLS1_HB_REQUEST)
2054 return;
2055
2056 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
2057 goto kill_it;
2058
2059 payload = (p[1] * 256) + p[2];
2060 if (3 + payload + 16 <= len)
2061 return; /* OK no problem */
2062 kill_it:
2063 /* We have a clear heartbleed attack (CVE-2014-0160), the
2064 * advertised payload is larger than the advertised packet
2065 * length, so we have garbage in the buffer between the
2066 * payload and the end of the buffer (p+len). We can't know
2067 * if the SSL stack is patched, and we don't know if we can
2068 * safely wipe out the area between p+3+len and payload.
2069 * So instead, we prevent the response from being sent by
2070 * setting the max_send_fragment to 0 and we report an SSL
2071 * error, which will kill this connection. It will be reported
2072 * above as SSL_ERROR_SSL while an other handshake failure with
2073 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
2074 */
2075 ssl->max_send_fragment = 0;
2076 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
2077 }
2078}
2079#endif
2080
2081static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
2082 int content_type, const void *buf, size_t len,
2083 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01002084{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01002085 struct ssl_capture *capture;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02002086 uchar *msg;
2087 uchar *end;
2088 uchar *extensions_end;
2089 uchar *ec_start = NULL;
2090 uchar *ec_formats_start = NULL;
2091 uchar *list_end;
2092 ushort protocol_version;
2093 ushort extension_id;
2094 ushort ec_len = 0;
2095 uchar ec_formats_len = 0;
2096 int offset = 0;
2097 int rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01002098
2099 /* This function is called for "from client" and "to server"
2100 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08002101 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01002102 */
2103
2104 /* "write_p" is set to 0 is the bytes are received messages,
2105 * otherwise it is set to 1.
2106 */
2107 if (write_p != 0)
2108 return;
2109
2110 /* content_type contains the type of message received or sent
2111 * according with the SSL/TLS protocol spec. This message is
2112 * encoded with one byte. The value 256 (two bytes) is used
2113 * for designing the SSL/TLS record layer. According with the
2114 * rfc6101, the expected message (other than 256) are:
2115 * - change_cipher_spec(20)
2116 * - alert(21)
2117 * - handshake(22)
2118 * - application_data(23)
2119 * - (255)
2120 * We are interessed by the handshake and specially the client
2121 * hello.
2122 */
2123 if (content_type != 22)
2124 return;
2125
2126 /* The message length is at least 4 bytes, containing the
2127 * message type and the message length.
2128 */
2129 if (len < 4)
2130 return;
2131
2132 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002133 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01002134 * - hello_request(0)
2135 * - client_hello(1)
2136 * - server_hello(2)
2137 * - certificate(11)
2138 * - server_key_exchange (12)
2139 * - certificate_request(13)
2140 * - server_hello_done(14)
2141 * We are interested by the client hello.
2142 */
2143 msg = (unsigned char *)buf;
2144 if (msg[0] != 1)
2145 return;
2146
2147 /* Next three bytes are the length of the message. The total length
2148 * must be this decoded length + 4. If the length given as argument
2149 * is not the same, we abort the protocol dissector.
2150 */
2151 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
2152 if (len < rec_len + 4)
2153 return;
2154 msg += 4;
2155 end = msg + rec_len;
2156 if (end < msg)
2157 return;
2158
Marcin Deranek769fd2e2021-07-12 14:16:55 +02002159 /* Expect 2 bytes for protocol version
2160 * (1 byte for major and 1 byte for minor)
Baptiste Assmann6be139f2018-11-28 15:20:25 +01002161 */
Marcin Deranek769fd2e2021-07-12 14:16:55 +02002162 if (msg + 2 > end)
2163 return;
2164 protocol_version = (msg[0] << 8) + msg[1];
2165 msg += 2;
2166
2167 /* Expect the random, composed by 4 bytes for the unix time and
2168 * 28 bytes for unix payload. So we jump 4 + 28.
2169 */
2170 msg += 4 + 28;
Baptiste Assmann6be139f2018-11-28 15:20:25 +01002171 if (msg > end)
2172 return;
2173
2174 /* Next, is session id:
2175 * if present, we have to jump by length + 1 for the size information
2176 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01002177 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01002178 if (msg[0] > 0)
2179 msg += msg[0];
2180 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01002181 if (msg > end)
2182 return;
2183
2184 /* Next two bytes are the ciphersuite length. */
2185 if (msg + 2 > end)
2186 return;
2187 rec_len = (msg[0] << 8) + msg[1];
2188 msg += 2;
2189 if (msg + rec_len > end || msg + rec_len < msg)
2190 return;
2191
Marcin Deranek769fd2e2021-07-12 14:16:55 +02002192 capture = pool_zalloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01002193 if (!capture)
2194 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01002195 /* Compute the xxh64 of the ciphersuite. */
2196 capture->xxh64 = XXH64(msg, rec_len, 0);
2197
2198 /* Capture the ciphersuite. */
Marcin Deranek310a2602021-07-13 19:04:24 +02002199 capture->ciphersuite_len = MIN(global_ssl.capture_buffer_size, rec_len);
Marcin Deranek769fd2e2021-07-12 14:16:55 +02002200 capture->ciphersuite_offset = 0;
2201 memcpy(capture->data, msg, capture->ciphersuite_len);
2202 msg += rec_len;
2203 offset += capture->ciphersuite_len;
2204
2205 /* Initialize other data */
2206 capture->protocol_version = protocol_version;
2207
2208 /* Next, compression methods:
2209 * if present, we have to jump by length + 1 for the size information
2210 * if not present, we have to jump by 1 only
2211 */
2212 if (msg[0] > 0)
2213 msg += msg[0];
2214 msg += 1;
2215 if (msg > end)
2216 goto store_capture;
2217
2218 /* We reached extensions */
2219 if (msg + 2 > end)
2220 goto store_capture;
2221 rec_len = (msg[0] << 8) + msg[1];
2222 msg += 2;
2223 if (msg + rec_len > end || msg + rec_len < msg)
2224 goto store_capture;
2225 extensions_end = msg + rec_len;
2226 capture->extensions_offset = offset;
2227
2228 /* Parse each extension */
2229 while (msg + 4 < extensions_end) {
2230 /* Add 2 bytes of extension_id */
Marcin Deranek310a2602021-07-13 19:04:24 +02002231 if (global_ssl.capture_buffer_size >= offset + 2) {
Marcin Deranek769fd2e2021-07-12 14:16:55 +02002232 capture->data[offset++] = msg[0];
2233 capture->data[offset++] = msg[1];
2234 capture->extensions_len += 2;
2235 }
2236 else
2237 break;
2238 extension_id = (msg[0] << 8) + msg[1];
2239 /* Length of the extension */
2240 rec_len = (msg[2] << 8) + msg[3];
2241
2242 /* Expect 2 bytes extension id + 2 bytes extension size */
2243 msg += 2 + 2;
2244 if (msg + rec_len > extensions_end || msg + rec_len < msg)
2245 goto store_capture;
2246 /* TLS Extensions
2247 * https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml */
2248 if (extension_id == 0x000a) {
2249 /* Elliptic Curves:
2250 * https://www.rfc-editor.org/rfc/rfc8422.html
2251 * https://www.rfc-editor.org/rfc/rfc7919.html */
2252 list_end = msg + rec_len;
2253 if (msg + 2 > list_end)
2254 goto store_capture;
2255 rec_len = (msg[0] << 8) + msg[1];
2256 msg += 2;
2257
2258 if (msg + rec_len > list_end || msg + rec_len < msg)
2259 goto store_capture;
2260 /* Store location/size of the list */
2261 ec_start = msg;
2262 ec_len = rec_len;
2263 }
2264 else if (extension_id == 0x000b) {
2265 /* Elliptic Curves Point Formats:
2266 * https://www.rfc-editor.org/rfc/rfc8422.html */
2267 list_end = msg + rec_len;
2268 if (msg + 1 > list_end)
2269 goto store_capture;
2270 rec_len = msg[0];
2271 msg += 1;
2272
2273 if (msg + rec_len > list_end || msg + rec_len < msg)
2274 goto store_capture;
2275 /* Store location/size of the list */
2276 ec_formats_start = msg;
2277 ec_formats_len = rec_len;
2278 }
2279 msg += rec_len;
2280 }
2281
2282 if (ec_start) {
2283 rec_len = ec_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02002284 if (offset + rec_len > global_ssl.capture_buffer_size)
2285 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02002286 memcpy(capture->data + offset, ec_start, rec_len);
2287 capture->ec_offset = offset;
2288 capture->ec_len = rec_len;
2289 offset += rec_len;
2290 }
2291 if (ec_formats_start) {
2292 rec_len = ec_formats_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02002293 if (offset + rec_len > global_ssl.capture_buffer_size)
2294 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02002295 memcpy(capture->data + offset, ec_formats_start, rec_len);
2296 capture->ec_formats_offset = offset;
2297 capture->ec_formats_len = rec_len;
2298 offset += rec_len;
2299 }
Emmanuel Hocdete3804742017-03-08 11:07:10 +01002300
Marcin Deranek769fd2e2021-07-12 14:16:55 +02002301 store_capture:
Emmanuel Hocdete3804742017-03-08 11:07:10 +01002302 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01002303}
William Lallemand7d42ef52020-07-06 11:41:30 +02002304
2305
William Lallemand722180a2021-06-09 16:46:12 +02002306#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02002307static void ssl_init_keylog(struct connection *conn, int write_p, int version,
2308 int content_type, const void *buf, size_t len,
2309 SSL *ssl)
2310{
2311 struct ssl_keylog *keylog;
2312
2313 if (SSL_get_ex_data(ssl, ssl_keylog_index))
2314 return;
2315
Willy Tarreauf208ac02021-03-22 21:10:12 +01002316 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02002317 if (!keylog)
2318 return;
2319
William Lallemand7d42ef52020-07-06 11:41:30 +02002320 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
2321 pool_free(pool_head_ssl_keylog, keylog);
2322 return;
2323 }
2324}
2325#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01002326
Emeric Brun29f037d2014-04-25 19:05:36 +02002327/* Callback is called for ssl protocol analyse */
2328void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
2329{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02002330 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2331 struct ssl_sock_msg_callback *cbk;
2332
Dragan Dosen1e7ed042020-05-08 18:30:00 +02002333 /* Try to call all callback functions that were registered by using
2334 * ssl_sock_register_msg_callback().
2335 */
2336 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
2337 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
2338 }
Emeric Brun29f037d2014-04-25 19:05:36 +02002339}
2340
Bernard Spil13c53f82018-02-15 13:34:58 +01002341#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01002342static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
2343 const unsigned char *in, unsigned int inlen,
2344 void *arg)
2345{
2346 struct server *srv = arg;
2347
2348 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
2349 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
2350 return SSL_TLSEXT_ERR_OK;
2351 return SSL_TLSEXT_ERR_NOACK;
2352}
2353#endif
2354
2355#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02002356/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002357 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02002358 */
2359static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
2360 unsigned int *len, void *arg)
2361{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002362 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02002363
2364 *data = (const unsigned char *)conf->npn_str;
2365 *len = conf->npn_len;
2366 return SSL_TLSEXT_ERR_OK;
2367}
2368#endif
2369
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002370#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02002371/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002372 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02002373 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002374static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
2375 unsigned char *outlen,
2376 const unsigned char *server,
2377 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02002378{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002379 struct ssl_bind_conf *conf = arg;
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002380#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002381 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002382#endif
Willy Tarreauab861d32013-04-02 02:30:41 +02002383
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002384 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
2385 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01002386#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002387 if (qc)
2388 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01002389#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002390 return SSL_TLSEXT_ERR_NOACK;
2391 }
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002392
2393#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002394 if (qc && !quic_set_app_ops(qc, *out, *outlen)) {
2395 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002396 return SSL_TLSEXT_ERR_NOACK;
2397 }
2398#endif
2399
Willy Tarreauab861d32013-04-02 02:30:41 +02002400 return SSL_TLSEXT_ERR_OK;
2401}
2402#endif
2403
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02002404#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002405#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002406
cui flitera94bedc2022-08-29 14:42:57 +08002407/* Configure a DNS SAN extension on a certificate. */
Shimi Gersneradabbfe2020-08-23 13:58:13 +03002408int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
2409 int failure = 0;
2410 X509_EXTENSION *san_ext = NULL;
2411 CONF *conf = NULL;
2412 struct buffer *san_name = get_trash_chunk();
2413
2414 conf = NCONF_new(NULL);
2415 if (!conf) {
2416 failure = 1;
2417 goto cleanup;
2418 }
2419
2420 /* Build an extension based on the DNS entry above */
2421 chunk_appendf(san_name, "DNS:%s", servername);
2422 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
2423 if (!san_ext) {
2424 failure = 1;
2425 goto cleanup;
2426 }
2427
2428 /* Add the extension */
2429 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
2430 failure = 1;
2431 goto cleanup;
2432 }
2433
2434 /* Success */
2435 failure = 0;
2436
2437cleanup:
2438 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
2439 if (NULL != conf) NCONF_free(conf);
2440
2441 return failure;
2442}
2443
Christopher Faulet30548802015-06-11 13:39:32 +02002444/* Create a X509 certificate with the specified servername and serial. This
2445 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02002446static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002447ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002448{
Shimi Gersner5846c492020-08-23 13:58:12 +03002449 X509 *cacert = bind_conf->ca_sign_ckch->cert;
2450 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002451 SSL_CTX *ssl_ctx = NULL;
2452 X509 *newcrt = NULL;
2453 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002454 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002455 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002456 X509_NAME *name;
2457 const EVP_MD *digest;
2458 X509V3_CTX ctx;
2459 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002460 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002461
Christopher Faulet48a83322017-07-28 16:56:09 +02002462 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05002463#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002464 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
2465#else
2466 tmp_ssl = SSL_new(bind_conf->default_ctx);
2467 if (tmp_ssl)
2468 pkey = SSL_get_privatekey(tmp_ssl);
2469#endif
2470 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002471 goto mkcert_error;
2472
2473 /* Create the certificate */
2474 if (!(newcrt = X509_new()))
2475 goto mkcert_error;
2476
2477 /* Set version number for the certificate (X509v3) and the serial
2478 * number */
2479 if (X509_set_version(newcrt, 2L) != 1)
2480 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02002481 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002482
2483 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08002484 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
2485 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02002486 goto mkcert_error;
2487
2488 /* set public key in the certificate */
2489 if (X509_set_pubkey(newcrt, pkey) != 1)
2490 goto mkcert_error;
2491
2492 /* Set issuer name from the CA */
2493 if (!(name = X509_get_subject_name(cacert)))
2494 goto mkcert_error;
2495 if (X509_set_issuer_name(newcrt, name) != 1)
2496 goto mkcert_error;
2497
2498 /* Set the subject name using the same, but the CN */
2499 name = X509_NAME_dup(name);
2500 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
2501 (const unsigned char *)servername,
2502 -1, -1, 0) != 1) {
2503 X509_NAME_free(name);
2504 goto mkcert_error;
2505 }
2506 if (X509_set_subject_name(newcrt, name) != 1) {
2507 X509_NAME_free(name);
2508 goto mkcert_error;
2509 }
2510 X509_NAME_free(name);
2511
2512 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002513 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002514 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
2515 for (i = 0; i < X509V3_EXT_SIZE; i++) {
2516 X509_EXTENSION *ext;
2517
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002518 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02002519 goto mkcert_error;
2520 if (!X509_add_ext(newcrt, ext, -1)) {
2521 X509_EXTENSION_free(ext);
2522 goto mkcert_error;
2523 }
2524 X509_EXTENSION_free(ext);
2525 }
2526
Shimi Gersneradabbfe2020-08-23 13:58:13 +03002527 /* Add SAN extension */
2528 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
2529 goto mkcert_error;
2530 }
2531
Christopher Faulet31af49d2015-06-09 17:29:50 +02002532 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002533
2534 key_type = EVP_PKEY_base_id(capkey);
2535
2536 if (key_type == EVP_PKEY_DSA)
2537 digest = EVP_sha1();
2538 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002539 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002540 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02002541 digest = EVP_sha256();
2542 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05002543#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02002544 int nid;
2545
2546 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
2547 goto mkcert_error;
2548 if (!(digest = EVP_get_digestbynid(nid)))
2549 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02002550#else
2551 goto mkcert_error;
2552#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02002553 }
2554
Christopher Faulet31af49d2015-06-09 17:29:50 +02002555 if (!(X509_sign(newcrt, capkey, digest)))
2556 goto mkcert_error;
2557
2558 /* Create and set the new SSL_CTX */
2559 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
2560 goto mkcert_error;
2561 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
2562 goto mkcert_error;
2563 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
2564 goto mkcert_error;
2565 if (!SSL_CTX_check_private_key(ssl_ctx))
2566 goto mkcert_error;
2567
Shimi Gersner5846c492020-08-23 13:58:12 +03002568 /* Build chaining the CA cert and the rest of the chain, keep these order */
2569#if defined(SSL_CTX_add1_chain_cert)
2570 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
2571 goto mkcert_error;
2572 }
2573
2574 if (bind_conf->ca_sign_ckch->chain) {
2575 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2576 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2577 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2578 goto mkcert_error;
2579 }
2580 }
2581 }
2582#endif
2583
Christopher Faulet31af49d2015-06-09 17:29:50 +02002584 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002585
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002586#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002587#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002588 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002589#else
2590 ssl_sock_set_tmp_dh_from_pkey(ssl_ctx, pkey);
2591#endif
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002592#endif
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002593
2594#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
2595#if defined(SSL_CTX_set1_curves_list)
2596 {
2597 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
2598 if (!SSL_CTX_set1_curves_list(ssl_ctx, ecdhe))
2599 goto end;
2600 }
2601#endif
2602#else
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002603#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2604 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002605 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002606 EC_KEY *ecc;
2607 int nid;
2608
2609 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2610 goto end;
2611 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2612 goto end;
2613 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2614 EC_KEY_free(ecc);
2615 }
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002616#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
2617#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002618 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002619 return ssl_ctx;
2620
2621 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002622 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002623 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002624 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2625 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002626 return NULL;
2627}
2628
Christopher Faulet7969a332015-10-09 11:15:03 +02002629
Christopher Faulet30548802015-06-11 13:39:32 +02002630/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002631 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002632SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002633ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002634{
2635 struct lru64 *lru = NULL;
2636
2637 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002638 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002639 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002640 if (lru && lru->domain) {
2641 if (ssl)
2642 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002643 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002644 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002645 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002646 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002647 }
2648 return NULL;
2649}
2650
Emeric Brun821bb9b2017-06-15 16:37:39 +02002651/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2652 * function is not thread-safe, it should only be used to check if a certificate
2653 * exists in the lru cache (with no warranty it will not be removed by another
2654 * thread). It is kept for backward compatibility. */
2655SSL_CTX *
2656ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2657{
2658 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2659}
2660
Christopher Fauletd2cab922015-07-28 16:03:47 +02002661/* Set a certificate int the LRU cache used to store generated
2662 * certificate. Return 0 on success, otherwise -1 */
2663int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002664ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002665{
2666 struct lru64 *lru = NULL;
2667
2668 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002669 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002670 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002671 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002672 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002673 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002674 }
Christopher Faulet30548802015-06-11 13:39:32 +02002675 if (lru->domain && lru->data)
2676 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002677 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002678 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002679 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002680 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002681 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002682}
2683
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002684/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002685unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002686ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002687{
2688 return XXH32(data, len, ssl_ctx_lru_seed);
2689}
2690
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002691/* Generate a cert and immediately assign it to the SSL session so that the cert's
2692 * refcount is maintained regardless of the cert's presence in the LRU cache.
2693 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002694static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002695ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002696{
Shimi Gersner5846c492020-08-23 13:58:12 +03002697 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002698 SSL_CTX *ssl_ctx = NULL;
2699 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002700 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002701
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002702 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002703 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002704 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002705 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002706 if (lru && lru->domain)
2707 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002708 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002709 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002710 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002711 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002712 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002713 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002714 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002715 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002716 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002717 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002718 SSL_set_SSL_CTX(ssl, ssl_ctx);
2719 /* No LRU cache, this CTX will be released as soon as the session dies */
2720 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002721 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002722 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002723 return 0;
2724}
2725static int
2726ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2727{
2728 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002729 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002730
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002731 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002732 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002733 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002734 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002735 }
2736 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002737}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002738#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002739
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002740#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002741
2742static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002743{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002744#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002745 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002746 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2747#endif
2748}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002749static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2750 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002751 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2752}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002753static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002754#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002755 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002756 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2757#endif
2758}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002759static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002760#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002761 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002762 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2763#endif
2764}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002765/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002766static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2767/* Unusable in this context. */
2768static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2769static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2770static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2771static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2772static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002773#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002774
2775static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2776 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002777 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2778}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002779static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2780 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2781 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2782}
2783static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2784 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002785 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2786}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002787static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2788 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2789 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2790}
2791static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2792 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002793 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2794}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002795static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2796 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2797 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2798}
2799static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2800 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002801 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2802}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002803static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2804 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2805 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2806}
2807static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002808#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002809 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002810 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2811#endif
2812}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002813static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002814#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002815 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2816 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002817#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002818}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002819#endif
2820static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2821static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002822
William Lallemand7fd8b452020-05-07 15:20:43 +02002823struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002824 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2825 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2826 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2827 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2828 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2829 {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 +02002830};
2831
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002832static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2833{
2834 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2835 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2836 SSL_set_SSL_CTX(ssl, ctx);
2837}
2838
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002839#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002840
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002841int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002842{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002843 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002844 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002845
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002846 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || (s->options & BC_O_GENERATE_CERTS))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002847 return SSL_TLSEXT_ERR_OK;
2848 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002849}
2850
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002851#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002852int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002853{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002854 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002855#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002856int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002857{
2858#endif
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002859 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2860#ifdef USE_QUIC
2861 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2862#endif /* USE_QUIC */
2863 struct bind_conf *s = NULL;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002864 const uint8_t *extension_data;
2865 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002866 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002867
2868 char *wildp = NULL;
2869 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002870 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002871 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002872 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002873 int i;
2874
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002875 if (conn)
2876 s = __objt_listener(conn->target)->bind_conf;
2877#ifdef USE_QUIC
2878 else if (qc)
2879 s = qc->li->bind_conf;
2880#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01002881
2882 if (!s) {
2883 /* must never happen */
2884 ABORT_NOW();
2885 return 0;
2886 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002887
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002888#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002889 if (qc) {
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002890 /* Look for the QUIC transport parameters. */
2891#ifdef OPENSSL_IS_BORINGSSL
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002892 if (!SSL_early_callback_ctx_extension_get(ctx, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002893 &extension_data, &extension_len))
2894#else
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002895 if (!SSL_client_hello_get0_ext(ssl, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002896 &extension_data, &extension_len))
2897#endif
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002898 {
2899 /* This is not redundant. It we only return 0 without setting
2900 * <*al>, this has as side effect to generate another TLS alert
2901 * which would be set after calling quic_set_tls_alert().
2902 */
2903 *al = SSL_AD_MISSING_EXTENSION;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002904 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002905 return 0;
2906 }
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002907
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002908 if (!quic_transport_params_store(qc, 0, extension_data,
Frédéric Lécaille301425b2022-06-14 17:40:39 +02002909 extension_data + extension_len) ||
2910 !qc_conn_finalize(qc, 0))
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002911 goto abort;
2912 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002913#endif /* USE_QUIC */
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002914
Olivier Houchard9679ac92017-10-27 14:58:08 +02002915 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002916 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002917#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002918 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2919 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002920#else
2921 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2922#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002923 /*
2924 * The server_name extension was given too much extensibility when it
2925 * was written, so parsing the normal case is a bit complex.
2926 */
2927 size_t len;
2928 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002929 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002930 /* Extract the length of the supplied list of names. */
2931 len = (*extension_data++) << 8;
2932 len |= *extension_data++;
2933 if (len + 2 != extension_len)
2934 goto abort;
2935 /*
2936 * The list in practice only has a single element, so we only consider
2937 * the first one.
2938 */
2939 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2940 goto abort;
2941 extension_len = len - 1;
2942 /* Now we can finally pull out the byte array with the actual hostname. */
2943 if (extension_len <= 2)
2944 goto abort;
2945 len = (*extension_data++) << 8;
2946 len |= *extension_data++;
2947 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2948 || memchr(extension_data, 0, len) != NULL)
2949 goto abort;
2950 servername = extension_data;
2951 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002952 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002953#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002954 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002955 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002956 }
2957#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002958 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002959 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002960 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002961 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002962 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002963 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002964 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002965 goto abort;
2966 }
2967
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002968 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002969#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002970 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002971#else
2972 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2973#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002974 uint8_t sign;
2975 size_t len;
2976 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002977 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002978 len = (*extension_data++) << 8;
2979 len |= *extension_data++;
2980 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002981 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002982 if (len % 2 != 0)
2983 goto abort;
2984 for (; len > 0; len -= 2) {
2985 extension_data++; /* hash */
2986 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002987 switch (sign) {
2988 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002989 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002990 break;
2991 case TLSEXT_signature_ecdsa:
2992 has_ecdsa_sig = 1;
2993 break;
2994 default:
2995 continue;
2996 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002997 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002998 break;
2999 }
3000 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01003001 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02003002 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003003 }
3004 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02003005 const SSL_CIPHER *cipher;
3006 size_t len;
3007 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02003008 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003009#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02003010 len = ctx->cipher_suites_len;
3011 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003012#else
3013 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
3014#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02003015 if (len % 2 != 0)
3016 goto abort;
3017 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003018#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02003019 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003020 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003021#else
3022 cipher = SSL_CIPHER_find(ssl, cipher_suites);
3023#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02003024 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02003025 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003026 break;
3027 }
3028 }
3029 }
3030
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02003031 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003032 trash.area[i] = tolower(servername[i]);
3033 if (!wildp && (trash.area[i] == '.'))
3034 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003035 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003036 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003037
William Lallemand150bfa82019-09-19 17:12:49 +02003038 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003039
William Lallemand94bd3192020-08-14 14:43:35 +02003040 /* Look for an ECDSA, RSA and DSA certificate, first in the single
3041 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01003042 for (i = 0; i < 2; i++) {
3043 if (i == 0) /* lookup in full qualified names */
3044 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02003045 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01003046 node = ebst_lookup(&s->sni_w_ctx, wildp);
3047 else
3048 break;
William Lallemand30f9e092020-08-17 14:31:19 +02003049
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003050 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02003051
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01003052 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003053 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02003054 struct sni_ctx *sni, *sni_tmp;
3055 int skip = 0;
3056
3057 if (i == 1 && wildp) { /* wildcard */
3058 /* If this is a wildcard, look for an exclusion on the same crt-list line */
3059 sni = container_of(n, struct sni_ctx, name);
3060 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01003061 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02003062 skip = 1;
3063 break;
3064 }
3065 }
3066 if (skip)
3067 continue;
3068 }
3069
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003070 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003071 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02003072 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003073 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003074 break;
3075 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02003076 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003077 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003078 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003079 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003080 if (!node_anonymous)
3081 node_anonymous = n;
3082 break;
3083 }
3084 }
3085 }
William Lallemand94bd3192020-08-14 14:43:35 +02003086 }
3087 /* Once the certificates are found, select them depending on what is
3088 * supported in the client and by key_signature priority order: EDSA >
3089 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02003090 if (has_ecdsa_sig && node_ecdsa)
3091 node = node_ecdsa;
3092 else if (has_rsa_sig && node_rsa)
3093 node = node_rsa;
3094 else if (node_anonymous)
3095 node = node_anonymous;
3096 else if (node_ecdsa)
3097 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
3098 else
3099 node = node_rsa; /* no rsa signature case (far far away) */
3100
William Lallemand94bd3192020-08-14 14:43:35 +02003101 if (node) {
3102 /* switch ctx */
3103 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
3104 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
3105 if (conf) {
3106 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
3107 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
3108 if (conf->early_data)
3109 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01003110 }
William Lallemand94bd3192020-08-14 14:43:35 +02003111 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
3112 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003113 }
William Lallemand150bfa82019-09-19 17:12:49 +02003114
William Lallemand02010472019-10-18 11:02:19 +02003115 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003116#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02003117 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003118 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02003119 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003120 }
3121#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003122 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003123 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01003124 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02003125 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01003126 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
William Lallemand7980dff2021-11-18 17:46:26 +01003127 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003128 }
William Lallemand7980dff2021-11-18 17:46:26 +01003129
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01003130 /* We are about to raise an handshake error so the servername extension
3131 * callback will never be called and the SNI will never be stored in the
3132 * SSL context. In order for the ssl_fc_sni sample fetch to still work
3133 * in such a case, we store the SNI ourselves as an ex_data information
3134 * in the SSL context.
3135 */
3136 {
3137 char *client_sni = pool_alloc(ssl_sock_client_sni_pool);
3138 if (client_sni) {
3139 strncpy(client_sni, trash.area, TLSEXT_MAXLEN_host_name);
3140 client_sni[TLSEXT_MAXLEN_host_name] = '\0';
3141 SSL_set_ex_data(ssl, ssl_client_sni_index, client_sni);
3142 }
3143 }
3144
William Lallemand7980dff2021-11-18 17:46:26 +01003145 /* other cases fallback on abort, if strict-sni is set but no node was found */
3146
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003147 abort:
3148 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01003149 if (conn)
3150 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003151#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02003152 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003153#else
3154 *al = SSL_AD_UNRECOGNIZED_NAME;
3155 return 0;
3156#endif
William Lallemand7980dff2021-11-18 17:46:26 +01003157
3158allow_early:
3159#ifdef OPENSSL_IS_BORINGSSL
3160 if (allow_early)
3161 SSL_set_early_data_enabled(ssl, 1);
3162#else
3163 if (!allow_early)
3164 SSL_set_max_early_data(ssl, 0);
3165#endif
3166 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003167}
3168
William Lallemand002e2062021-11-18 15:25:16 +01003169#else /* ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003170
Emeric Brunfc0421f2012-09-07 17:30:07 +02003171/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
3172 * warning when no match is found, which implies the default (first) cert
3173 * will keep being used.
3174 */
William Lallemand844009d2022-09-02 15:27:32 +02003175int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003176{
3177 const char *servername;
3178 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003179 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01003180 struct bind_conf *s = priv;
William Lallemand70a6e632022-09-07 11:21:34 +02003181#ifdef USE_QUIC
3182 const uint8_t *extension_data;
3183 size_t extension_len;
3184 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
3185#endif /* USE_QUIC */
Emeric Brunfc0421f2012-09-07 17:30:07 +02003186 int i;
3187 (void)al; /* shut gcc stupid warning */
3188
William Lallemand70a6e632022-09-07 11:21:34 +02003189#ifdef USE_QUIC
3190 if (qc) {
3191
3192 /* Look for the QUIC transport parameters. */
3193 SSL_get_peer_quic_transport_params(ssl, &extension_data, &extension_len);
3194 if (extension_len == 0) {
3195 /* This is not redundant. It we only return 0 without setting
3196 * <*al>, this has as side effect to generate another TLS alert
3197 * which would be set after calling quic_set_tls_alert().
3198 */
3199 *al = SSL_AD_MISSING_EXTENSION;
3200 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
3201 return SSL_TLSEXT_ERR_NOACK;
3202 }
3203
3204 if (!quic_transport_params_store(qc, 0, extension_data,
3205 extension_data + extension_len) ||
3206 !qc_conn_finalize(qc, 0)) {
3207 return SSL_TLSEXT_ERR_NOACK;
3208 }
3209 }
3210#endif /* USE_QUIC */
3211
Emeric Brunfc0421f2012-09-07 17:30:07 +02003212 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01003213 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01003214#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02003215 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003216 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01003217#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003218 if (s->strict_sni)
3219 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01003220 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003221 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01003222 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003223 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01003224 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003225
Willy Tarreau19d14ef2012-10-29 16:51:55 +01003226 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003227 if (!servername[i])
3228 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02003229 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003230 if (!wildp && (trash.area[i] == '.'))
3231 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02003232 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003233 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003234
William Lallemand150bfa82019-09-19 17:12:49 +02003235 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01003236 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003237 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01003238 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
3239 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003240 if (!container_of(n, struct sni_ctx, name)->neg) {
3241 node = n;
3242 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01003243 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003244 }
3245 if (!node && wildp) {
3246 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01003247 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
3248 /* lookup a not neg filter */
3249 if (!container_of(n, struct sni_ctx, name)->neg) {
3250 node = n;
3251 break;
3252 }
3253 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003254 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01003255 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01003256#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02003257 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(servername, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003258 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02003259 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02003260 return SSL_TLSEXT_ERR_OK;
3261 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01003262#endif
William Lallemand21724f02019-11-04 17:56:13 +01003263 if (s->strict_sni) {
3264 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003265 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01003266 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003267 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01003268 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003269 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003270 }
3271
3272 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01003273 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02003274 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003275 return SSL_TLSEXT_ERR_OK;
3276}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003277#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02003278#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
3279
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003280#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003281
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01003282static inline HASSL_DH *ssl_new_dh_fromdata(BIGNUM *p, BIGNUM *g)
3283{
3284#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3285 OSSL_PARAM_BLD *tmpl = NULL;
3286 OSSL_PARAM *params = NULL;
3287 EVP_PKEY_CTX *ctx = NULL;
3288 EVP_PKEY *pkey = NULL;
3289
3290 if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
3291 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
3292 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)
3293 || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
3294 goto end;
3295 }
3296 ctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
3297 if (ctx == NULL
3298 || !EVP_PKEY_fromdata_init(ctx)
3299 || !EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params)) {
3300 goto end;
3301 }
3302
3303end:
3304 EVP_PKEY_CTX_free(ctx);
3305 OSSL_PARAM_free(params);
3306 OSSL_PARAM_BLD_free(tmpl);
Remi Tricot-Le Bretona2c21db2022-11-03 15:16:47 +01003307 BN_free(p);
3308 BN_free(g);
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01003309 return pkey;
3310#else
3311
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003312 HASSL_DH *dh = DH_new();
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01003313
3314 if (!dh)
3315 return NULL;
3316
3317 DH_set0_pqg(dh, p, NULL, g);
3318
3319 return dh;
3320#endif
3321}
3322
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02003323#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003324static inline HASSL_DH *ssl_get_dh_by_nid(int nid)
3325{
3326#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3327 OSSL_PARAM params[2];
3328 EVP_PKEY *pkey = NULL;
3329 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
3330 const char *named_group = NULL;
3331
3332 if (!pctx)
3333 goto end;
3334
3335 named_group = OBJ_nid2ln(nid);
3336
3337 if (!named_group)
3338 goto end;
3339
3340 params[0] = OSSL_PARAM_construct_utf8_string("group", (char*)named_group, 0);
3341 params[1] = OSSL_PARAM_construct_end();
3342
3343 if (EVP_PKEY_keygen_init(pctx) && EVP_PKEY_CTX_set_params(pctx, params))
3344 EVP_PKEY_generate(pctx, &pkey);
3345
3346end:
3347 EVP_PKEY_CTX_free(pctx);
3348 return pkey;
3349#else
3350
3351 HASSL_DH *dh = NULL;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003352 dh = DH_new_by_nid(nid);
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003353 return dh;
3354#endif
3355}
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02003356#endif
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003357
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01003358
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003359static HASSL_DH * ssl_get_dh_1024(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003360{
Remi Gacogned3a341a2015-05-29 16:26:17 +02003361 static unsigned char dh1024_p[]={
3362 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
3363 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
3364 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
3365 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
3366 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
3367 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
3368 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
3369 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
3370 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
3371 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
3372 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
3373 };
3374 static unsigned char dh1024_g[]={
3375 0x02,
3376 };
3377
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003378 BIGNUM *p;
3379 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02003380
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003381 HASSL_DH *dh = NULL;
3382
3383 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
3384 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
3385
3386 if (p && g)
3387 dh = ssl_new_dh_fromdata(p, g);
3388
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003389 return dh;
3390}
3391
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003392static HASSL_DH *ssl_get_dh_2048(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003393{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003394#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02003395 static unsigned char dh2048_p[]={
3396 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
3397 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
3398 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
3399 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
3400 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
3401 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
3402 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
3403 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
3404 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
3405 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
3406 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
3407 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
3408 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
3409 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
3410 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
3411 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
3412 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
3413 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
3414 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
3415 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
3416 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
3417 0xB7,0x1F,0x77,0xF3,
3418 };
3419 static unsigned char dh2048_g[]={
3420 0x02,
3421 };
3422
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003423 BIGNUM *p;
3424 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02003425
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003426 HASSL_DH *dh = NULL;
3427
3428 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
3429 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
3430
3431 if (p && g)
3432 dh = ssl_new_dh_fromdata(p, g);
3433
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003434 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003435#else
3436 return ssl_get_dh_by_nid(NID_ffdhe2048);
3437#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003438}
3439
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003440static HASSL_DH *ssl_get_dh_4096(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003441{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003442#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02003443 static unsigned char dh4096_p[]={
3444 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
3445 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
3446 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
3447 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
3448 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
3449 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
3450 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
3451 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
3452 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
3453 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
3454 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
3455 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
3456 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
3457 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
3458 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
3459 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
3460 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
3461 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
3462 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
3463 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
3464 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
3465 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
3466 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
3467 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
3468 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
3469 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
3470 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
3471 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
3472 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
3473 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
3474 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
3475 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
3476 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
3477 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
3478 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
3479 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
3480 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
3481 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
3482 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
3483 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
3484 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
3485 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
3486 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003487 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02003488 static unsigned char dh4096_g[]={
3489 0x02,
3490 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003491
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003492 BIGNUM *p;
3493 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02003494
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003495 HASSL_DH *dh = NULL;
3496
3497 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
3498 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
3499
3500 if (p && g)
3501 dh = ssl_new_dh_fromdata(p, g);
3502
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003503 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003504#else
3505 return ssl_get_dh_by_nid(NID_ffdhe4096);
3506#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003507}
3508
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003509static HASSL_DH *ssl_get_tmp_dh(EVP_PKEY *pkey)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003510{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003511 HASSL_DH *dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003512 int type;
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003513 int keylen = 0;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003514
3515 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003516
Ilya Shipitsin52f2ff52022-07-23 23:55:19 +05003517 if (type == EVP_PKEY_EC) {
3518 keylen = global_ssl.default_dh_param;
3519 }
3520
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003521 /* The keylen supplied by OpenSSL can only be 512 or 1024.
3522 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
3523 */
3524 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
3525 keylen = EVP_PKEY_bits(pkey);
3526 }
3527
Willy Tarreauef934602016-12-22 23:12:01 +01003528 if (keylen > global_ssl.default_dh_param) {
3529 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003530 }
3531
Remi Gacogned3a341a2015-05-29 16:26:17 +02003532 if (keylen >= 4096) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003533 if (!local_dh_4096)
3534 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02003535 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003536 }
3537 else if (keylen >= 2048) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003538 if (!local_dh_2048)
3539 local_dh_2048 = ssl_get_dh_2048();
Remi Gacogne8de54152014-07-15 11:36:40 +02003540 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003541 }
3542 else {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003543 if (!local_dh_1024)
3544 local_dh_1024 = ssl_get_dh_1024();
Remi Gacogne8de54152014-07-15 11:36:40 +02003545 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003546 }
3547
3548 return dh;
3549}
3550
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003551#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003552/* Returns Diffie-Hellman parameters matching the private key length
3553 but not exceeding global_ssl.default_dh_param */
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003554static HASSL_DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003555{
3556 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
3557
3558 return ssl_get_tmp_dh(pkey);
3559}
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003560#endif
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003561
Remi Tricot-Le Breton846eda92022-02-11 12:04:50 +01003562static int ssl_sock_set_tmp_dh(SSL_CTX *ctx, HASSL_DH *dh)
3563{
3564#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
3565 return SSL_CTX_set_tmp_dh(ctx, dh);
3566#else
3567 int retval = 0;
3568 HASSL_DH_up_ref(dh);
3569
3570 retval = SSL_CTX_set0_tmp_dh_pkey(ctx, dh);
3571
3572 if (!retval)
3573 HASSL_DH_free(dh);
3574
3575 return retval;
3576#endif
3577}
3578
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003579#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3580static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey)
3581{
3582 HASSL_DH *dh = NULL;
3583 if (pkey && (dh = ssl_get_tmp_dh(pkey))) {
3584 HASSL_DH_up_ref(dh);
3585 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dh))
3586 HASSL_DH_free(dh);
3587 }
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003588}
3589#endif
3590
Remi Tricot-Le Breton09ebb332022-02-11 12:04:48 +01003591HASSL_DH *ssl_sock_get_dh_from_bio(BIO *bio)
3592{
3593#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3594 HASSL_DH *dh = NULL;
3595 OSSL_DECODER_CTX *dctx = NULL;
3596 const char *format = "PEM";
3597 const char *keytype = "DH";
3598
3599 dctx = OSSL_DECODER_CTX_new_for_pkey(&dh, format, NULL, keytype,
3600 OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
3601 NULL, NULL);
3602
3603 if (dctx == NULL || OSSL_DECODER_CTX_get_num_decoders(dctx) == 0)
3604 goto end;
3605
3606 /* The DH parameters might not be the first section found in the PEM
3607 * file so we need to iterate over all of them until we find the right
3608 * one.
3609 */
3610 while (!BIO_eof(bio) && !dh)
3611 OSSL_DECODER_from_bio(dctx, bio);
3612
3613end:
3614 OSSL_DECODER_CTX_free(dctx);
3615 return dh;
3616#else
3617 HASSL_DH *dh = NULL;
3618
3619 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3620
3621 return dh;
3622#endif
3623}
3624
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003625static HASSL_DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003626{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003627 HASSL_DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02003628 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003629
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003630 if (in == NULL)
3631 goto end;
3632
Remi Gacogne47783ef2015-05-29 15:53:22 +02003633 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003634 goto end;
3635
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003636 dh = ssl_sock_get_dh_from_bio(in);
Remi Gacogne47783ef2015-05-29 15:53:22 +02003637
3638end:
3639 if (in)
3640 BIO_free(in);
3641
Emeric Brune1b4ed42018-08-16 15:14:12 +02003642 ERR_clear_error();
3643
Remi Gacogne47783ef2015-05-29 15:53:22 +02003644 return dh;
3645}
3646
3647int ssl_sock_load_global_dh_param_from_file(const char *filename)
3648{
3649 global_dh = ssl_sock_get_dh_from_file(filename);
3650
3651 if (global_dh) {
3652 return 0;
3653 }
3654
3655 return -1;
3656}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003657#endif
3658
William Lallemand9117de92019-10-04 00:29:42 +02003659/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02003660static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02003661 struct bind_conf *s, struct ssl_bind_conf *conf,
3662 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003663{
3664 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003665 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003666
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003667 if (*name == '!') {
3668 neg = 1;
3669 name++;
3670 }
3671 if (*name == '*') {
3672 wild = 1;
3673 name++;
3674 }
3675 /* !* filter is a nop */
3676 if (neg && wild)
3677 return order;
3678 if (*name) {
3679 int j, len;
3680 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003681 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02003682 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003683 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02003684 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003685 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003686
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003687 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02003688 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02003689 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003690 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02003691 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003692 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003693 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003694 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003695 sc->order = order++;
3696 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02003697 sc->wild = wild;
3698 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01003699 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02003700 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003701 }
3702 return order;
3703}
3704
William Lallemand6af03992019-07-23 15:00:54 +02003705/*
William Lallemand1d29c742019-10-04 00:53:29 +02003706 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
3707 * This function can't return an error.
3708 *
3709 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
3710 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003711void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02003712{
3713
3714 struct sni_ctx *sc0, *sc0b, *sc1;
3715 struct ebmb_node *node;
3716
3717 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
3718
3719 /* ignore if sc0 was already inserted in a tree */
3720 if (sc0->name.node.leaf_p)
3721 continue;
3722
3723 /* Check for duplicates. */
3724 if (sc0->wild)
3725 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
3726 else
3727 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
3728
3729 for (; node; node = ebmb_next_dup(node)) {
3730 sc1 = ebmb_entry(node, struct sni_ctx, name);
3731 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
3732 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
3733 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02003734 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02003735 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003736 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02003737 break;
William Lallemand1d29c742019-10-04 00:53:29 +02003738 }
3739 }
3740
3741 /* if duplicate, ignore the insertion */
3742 if (!sc0)
3743 continue;
3744
3745 if (sc0->wild)
3746 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
3747 else
3748 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003749 }
William Lallemand21724f02019-11-04 17:56:13 +01003750
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003751 /* replace the default_ctx if required with the instance's ctx. */
3752 if (ckch_inst->is_default) {
3753 SSL_CTX_free(bind_conf->default_ctx);
3754 SSL_CTX_up_ref(ckch_inst->ctx);
3755 bind_conf->default_ctx = ckch_inst->ctx;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003756 bind_conf->default_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02003757 }
3758}
3759
3760/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003761 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02003762 */
William Lallemande3af8fb2019-10-08 11:36:53 +02003763struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02003764
William Lallemand2954c472020-03-06 21:54:13 +01003765/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02003766struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02003767
Emeric Brun7a883362019-10-17 13:27:40 +02003768/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003769 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02003770 * DH parameter is loaded into the SSL_CTX and if there is no
3771 * DH parameter available in ckchs nor in global, the default
3772 * DH parameters are applied on the SSL_CTX.
3773 * Returns a bitfield containing the flags:
3774 * ERR_FATAL in any fatal error case
3775 * ERR_ALERT if a reason of the error is availabine in err
3776 * ERR_WARN if a warning is available into err
3777 * The value 0 means there is no error nor warning and
3778 * the operation succeed.
3779 */
William Lallemandfa892222019-07-23 16:06:08 +02003780#ifndef OPENSSL_NO_DH
William Lallemand52ddd992022-11-22 11:51:53 +01003781static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct ckch_data *data,
Emeric Brun7a883362019-10-17 13:27:40 +02003782 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02003783{
Emeric Brun7a883362019-10-17 13:27:40 +02003784 int ret = 0;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003785 HASSL_DH *dh = NULL;
William Lallemandfa892222019-07-23 16:06:08 +02003786
William Lallemand52ddd992022-11-22 11:51:53 +01003787 if (data && data->dh) {
3788 dh = data->dh;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003789 if (!ssl_sock_set_tmp_dh(ctx, dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003790 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
3791 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003792 memprintf(err, "%s, DH ciphers won't be available.\n",
3793 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003794 ret |= ERR_WARN;
3795 goto end;
3796 }
William Lallemandfa892222019-07-23 16:06:08 +02003797
3798 if (ssl_dh_ptr_index >= 0) {
3799 /* store a pointer to the DH params to avoid complaining about
3800 ssl-default-dh-param not being set for this SSL_CTX */
3801 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
3802 }
3803 }
3804 else if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003805 if (!ssl_sock_set_tmp_dh(ctx, global_dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003806 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
3807 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003808 memprintf(err, "%s, DH ciphers won't be available.\n",
3809 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003810 ret |= ERR_WARN;
3811 goto end;
3812 }
William Lallemandfa892222019-07-23 16:06:08 +02003813 }
3814 else {
3815 /* Clear openssl global errors stack */
3816 ERR_clear_error();
3817
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003818 /* We do not want DHE ciphers to be added to the cipher list
3819 * unless there is an explicit global dh option in the conf.
3820 */
3821 if (global_ssl.default_dh_param) {
3822 if (global_ssl.default_dh_param <= 1024) {
3823 /* we are limited to DH parameter of 1024 bits anyway */
3824 if (local_dh_1024 == NULL)
3825 local_dh_1024 = ssl_get_dh_1024();
William Lallemandfa892222019-07-23 16:06:08 +02003826
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003827 if (local_dh_1024 == NULL) {
3828 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3829 err && *err ? *err : "", path);
3830 ret |= ERR_ALERT | ERR_FATAL;
3831 goto end;
3832 }
William Lallemandfa892222019-07-23 16:06:08 +02003833
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003834 if (!ssl_sock_set_tmp_dh(ctx, local_dh_1024)) {
3835 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3836 err && *err ? *err : "", path);
3837 memprintf(err, "%s, DH ciphers won't be available.\n",
3838 err && *err ? *err : "");
3839 ret |= ERR_WARN;
3840 goto end;
3841 }
Emeric Bruna9363eb2019-10-17 14:53:03 +02003842 }
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003843 else {
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003844#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003845 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003846#else
William Lallemand52ddd992022-11-22 11:51:53 +01003847 ssl_sock_set_tmp_dh_from_pkey(ctx, data ? data->key : NULL);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003848#endif
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003849 }
William Lallemandfa892222019-07-23 16:06:08 +02003850 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003851 }
3852
William Lallemandf9568fc2019-10-16 18:27:58 +02003853end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003854 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003855 return ret;
3856}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003857#endif
William Lallemandfa892222019-07-23 16:06:08 +02003858
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003859
3860/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003861 * Returns a bitfield containing the flags:
3862 * ERR_FATAL in any fatal error case
3863 * ERR_ALERT if the reason of the error is available in err
3864 * ERR_WARN if a warning is available into err
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003865 * The caller is responsible of freeing the newly built or newly refcounted
3866 * find_chain element.
Emeric Bruna96b5822019-10-17 13:25:14 +02003867 * The value 0 means there is no error nor warning and
3868 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003869 */
William Lallemand52ddd992022-11-22 11:51:53 +01003870static int ssl_sock_load_cert_chain(const char *path, const struct ckch_data *data,
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003871 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003872{
Emeric Bruna96b5822019-10-17 13:25:14 +02003873 int errcode = 0;
William Lallemand45fed2c2022-11-15 16:56:03 +01003874 int ret;
3875
3876 ERR_clear_error();
Emeric Bruna96b5822019-10-17 13:25:14 +02003877
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003878 if (find_chain == NULL) {
3879 errcode |= ERR_FATAL;
3880 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003881 }
3882
William Lallemand52ddd992022-11-22 11:51:53 +01003883 if (!SSL_CTX_use_certificate(ctx, data->cert)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003884 ret = ERR_get_error();
3885 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s': %s.\n",
3886 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Emeric Bruna96b5822019-10-17 13:25:14 +02003887 errcode |= ERR_ALERT | ERR_FATAL;
3888 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003889 }
3890
William Lallemand52ddd992022-11-22 11:51:53 +01003891 if (data->chain) {
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003892 *find_chain = X509_chain_up_ref(data->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003893 } else {
3894 /* Find Certificate Chain in global */
3895 struct issuer_chain *issuer;
William Lallemand52ddd992022-11-22 11:51:53 +01003896 issuer = ssl_get0_issuer_chain(data->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003897 if (issuer)
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003898 *find_chain = X509_chain_up_ref(issuer->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003899 }
William Lallemand85888572020-02-27 14:48:35 +01003900
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003901 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003902 /* always put a null chain stack in the SSL_CTX so it does not
3903 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003904 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003905 }
3906
William Lallemand52ddd992022-11-22 11:51:53 +01003907 /* Load all certs in the data into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003908#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003909 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand45fed2c2022-11-15 16:56:03 +01003910 ret = ERR_get_error();
3911 memprintf(err, "%sunable to load chain certificate into SSL Context '%s': %s. Make sure you are linking against Openssl >= 1.0.2.\n",
3912 err && *err ? *err : "", path, ERR_reason_error_string(ret));
William Lallemand935d8292020-08-12 20:02:10 +02003913 errcode |= ERR_ALERT | ERR_FATAL;
3914 goto end;
3915 }
William Lallemandf187ce62020-06-02 18:27:20 +02003916#else
3917 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003918 X509 *ca;
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01003919 while ((ca = sk_X509_shift(*find_chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003920 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003921 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3922 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003923 X509_free(ca);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003924 errcode |= ERR_ALERT | ERR_FATAL;
3925 goto end;
3926 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003927 }
William Lallemandf187ce62020-06-02 18:27:20 +02003928#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003929
William Lallemand9a1d8392020-08-10 17:28:23 +02003930#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003931 /* remove the Root CA from the SSL_CTX if the option is activated */
3932 if (global_ssl.skip_self_issued_ca) {
3933 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3934 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3935 err && *err ? *err : "", path);
3936 errcode |= ERR_ALERT | ERR_FATAL;
3937 goto end;
3938 }
3939 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003940#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003941
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003942end:
3943 return errcode;
3944}
3945
3946
3947/* Loads the info in ckch into ctx
3948 * Returns a bitfield containing the flags:
3949 * ERR_FATAL in any fatal error case
3950 * ERR_ALERT if the reason of the error is available in err
3951 * ERR_WARN if a warning is available into err
3952 * The value 0 means there is no error nor warning and
3953 * the operation succeed.
3954 */
Remi Tricot-Le Bretoncc346672022-12-20 11:11:08 +01003955static int ssl_sock_put_ckch_into_ctx(const char *path, struct ckch_data *data, SSL_CTX *ctx, char **err)
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003956{
3957 int errcode = 0;
3958 STACK_OF(X509) *find_chain = NULL;
3959
William Lallemand5de49512022-10-27 14:41:07 +02003960 ERR_clear_error();
3961
William Lallemand52ddd992022-11-22 11:51:53 +01003962 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
William Lallemand5de49512022-10-27 14:41:07 +02003963 int ret;
3964
3965 ret = ERR_get_error();
3966 memprintf(err, "%sunable to load SSL private key into SSL Context '%s': %s.\n",
3967 err && *err ? *err : "", path, ERR_reason_error_string(ret));
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003968 errcode |= ERR_ALERT | ERR_FATAL;
3969 return errcode;
3970 }
3971
3972 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01003973 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003974 if (errcode & ERR_CODE)
3975 goto end;
3976
William Lallemandfa892222019-07-23 16:06:08 +02003977#ifndef OPENSSL_NO_DH
3978 /* store a NULL pointer to indicate we have not yet loaded
3979 a custom DH param file */
3980 if (ssl_dh_ptr_index >= 0) {
3981 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3982 }
3983
William Lallemand52ddd992022-11-22 11:51:53 +01003984 errcode |= ssl_sock_load_dh_params(ctx, data, path, err);
Emeric Brun7a883362019-10-17 13:27:40 +02003985 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003986 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3987 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003988 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003989 }
3990#endif
3991
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003992#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemand52ddd992022-11-22 11:51:53 +01003993 if (sctl_ex_index >= 0 && data->sctl) {
3994 if (ssl_sock_load_sctl(ctx, data->sctl) < 0) {
William Lallemanda17f4112019-10-10 15:16:44 +02003995 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003996 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003997 errcode |= ERR_ALERT | ERR_FATAL;
3998 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003999 }
4000 }
4001#endif
4002
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01004003#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
William Lallemand246c0242019-10-11 08:59:13 +02004004 /* Load OCSP Info into context */
William Lallemand52ddd992022-11-22 11:51:53 +01004005 if (data->ocsp_response) {
4006 if (ssl_sock_load_ocsp(ctx, data, find_chain) < 0) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004007 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",
4008 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02004009 errcode |= ERR_ALERT | ERR_FATAL;
4010 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02004011 }
4012 }
William Lallemand246c0242019-10-11 08:59:13 +02004013#endif
4014
Emeric Bruna96b5822019-10-17 13:25:14 +02004015 end:
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01004016 sk_X509_pop_free(find_chain, X509_free);
Emeric Bruna96b5822019-10-17 13:25:14 +02004017 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05004018}
4019
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004020
4021/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
4022 * Returns a bitfield containing the flags:
4023 * ERR_FATAL in any fatal error case
4024 * ERR_ALERT if the reason of the error is available in err
4025 * ERR_WARN if a warning is available into err
4026 * The value 0 means there is no error nor warning and
4027 * the operation succeed.
4028 */
William Lallemand52ddd992022-11-22 11:51:53 +01004029static 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 +01004030 SSL_CTX *ctx, char **err)
4031{
4032 int errcode = 0;
4033 STACK_OF(X509) *find_chain = NULL;
4034
4035 /* Load the private key */
William Lallemand52ddd992022-11-22 11:51:53 +01004036 if (SSL_CTX_use_PrivateKey(ctx, data->key) <= 0) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004037 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
4038 err && *err ? *err : "", path);
4039 errcode |= ERR_ALERT | ERR_FATAL;
4040 }
4041
4042 /* Load certificate chain */
William Lallemand52ddd992022-11-22 11:51:53 +01004043 errcode |= ssl_sock_load_cert_chain(path, data, ctx, &find_chain, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004044 if (errcode & ERR_CODE)
4045 goto end;
4046
4047 if (SSL_CTX_check_private_key(ctx) <= 0) {
4048 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
4049 err && *err ? *err : "", path);
4050 errcode |= ERR_ALERT | ERR_FATAL;
4051 }
4052
4053end:
Remi Tricot-Le Breton4cf0d3f2022-12-15 15:44:37 +01004054 sk_X509_pop_free(find_chain, X509_free);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004055 return errcode;
4056}
4057
4058
William Lallemand614ca0d2019-10-07 13:52:11 +02004059/*
4060 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02004061 *
4062 * Returns a bitfield containing the flags:
4063 * ERR_FATAL in any fatal error case
4064 * ERR_ALERT if the reason of the error is available in err
4065 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02004066 */
William Lallemandc756bbd2020-05-13 17:23:59 +02004067int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02004068 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004069{
William Lallemandc9402072019-05-15 15:33:54 +02004070 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02004071 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004072 int order = 0;
4073 X509_NAME *xname;
4074 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01004075 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02004076 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02004077#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
4078 STACK_OF(GENERAL_NAME) *names;
4079#endif
William Lallemand52ddd992022-11-22 11:51:53 +01004080 struct ckch_data *data;
William Lallemand614ca0d2019-10-07 13:52:11 +02004081 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02004082 int errcode = 0;
4083
4084 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02004085
William Lallemand52ddd992022-11-22 11:51:53 +01004086 if (!ckchs || !ckchs->data)
Emeric Brun054563d2019-10-17 13:16:58 +02004087 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004088
William Lallemand52ddd992022-11-22 11:51:53 +01004089 data = ckchs->data;
William Lallemand36b84632019-07-18 19:28:17 +02004090
William Lallemandc9402072019-05-15 15:33:54 +02004091 ctx = SSL_CTX_new(SSLv23_server_method());
4092 if (!ctx) {
4093 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
4094 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02004095 errcode |= ERR_ALERT | ERR_FATAL;
4096 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02004097 }
4098
William Lallemand52ddd992022-11-22 11:51:53 +01004099 errcode |= ssl_sock_put_ckch_into_ctx(path, data, ctx, err);
Emeric Bruna96b5822019-10-17 13:25:14 +02004100 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02004101 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02004102
4103 ckch_inst = ckch_inst_new();
4104 if (!ckch_inst) {
4105 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
4106 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02004107 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02004108 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02004109 }
4110
William Lallemand52ddd992022-11-22 11:51:53 +01004111 pkey = X509_get_pubkey(data->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01004112 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02004113 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01004114 switch(EVP_PKEY_base_id(pkey)) {
4115 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02004116 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01004117 break;
4118 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02004119 kinfo.sig = TLSEXT_signature_ecdsa;
4120 break;
4121 case EVP_PKEY_DSA:
4122 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01004123 break;
4124 }
4125 EVP_PKEY_free(pkey);
4126 }
4127
Emeric Brun50bcecc2013-04-22 13:05:23 +02004128 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02004129 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02004130 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 +02004131 if (order < 0) {
4132 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02004133 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02004134 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02004135 }
4136 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01004137 }
4138 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02004139#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand52ddd992022-11-22 11:51:53 +01004140 names = X509_get_ext_d2i(data->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01004141 if (names) {
4142 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
4143 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
4144 if (name->type == GEN_DNS) {
4145 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02004146 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01004147 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02004148 if (order < 0) {
4149 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02004150 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02004151 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02004152 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004153 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004154 }
4155 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01004156 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004157 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004158#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand52ddd992022-11-22 11:51:53 +01004159 xname = X509_get_subject_name(data->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01004160 i = -1;
4161 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
4162 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004163 ASN1_STRING *value;
4164
4165 value = X509_NAME_ENTRY_get_data(entry);
4166 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02004167 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01004168 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02004169 if (order < 0) {
4170 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02004171 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02004172 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02004173 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004174 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004175 }
4176 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004177 /* we must not free the SSL_CTX anymore below, since it's already in
4178 * the tree, so it will be discovered and cleaned in time.
4179 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02004180
Emeric Brunfc0421f2012-09-07 17:30:07 +02004181#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004182 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004183 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
4184 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02004185 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02004186 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004187 }
4188#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004189 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004190 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004191 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01004192 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02004193 SSL_CTX_up_ref(ctx);
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02004194 bind_conf->default_inst = ckch_inst;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004195 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004196
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01004197 /* Always keep a reference to the newly constructed SSL_CTX in the
4198 * instance. This way if the instance has no SNIs, the SSL_CTX will
4199 * still be linked. */
4200 SSL_CTX_up_ref(ctx);
4201 ckch_inst->ctx = ctx;
4202
William Lallemand9117de92019-10-04 00:29:42 +02004203 /* everything succeed, the ckch instance can be used */
4204 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02004205 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01004206 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02004207
William Lallemand02e19a52020-04-08 16:11:26 +02004208 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
4209
Emeric Brun054563d2019-10-17 13:16:58 +02004210 *ckchi = ckch_inst;
4211 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02004212
4213error:
4214 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02004215 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02004216 if (ckch_inst->is_default)
4217 SSL_CTX_free(ctx);
4218
William Lallemandd9d5d1b2020-04-09 16:31:05 +02004219 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02004220 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02004221 }
William Lallemandd9199372019-10-04 15:37:05 +02004222 SSL_CTX_free(ctx);
4223
Emeric Brun054563d2019-10-17 13:16:58 +02004224 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004225}
4226
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004227
4228/*
4229 * This function allocate a ckch_inst that will be used on the backend side
4230 * (server line)
4231 *
4232 * Returns a bitfield containing the flags:
4233 * ERR_FATAL in any fatal error case
4234 * ERR_ALERT if the reason of the error is available in err
4235 * ERR_WARN if a warning is available into err
4236 */
4237int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01004238 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004239{
4240 SSL_CTX *ctx;
William Lallemand52ddd992022-11-22 11:51:53 +01004241 struct ckch_data *data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004242 struct ckch_inst *ckch_inst = NULL;
4243 int errcode = 0;
4244
4245 *ckchi = NULL;
4246
William Lallemand52ddd992022-11-22 11:51:53 +01004247 if (!ckchs || !ckchs->data)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004248 return ERR_FATAL;
4249
William Lallemand52ddd992022-11-22 11:51:53 +01004250 data = ckchs->data;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004251
4252 ctx = SSL_CTX_new(SSLv23_client_method());
4253 if (!ctx) {
4254 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
4255 err && *err ? *err : "", path);
4256 errcode |= ERR_ALERT | ERR_FATAL;
4257 goto error;
4258 }
4259
William Lallemand52ddd992022-11-22 11:51:53 +01004260 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, data, ctx, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004261 if (errcode & ERR_CODE)
4262 goto error;
4263
4264 ckch_inst = ckch_inst_new();
4265 if (!ckch_inst) {
4266 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
4267 err && *err ? *err : "", path);
4268 errcode |= ERR_ALERT | ERR_FATAL;
4269 goto error;
4270 }
4271
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004272 /* everything succeed, the ckch instance can be used */
4273 ckch_inst->bind_conf = NULL;
4274 ckch_inst->ssl_conf = NULL;
4275 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01004276 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01004277 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004278
4279 *ckchi = ckch_inst;
4280 return errcode;
4281
4282error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004283 SSL_CTX_free(ctx);
4284
4285 return errcode;
4286}
4287
Willy Tarreau8c5414a2019-10-16 17:06:25 +02004288/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02004289static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
4290 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01004291 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02004292{
Emeric Brun054563d2019-10-17 13:16:58 +02004293 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02004294
4295 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02004296 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 +02004297
Emeric Brun054563d2019-10-17 13:16:58 +02004298 if (errcode & ERR_CODE)
4299 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02004300
William Lallemand24bde432020-03-09 16:48:43 +01004301 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02004302
4303 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02004304 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02004305 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02004306}
4307
William Lallemanddb26e2b2021-01-26 12:01:46 +01004308/* This function generates a <struct ckch_inst *> for a <struct server *>, and
4309 * fill the SSL_CTX of the server.
4310 *
4311 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004312static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01004313 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004314{
4315 int errcode = 0;
4316
4317 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01004318 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004319
4320 if (errcode & ERR_CODE)
4321 return errcode;
4322
William Lallemanddb26e2b2021-01-26 12:01:46 +01004323 (*ckch_inst)->server = server;
4324 /* Keep the reference to the SSL_CTX in the server. */
4325 SSL_CTX_up_ref((*ckch_inst)->ctx);
4326 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004327 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02004328 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004329 return errcode;
4330}
4331
William Lallemand6be66ec2020-03-06 22:26:32 +01004332
William Lallemand4c68bba2020-03-30 18:45:10 +02004333
4334
4335/* Make sure openssl opens /dev/urandom before the chroot. The work is only
4336 * done once. Zero is returned if the operation fails. No error is returned
4337 * if the random is said as not implemented, because we expect that openssl
4338 * will use another method once needed.
4339 */
Amaury Denoyellec593bcd2021-05-19 15:35:29 +02004340int ssl_initialize_random(void)
William Lallemand4c68bba2020-03-30 18:45:10 +02004341{
4342 unsigned char random;
4343 static int random_initialized = 0;
4344
4345 if (!random_initialized && RAND_bytes(&random, 1) != 0)
4346 random_initialized = 1;
4347
4348 return random_initialized;
4349}
4350
William Lallemand2954c472020-03-06 21:54:13 +01004351/* Load a crt-list file, this is done in 2 parts:
4352 * - store the content of the file in a crtlist structure with crtlist_entry structures
4353 * - generate the instances by iterating on entries in the crtlist struct
4354 *
4355 * Nothing is locked there, this function is used in the configuration parser.
4356 *
4357 * Returns a set of ERR_* flags possibly with an error in <err>.
4358 */
William Lallemand6be66ec2020-03-06 22:26:32 +01004359int 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 +01004360{
4361 struct crtlist *crtlist = NULL;
4362 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02004363 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01004364 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01004365 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02004366 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01004367
William Lallemand79d31ec2020-03-25 15:10:49 +01004368 bind_conf_node = malloc(sizeof(*bind_conf_node));
4369 if (!bind_conf_node) {
4370 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
4371 cfgerr |= ERR_FATAL | ERR_ALERT;
4372 goto error;
4373 }
4374 bind_conf_node->next = NULL;
4375 bind_conf_node->bind_conf = bind_conf;
4376
William Lallemand41ca9302020-04-08 13:15:18 +02004377 /* strip trailing slashes, including first one */
4378 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
4379 *end = 0;
4380
William Lallemand2954c472020-03-06 21:54:13 +01004381 /* look for an existing crtlist or create one */
4382 eb = ebst_lookup(&crtlists_tree, file);
4383 if (eb) {
4384 crtlist = ebmb_entry(eb, struct crtlist, node);
4385 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01004386 /* load a crt-list OR a directory */
4387 if (dir)
4388 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
4389 else
4390 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
4391
William Lallemand2954c472020-03-06 21:54:13 +01004392 if (!(cfgerr & ERR_CODE))
4393 ebst_insert(&crtlists_tree, &crtlist->node);
4394 }
4395
4396 if (cfgerr & ERR_CODE) {
4397 cfgerr |= ERR_FATAL | ERR_ALERT;
4398 goto error;
4399 }
4400
4401 /* generates ckch instance from the crtlist_entry */
4402 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
4403 struct ckch_store *store;
4404 struct ckch_inst *ckch_inst = NULL;
4405
4406 store = entry->node.key;
4407 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
4408 if (cfgerr & ERR_CODE) {
4409 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
4410 goto error;
4411 }
Willy Tarreau2b718102021-04-21 07:32:39 +02004412 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02004413 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01004414 }
William Lallemand2954c472020-03-06 21:54:13 +01004415
William Lallemand79d31ec2020-03-25 15:10:49 +01004416 /* add the bind_conf to the list */
4417 bind_conf_node->next = crtlist->bind_conf;
4418 crtlist->bind_conf = bind_conf_node;
4419
William Lallemand2954c472020-03-06 21:54:13 +01004420 return cfgerr;
4421error:
4422 {
William Lallemand49398312020-03-30 17:01:33 +02004423 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01004424 struct ckch_inst *inst, *s_inst;
4425
William Lallemand49398312020-03-30 17:01:33 +02004426 lastentry = entry; /* which entry we tried to generate last */
4427 if (lastentry) {
4428 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
4429 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
4430 break;
4431
4432 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01004433
William Lallemand49398312020-03-30 17:01:33 +02004434 /* this was not generated for this bind_conf, skip */
4435 if (inst->bind_conf != bind_conf)
4436 continue;
4437
William Lallemandd9d5d1b2020-04-09 16:31:05 +02004438 /* free the sni_ctx and instance */
4439 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02004440 }
William Lallemand2954c472020-03-06 21:54:13 +01004441 }
William Lallemand2954c472020-03-06 21:54:13 +01004442 }
William Lallemand79d31ec2020-03-25 15:10:49 +01004443 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01004444 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01004445 return cfgerr;
4446}
4447
William Lallemand06b22a82020-03-16 14:45:55 +01004448/* Returns a set of ERR_* flags possibly with an error in <err>. */
4449int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
4450{
4451 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01004452 int cfgerr = 0;
4453 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01004454 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01004455 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01004456
4457 if ((ckchs = ckchs_lookup(path))) {
4458 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01004459 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
4460 found++;
4461 } else if (stat(path, &buf) == 0) {
4462 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01004463 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02004464 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01004465 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01004466 cfgerr |= ERR_ALERT | ERR_FATAL;
4467 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01004468 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01004469 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01004470 }
4471 } else {
4472 /* stat failed, could be a bundle */
4473 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02004474 char fp[MAXPATHLEN+1] = {0};
4475 int n = 0;
4476
4477 /* Load all possible certs and keys in separate ckch_store */
4478 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
4479 struct stat buf;
4480 int ret;
4481
4482 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
4483 if (ret > sizeof(fp))
4484 continue;
4485
4486 if ((ckchs = ckchs_lookup(fp))) {
4487 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01004488 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02004489 } else {
4490 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01004491 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02004492 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02004493 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01004494 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02004495 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
4496 }
4497 }
4498 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01004499#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
4500 if (found) {
4501 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
4502 err && *err ? *err : "", path);
4503 cfgerr |= ERR_ALERT | ERR_FATAL;
4504 }
4505#endif
William Lallemand06b22a82020-03-16 14:45:55 +01004506 }
4507 }
William Lallemand06ce84a2020-11-20 15:36:13 +01004508 if (!found) {
4509 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
4510 err && *err ? *err : "", path, strerror(errno));
4511 cfgerr |= ERR_ALERT | ERR_FATAL;
4512 }
William Lallemand06b22a82020-03-16 14:45:55 +01004513
4514 return cfgerr;
4515}
4516
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004517
4518/* Create a full ssl context and ckch instance that will be used for a specific
4519 * backend server (server configuration line).
4520 * Returns a set of ERR_* flags possibly with an error in <err>.
4521 */
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004522int 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 +01004523{
4524 struct stat buf;
4525 int cfgerr = 0;
4526 struct ckch_store *ckchs;
4527 int found = 0; /* did we found a file to load ? */
4528
4529 if ((ckchs = ckchs_lookup(path))) {
4530 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01004531 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004532 found++;
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004533 } else {
4534 if (!create_if_none) {
4535 memprintf(err, "%sunable to stat SSL certificate '%s'.\n",
4536 err && *err ? *err : "", path);
4537 cfgerr |= ERR_ALERT | ERR_FATAL;
4538 goto out;
4539 }
4540
4541 if (stat(path, &buf) == 0) {
4542 /* We do not manage directories on backend side. */
4543 if (S_ISDIR(buf.st_mode) == 0) {
4544 ++found;
4545 ckchs = ckchs_load_cert_file(path, err);
4546 if (!ckchs)
4547 cfgerr |= ERR_ALERT | ERR_FATAL;
4548 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
4549 }
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004550 }
4551 }
4552 if (!found) {
4553 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
4554 err && *err ? *err : "", path, strerror(errno));
4555 cfgerr |= ERR_ALERT | ERR_FATAL;
4556 }
4557
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004558out:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004559 return cfgerr;
4560}
4561
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004562/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004563static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004564ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004565{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004566 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004567 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004568 SSL_OP_ALL | /* all known workarounds for bugs */
4569 SSL_OP_NO_SSLv2 |
4570 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02004571 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02004572 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004573 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02004574 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004575 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004576 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004577 SSL_MODE_ENABLE_PARTIAL_WRITE |
4578 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004579 SSL_MODE_RELEASE_BUFFERS |
4580 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004581 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004582 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004583 int flags = MC_SSL_O_ALL;
4584 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02004585 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004586
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004587 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004588 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004589
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004590 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004591 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
4592 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4593 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004594 else
4595 flags = conf_ssl_methods->flags;
4596
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004597 min = conf_ssl_methods->min;
4598 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02004599
4600 /* default minimum is TLSV12, */
4601 if (!min) {
4602 if (!max || (max >= default_min_ver)) {
4603 min = default_min_ver;
4604 } else {
4605 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). "
4606 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
4607 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
4608 min = max;
4609 }
4610 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004611 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004612 if (min)
4613 flags |= (methodVersions[min].flag - 1);
4614 if (max)
4615 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004616 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004617 min = max = CONF_TLSV_NONE;
4618 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004619 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004620 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004621 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004622 if (min) {
4623 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004624 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
4625 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4626 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
4627 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004628 hole = 0;
4629 }
4630 max = i;
4631 }
4632 else {
4633 min = max = i;
4634 }
4635 }
4636 else {
4637 if (min)
4638 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004639 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004640 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004641 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4642 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004643 cfgerr += 1;
4644 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004645 /* save real min/max in bind_conf */
4646 conf_ssl_methods->min = min;
4647 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004648
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004649#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004650 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004651 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004652 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004653 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004654 else
William Lallemandd0712f32020-06-11 17:34:00 +02004655 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
4656 /* clear every version flags in case SSL_CTX_new()
4657 * returns an SSL_CTX with disabled versions */
4658 SSL_CTX_clear_options(ctx, methodVersions[i].option);
4659
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004660 if (flags & methodVersions[i].flag)
4661 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02004662
4663 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004664#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004665 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004666 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4667 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02004668#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004669
4670 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
4671 options |= SSL_OP_NO_TICKET;
4672 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
4673 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08004674
4675#ifdef SSL_OP_NO_RENEGOTIATION
4676 options |= SSL_OP_NO_RENEGOTIATION;
4677#endif
4678
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004679 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004680
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004681#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004682 if (global_ssl.async)
4683 mode |= SSL_MODE_ASYNC;
4684#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004685 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004686 if (global_ssl.life_time)
4687 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004688
4689#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand4b7938d2022-09-07 10:54:17 +02004690# ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004691 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
4692 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004693# elif defined(HAVE_SSL_CLIENT_HELLO_CB)
4694# if defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01004695 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01004696 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
William Lallemand4b7938d2022-09-07 10:54:17 +02004697# endif /* ! SSL_OP_NO_ANTI_REPLAY */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02004698 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
4699 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004700# else /* ! OPENSSL_IS_BORINGSSL && ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004701 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
William Lallemand4b7938d2022-09-07 10:54:17 +02004702# endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02004703 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
William Lallemand4b7938d2022-09-07 10:54:17 +02004704#endif /* ! SSL_CTRL_SET_TLSEXT_HOSTNAME */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004705 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004706}
4707
William Lallemand4f45bb92017-10-30 20:08:51 +01004708
4709static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
4710{
4711 if (first == block) {
4712 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4713 if (first->len > 0)
4714 sh_ssl_sess_tree_delete(sh_ssl_sess);
4715 }
4716}
4717
4718/* return first block from sh_ssl_sess */
4719static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
4720{
4721 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
4722
4723}
4724
4725/* store a session into the cache
4726 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
4727 * data: asn1 encoded session
4728 * data_len: asn1 encoded session length
4729 * Returns 1 id session was stored (else 0)
4730 */
4731static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
4732{
4733 struct shared_block *first;
4734 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
4735
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004736 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01004737 if (!first) {
4738 /* Could not retrieve enough free blocks to store that session */
4739 return 0;
4740 }
4741
4742 /* STORE the key in the first elem */
4743 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4744 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
4745 first->len = sizeof(struct sh_ssl_sess_hdr);
4746
4747 /* it returns the already existing node
4748 or current node if none, never returns null */
4749 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
4750 if (oldsh_ssl_sess != sh_ssl_sess) {
4751 /* NOTE: Row couldn't be in use because we lock read & write function */
4752 /* release the reserved row */
4753 shctx_row_dec_hot(ssl_shctx, first);
4754 /* replace the previous session already in the tree */
4755 sh_ssl_sess = oldsh_ssl_sess;
4756 /* ignore the previous session data, only use the header */
4757 first = sh_ssl_sess_first_block(sh_ssl_sess);
4758 shctx_row_inc_hot(ssl_shctx, first);
4759 first->len = sizeof(struct sh_ssl_sess_hdr);
4760 }
4761
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004762 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01004763 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004764 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01004765 }
4766
4767 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004768
4769 return 1;
4770}
William Lallemanded0b5ad2017-10-30 19:36:36 +01004771
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004772/* SSL callback used when a new session is created while connecting to a server */
4773static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4774{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004775 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004776 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004777
Willy Tarreau07d94e42018-09-20 10:57:52 +02004778 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004779
William Lallemand3ce6eed2021-02-08 10:43:44 +01004780 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4781 * one cache per thread, it only prevents to flush it from the CLI in
4782 * another thread */
4783
Olivier Houcharde6060c52017-11-16 17:42:52 +01004784 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4785 int len;
4786 unsigned char *ptr;
William Lallemande18d4e82021-11-17 02:59:21 +01004787 const char *sni;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004788
Olivier Houcharde6060c52017-11-16 17:42:52 +01004789 len = i2d_SSL_SESSION(sess, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01004790 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004791 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004792 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4793 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4794 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004795 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
4796 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004797 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4798 }
4799 if (s->ssl_ctx.reused_sess[tid].ptr) {
4800 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4801 &ptr);
4802 }
William Lallemande18d4e82021-11-17 02:59:21 +01004803
4804 if (s->ssl_ctx.reused_sess[tid].sni) {
4805 /* if the new sni is empty or isn' t the same as the old one */
4806 if ((!sni) || strcmp(s->ssl_ctx.reused_sess[tid].sni, sni) != 0) {
4807 ha_free(&s->ssl_ctx.reused_sess[tid].sni);
4808 if (sni)
4809 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4810 }
4811 } else if (sni) {
4812 /* if there wasn't an old sni but there is a new one */
4813 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4814 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004815 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004816 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004817 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004818 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004819 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004820 }
4821
4822 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004823}
4824
Olivier Houcharde6060c52017-11-16 17:42:52 +01004825
William Lallemanded0b5ad2017-10-30 19:36:36 +01004826/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004827int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004828{
4829 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4830 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4831 unsigned char *p;
4832 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004833 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004834 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004835
4836 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004837 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004838 * note: SSL_SESSION_set1_id is using
4839 * a memcpy so we need to use a different pointer
4840 * than sid_data or sid_ctx_data to avoid valgrind
4841 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004842 */
4843
4844 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004845
4846 /* copy value in an other buffer */
4847 memcpy(encid, sid_data, sid_length);
4848
4849 /* pad with 0 */
4850 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4851 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4852
4853 /* force length to zero to avoid ASN1 encoding */
4854 SSL_SESSION_set1_id(sess, encid, 0);
4855
4856 /* force length to zero to avoid ASN1 encoding */
4857 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004858
4859 /* check if buffer is large enough for the ASN1 encoded session */
4860 data_len = i2d_SSL_SESSION(sess, NULL);
4861 if (data_len > SHSESS_MAX_DATA_LEN)
4862 goto err;
4863
4864 p = encsess;
4865
4866 /* process ASN1 session encoding before the lock */
4867 i2d_SSL_SESSION(sess, &p);
4868
William Lallemanded0b5ad2017-10-30 19:36:36 +01004869
William Lallemanda3c77cf2017-10-30 23:44:40 +01004870 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004871 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004872 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004873 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004874err:
4875 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004876 SSL_SESSION_set1_id(sess, encid, sid_length);
4877 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004878
4879 return 0; /* do not increment session reference count */
4880}
4881
4882/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004883SSL_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 +01004884{
William Lallemand4f45bb92017-10-30 20:08:51 +01004885 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004886 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4887 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004888 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004889 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004890
Willy Tarreau4c19e992021-06-15 16:39:22 +02004891 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004892
4893 /* allow the session to be freed automatically by openssl */
4894 *do_copy = 0;
4895
4896 /* tree key is zeros padded sessionid */
4897 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4898 memcpy(tmpkey, key, key_len);
4899 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4900 key = tmpkey;
4901 }
4902
4903 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004904 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004905
4906 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004907 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4908 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004909 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004910 shctx_unlock(ssl_shctx);
Willy Tarreau4c19e992021-06-15 16:39:22 +02004911 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004912 return NULL;
4913 }
4914
William Lallemand4f45bb92017-10-30 20:08:51 +01004915 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4916 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004917
William Lallemand4f45bb92017-10-30 20:08:51 +01004918 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 +01004919
William Lallemanda3c77cf2017-10-30 23:44:40 +01004920 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004921
4922 /* decode ASN1 session */
4923 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004924 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004925 /* Reset session id and session id contenxt */
4926 if (sess) {
4927 SSL_SESSION_set1_id(sess, key, key_len);
4928 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4929 }
4930
4931 return sess;
4932}
4933
William Lallemand4f45bb92017-10-30 20:08:51 +01004934
William Lallemanded0b5ad2017-10-30 19:36:36 +01004935/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004936void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004937{
William Lallemand4f45bb92017-10-30 20:08:51 +01004938 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004939 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4940 unsigned int sid_length;
4941 const unsigned char *sid_data;
4942 (void)ctx;
4943
4944 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4945 /* tree key is zeros padded sessionid */
4946 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4947 memcpy(tmpkey, sid_data, sid_length);
4948 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4949 sid_data = tmpkey;
4950 }
4951
William Lallemanda3c77cf2017-10-30 23:44:40 +01004952 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004953
4954 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004955 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4956 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004957 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004958 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004959 }
4960
4961 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004962 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004963}
4964
4965/* Set session cache mode to server and disable openssl internal cache.
4966 * Set shared cache callbacks on an ssl context.
4967 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004968void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004969{
4970 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4971
4972 if (!ssl_shctx) {
4973 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4974 return;
4975 }
4976
4977 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4978 SSL_SESS_CACHE_NO_INTERNAL |
4979 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4980
4981 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004982 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4983 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4984 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004985}
William Lallemand7d42ef52020-07-06 11:41:30 +02004986
4987/*
4988 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4989 *
4990 * The format is:
4991 * * <Label> <space> <ClientRandom> <space> <Secret>
4992 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4993 */
4994
William Lallemand722180a2021-06-09 16:46:12 +02004995#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004996void SSL_CTX_keylog(const SSL *ssl, const char *line)
4997{
4998 struct ssl_keylog *keylog;
4999 char *lastarg = NULL;
5000 char *dst = NULL;
5001
5002 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
5003 if (!keylog)
5004 return;
5005
5006 lastarg = strrchr(line, ' ');
5007 if (lastarg == NULL || ++lastarg == NULL)
5008 return;
5009
5010 dst = pool_alloc(pool_head_ssl_keylog_str);
5011 if (!dst)
5012 return;
5013
5014 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
5015 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
5016
5017 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
5018 if (keylog->client_random)
5019 goto error;
5020 keylog->client_random = dst;
5021
5022 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
5023 if (keylog->client_early_traffic_secret)
5024 goto error;
5025 keylog->client_early_traffic_secret = dst;
5026
5027 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
5028 if(keylog->client_handshake_traffic_secret)
5029 goto error;
5030 keylog->client_handshake_traffic_secret = dst;
5031
5032 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
5033 if (keylog->server_handshake_traffic_secret)
5034 goto error;
5035 keylog->server_handshake_traffic_secret = dst;
5036
5037 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
5038 if (keylog->client_traffic_secret_0)
5039 goto error;
5040 keylog->client_traffic_secret_0 = dst;
5041
5042 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
5043 if (keylog->server_traffic_secret_0)
5044 goto error;
5045 keylog->server_traffic_secret_0 = dst;
5046
5047 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
5048 if (keylog->early_exporter_secret)
5049 goto error;
5050 keylog->early_exporter_secret = dst;
5051
5052 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
5053 if (keylog->exporter_secret)
5054 goto error;
5055 keylog->exporter_secret = dst;
5056 } else {
5057 goto error;
5058 }
5059
5060 return;
5061
5062error:
5063 pool_free(pool_head_ssl_keylog_str, dst);
5064
5065 return;
5066}
5067#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01005068
William Lallemand8b453912019-11-21 15:48:10 +01005069/*
5070 * This function applies the SSL configuration on a SSL_CTX
5071 * It returns an error code and fills the <err> buffer
5072 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005073static 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 +01005074{
5075 struct proxy *curproxy = bind_conf->frontend;
5076 int cfgerr = 0;
5077 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01005078 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005079 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05005080#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005081 const char *conf_ciphersuites;
5082#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01005083 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02005084
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02005085 if (ssl_conf) {
5086 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
5087 int i, min, max;
5088 int flags = MC_SSL_O_ALL;
5089
5090 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02005091 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
5092 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02005093 if (min)
5094 flags |= (methodVersions[min].flag - 1);
5095 if (max)
5096 flags |= ~((methodVersions[max].flag << 1) - 1);
5097 min = max = CONF_TLSV_NONE;
5098 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
5099 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
5100 if (min)
5101 max = i;
5102 else
5103 min = max = i;
5104 }
5105 /* save real min/max */
5106 conf_ssl_methods->min = min;
5107 conf_ssl_methods->max = max;
5108 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01005109 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
5110 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01005111 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02005112 }
5113 }
5114
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005115 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01005116 case SSL_SOCK_VERIFY_NONE:
5117 verify = SSL_VERIFY_NONE;
5118 break;
5119 case SSL_SOCK_VERIFY_OPTIONAL:
5120 verify = SSL_VERIFY_PEER;
5121 break;
5122 case SSL_SOCK_VERIFY_REQUIRED:
5123 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
5124 break;
5125 }
5126 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
5127 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005128 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 +01005129 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 +01005130 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 +01005131 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02005132 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01005133 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02005134 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01005135 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01005136 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02005137 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01005138 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
5139 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
5140 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
5141 cfgerr |= ERR_ALERT | ERR_FATAL;
5142 }
5143 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02005144 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02005145 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 +02005146 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02005147 }
Emeric Brun850efd52014-01-29 12:24:34 +01005148 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01005149 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
5150 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01005151 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01005152 }
Emeric Brun051cdab2012-10-02 19:25:50 +02005153#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005154 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02005155 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
5156
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01005157 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01005158 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
5159 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01005160 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02005161 }
Emeric Brun561e5742012-10-02 15:20:55 +02005162 else {
5163 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5164 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02005165 }
Emeric Brun051cdab2012-10-02 19:25:50 +02005166#endif
Emeric Brun644cde02012-12-14 11:21:13 +01005167 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02005168 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01005169#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02005170 if(bind_conf->keys_ref) {
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +01005171 if (!SSL_CTX_set_tlsext_ticket_key_evp_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01005172 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
5173 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01005174 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01005175 }
5176 }
5177#endif
5178
William Lallemand4f45bb92017-10-30 20:08:51 +01005179 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005180 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
5181 if (conf_ciphers &&
5182 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01005183 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
5184 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01005185 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02005186 }
5187
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05005188#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005189 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
5190 if (conf_ciphersuites &&
5191 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01005192 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
5193 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01005194 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005195 }
5196#endif
5197
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01005198#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02005199 if (!local_dh_1024)
5200 local_dh_1024 = ssl_get_dh_1024();
5201 if (!local_dh_2048)
5202 local_dh_2048 = ssl_get_dh_2048();
5203 if (!local_dh_4096)
5204 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02005205#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02005206
Emeric Brunfc0421f2012-09-07 17:30:07 +02005207 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05005208#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02005209 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02005210#endif
William Lallemand722180a2021-06-09 16:46:12 +02005211#ifdef HAVE_SSL_KEYLOG
William Lallemandb60a77b2022-11-18 15:00:15 +01005212 /* only activate the keylog callback if it was required to prevent performance loss */
5213 if (global_ssl.keylog > 0)
5214 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02005215#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02005216
Bernard Spil13c53f82018-02-15 13:34:58 +01005217#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005218 ssl_conf_cur = NULL;
5219 if (ssl_conf && ssl_conf->npn_str)
5220 ssl_conf_cur = ssl_conf;
5221 else if (bind_conf->ssl_conf.npn_str)
5222 ssl_conf_cur = &bind_conf->ssl_conf;
5223 if (ssl_conf_cur)
5224 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02005225#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01005226#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005227 ssl_conf_cur = NULL;
5228 if (ssl_conf && ssl_conf->alpn_str)
5229 ssl_conf_cur = ssl_conf;
5230 else if (bind_conf->ssl_conf.alpn_str)
5231 ssl_conf_cur = &bind_conf->ssl_conf;
5232 if (ssl_conf_cur)
5233 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02005234#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05005235#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01005236 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
5237 if (conf_curves) {
5238 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01005239 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
5240 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01005241 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01005242 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01005243 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01005244 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01005245#endif /* defined(SSL_CTX_set1_curves_list) */
5246
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01005247 if (!conf_curves) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005248#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01005249#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005250 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02005251 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
5252 NULL);
5253
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01005254 if (ecdhe && SSL_CTX_set1_curves_list(ctx, ecdhe) == 0) {
5255 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
5256 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
5257 cfgerr |= ERR_ALERT | ERR_FATAL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005258 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01005259#endif /* defined(SSL_CTX_set1_curves_list) */
Olivier Houchardc2aae742017-09-22 18:26:28 +02005260#else
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01005261#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
5262 int i;
5263 EC_KEY *ecdh;
5264
Olivier Houchardc2aae742017-09-22 18:26:28 +02005265 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
5266 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
5267 ECDHE_DEFAULT_CURVE);
Emeric Brun2b58d042012-09-20 17:10:03 +02005268
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005269 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02005270 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01005271 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 +01005272 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01005273 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02005274 }
5275 else {
5276 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
5277 EC_KEY_free(ecdh);
5278 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01005279#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
5280#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Emeric Brun2b58d042012-09-20 17:10:03 +02005281 }
Emeric Brun2b58d042012-09-20 17:10:03 +02005282
Emeric Brunfc0421f2012-09-07 17:30:07 +02005283 return cfgerr;
5284}
5285
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005286
5287/*
5288 * Prepare the SSL_CTX based on the bind line configuration.
5289 * Since the CA file loading is made depending on the verify option of the bind
5290 * line, the link between the SSL_CTX and the CA file tree entry is made here.
5291 * If we want to create a link between the CA file entry and the corresponding
5292 * ckch instance (for CA file hot update), it needs to be done after
5293 * ssl_sock_prepare_ctx.
5294 * Returns 0 in case of success.
5295 */
5296int ssl_sock_prep_ctx_and_inst(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
5297 SSL_CTX *ctx, struct ckch_inst *ckch_inst, char **err)
5298{
5299 int errcode = 0;
5300
5301 errcode |= ssl_sock_prepare_ctx(bind_conf, ssl_conf, ctx, err);
5302 if (!errcode && ckch_inst)
5303 ckch_inst_add_cafile_link(ckch_inst, bind_conf, ssl_conf, NULL);
5304
5305 return errcode;
5306}
5307
Evan Broderbe554312013-06-27 00:05:25 -07005308static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
5309{
5310 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
5311 size_t prefixlen, suffixlen;
5312
5313 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02005314 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07005315 return 1;
5316
Evan Broderbe554312013-06-27 00:05:25 -07005317 /* The rest of this logic is based on RFC 6125, section 6.4.3
5318 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
5319
Emeric Bruna848dae2013-10-08 11:27:28 +02005320 pattern_wildcard = NULL;
5321 pattern_left_label_end = pattern;
5322 while (*pattern_left_label_end != '.') {
5323 switch (*pattern_left_label_end) {
5324 case 0:
5325 /* End of label not found */
5326 return 0;
5327 case '*':
5328 /* If there is more than one wildcards */
5329 if (pattern_wildcard)
5330 return 0;
5331 pattern_wildcard = pattern_left_label_end;
5332 break;
5333 }
5334 pattern_left_label_end++;
5335 }
5336
5337 /* If it's not trivial and there is no wildcard, it can't
5338 * match */
5339 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07005340 return 0;
5341
5342 /* Make sure all labels match except the leftmost */
5343 hostname_left_label_end = strchr(hostname, '.');
5344 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02005345 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07005346 return 0;
5347
5348 /* Make sure the leftmost label of the hostname is long enough
5349 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02005350 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07005351 return 0;
5352
5353 /* Finally compare the string on either side of the
5354 * wildcard */
5355 prefixlen = pattern_wildcard - pattern;
5356 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02005357 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
5358 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07005359 return 0;
5360
5361 return 1;
5362}
5363
5364static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
5365{
5366 SSL *ssl;
5367 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005368 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02005369 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02005370 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07005371
5372 int depth;
5373 X509 *cert;
5374 STACK_OF(GENERAL_NAME) *alt_names;
5375 int i;
5376 X509_NAME *cert_subject;
5377 char *str;
5378
5379 if (ok == 0)
5380 return ok;
5381
5382 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02005383 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02005384 ssl_ctx = __conn_get_ssl_sock_ctx(conn);
Evan Broderbe554312013-06-27 00:05:25 -07005385
Willy Tarreauad92a9a2017-07-28 11:38:41 +02005386 /* We're checking if the provided hostnames match the desired one. The
5387 * desired hostname comes from the SNI we presented if any, or if not
5388 * provided then it may have been explicitly stated using a "verifyhost"
5389 * directive. If neither is set, we don't care about the name so the
5390 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02005391 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005392 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02005393 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02005394 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02005395 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02005396 if (!servername)
5397 return ok;
5398 }
Evan Broderbe554312013-06-27 00:05:25 -07005399
5400 /* We only need to verify the CN on the actual server cert,
5401 * not the indirect CAs */
5402 depth = X509_STORE_CTX_get_error_depth(ctx);
5403 if (depth != 0)
5404 return ok;
5405
5406 /* At this point, the cert is *not* OK unless we can find a
5407 * hostname match */
5408 ok = 0;
5409
5410 cert = X509_STORE_CTX_get_current_cert(ctx);
5411 /* It seems like this might happen if verify peer isn't set */
5412 if (!cert)
5413 return ok;
5414
5415 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
5416 if (alt_names) {
5417 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
5418 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
5419 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005420#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02005421 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
5422#else
Evan Broderbe554312013-06-27 00:05:25 -07005423 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02005424#endif
Evan Broderbe554312013-06-27 00:05:25 -07005425 ok = ssl_sock_srv_hostcheck(str, servername);
5426 OPENSSL_free(str);
5427 }
5428 }
5429 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02005430 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07005431 }
5432
5433 cert_subject = X509_get_subject_name(cert);
5434 i = -1;
5435 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
5436 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005437 ASN1_STRING *value;
5438 value = X509_NAME_ENTRY_get_data(entry);
5439 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07005440 ok = ssl_sock_srv_hostcheck(str, servername);
5441 OPENSSL_free(str);
5442 }
5443 }
5444
Willy Tarreau71d058c2017-07-26 20:09:56 +02005445 /* report the mismatch and indicate if SNI was used or not */
5446 if (!ok && !conn->err_code)
5447 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07005448 return ok;
5449}
5450
Emeric Brun94324a42012-10-11 14:00:19 +02005451/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01005452int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02005453{
5454 int cfgerr = 0;
William Lallemand2c776f12021-12-28 18:47:17 +01005455 SSL_CTX *ctx;
William Lallemand0adafb32022-12-13 18:17:44 +01005456 /* Automatic memory computations need to know we use SSL there
5457 * If this is an internal proxy, don't use it for the computation */
William Lallemand04007cb2022-12-14 10:34:36 +01005458 if (!(srv->proxy->cap & PR_CAP_INT))
William Lallemand0adafb32022-12-13 18:17:44 +01005459 global.ssl_used_backend = 1;
Willy Tarreaufce03112015-01-15 21:32:40 +01005460
5461 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02005462 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005463 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005464 ha_alert("out of memory.\n");
Emeric Brun821bb9b2017-06-15 16:37:39 +02005465 cfgerr++;
5466 return cfgerr;
5467 }
5468 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01005469 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02005470 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02005471
William Lallemand2c776f12021-12-28 18:47:17 +01005472 if (srv->ssl_ctx.client_crt) {
5473 const int create_if_none = srv->flags & SRV_F_DYNAMIC ? 0 : 1;
5474 char *err = NULL;
5475 int err_code = 0;
5476
5477 /* If there is a crt keyword there, the SSL_CTX will be created here. */
5478 err_code = ssl_sock_load_srv_cert(srv->ssl_ctx.client_crt, srv, create_if_none, &err);
5479 if (err_code != ERR_NONE) {
5480 if ((err_code & ERR_WARN) && !(err_code & ERR_ALERT))
5481 ha_warning("%s", err);
5482 else
5483 ha_alert("%s", err);
5484
5485 if (err_code & (ERR_FATAL|ERR_ABORT))
5486 cfgerr++;
5487 }
5488 ha_free(&err);
5489 }
5490
5491 ctx = srv->ssl_ctx.ctx;
5492
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005493 /* The context will be uninitialized if there wasn't any "cert" option
5494 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005495 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005496 ctx = SSL_CTX_new(SSLv23_client_method());
5497 if (!ctx) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005498 ha_alert("unable to allocate ssl context.\n");
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005499 cfgerr++;
5500 return cfgerr;
5501 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005502
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005503 srv->ssl_ctx.ctx = ctx;
5504 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005505
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005506 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 +01005507
5508 return cfgerr;
5509}
5510
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005511/* Initialize an SSL context that will be used on the backend side.
5512 * Returns an error count.
5513 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005514static int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005515{
5516 struct proxy *curproxy = srv->proxy;
5517 int cfgerr = 0;
5518 long options =
5519 SSL_OP_ALL | /* all known workarounds for bugs */
5520 SSL_OP_NO_SSLv2 |
5521 SSL_OP_NO_COMPRESSION;
5522 long mode =
5523 SSL_MODE_ENABLE_PARTIAL_WRITE |
5524 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
5525 SSL_MODE_RELEASE_BUFFERS |
5526 SSL_MODE_SMALL_BUFFERS;
5527 int verify = SSL_VERIFY_NONE;
5528 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
5529 int i, min, max, hole;
5530 int flags = MC_SSL_O_ALL;
5531
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005532 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005533 ha_warning("no-sslv3/no-tlsv1x are ignored for this server. "
5534 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n");
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005535 else
5536 flags = conf_ssl_methods->flags;
5537
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005538 /* Real min and max should be determinate with configuration and openssl's capabilities */
5539 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005540 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005541 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005542 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005543
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005544 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005545 min = max = CONF_TLSV_NONE;
5546 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005547 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005548 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005549 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005550 if (min) {
5551 if (hole) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005552 ha_warning("%s '%s': SSL/TLS versions range not contiguous for server '%s'. "
Christopher Faulet767a84b2017-11-24 16:50:31 +01005553 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
5554 proxy_type_str(curproxy), curproxy->id, srv->id,
5555 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005556 hole = 0;
5557 }
5558 max = i;
5559 }
5560 else {
5561 min = max = i;
5562 }
5563 }
5564 else {
5565 if (min)
5566 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005567 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005568 if (!min) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005569 ha_alert("%s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01005570 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005571 cfgerr += 1;
5572 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005573
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005574#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005575 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08005576 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005577 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005578 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005579 else
5580 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
5581 if (flags & methodVersions[i].flag)
5582 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005583#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005584 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005585 methodVersions[min].ctx_set_version(ctx, SET_MIN);
5586 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005587#endif
5588
5589 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
5590 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005591 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005592
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005593#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005594 if (global_ssl.async)
5595 mode |= SSL_MODE_ASYNC;
5596#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005597 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005598
Emeric Brun850efd52014-01-29 12:24:34 +01005599 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
5600 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01005601 switch (srv->ssl_ctx.verify) {
5602 case SSL_SOCK_VERIFY_NONE:
5603 verify = SSL_VERIFY_NONE;
5604 break;
5605 case SSL_SOCK_VERIFY_REQUIRED:
5606 verify = SSL_VERIFY_PEER;
5607 break;
5608 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005609 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02005610 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01005611 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02005612 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02005613 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005614 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005615 ha_alert("unable to set CA file '%s'.\n",
5616 srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005617 cfgerr++;
5618 }
5619 }
Emeric Brun850efd52014-01-29 12:24:34 +01005620 else {
5621 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005622 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 +01005623 else
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005624 ha_alert("verify is enabled but no CA file specified.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01005625 cfgerr++;
5626 }
Emeric Brunef42d922012-10-11 16:11:36 +02005627#ifdef X509_V_FLAG_CRL_CHECK
5628 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005629 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02005630
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01005631 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005632 ha_alert("unable to configure CRL file '%s'.\n",
5633 srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005634 cfgerr++;
5635 }
5636 else {
5637 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5638 }
5639 }
5640#endif
5641 }
5642
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005643 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5644 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02005645 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005646 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005647 ha_alert("unable to set SSL cipher list to '%s'.\n",
5648 srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02005649 cfgerr++;
5650 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005651
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05005652#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005653 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005654 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005655 ha_alert("unable to set TLS 1.3 cipher suites to '%s'.\n",
5656 srv->ssl_ctx.ciphersuites);
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005657 cfgerr++;
5658 }
5659#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01005660#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
5661 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005662 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01005663#endif
5664#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5665 if (srv->ssl_ctx.alpn_str)
5666 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
5667#endif
5668
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005669
5670 return cfgerr;
5671}
5672
5673/*
5674 * Prepare the frontend's SSL_CTX based on the server line configuration.
5675 * Since the CA file loading is made depending on the verify option of the
5676 * server line, the link between the SSL_CTX and the CA file tree entry is
5677 * made here.
5678 * If we want to create a link between the CA file entry and the corresponding
5679 * ckch instance (for CA file hot update), it needs to be done after
5680 * ssl_sock_prepare_srv_ssl_ctx.
5681 * Returns an error count.
5682 */
5683int ssl_sock_prep_srv_ctx_and_inst(const struct server *srv, SSL_CTX *ctx,
5684 struct ckch_inst *ckch_inst)
5685{
5686 int cfgerr = 0;
5687
5688 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, ctx);
5689 if (!cfgerr && ckch_inst)
5690 ckch_inst_add_cafile_link(ckch_inst, NULL, NULL, srv);
Emeric Brun94324a42012-10-11 14:00:19 +02005691
5692 return cfgerr;
5693}
5694
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005695
Frédéric Lécailleec216522020-11-23 14:33:30 +01005696/*
5697 * Create an initial CTX used to start the SSL connections.
5698 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
5699 * Returns 0 if succeeded, or something >0 if not.
5700 */
5701#ifdef USE_QUIC
5702static int ssl_initial_ctx(struct bind_conf *bind_conf)
5703{
5704 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
5705 return ssl_quic_initial_ctx(bind_conf);
5706 else
5707 return ssl_sock_initial_ctx(bind_conf);
5708}
5709#else
5710static int ssl_initial_ctx(struct bind_conf *bind_conf)
5711{
5712 return ssl_sock_initial_ctx(bind_conf);
5713}
5714#endif
5715
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005716/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005717 * be NULL, in which case nothing is done. Returns the number of errors
5718 * encountered.
5719 */
Willy Tarreau03209342016-12-22 17:08:28 +01005720int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005721{
5722 struct ebmb_node *node;
5723 struct sni_ctx *sni;
5724 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01005725 int errcode = 0;
5726 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02005727
Willy Tarreaufce03112015-01-15 21:32:40 +01005728 /* Automatic memory computations need to know we use SSL there */
5729 global.ssl_used_frontend = 1;
5730
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005731 /* Create initial_ctx used to start the ssl connection before do switchctx */
5732 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01005733 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005734 /* It should not be necessary to call this function, but it's
5735 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01005736 to initial_ctx in ssl_initial_ctx. */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005737 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, NULL, bind_conf->initial_ctx, NULL, &errmsg);
5738 }
5739 if (bind_conf->default_ctx) {
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005740 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 +01005741 }
Emeric Brun0bed9942014-10-30 19:25:24 +01005742
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005743 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005744 while (node) {
5745 sni = ebmb_entry(node, struct sni_ctx, name);
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005746 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005747 /* only initialize the CTX on its first occurrence and
5748 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005749 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
5750 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005751 node = ebmb_next(node);
5752 }
5753
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005754 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005755 while (node) {
5756 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01005757 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005758 /* only initialize the CTX on its first occurrence and
5759 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005760 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005761 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005762 node = ebmb_next(node);
5763 }
William Lallemand8b453912019-11-21 15:48:10 +01005764
5765 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005766 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005767 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005768 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005769 err++;
5770 }
5771
5772 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005773 return err;
5774}
5775
Willy Tarreau55d37912016-12-21 23:38:39 +01005776/* Prepares all the contexts for a bind_conf and allocates the shared SSL
5777 * context if needed. Returns < 0 on error, 0 on success. The warnings and
5778 * alerts are directly emitted since the rest of the stack does it below.
5779 */
5780int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
5781{
5782 struct proxy *px = bind_conf->frontend;
5783 int alloc_ctx;
5784 int err;
5785
Willy Tarreau11ba4042022-05-20 15:56:32 +02005786 if (!(bind_conf->options & BC_O_USE_SSL)) {
Willy Tarreau55d37912016-12-21 23:38:39 +01005787 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005788 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
5789 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01005790 }
5791 return 0;
5792 }
5793 if (!bind_conf->default_ctx) {
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005794 if (bind_conf->strict_sni && !(bind_conf->options & BC_O_GENERATE_CERTS)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005795 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5796 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005797 }
5798 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005799 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5800 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005801 return -1;
5802 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005803 }
William Lallemandc61c0b32017-12-04 18:46:39 +01005804 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005805 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02005806 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
Willy Tarreau91358592021-06-15 08:08:04 +02005807 sizeof(*sh_ssl_sess_tree), (global.nbthread > 1));
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02005808 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005809 if (alloc_ctx == SHCTX_E_INIT_LOCK)
5810 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");
5811 else
5812 ha_alert("Unable to allocate SSL session cache.\n");
5813 return -1;
5814 }
5815 /* free block callback */
5816 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5817 /* init the root tree within the extra space */
5818 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5819 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01005820 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005821 err = 0;
5822 /* initialize all certificate contexts */
5823 err += ssl_sock_prepare_all_ctx(bind_conf);
5824
5825 /* initialize CA variables if the certificates generation is enabled */
5826 err += ssl_sock_load_ca(bind_conf);
5827
5828 return -err;
5829}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005830
William Lallemand231610a2021-12-30 11:25:43 +01005831/* release ssl context allocated for servers. Most of the field free here
5832 * must also be allocated in srv_ssl_settings_cpy() */
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005833void ssl_sock_free_srv_ctx(struct server *srv)
5834{
Olivier Houchardc7566002018-11-20 23:33:50 +01005835#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
William Lallemand231610a2021-12-30 11:25:43 +01005836 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005837#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005838#ifdef OPENSSL_NPN_NEGOTIATED
William Lallemand231610a2021-12-30 11:25:43 +01005839 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005840#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005841 if (srv->ssl_ctx.reused_sess) {
5842 int i;
5843
William Lallemande18d4e82021-11-17 02:59:21 +01005844 for (i = 0; i < global.nbthread; i++) {
Willy Tarreaue709e822021-02-26 21:06:32 +01005845 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
William Lallemande18d4e82021-11-17 02:59:21 +01005846 ha_free(&srv->ssl_ctx.reused_sess[i].sni);
5847 }
Willy Tarreaue709e822021-02-26 21:06:32 +01005848 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005849 }
5850
Willy Tarreaue709e822021-02-26 21:06:32 +01005851 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005852 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005853 srv->ssl_ctx.ctx = NULL;
5854 }
William Lallemand231610a2021-12-30 11:25:43 +01005855
5856 ha_free(&srv->ssl_ctx.ca_file);
5857 ha_free(&srv->ssl_ctx.crl_file);
5858 ha_free(&srv->ssl_ctx.client_crt);
5859 ha_free(&srv->ssl_ctx.verify_host);
5860#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5861 ha_free(&srv->sni_expr);
William Lallemand43c2ce42022-03-16 17:48:19 +01005862 release_sample_expr(srv->ssl_ctx.sni);
5863 srv->ssl_ctx.sni = NULL;
William Lallemand231610a2021-12-30 11:25:43 +01005864#endif
5865 ha_free(&srv->ssl_ctx.ciphers);
5866#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
5867 ha_free(&srv->ssl_ctx.ciphersuites);
5868#endif
William Lallemande69563f2021-12-30 14:45:19 +01005869 /* If there is a certificate we must unlink the ckch instance */
5870 ckch_inst_free(srv->ssl_ctx.inst);
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005871}
5872
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005873/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005874 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5875 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005876void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005877{
5878 struct ebmb_node *node, *back;
5879 struct sni_ctx *sni;
5880
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005881 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005882 while (node) {
5883 sni = ebmb_entry(node, struct sni_ctx, name);
5884 back = ebmb_next(node);
5885 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005886 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005887 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005888 free(sni);
5889 node = back;
5890 }
5891
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005892 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005893 while (node) {
5894 sni = ebmb_entry(node, struct sni_ctx, name);
5895 back = ebmb_next(node);
5896 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005897 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005898 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005899 free(sni);
5900 node = back;
5901 }
William Lallemandb2408692020-06-24 09:54:29 +02005902
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005903 SSL_CTX_free(bind_conf->initial_ctx);
5904 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005905 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005906 bind_conf->default_ctx = NULL;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005907 bind_conf->default_inst = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005908 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005909}
William Lallemandb2408692020-06-24 09:54:29 +02005910
5911
5912void ssl_sock_deinit()
5913{
5914 crtlist_deinit(); /* must be free'd before the ckchs */
5915 ckch_deinit();
5916}
5917REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005918
Willy Tarreau795cdab2016-12-22 17:30:54 +01005919/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5920void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5921{
5922 ssl_sock_free_ca(bind_conf);
5923 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005924 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005925 free(bind_conf->ca_sign_file);
5926 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005927 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005928 free(bind_conf->keys_ref->filename);
5929 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005930 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005931 free(bind_conf->keys_ref);
5932 }
5933 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005934 bind_conf->ca_sign_pass = NULL;
5935 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005936}
5937
Christopher Faulet31af49d2015-06-09 17:29:50 +02005938/* Load CA cert file and private key used to generate certificates */
5939int
Willy Tarreau03209342016-12-22 17:08:28 +01005940ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005941{
Willy Tarreau03209342016-12-22 17:08:28 +01005942 struct proxy *px = bind_conf->frontend;
William Lallemand52ddd992022-11-22 11:51:53 +01005943 struct ckch_data *data = NULL;
Shimi Gersner5846c492020-08-23 13:58:12 +03005944 int ret = 0;
5945 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005946
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005947 if (!(bind_conf->options & BC_O_GENERATE_CERTS))
Shimi Gersner5846c492020-08-23 13:58:12 +03005948 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005949
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005950#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005951 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005952 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005953 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005954 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005955 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005956#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005957
Christopher Faulet31af49d2015-06-09 17:29:50 +02005958 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005959 ha_alert("Proxy '%s': cannot enable certificate generation, "
5960 "no CA certificate File configured at [%s:%d].\n",
5961 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005962 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005963 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005964
Shimi Gersner5846c492020-08-23 13:58:12 +03005965 /* Allocate cert structure */
William Lallemand52ddd992022-11-22 11:51:53 +01005966 data = calloc(1, sizeof(*data));
5967 if (!data) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005968 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5969 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5970 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005971 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005972
5973 /* Try to parse file */
William Lallemand52ddd992022-11-22 11:51:53 +01005974 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, data, &err)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005975 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5976 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005977 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005978 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005979 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005980
5981 /* Fail if missing cert or pkey */
William Lallemand52ddd992022-11-22 11:51:53 +01005982 if ((!data->cert) || (!data->key)) {
Shimi Gersner5846c492020-08-23 13:58:12 +03005983 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5984 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5985 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005986 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005987
Shimi Gersner5846c492020-08-23 13:58:12 +03005988 /* Final assignment to bind */
William Lallemand52ddd992022-11-22 11:51:53 +01005989 bind_conf->ca_sign_ckch = data;
Shimi Gersner5846c492020-08-23 13:58:12 +03005990 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005991
Shimi Gersner5846c492020-08-23 13:58:12 +03005992 failed:
William Lallemand52ddd992022-11-22 11:51:53 +01005993 if (data) {
5994 ssl_sock_free_cert_key_and_chain_contents(data);
5995 free(data);
Shimi Gersner5846c492020-08-23 13:58:12 +03005996 }
5997
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005998 bind_conf->options &= ~BC_O_GENERATE_CERTS;
Shimi Gersner5846c492020-08-23 13:58:12 +03005999 ret++;
6000 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02006001}
6002
6003/* Release CA cert and private key used to generate certificated */
6004void
6005ssl_sock_free_ca(struct bind_conf *bind_conf)
6006{
Shimi Gersner5846c492020-08-23 13:58:12 +03006007 if (bind_conf->ca_sign_ckch) {
6008 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01006009 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03006010 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02006011}
6012
Emeric Brun46591952012-05-18 15:47:34 +02006013/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01006014 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
6015 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
6016 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
6017 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05006018 * 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 +01006019 * as parameters to this function.
6020 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
6021 * CO_ER_SSL_NO_MEM.
6022 */
6023int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
6024 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
6025{
6026 int retry = 1;
6027
6028 retry:
6029 /* Alloc a new SSL session. */
6030 *ssl = SSL_new(ssl_ctx);
6031 if (!*ssl) {
6032 if (!retry--)
6033 goto err;
6034
6035 pool_gc(NULL);
6036 goto retry;
6037 }
6038
6039 *bio = BIO_new(bio_meth);
6040 if (!*bio) {
6041 SSL_free(*ssl);
6042 *ssl = NULL;
6043 if (!retry--)
6044 goto err;
6045
6046 pool_gc(NULL);
6047 goto retry;
6048 }
6049
6050 BIO_set_data(*bio, ctx);
6051 SSL_set_bio(*ssl, *bio, *bio);
6052
6053 /* set connection pointer. */
6054 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
6055 SSL_free(*ssl);
6056 *ssl = NULL;
6057 if (!retry--)
6058 goto err;
6059
6060 pool_gc(NULL);
6061 goto retry;
6062 }
6063
6064 return 0;
6065
6066 err:
6067 conn->err_code = CO_ER_SSL_NO_MEM;
6068 return -1;
6069}
6070
Olivier Houchardbc5ce922021-03-05 23:47:00 +01006071/* This function is called when all the XPRT have been initialized. We can
6072 * now attempt to start the SSL handshake.
6073 */
6074static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
6075{
6076 struct ssl_sock_ctx *ctx = xprt_ctx;
6077
6078 if (ctx->xprt->start) {
6079 int ret;
6080
6081 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
6082 if (ret < 0)
6083 return ret;
6084 }
6085 tasklet_wakeup(ctx->wait_event.tasklet);
6086
6087 return 0;
6088}
6089
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01006090/*
Emeric Brun46591952012-05-18 15:47:34 +02006091 * This function is called if SSL * context is not yet allocated. The function
6092 * is designed to be called before any other data-layer operation and sets the
6093 * handshake flag on the connection. It is safe to call it multiple times.
6094 * It returns 0 on success and -1 in error case.
6095 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006096static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006097{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006098 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02006099 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006100 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006101 return 0;
6102
Olivier Houchard66ab4982019-02-26 18:37:15 +01006103 ctx = pool_alloc(ssl_sock_ctx_pool);
6104 if (!ctx) {
6105 conn->err_code = CO_ER_SSL_NO_MEM;
6106 return -1;
6107 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006108 ctx->wait_event.tasklet = tasklet_new();
6109 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006110 conn->err_code = CO_ER_SSL_NO_MEM;
6111 pool_free(ssl_sock_ctx_pool, ctx);
6112 return -1;
6113 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006114 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
6115 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01006116 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02006117 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006118 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01006119 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02006120 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006121 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02006122 ctx->xprt_st = 0;
6123 ctx->xprt_ctx = NULL;
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02006124 ctx->error_code = 0;
Olivier Houcharda8955d52019-04-07 22:00:38 +02006125
6126 /* Only work with sockets for now, this should be adapted when we'll
6127 * add QUIC support.
6128 */
6129 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02006130 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006131 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
6132 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02006133 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006134
Willy Tarreau82531f62021-10-06 12:15:18 +02006135 if (global.maxsslconn && global.sslconns >= global.maxsslconn) {
Willy Tarreau20879a02012-12-03 16:32:10 +01006136 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006137 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01006138 }
Willy Tarreau403edff2012-09-06 11:58:37 +02006139
Emeric Brun46591952012-05-18 15:47:34 +02006140 /* If it is in client mode initiate SSL session
6141 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01006142 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01006143 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
6144 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006145 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01006146
Olivier Houchard66ab4982019-02-26 18:37:15 +01006147 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01006148 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02006149 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
6150 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
6151 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 +01006152 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01006153 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01006154 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01006155 } else if (sess) {
6156 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01006157 }
6158 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01006159 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07006160
Emeric Brun46591952012-05-18 15:47:34 +02006161 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02006162 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02006163
Willy Tarreau82531f62021-10-06 12:15:18 +02006164 _HA_ATOMIC_INC(&global.sslconns);
6165 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006166 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02006167 return 0;
6168 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01006169 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01006170 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01006171
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01006172 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
6173 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006174 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01006175
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006176#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01006177 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01006178 b_alloc(&ctx->early_buf);
6179 SSL_set_max_early_data(ctx->ssl,
6180 /* Only allow early data if we managed to allocate
6181 * a buffer.
6182 */
6183 (!b_is_null(&ctx->early_buf)) ?
6184 global.tune.bufsize - global.tune.maxrewrite : 0);
6185 }
6186#endif
6187
Olivier Houchard66ab4982019-02-26 18:37:15 +01006188 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02006189
Emeric Brun46591952012-05-18 15:47:34 +02006190 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02006191 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006192#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01006193 if (bc->ssl_conf.early_data)
6194 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006195#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02006196
Willy Tarreau82531f62021-10-06 12:15:18 +02006197 _HA_ATOMIC_INC(&global.sslconns);
6198 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006199 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02006200 return 0;
6201 }
6202 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01006203 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006204err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006205 if (ctx && ctx->wait_event.tasklet)
6206 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006207 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02006208 return -1;
6209}
6210
6211
6212/* This is the callback which is used when an SSL handshake is pending. It
6213 * updates the FD status if it wants some polling before being called again.
6214 * It returns 0 if it fails in a fatal way or needs to poll to go further,
6215 * otherwise it returns non-zero and removes itself from the connection's
6216 * flags (the bit is provided in <flag> by the caller).
6217 */
Olivier Houchard000694c2019-05-23 14:45:12 +02006218static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02006219{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006220 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Emeric Brun46591952012-05-18 15:47:34 +02006221 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01006222 struct ssl_counters *counters = NULL;
6223 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006224 struct listener *li;
6225 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01006226 socklen_t lskerr;
6227 int skerr;
6228
Emeric Brun46591952012-05-18 15:47:34 +02006229
Willy Tarreau3c728722014-01-23 13:50:42 +01006230 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02006231 return 0;
6232
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006233 /* get counters */
6234 switch (obj_type(conn->target)) {
6235 case OBJ_TYPE_LISTENER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02006236 li = __objt_listener(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006237 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
6238 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
6239 &ssl_stats_module);
6240 break;
6241
6242 case OBJ_TYPE_SERVER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02006243 srv = __objt_server(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006244 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
6245 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
6246 &ssl_stats_module);
6247 break;
6248
6249 default:
6250 break;
6251 }
6252
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006253 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006254 goto out_error;
6255
Willy Tarreau06300382021-02-02 15:42:25 +01006256 /* don't start calculating a handshake on a dead connection */
6257 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
6258 goto out_error;
6259
6260 /* FIXME/WT: for now we don't have a clear way to inspect the connection
6261 * status from the lower layers, so let's check the FD directly. Ideally
6262 * the xprt layers should provide some status indicating their knowledge
6263 * of shutdowns or error.
6264 */
Willy Tarreau07ecfc52022-04-11 18:07:03 +02006265 BUG_ON(conn->flags & CO_FL_FDLESS);
6266
Willy Tarreau06300382021-02-02 15:42:25 +01006267 skerr = 0;
6268 lskerr = sizeof(skerr);
6269 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
6270 skerr != 0)
6271 goto out_error;
6272
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006273#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006274 /*
6275 * Check if we have early data. If we do, we have to read them
6276 * before SSL_do_handshake() is called, And there's no way to
6277 * detect early data, except to try to read them
6278 */
6279 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01006280 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006281
Olivier Houchard54907bb2019-12-19 15:02:39 +01006282 while (1) {
6283 ret = SSL_read_early_data(ctx->ssl,
6284 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
6285 &read_data);
6286 if (ret == SSL_READ_EARLY_DATA_ERROR)
6287 goto check_error;
6288 if (read_data > 0) {
6289 conn->flags |= CO_FL_EARLY_DATA;
6290 b_add(&ctx->early_buf, read_data);
6291 }
6292 if (ret == SSL_READ_EARLY_DATA_FINISH) {
6293 conn->flags &= ~CO_FL_EARLY_SSL_HS;
6294 if (!b_data(&ctx->early_buf))
6295 b_free(&ctx->early_buf);
6296 break;
6297 }
6298 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006299 }
6300#endif
Emeric Brun674b7432012-11-08 19:21:55 +01006301 /* If we use SSL_do_handshake to process a reneg initiated by
6302 * the remote peer, it sometimes returns SSL_ERROR_SSL.
6303 * Usually SSL_write and SSL_read are used and process implicitly
6304 * the reneg handshake.
6305 * Here we use SSL_peek as a workaround for reneg.
6306 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006307 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01006308 char c;
6309
Olivier Houchard66ab4982019-02-26 18:37:15 +01006310 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01006311 if (ret <= 0) {
6312 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006313 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006314
Emeric Brun674b7432012-11-08 19:21:55 +01006315 if (ret == SSL_ERROR_WANT_WRITE) {
6316 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02006317 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02006318 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01006319 return 0;
6320 }
6321 else if (ret == SSL_ERROR_WANT_READ) {
6322 /* handshake may have been completed but we have
6323 * no more data to read.
6324 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006325 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01006326 ret = 1;
6327 goto reneg_ok;
6328 }
6329 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02006330 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02006331 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01006332 return 0;
6333 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006334#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006335 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006336 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006337 return 0;
6338 }
6339#endif
Emeric Brun674b7432012-11-08 19:21:55 +01006340 else if (ret == SSL_ERROR_SYSCALL) {
6341 /* if errno is null, then connection was successfully established */
6342 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
6343 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01006344 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02006345#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
6346 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006347 conn->err_code = CO_ER_SSL_HANDSHAKE;
6348#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006349 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02006350#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02006351 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006352 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006353 empty_handshake = state == TLS_ST_BEFORE;
6354#else
Lukas Tribus49799162019-07-08 14:29:15 +02006355 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
6356 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006357#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006358 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02006359 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006360 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006361 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6362 else
6363 conn->err_code = CO_ER_SSL_EMPTY;
6364 }
6365 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006366 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006367 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6368 else
6369 conn->err_code = CO_ER_SSL_ABORT;
6370 }
6371 }
6372 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006373 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006374 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01006375 else
Emeric Brun29f037d2014-04-25 19:05:36 +02006376 conn->err_code = CO_ER_SSL_HANDSHAKE;
6377 }
Lukas Tribus49799162019-07-08 14:29:15 +02006378#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01006379 }
Emeric Brun674b7432012-11-08 19:21:55 +01006380 goto out_error;
6381 }
6382 else {
6383 /* Fail on all other handshake errors */
6384 /* Note: OpenSSL may leave unread bytes in the socket's
6385 * buffer, causing an RST to be emitted upon close() on
6386 * TCP sockets. We first try to drain possibly pending
6387 * data to avoid this as much as possible.
6388 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01006389 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01006390 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006391 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02006392 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01006393 goto out_error;
6394 }
6395 }
6396 /* read some data: consider handshake completed */
6397 goto reneg_ok;
6398 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006399 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006400check_error:
Emeric Brun46591952012-05-18 15:47:34 +02006401 if (ret != 1) {
6402 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006403 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006404
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02006405 if (!ctx->error_code)
6406 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton7c6898e2021-07-29 09:45:51 +02006407
Emeric Brun46591952012-05-18 15:47:34 +02006408 if (ret == SSL_ERROR_WANT_WRITE) {
6409 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02006410 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02006411 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02006412 return 0;
6413 }
6414 else if (ret == SSL_ERROR_WANT_READ) {
6415 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02006416 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02006417 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6418 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02006419 return 0;
6420 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006421#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006422 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006423 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006424 return 0;
6425 }
6426#endif
Willy Tarreau89230192012-09-28 20:22:13 +02006427 else if (ret == SSL_ERROR_SYSCALL) {
6428 /* if errno is null, then connection was successfully established */
6429 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
6430 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006431 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02006432#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
6433 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006434 conn->err_code = CO_ER_SSL_HANDSHAKE;
6435#else
6436 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02006437#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02006438 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006439 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006440 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006441#else
Lukas Tribus49799162019-07-08 14:29:15 +02006442 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
6443 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006444#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006445 if (empty_handshake) {
6446 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006447 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006448 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6449 else
6450 conn->err_code = CO_ER_SSL_EMPTY;
6451 }
6452 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006453 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006454 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6455 else
6456 conn->err_code = CO_ER_SSL_ABORT;
6457 }
Emeric Brun29f037d2014-04-25 19:05:36 +02006458 }
6459 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006460 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006461 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6462 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006463 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02006464 }
Lukas Tribus49799162019-07-08 14:29:15 +02006465#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02006466 }
Willy Tarreau89230192012-09-28 20:22:13 +02006467 goto out_error;
6468 }
Emeric Brun46591952012-05-18 15:47:34 +02006469 else {
6470 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02006471 /* Note: OpenSSL may leave unread bytes in the socket's
6472 * buffer, causing an RST to be emitted upon close() on
6473 * TCP sockets. We first try to drain possibly pending
6474 * data to avoid this as much as possible.
6475 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01006476 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01006477 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006478 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02006479 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006480 goto out_error;
6481 }
6482 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006483#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01006484 else {
6485 /*
6486 * If the server refused the early data, we have to send a
6487 * 425 to the client, as we no longer have the data to sent
6488 * them again.
6489 */
6490 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006491 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006492 conn->err_code = CO_ER_SSL_EARLY_FAILED;
6493 goto out_error;
6494 }
6495 }
6496 }
6497#endif
6498
Emeric Brun46591952012-05-18 15:47:34 +02006499
Emeric Brun674b7432012-11-08 19:21:55 +01006500reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00006501
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006502#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006503 /* ASYNC engine API doesn't support moving read/write
6504 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006505 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00006506 */
6507 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006508 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006509#endif
Emeric Brun46591952012-05-18 15:47:34 +02006510 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006511 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02006512 if (objt_server(conn->target)) {
6513 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
6514 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
6515 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02006516 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02006517 else {
6518 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
6519 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
6520 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
6521 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006522
Willy Tarreau42995282020-11-06 13:19:18 +01006523 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006524 HA_ATOMIC_INC(&counters->sess);
6525 HA_ATOMIC_INC(&counters_px->sess);
Willy Tarreau42995282020-11-06 13:19:18 +01006526 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006527 }
Willy Tarreau42995282020-11-06 13:19:18 +01006528 else if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006529 HA_ATOMIC_INC(&counters->reused_sess);
6530 HA_ATOMIC_INC(&counters_px->reused_sess);
Emeric Brun46591952012-05-18 15:47:34 +02006531 }
6532
6533 /* The connection is now established at both layers, it's time to leave */
6534 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
6535 return 1;
6536
6537 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006538 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006539 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006540 ERR_clear_error();
6541
Emeric Brun9fa89732012-10-04 17:09:56 +02006542 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01006543 if (objt_server(conn->target)) {
6544 struct server *s = __objt_server(conn->target);
6545 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
6546 * one cache per thread, it only prevents to flush it from the CLI in
6547 * another thread */
6548
6549 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01006550 if (s->ssl_ctx.reused_sess[tid].ptr)
6551 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01006552 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02006553 }
6554
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006555 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006556 HA_ATOMIC_INC(&counters->failed_handshake);
6557 HA_ATOMIC_INC(&counters_px->failed_handshake);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006558 }
6559
Emeric Brun46591952012-05-18 15:47:34 +02006560 /* Fail on all other handshake errors */
6561 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01006562 if (!conn->err_code)
6563 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006564 return 0;
6565}
6566
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006567/* Called from the upper layer, to subscribe <es> to events <event_type>. The
6568 * event subscriber <es> is not allowed to change from a previous call as long
6569 * as at least one event is still subscribed. The <event_type> must only be a
6570 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
6571 * unless the transport layer was already released.
6572 */
6573static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006574{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006575 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006576
Olivier Houchard0ff28652019-06-24 18:57:39 +02006577 if (!ctx)
6578 return -1;
6579
Willy Tarreau113d52b2020-01-10 09:20:26 +01006580 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006581 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006582
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006583 ctx->subs = es;
6584 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006585
6586 /* we may have to subscribe to lower layers for new events */
6587 event_type &= ~ctx->wait_event.events;
6588 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
6589 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006590 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006591}
6592
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006593/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
6594 * The <es> pointer is not allowed to differ from the one passed to the
6595 * subscribe() call. It always returns zero.
6596 */
6597static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006598{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006599 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006600
Willy Tarreau113d52b2020-01-10 09:20:26 +01006601 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006602 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006603
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006604 es->events &= ~event_type;
6605 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01006606 ctx->subs = NULL;
6607
6608 /* If we subscribed, and we're not doing the handshake,
6609 * then we subscribed because the upper layer asked for it,
6610 * as the upper layer is no longer interested, we can
6611 * unsubscribe too.
6612 */
6613 event_type &= ctx->wait_event.events;
6614 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
6615 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006616
6617 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006618}
6619
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006620/* The connection has been taken over, so destroy the old tasklet and create
6621 * a new one. The original thread ID must be passed into orig_tid
6622 * It should be called with the takeover lock for the old thread held.
6623 * Returns 0 on success, and -1 on failure
6624 */
6625static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
6626{
6627 struct ssl_sock_ctx *ctx = xprt_ctx;
6628 struct tasklet *tl = tasklet_new();
6629
6630 if (!tl)
6631 return -1;
6632
6633 ctx->wait_event.tasklet->context = NULL;
6634 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
6635 ctx->wait_event.tasklet = tl;
6636 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
6637 ctx->wait_event.tasklet->context = ctx;
6638 return 0;
6639}
6640
Willy Tarreau41491682021-03-02 17:29:56 +01006641/* notify the next xprt that the connection is about to become idle and that it
6642 * may be stolen at any time after the function returns and that any tasklet in
6643 * the chain must be careful before dereferencing its context.
6644 */
6645static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
6646{
6647 struct ssl_sock_ctx *ctx = xprt_ctx;
6648
6649 if (!ctx || !ctx->wait_event.tasklet)
6650 return;
6651
6652 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6653 if (ctx->xprt)
6654 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
6655}
6656
6657/* notify the next xprt that the connection is not idle anymore and that it may
6658 * not be stolen before the next xprt_set_idle().
6659 */
6660static void ssl_set_used(struct connection *conn, void *xprt_ctx)
6661{
6662 struct ssl_sock_ctx *ctx = xprt_ctx;
6663
6664 if (!ctx || !ctx->wait_event.tasklet)
6665 return;
6666
6667 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6668 if (ctx->xprt)
6669 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
6670}
6671
Olivier Houchard2e055482019-05-27 19:50:12 +02006672/* Use the provided XPRT as an underlying XPRT, and provide the old one.
6673 * Returns 0 on success, and non-zero on failure.
6674 */
6675static 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)
6676{
6677 struct ssl_sock_ctx *ctx = xprt_ctx;
6678
6679 if (oldxprt_ops != NULL)
6680 *oldxprt_ops = ctx->xprt;
6681 if (oldxprt_ctx != NULL)
6682 *oldxprt_ctx = ctx->xprt_ctx;
6683 ctx->xprt = toadd_ops;
6684 ctx->xprt_ctx = toadd_ctx;
6685 return 0;
6686}
6687
Olivier Houchard5149b592019-05-23 17:47:36 +02006688/* Remove the specified xprt. If if it our underlying XPRT, remove it and
6689 * return 0, otherwise just call the remove_xprt method from the underlying
6690 * XPRT.
6691 */
6692static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
6693{
6694 struct ssl_sock_ctx *ctx = xprt_ctx;
6695
6696 if (ctx->xprt_ctx == toremove_ctx) {
6697 ctx->xprt_ctx = newctx;
6698 ctx->xprt = newops;
6699 return 0;
6700 }
6701 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
6702}
6703
Willy Tarreau144f84a2021-03-02 16:09:26 +01006704struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02006705{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006706 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006707 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006708 struct connection *conn;
6709 int conn_in_list;
6710 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006711
Willy Tarreau41491682021-03-02 17:29:56 +01006712 if (state & TASK_F_USR1) {
6713 /* the tasklet was idling on an idle connection, it might have
6714 * been stolen, let's be careful!
6715 */
6716 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6717 if (tl->context == NULL) {
6718 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6719 tasklet_free(tl);
6720 return NULL;
6721 }
6722 conn = ctx->conn;
6723 conn_in_list = conn->flags & CO_FL_LIST_MASK;
6724 if (conn_in_list)
6725 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006726 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01006727 } else {
6728 conn = ctx->conn;
6729 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006730 }
Willy Tarreau41491682021-03-02 17:29:56 +01006731
Olivier Houchardea8dd942019-05-20 14:02:16 +02006732 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01006733 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006734 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006735 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
6736 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01006737 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006738 }
6739 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006740 /* If we had an error, or the handshake is done and I/O is available,
6741 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01006742 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02006743 * we can't be sure conn_fd_handler() will be called again.
6744 */
6745 if ((ctx->conn->flags & CO_FL_ERROR) ||
6746 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006747 int woke = 0;
6748
6749 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006750 if (ctx->subs) {
6751 tasklet_wakeup(ctx->subs->tasklet);
6752 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006753 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006754 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006755 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006756
Olivier Houchardea8dd942019-05-20 14:02:16 +02006757 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01006758 * upper layers know. If we have no mux, create it,
6759 * and once we have a mux, call its wake method if we didn't
6760 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02006761 */
6762 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01006763 if (!ctx->conn->mux)
6764 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006765 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006766 ret = ctx->conn->mux->wake(ctx->conn);
6767 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006768 }
6769 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006770#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006771 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006772 else if (b_data(&ctx->early_buf) && ctx->subs &&
6773 ctx->subs->events & SUB_RETRY_RECV) {
6774 tasklet_wakeup(ctx->subs->tasklet);
6775 ctx->subs->events &= ~SUB_RETRY_RECV;
6776 if (!ctx->subs->events)
6777 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01006778 }
6779#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006780leave:
6781 if (!ret && conn_in_list) {
6782 struct server *srv = objt_server(conn->target);
6783
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006784 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006785 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau85223482022-09-29 20:32:43 +02006786 eb64_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006787 else
Willy Tarreau85223482022-09-29 20:32:43 +02006788 eb64_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006789 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006790 }
Willy Tarreau74163142021-03-13 11:30:19 +01006791 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006792}
6793
Emeric Brun46591952012-05-18 15:47:34 +02006794/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01006795 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02006796 * buffer wraps, in which case a second call may be performed. The connection's
6797 * flags are updated with whatever special event is detected (error, read0,
6798 * empty). The caller is responsible for taking care of those events and
6799 * avoiding the call if inappropriate. The function does not call the
6800 * connection's polling update function, so the caller is responsible for this.
6801 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006802static 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 +02006803{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006804 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02006805 ssize_t ret;
6806 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02006807
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006808 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006809 goto out_error;
6810
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006811#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006812 if (b_data(&ctx->early_buf)) {
6813 try = b_contig_space(buf);
6814 if (try > b_data(&ctx->early_buf))
6815 try = b_data(&ctx->early_buf);
6816 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
6817 b_add(buf, try);
6818 b_del(&ctx->early_buf, try);
6819 if (b_data(&ctx->early_buf) == 0)
6820 b_free(&ctx->early_buf);
6821 return try;
6822 }
6823#endif
6824
Willy Tarreau911db9b2020-01-23 16:27:54 +01006825 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006826 /* a handshake was requested */
6827 return 0;
6828
Emeric Brun46591952012-05-18 15:47:34 +02006829 /* read the largest possible block. For this, we perform only one call
6830 * to recv() unless the buffer wraps and we exactly fill the first hunk,
6831 * in which case we accept to do it once again. A new attempt is made on
6832 * EINTR too.
6833 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01006834 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006835
Willy Tarreau591d4452018-06-15 17:21:00 +02006836 try = b_contig_space(buf);
6837 if (!try)
6838 break;
6839
Willy Tarreauabf08d92014-01-14 11:31:27 +01006840 if (try > count)
6841 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02006842
Olivier Houchard66ab4982019-02-26 18:37:15 +01006843 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02006844
Emeric Brune1f38db2012-09-03 20:36:47 +02006845 if (conn->flags & CO_FL_ERROR) {
6846 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006847 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006848 }
Emeric Brun46591952012-05-18 15:47:34 +02006849 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006850 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006851 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006852 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006853 }
Emeric Brun46591952012-05-18 15:47:34 +02006854 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006855 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006856 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006857 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006858 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006859 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006860#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006861 /* Async mode can be re-enabled, because we're leaving data state.*/
6862 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006863 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006864#endif
Emeric Brun46591952012-05-18 15:47:34 +02006865 break;
6866 }
6867 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006868 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006869 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6870 SUB_RETRY_RECV,
6871 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006872 /* handshake is running, and it may need to re-enable read */
6873 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006874#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006875 /* Async mode can be re-enabled, because we're leaving data state.*/
6876 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006877 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006878#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006879 break;
6880 }
Emeric Brun46591952012-05-18 15:47:34 +02006881 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006882 } else if (ret == SSL_ERROR_ZERO_RETURN)
6883 goto read0;
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006884 else if (ret == SSL_ERROR_SSL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006885 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6886 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006887 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006888 conn->err_code = CO_ERR_SSL_FATAL;
6889 }
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006890 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6891 * stack before shutting down the connection for
6892 * reading. */
Willy Tarreauacef5e22022-04-25 20:32:15 +02006893 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN || errno == EWOULDBLOCK))
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006894 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006895 /* otherwise it's a real error */
6896 goto out_error;
6897 }
6898 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006899 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006900 return done;
6901
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006902 clear_ssl_error:
6903 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006904 ssl_sock_dump_errors(conn, NULL);
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006905 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006906 read0:
6907 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006908 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006909
Emeric Brun46591952012-05-18 15:47:34 +02006910 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006911 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006912 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02006913 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01006914 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006915 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006916}
6917
6918
Willy Tarreau787db9a2018-06-14 18:31:46 +02006919/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6920 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6921 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006922 * Only one call to send() is performed, unless the buffer wraps, in which case
6923 * a second call may be performed. The connection's flags are updated with
6924 * whatever special event is detected (error, empty). The caller is responsible
6925 * for taking care of those events and avoiding the call if inappropriate. The
6926 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006927 * is responsible for this. The buffer's output is not adjusted, it's up to the
6928 * caller to take care of this. It's up to the caller to update the buffer's
6929 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006930 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006931static 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 +02006932{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006933 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006934 ssize_t ret;
6935 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006936
6937 done = 0;
6938
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006939 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006940 goto out_error;
6941
Willy Tarreau911db9b2020-01-23 16:27:54 +01006942 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006943 /* a handshake was requested */
6944 return 0;
6945
6946 /* send the largest possible block. For this we perform only one call
6947 * to send() unless the buffer wraps and we exactly fill the first hunk,
6948 * in which case we accept to do it once again.
6949 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006950 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006951#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006952 size_t written_data;
6953#endif
6954
Willy Tarreau787db9a2018-06-14 18:31:46 +02006955 try = b_contig_data(buf, done);
6956 if (try > count)
6957 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006958
Thomas Prückl10243932022-04-27 13:04:54 +02006959 if (global_ssl.hard_max_record && try > global_ssl.hard_max_record)
6960 try = global_ssl.hard_max_record;
6961
Willy Tarreau7bed9452014-02-02 02:00:24 +01006962 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006963 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006964 global_ssl.max_record && try > global_ssl.max_record) {
6965 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006966 }
6967 else {
6968 /* we need to keep the information about the fact that
6969 * we're not limiting the upcoming send(), because if it
6970 * fails, we'll have to retry with at least as many data.
6971 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006972 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006973 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006974
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006975#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006976 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006977 unsigned int max_early;
6978
Olivier Houchard522eea72017-11-03 16:27:47 +01006979 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006980 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006981 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006982 if (SSL_get0_session(ctx->ssl))
6983 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006984 else
6985 max_early = 0;
6986 }
6987
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006988 if (try + ctx->sent_early_data > max_early) {
6989 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006990 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006991 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006992 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006993 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006994 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006995 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006996 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006997 if (ret == 1) {
6998 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006999 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02007000 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01007001 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02007002 /* Initiate the handshake, now */
7003 tasklet_wakeup(ctx->wait_event.tasklet);
7004 }
Olivier Houchard522eea72017-11-03 16:27:47 +01007005
Olivier Houchardc2aae742017-09-22 18:26:28 +02007006 }
7007
7008 } else
7009#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01007010 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01007011
Emeric Brune1f38db2012-09-03 20:36:47 +02007012 if (conn->flags & CO_FL_ERROR) {
7013 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01007014 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02007015 }
Emeric Brun46591952012-05-18 15:47:34 +02007016 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01007017 /* A send succeeded, so we can consider ourself connected */
7018 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01007019 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02007020 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02007021 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02007022 }
7023 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01007024 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007025
Emeric Brun46591952012-05-18 15:47:34 +02007026 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01007027 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01007028 /* handshake is running, and it may need to re-enable write */
7029 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02007030 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05007031#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00007032 /* Async mode can be re-enabled, because we're leaving data state.*/
7033 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01007034 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00007035#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01007036 break;
7037 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02007038
Emeric Brun46591952012-05-18 15:47:34 +02007039 break;
7040 }
7041 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01007042 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02007043 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02007044 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
7045 SUB_RETRY_RECV,
7046 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05007047#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00007048 /* Async mode can be re-enabled, because we're leaving data state.*/
7049 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01007050 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00007051#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007052 break;
7053 }
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02007054 else if (ret == SSL_ERROR_SSL || ret == SSL_ERROR_SYSCALL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007055 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
7056
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02007057 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02007058 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02007059 conn->err_code = CO_ERR_SSL_FATAL;
7060 }
Emeric Brun46591952012-05-18 15:47:34 +02007061 goto out_error;
7062 }
7063 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02007064 leave:
Emeric Brun46591952012-05-18 15:47:34 +02007065 return done;
7066
7067 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01007068 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02007069 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01007070 ERR_clear_error();
7071
Emeric Brun46591952012-05-18 15:47:34 +02007072 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02007073 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02007074}
7075
Willy Tarreau832e2422021-05-13 10:11:03 +02007076void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02007077
Olivier Houcharde179d0e2019-03-21 18:27:17 +01007078 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01007079
Olivier Houchardea8dd942019-05-20 14:02:16 +02007080
Olivier Houcharde179d0e2019-03-21 18:27:17 +01007081 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02007082 if (ctx->wait_event.events != 0)
7083 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
7084 ctx->wait_event.events,
7085 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01007086 if (ctx->subs) {
7087 ctx->subs->events = 0;
7088 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02007089 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01007090
Olivier Houchard692c1d02019-05-23 18:41:47 +02007091 if (ctx->xprt->close)
7092 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05007093#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02007094 if (global_ssl.async) {
7095 OSSL_ASYNC_FD all_fd[32], afd;
7096 size_t num_all_fds = 0;
7097 int i;
7098
Olivier Houchard66ab4982019-02-26 18:37:15 +01007099 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02007100 if (num_all_fds > 32) {
7101 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
7102 return;
7103 }
7104
Olivier Houchard66ab4982019-02-26 18:37:15 +01007105 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02007106
7107 /* If an async job is pending, we must try to
7108 to catch the end using polling before calling
7109 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01007110 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02007111 for (i=0 ; i < num_all_fds ; i++) {
7112 /* switch on an handler designed to
7113 * handle the SSL_free
7114 */
7115 afd = all_fd[i];
7116 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01007117 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02007118 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00007119 /* To ensure that the fd cache won't be used
7120 * and we'll catch a real RD event.
7121 */
7122 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02007123 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02007124 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01007125 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02007126 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007127 return;
7128 }
Emeric Brun3854e012017-05-17 20:42:48 +02007129 /* Else we can remove the fds from the fdtab
7130 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02007131 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02007132 * because the fd is owned by the engine.
7133 * the engine is responsible to close
7134 */
Emeric Brun7d392a52022-07-01 17:36:50 +02007135 for (i=0 ; i < num_all_fds ; i++) {
7136 /* We want to remove the fd from the fdtab
7137 * but we flag it to disown because the
7138 * close is performed by the engine itself
7139 */
7140 fdtab[all_fd[i]].state |= FD_DISOWN;
7141 fd_delete(all_fd[i]);
7142 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007143 }
7144#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01007145 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01007146 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02007147 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01007148 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau82531f62021-10-06 12:15:18 +02007149 _HA_ATOMIC_DEC(&global.sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02007150 }
Emeric Brun46591952012-05-18 15:47:34 +02007151}
7152
7153/* This function tries to perform a clean shutdown on an SSL connection, and in
7154 * any case, flags the connection as reusable if no handshake was in progress.
7155 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01007156static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02007157{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01007158 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01007159
Willy Tarreau911db9b2020-01-23 16:27:54 +01007160 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02007161 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01007162 if (!clean)
7163 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01007164 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02007165 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01007166 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01007167 /* Clear openssl global errors stack */
Frédéric Lécaille2be0ac52022-09-06 19:37:08 +02007168 ssl_sock_dump_errors(conn, NULL);
Emeric Brun644cde02012-12-14 11:21:13 +01007169 ERR_clear_error();
7170 }
Emeric Brun46591952012-05-18 15:47:34 +02007171}
7172
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01007173
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05007174/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01007175int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
7176{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007177 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemandd4f946c2019-12-05 10:26:40 +01007178 X509 *crt;
7179
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007180 if (!ctx)
William Lallemandd4f946c2019-12-05 10:26:40 +01007181 return 0;
William Lallemandd4f946c2019-12-05 10:26:40 +01007182 crt = SSL_get_certificate(ctx->ssl);
7183 if (!crt)
7184 return 0;
7185
7186 return cert_get_pkey_algo(crt, out);
7187}
7188
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01007189/* used for ppv2 cert signature (can be used for logging) */
7190const char *ssl_sock_get_cert_sig(struct connection *conn)
7191{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007192 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01007193
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01007194 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
7195 X509 *crt;
7196
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007197 if (!ctx)
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01007198 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01007199 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01007200 if (!crt)
7201 return NULL;
7202 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
7203 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
7204}
7205
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01007206/* used for ppv2 authority */
7207const char *ssl_sock_get_sni(struct connection *conn)
7208{
7209#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007210 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01007211
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007212 if (!ctx)
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01007213 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01007214 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01007215#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01007216 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01007217#endif
7218}
7219
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02007220/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02007221const char *ssl_sock_get_cipher_name(struct connection *conn)
7222{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007223 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01007224
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007225 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02007226 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01007227 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02007228}
7229
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02007230/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02007231const char *ssl_sock_get_proto_version(struct connection *conn)
7232{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007233 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01007234
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007235 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02007236 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01007237 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02007238}
7239
Olivier Houchardab28a322018-12-21 19:45:40 +01007240void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
7241{
7242#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007243 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01007244
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007245 if (!ctx)
Olivier Houcharde488ea82019-06-28 14:10:33 +02007246 return;
Olivier Houchard66ab4982019-02-26 18:37:15 +01007247 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01007248#endif
7249}
7250
Willy Tarreau119a4082016-12-22 21:58:38 +01007251/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
7252 * to disable SNI.
7253 */
Willy Tarreau63076412015-07-10 11:33:32 +02007254void ssl_sock_set_servername(struct connection *conn, const char *hostname)
7255{
7256#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007257 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemande18d4e82021-11-17 02:59:21 +01007258 struct server *s;
Willy Tarreau119a4082016-12-22 21:58:38 +01007259 char *prev_name;
7260
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007261 if (!ctx)
Willy Tarreau63076412015-07-10 11:33:32 +02007262 return;
Willy Tarreau77bfa662021-12-23 11:12:13 +01007263
7264 BUG_ON(!(conn->flags & CO_FL_WAIT_L6_CONN));
7265 BUG_ON(!(conn->flags & CO_FL_SSL_WAIT_HS));
7266
William Lallemande18d4e82021-11-17 02:59:21 +01007267 s = __objt_server(conn->target);
Willy Tarreau63076412015-07-10 11:33:32 +02007268
Willy Tarreau119a4082016-12-22 21:58:38 +01007269 /* if the SNI changes, we must destroy the reusable context so that a
William Lallemande18d4e82021-11-17 02:59:21 +01007270 * new connection will present a new SNI. compare with the SNI
7271 * previously stored in the reused_sess */
7272 /* the RWLOCK is used to ensure that we are not trying to flush the
7273 * cache from the CLI */
7274
7275 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
7276 prev_name = s->ssl_ctx.reused_sess[tid].sni;
Willy Tarreau119a4082016-12-22 21:58:38 +01007277 if ((!prev_name && hostname) ||
7278 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01007279 SSL_set_session(ctx->ssl, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01007280 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau119a4082016-12-22 21:58:38 +01007281
Olivier Houchard66ab4982019-02-26 18:37:15 +01007282 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02007283#endif
7284}
7285
Emeric Brun0abf8362014-06-24 18:26:41 +02007286/* Extract peer certificate's common name into the chunk dest
7287 * Returns
7288 * the len of the extracted common name
7289 * or 0 if no CN found in DN
7290 * or -1 on error case (i.e. no peer certificate)
7291 */
Willy Tarreau83061a82018-07-13 11:56:34 +02007292int ssl_sock_get_remote_common_name(struct connection *conn,
7293 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04007294{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007295 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
David Safb76832014-05-08 23:42:08 -04007296 X509 *crt = NULL;
7297 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04007298 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02007299 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007300 .area = (char *)&find_cn,
7301 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04007302 };
Emeric Brun0abf8362014-06-24 18:26:41 +02007303 int result = -1;
David Safb76832014-05-08 23:42:08 -04007304
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007305 if (!ctx)
Emeric Brun0abf8362014-06-24 18:26:41 +02007306 goto out;
David Safb76832014-05-08 23:42:08 -04007307
7308 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01007309 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04007310 if (!crt)
7311 goto out;
7312
7313 name = X509_get_subject_name(crt);
7314 if (!name)
7315 goto out;
David Safb76832014-05-08 23:42:08 -04007316
Emeric Brun0abf8362014-06-24 18:26:41 +02007317 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
7318out:
David Safb76832014-05-08 23:42:08 -04007319 if (crt)
7320 X509_free(crt);
7321
7322 return result;
7323}
7324
Dave McCowan328fb582014-07-30 10:39:13 -04007325/* returns 1 if client passed a certificate for this session, 0 if not */
7326int ssl_sock_get_cert_used_sess(struct connection *conn)
7327{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007328 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dave McCowan328fb582014-07-30 10:39:13 -04007329 X509 *crt = NULL;
7330
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007331 if (!ctx)
Dave McCowan328fb582014-07-30 10:39:13 -04007332 return 0;
7333
7334 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01007335 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04007336 if (!crt)
7337 return 0;
7338
7339 X509_free(crt);
7340 return 1;
7341}
7342
7343/* returns 1 if client passed a certificate for this connection, 0 if not */
7344int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04007345{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007346 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01007347
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007348 if (!ctx)
David Safb76832014-05-08 23:42:08 -04007349 return 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01007350 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04007351}
7352
7353/* returns result from SSL verify */
7354unsigned int ssl_sock_get_verify_result(struct connection *conn)
7355{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007356 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01007357
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007358 if (!ctx)
David Safb76832014-05-08 23:42:08 -04007359 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Olivier Houchard66ab4982019-02-26 18:37:15 +01007360 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04007361}
7362
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007363/* Returns the application layer protocol name in <str> and <len> when known.
7364 * Zero is returned if the protocol name was not found, otherwise non-zero is
7365 * returned. The string is allocated in the SSL context and doesn't have to be
7366 * freed by the caller. NPN is also checked if available since older versions
7367 * of openssl (1.0.1) which are more common in field only support this one.
7368 */
Amaury Denoyelle71e588c2021-11-12 11:23:29 +01007369int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007370{
Olivier Houchard66ab4982019-02-26 18:37:15 +01007371#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
7372 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01007373 struct ssl_sock_ctx *ctx = xprt_ctx;
7374 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007375 return 0;
7376
7377 *str = NULL;
7378
7379#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01007380 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007381 if (*str)
7382 return 1;
7383#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01007384#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01007385 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007386 if (*str)
7387 return 1;
7388#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01007389#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007390 return 0;
7391}
7392
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007393/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02007394int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007395{
7396 X509 *ca;
7397 X509_NAME *name = NULL;
7398 ASN1_OCTET_STRING *skid = NULL;
7399 STACK_OF(X509) *chain = NULL;
7400 struct issuer_chain *issuer;
7401 struct eb64_node *node;
7402 char *path;
7403 u64 key;
7404 int ret = 0;
7405
7406 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
7407 if (chain == NULL) {
7408 chain = sk_X509_new_null();
7409 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
7410 name = X509_get_subject_name(ca);
7411 }
7412 if (!sk_X509_push(chain, ca)) {
7413 X509_free(ca);
7414 goto end;
7415 }
7416 }
7417 if (!chain) {
7418 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
7419 goto end;
7420 }
7421 if (!skid) {
7422 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
7423 goto end;
7424 }
7425 if (!name) {
7426 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
7427 goto end;
7428 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01007429 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01007430 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007431 issuer = container_of(node, typeof(*issuer), node);
7432 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
7433 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
7434 goto end;
7435 }
7436 }
7437 issuer = calloc(1, sizeof *issuer);
7438 path = strdup(fp);
7439 if (!issuer || !path) {
7440 free(issuer);
7441 free(path);
7442 goto end;
7443 }
7444 issuer->node.key = key;
7445 issuer->path = path;
7446 issuer->chain = chain;
7447 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01007448 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007449 ret = 1;
7450 end:
7451 if (skid)
7452 ASN1_OCTET_STRING_free(skid);
7453 if (chain)
7454 sk_X509_pop_free(chain, X509_free);
7455 return ret;
7456}
7457
William Lallemandda8584c2020-05-14 10:14:37 +02007458 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007459{
7460 AUTHORITY_KEYID *akid;
7461 struct issuer_chain *issuer = NULL;
7462
7463 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01007464 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007465 struct eb64_node *node;
7466 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01007467 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007468 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
7469 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
7470 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
7471 issuer = ti;
7472 break;
7473 }
7474 }
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007475 }
Remi Tricot-Le Breton1621dc12022-11-03 15:16:48 +01007476 AUTHORITY_KEYID_free(akid);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007477 return issuer;
7478}
7479
William Lallemanddad31052020-05-14 17:47:32 +02007480void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007481{
7482 struct eb64_node *node, *back;
7483 struct issuer_chain *issuer;
7484
William Lallemande0f3fd52020-02-25 14:53:06 +01007485 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007486 while (node) {
7487 issuer = container_of(node, typeof(*issuer), node);
7488 back = eb64_next(node);
7489 eb64_delete(node);
7490 free(issuer->path);
7491 sk_X509_pop_free(issuer->chain, X509_free);
7492 free(issuer);
7493 node = back;
7494 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007495}
7496
William Lallemandd7bfbe22022-04-11 18:41:24 +02007497#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007498static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01007499 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007500
Emeric Brun3854e012017-05-17 20:42:48 +02007501 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01007502 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007503 err_code = ERR_ABORT;
7504 }
7505 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01007506}
Willy Tarreau9ceda382016-12-21 23:13:03 +01007507#endif
7508
Willy Tarreaude5675a2021-01-20 14:41:29 +01007509/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007510 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01007511 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01007512static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01007513{
7514 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007515 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007516
7517 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007518 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007519
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007520 if (sctx->conn != conn) {
7521 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
7522 ret = 1;
7523 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01007524 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
7525
7526 if (sctx->xprt) {
7527 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
7528 if (sctx->xprt_ctx)
7529 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
7530 }
7531
7532 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007533
7534 /* as soon as a shutdown is reported the lower layer unregisters its
7535 * subscriber, so the situations below are transient and rare enough to
7536 * be reported as suspicious. In any case they shouldn't last.
7537 */
7538 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
7539 ret = 1;
7540 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
7541 ret = 1;
7542
Willy Tarreaude5675a2021-01-20 14:41:29 +01007543 chunk_appendf(&trash, " .subs=%p", sctx->subs);
7544 if (sctx->subs) {
7545 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007546 if (sctx->subs->tasklet->calls >= 1000000)
7547 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007548 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
7549 sctx->subs->tasklet->calls,
7550 sctx->subs->tasklet->context);
7551 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
7552 chunk_appendf(&trash, ")");
7553 }
7554 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
7555 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007556 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007557}
7558
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007559#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02007560/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007561 * each reference. The variable <ref> must point to the current node's list
7562 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02007563 */
William Lallemand32af2032016-10-29 18:09:35 +02007564static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007565struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02007566{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007567 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007568 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02007569
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007570 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007571 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007572 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02007573
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007574 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02007575}
7576
7577static inline
7578struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
7579{
7580 int id;
7581 char *error;
7582
7583 /* If the reference starts by a '#', this is numeric id. */
7584 if (reference[0] == '#') {
7585 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
7586 id = strtol(reference + 1, &error, 10);
7587 if (*error != '\0')
7588 return NULL;
7589
7590 /* Perform the unique id lookup. */
7591 return tlskeys_ref_lookupid(id);
7592 }
7593
7594 /* Perform the string lookup. */
7595 return tlskeys_ref_lookup(reference);
7596}
7597#endif
7598
7599
7600#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7601
Willy Tarreaua9380522022-05-05 08:50:17 +02007602/* dumps all tls keys. Relies on the show_keys_ctx context from the appctx. */
Willy Tarreaubd338642022-05-05 08:59:17 +02007603static int cli_io_handler_tlskeys_files(struct appctx *appctx)
7604{
Willy Tarreaua9380522022-05-05 08:50:17 +02007605 struct show_keys_ctx *ctx = appctx->svcctx;
William Lallemand32af2032016-10-29 18:09:35 +02007606
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007607 switch (ctx->state) {
7608 case SHOW_KEYS_INIT:
William Lallemand32af2032016-10-29 18:09:35 +02007609 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08007610 * quit the function with returning 0. The function is called
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007611 * later and restart at the state "SHOW_KEYS_INIT".
William Lallemand32af2032016-10-29 18:09:35 +02007612 */
7613 chunk_reset(&trash);
7614
Willy Tarreaubd338642022-05-05 08:59:17 +02007615 if (ctx->dump_entries)
William Lallemand32af2032016-10-29 18:09:35 +02007616 chunk_appendf(&trash, "# id secret\n");
7617 else
7618 chunk_appendf(&trash, "# id (file)\n");
7619
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007620 if (applet_putchk(appctx, &trash) == -1)
William Lallemand32af2032016-10-29 18:09:35 +02007621 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007622
William Lallemand32af2032016-10-29 18:09:35 +02007623 /* Now, we start the browsing of the references lists.
7624 * Note that the following call to LIST_ELEM return bad pointer. The only
7625 * available field of this pointer is <list>. It is used with the function
7626 * tlskeys_list_get_next() for retruning the first available entry
7627 */
Willy Tarreaua9380522022-05-05 08:50:17 +02007628 if (ctx->next_ref == NULL)
7629 ctx->next_ref = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007630
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007631 ctx->state = SHOW_KEYS_LIST;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007632 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007633
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007634 case SHOW_KEYS_LIST:
Willy Tarreaua9380522022-05-05 08:50:17 +02007635 while (ctx->next_ref) {
7636 struct tls_keys_ref *ref = ctx->next_ref;
William Lallemand32af2032016-10-29 18:09:35 +02007637
7638 chunk_reset(&trash);
Willy Tarreaubd338642022-05-05 08:59:17 +02007639 if (ctx->dump_entries && ctx->next_index == 0)
William Lallemand32af2032016-10-29 18:09:35 +02007640 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007641
Willy Tarreaua9380522022-05-05 08:50:17 +02007642 if (ctx->next_index == 0)
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007643 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
7644
Willy Tarreaubd338642022-05-05 08:59:17 +02007645 if (ctx->dump_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01007646 int head;
7647
7648 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
7649 head = ref->tls_ticket_enc_index;
Willy Tarreaua9380522022-05-05 08:50:17 +02007650 while (ctx->next_index < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02007651 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02007652
7653 chunk_reset(t2);
7654 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01007655 if (ref->key_size_bits == 128) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007656 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007657 sizeof(struct tls_sess_key_128),
7658 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007659 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007660 t2->area);
7661 }
7662 else if (ref->key_size_bits == 256) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007663 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007664 sizeof(struct tls_sess_key_256),
7665 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007666 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007667 t2->area);
7668 }
7669 else {
7670 /* This case should never happen */
Willy Tarreaua9380522022-05-05 08:50:17 +02007671 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, ctx->next_index);
Emeric Brun9e754772019-01-10 17:51:55 +01007672 }
William Lallemand32af2032016-10-29 18:09:35 +02007673
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007674 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007675 /* let's try again later from this stream. We add ourselves into
7676 * this stream's users so that it can remove us upon termination.
7677 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01007678 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
William Lallemand32af2032016-10-29 18:09:35 +02007679 return 0;
7680 }
Willy Tarreaua9380522022-05-05 08:50:17 +02007681 ctx->next_index++;
William Lallemand32af2032016-10-29 18:09:35 +02007682 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01007683 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaua9380522022-05-05 08:50:17 +02007684 ctx->next_index = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007685 }
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007686 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007687 /* let's try again later from this stream. We add ourselves into
7688 * this stream's users so that it can remove us upon termination.
7689 */
William Lallemand32af2032016-10-29 18:09:35 +02007690 return 0;
7691 }
7692
Willy Tarreaua9380522022-05-05 08:50:17 +02007693 if (ctx->names_only == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02007694 break;
7695
7696 /* get next list entry and check the end of the list */
Willy Tarreaua9380522022-05-05 08:50:17 +02007697 ctx->next_ref = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007698 }
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007699 ctx->state = SHOW_KEYS_DONE;
Willy Tarreaua551f4f2022-11-14 07:34:43 +01007700 __fallthrough;
William Lallemand32af2032016-10-29 18:09:35 +02007701
7702 default:
William Lallemand32af2032016-10-29 18:09:35 +02007703 return 1;
7704 }
7705 return 0;
7706}
7707
Willy Tarreaua9380522022-05-05 08:50:17 +02007708/* Prepares a "show_keys_ctx" and sets the appropriate io_handler if needed */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007709static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007710{
Willy Tarreaua9380522022-05-05 08:50:17 +02007711 struct show_keys_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
7712
William Lallemand32af2032016-10-29 18:09:35 +02007713 /* no parameter, shows only file list */
7714 if (!*args[2]) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007715 ctx->names_only = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007716 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007717 }
7718
7719 if (args[2][0] == '*') {
7720 /* list every TLS ticket keys */
Willy Tarreaua9380522022-05-05 08:50:17 +02007721 ctx->names_only = 1;
William Lallemand32af2032016-10-29 18:09:35 +02007722 } else {
Willy Tarreaua9380522022-05-05 08:50:17 +02007723 ctx->next_ref = tlskeys_ref_lookup_ref(args[2]);
7724 if (!ctx->next_ref)
Willy Tarreau9d008692019-08-09 11:21:01 +02007725 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02007726 }
Willy Tarreaubd338642022-05-05 08:59:17 +02007727
7728 ctx->dump_entries = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007729 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007730}
7731
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007732static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007733{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007734 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02007735 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007736
William Lallemand32af2032016-10-29 18:09:35 +02007737 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02007738 if (!*args[3] || !*args[4])
7739 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 +02007740
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007741 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02007742 if (!ref)
7743 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02007744
Willy Tarreau1c913e42018-08-22 05:26:57 +02007745 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02007746 if (ret < 0)
7747 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01007748
Willy Tarreau1c913e42018-08-22 05:26:57 +02007749 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02007750 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
7751 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007752
Willy Tarreau9d008692019-08-09 11:21:01 +02007753 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02007754}
William Lallemandd4f946c2019-12-05 10:26:40 +01007755#endif
William Lallemand419e6342020-04-08 12:05:39 +02007756
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007757static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007758{
7759#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
7760 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02007761 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02007762
7763 if (!payload)
7764 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02007765
7766 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02007767 if (!*payload)
7768 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02007769
7770 /* remove \r and \n from the payload */
7771 for (i = 0, j = 0; payload[i]; i++) {
7772 if (payload[i] == '\r' || payload[i] == '\n')
7773 continue;
7774 payload[j++] = payload[i];
7775 }
7776 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007777
Willy Tarreau1c913e42018-08-22 05:26:57 +02007778 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02007779 if (ret < 0)
7780 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007781
Willy Tarreau1c913e42018-08-22 05:26:57 +02007782 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02007783 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02007784 if (err)
7785 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
7786 else
7787 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007788 }
Willy Tarreau9d008692019-08-09 11:21:01 +02007789
7790 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02007791#else
Willy Tarreau9d008692019-08-09 11:21:01 +02007792 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 +02007793#endif
7794
Elliot Otchet71f82972020-01-15 08:12:14 -05007795}
7796
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007797
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007798#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 +02007799static int cli_io_handler_show_ocspresponse_detail(struct appctx *appctx);
7800#endif
7801
Willy Tarreau170b35b2022-05-05 09:09:15 +02007802/* parsing function for 'show ssl ocsp-response [id]'. If an entry is forced,
7803 * it's set into appctx->svcctx.
7804 */
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007805static int cli_parse_show_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
7806{
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007807#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 +02007808 if (*args[3]) {
7809 struct certificate_ocsp *ocsp = NULL;
Remi Tricot-Le Breton93348432022-12-15 15:44:35 +01007810 char key[OCSP_MAX_CERTID_ASN1_LENGTH] = {};
7811 int key_length = OCSP_MAX_CERTID_ASN1_LENGTH;
7812 char *key_ptr = key;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007813
7814 if (strlen(args[3]) > OCSP_MAX_CERTID_ASN1_LENGTH*2) {
7815 return cli_err(appctx, "'show ssl ocsp-response' received a too big key.\n");
7816 }
7817
Remi Tricot-Le Breton93348432022-12-15 15:44:35 +01007818 if (!parse_binary(args[3], &key_ptr, &key_length, NULL)) {
7819 return cli_err(appctx, "'show ssl ocsp-response' received an invalid key.\n");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007820 }
Remi Tricot-Le Breton93348432022-12-15 15:44:35 +01007821
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01007822 HA_SPIN_LOCK(OCSP_LOCK, &ocsp_tree_lock);
Remi Tricot-Le Breton93348432022-12-15 15:44:35 +01007823 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007824
7825 if (!ocsp) {
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01007826 HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007827 return cli_err(appctx, "Certificate ID does not match any certificate.\n");
7828 }
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01007829 ++ocsp->refcount;
7830 HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007831
Willy Tarreau170b35b2022-05-05 09:09:15 +02007832 appctx->svcctx = ocsp;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007833 appctx->io_handler = cli_io_handler_show_ocspresponse_detail;
7834 }
7835
7836 return 0;
7837
7838#else
7839 return cli_err(appctx, "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n");
7840#endif
7841}
7842
7843
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007844#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 +02007845/*
7846 * This function dumps the details of an OCSP_CERTID. It is based on
7847 * ocsp_certid_print in OpenSSL.
7848 */
7849static inline int ocsp_certid_print(BIO *bp, OCSP_CERTID *certid, int indent)
7850{
7851 ASN1_OCTET_STRING *piNameHash = NULL;
7852 ASN1_OCTET_STRING *piKeyHash = NULL;
7853 ASN1_INTEGER *pSerial = NULL;
7854
7855 if (OCSP_id_get0_info(&piNameHash, NULL, &piKeyHash, &pSerial, certid)) {
7856
7857 BIO_printf(bp, "%*sCertificate ID:\n", indent, "");
7858 indent += 2;
Remi Tricot-Le Bretoncc750ef2021-12-17 18:53:23 +01007859 BIO_printf(bp, "%*sIssuer Name Hash: ", indent, "");
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01007860#ifndef USE_OPENSSL_WOLFSSL
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007861 i2a_ASN1_STRING(bp, piNameHash, 0);
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01007862#else
7863 wolfSSL_ASN1_STRING_print(bp, piNameHash);
7864#endif
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007865 BIO_printf(bp, "\n%*sIssuer Key Hash: ", indent, "");
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01007866#ifndef USE_OPENSSL_WOLFSSL
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007867 i2a_ASN1_STRING(bp, piKeyHash, 0);
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01007868#else
7869 wolfSSL_ASN1_STRING_print(bp, piNameHash);
7870#endif
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007871 BIO_printf(bp, "\n%*sSerial Number: ", indent, "");
7872 i2a_ASN1_INTEGER(bp, pSerial);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007873 }
7874 return 1;
7875}
7876#endif
7877
7878/*
7879 * IO handler of "show ssl ocsp-response". The command taking a specific ID
7880 * is managed in cli_io_handler_show_ocspresponse_detail.
Willy Tarreau170b35b2022-05-05 09:09:15 +02007881 * The current entry is taken from appctx->svcctx.
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007882 */
7883static int cli_io_handler_show_ocspresponse(struct appctx *appctx)
7884{
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007885#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 +02007886 struct buffer *trash = alloc_trash_chunk();
7887 struct buffer *tmp = NULL;
7888 struct ebmb_node *node;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007889 struct certificate_ocsp *ocsp = NULL;
7890 BIO *bio = NULL;
7891 int write = -1;
7892
7893 if (trash == NULL)
7894 return 1;
7895
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01007896 HA_SPIN_LOCK(OCSP_LOCK, &ocsp_tree_lock);
7897
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007898 tmp = alloc_trash_chunk();
7899 if (!tmp)
7900 goto end;
7901
7902 if ((bio = BIO_new(BIO_s_mem())) == NULL)
7903 goto end;
7904
Willy Tarreau170b35b2022-05-05 09:09:15 +02007905 if (!appctx->svcctx) {
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007906 chunk_appendf(trash, "# Certificate IDs\n");
7907 node = ebmb_first(&cert_ocsp_tree);
7908 } else {
Willy Tarreau170b35b2022-05-05 09:09:15 +02007909 node = &((struct certificate_ocsp *)appctx->svcctx)->key;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007910 }
7911
7912 while (node) {
7913 OCSP_CERTID *certid = NULL;
7914 const unsigned char *p = NULL;
7915 int i;
7916
7917 ocsp = ebmb_entry(node, struct certificate_ocsp, key);
7918
7919 /* Dump the key in hexadecimal */
7920 chunk_appendf(trash, "Certificate ID key : ");
7921 for (i = 0; i < ocsp->key_length; ++i) {
7922 chunk_appendf(trash, "%02x", ocsp->key_data[i]);
7923 }
7924 chunk_appendf(trash, "\n");
7925
7926 p = ocsp->key_data;
7927
7928 /* Decode the certificate ID (serialized into the key). */
7929 d2i_OCSP_CERTID(&certid, &p, ocsp->key_length);
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007930 if (!certid)
7931 goto end;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007932
7933 /* Dump the CERTID info */
7934 ocsp_certid_print(bio, certid, 1);
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007935 OCSP_CERTID_free(certid);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007936 write = BIO_read(bio, tmp->area, tmp->size-1);
Remi Tricot-Le Bretoncc750ef2021-12-17 18:53:23 +01007937 /* strip trailing LFs */
7938 while (write > 0 && tmp->area[write-1] == '\n')
7939 write--;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007940 tmp->area[write] = '\0';
7941
7942 chunk_appendf(trash, "%s\n", tmp->area);
7943
7944 node = ebmb_next(node);
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007945 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007946 goto yield;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007947 }
7948
7949end:
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01007950 HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
Willy Tarreau170b35b2022-05-05 09:09:15 +02007951 appctx->svcctx = NULL;
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01007952 free_trash_chunk(trash);
7953 free_trash_chunk(tmp);
7954 BIO_free(bio);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007955 return 1;
7956
7957yield:
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01007958 free_trash_chunk(trash);
7959 free_trash_chunk(tmp);
7960 BIO_free(bio);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007961
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01007962 ++ocsp->refcount;
Willy Tarreau170b35b2022-05-05 09:09:15 +02007963 appctx->svcctx = ocsp;
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01007964 HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007965 return 0;
7966#else
7967 return cli_err(appctx, "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n");
7968#endif
7969}
7970
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007971#ifdef HAVE_SSL_PROVIDERS
7972struct provider_name {
7973 const char *name;
7974 struct list list;
7975};
7976
7977
7978static int ssl_provider_get_name_cb(OSSL_PROVIDER *provider, void *cbdata)
7979{
7980 struct list *provider_names = cbdata;
7981 struct provider_name *item = NULL;
7982 const char *name = OSSL_PROVIDER_get0_name(provider);
7983
7984 if (!provider_names)
7985 return 0;
7986
7987 item = calloc(1, sizeof(*item));
7988
7989 if (!item)
7990 return 0;
7991
7992 item->name = name;
7993 LIST_APPEND(provider_names, &item->list);
7994
7995 return 1;
7996}
7997
7998static void ssl_provider_get_name_list(struct list *provider_names)
7999{
8000 if (!provider_names)
8001 return;
8002
8003 OSSL_PROVIDER_do_all(NULL, ssl_provider_get_name_cb, provider_names);
8004}
8005
8006static void ssl_provider_clear_name_list(struct list *provider_names)
8007{
8008 struct provider_name *item = NULL, *item_s = NULL;
8009
8010 if (provider_names) {
8011 list_for_each_entry_safe(item, item_s, provider_names, list) {
8012 LIST_DELETE(&item->list);
8013 free(item);
8014 }
8015 }
8016}
8017
8018static int cli_io_handler_show_providers(struct appctx *appctx)
8019{
8020 struct buffer *trash = get_trash_chunk();
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02008021 struct list provider_names;
8022 struct provider_name *name;
8023
8024 LIST_INIT(&provider_names);
8025
8026 chunk_appendf(trash, "Loaded providers : \n");
8027
8028 ssl_provider_get_name_list(&provider_names);
8029
8030 list_for_each_entry(name, &provider_names, list) {
8031 chunk_appendf(trash, "\t- %s\n", name->name);
8032 }
8033
8034 ssl_provider_clear_name_list(&provider_names);
8035
Willy Tarreaud0a06d52022-05-18 15:07:19 +02008036 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02008037 goto yield;
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02008038
8039 return 1;
8040
8041yield:
8042 return 0;
8043}
8044#endif
8045
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02008046
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02008047#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 +02008048/*
8049 * Dump the details about an OCSP response in DER format stored in
8050 * <ocsp_response> into buffer <out>.
8051 * Returns 0 in case of success.
8052 */
8053int ssl_ocsp_response_print(struct buffer *ocsp_response, struct buffer *out)
8054{
8055 BIO *bio = NULL;
8056 int write = -1;
8057 OCSP_RESPONSE *resp;
8058 const unsigned char *p;
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01008059 int retval = -1;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02008060
8061 if (!ocsp_response)
8062 return -1;
8063
8064 if ((bio = BIO_new(BIO_s_mem())) == NULL)
8065 return -1;
8066
8067 p = (const unsigned char*)ocsp_response->area;
8068
8069 resp = d2i_OCSP_RESPONSE(NULL, &p, ocsp_response->data);
8070 if (!resp) {
8071 chunk_appendf(out, "Unable to parse OCSP response");
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01008072 goto end;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02008073 }
8074
Uriah Pollock3cbf09e2022-11-23 16:41:25 +01008075#ifndef USE_OPENSSL_WOLFSSL
8076 if (OCSP_RESPONSE_print(bio, resp, 0) != 0) {
8077#else
8078 if (wolfSSL_d2i_OCSP_RESPONSE_bio(bio, &resp) != 0) {
8079#endif
Remi Tricot-Le Breton2e7d1eb2022-01-11 10:11:10 +01008080 struct buffer *trash = get_trash_chunk();
8081 struct ist ist_block = IST_NULL;
8082 struct ist ist_double_lf = IST_NULL;
8083 static struct ist double_lf = IST("\n\n");
8084
8085 write = BIO_read(bio, trash->area, trash->size - 1);
Remi Tricot-Le Breton1b01b7f2022-02-16 15:17:09 +01008086 if (write <= 0)
8087 goto end;
Remi Tricot-Le Breton2e7d1eb2022-01-11 10:11:10 +01008088 trash->data = write;
8089
8090 /* Look for empty lines in the 'trash' buffer and add a space to
8091 * the beginning to avoid having empty lines in the output
8092 * (without changing the appearance of the information
8093 * displayed).
8094 */
8095 ist_block = ist2(b_orig(trash), b_data(trash));
8096
8097 ist_double_lf = istist(ist_block, double_lf);
8098
8099 while (istlen(ist_double_lf)) {
8100 /* istptr(ist_double_lf) points to the first \n of a
8101 * \n\n pattern.
8102 */
8103 uint empty_line_offset = istptr(ist_double_lf) + 1 - istptr(ist_block);
8104
8105 /* Write up to the first '\n' of the "\n\n" pattern into
8106 * the output buffer.
8107 */
8108 b_putblk(out, istptr(ist_block), empty_line_offset);
8109 /* Add an extra space. */
8110 b_putchr(out, ' ');
8111
8112 /* Keep looking for empty lines in the rest of the data. */
8113 ist_block = istadv(ist_block, empty_line_offset);
8114
8115 ist_double_lf = istist(ist_block, double_lf);
8116 }
8117
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01008118 retval = (b_istput(out, ist_block) <= 0);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02008119 }
8120
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01008121end:
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02008122 if (bio)
8123 BIO_free(bio);
8124
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01008125 OCSP_RESPONSE_free(resp);
8126
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01008127 return retval;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02008128}
8129
8130/*
8131 * Dump the details of the OCSP response of ID <ocsp_certid> into buffer <out>.
8132 * Returns 0 in case of success.
8133 */
8134int ssl_get_ocspresponse_detail(unsigned char *ocsp_certid, struct buffer *out)
8135{
8136 struct certificate_ocsp *ocsp;
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01008137 int ret = 0;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02008138
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01008139 HA_SPIN_LOCK(OCSP_LOCK, &ocsp_tree_lock);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02008140 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, ocsp_certid, OCSP_MAX_CERTID_ASN1_LENGTH);
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01008141 if (!ocsp) {
8142 HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02008143 return -1;
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01008144 }
8145
8146 ret = ssl_ocsp_response_print(&ocsp->response, out);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02008147
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01008148 HA_SPIN_UNLOCK(OCSP_LOCK, &ocsp_tree_lock);
8149
8150 return ret;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02008151}
8152
8153
Willy Tarreau170b35b2022-05-05 09:09:15 +02008154/* IO handler of details "show ssl ocsp-response <id>".
8155 * The current entry is taken from appctx->svcctx.
8156 */
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02008157static int cli_io_handler_show_ocspresponse_detail(struct appctx *appctx)
8158{
Remi Tricot-Le Bretone3d5f9a2022-12-15 15:44:36 +01008159 struct buffer *trash = get_trash_chunk();
Willy Tarreau170b35b2022-05-05 09:09:15 +02008160 struct certificate_ocsp *ocsp = appctx->svcctx;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02008161
Remi Tricot-Le Bretone3d5f9a2022-12-15 15:44:36 +01008162 if (ssl_ocsp_response_print(&ocsp->response, trash))
8163 goto end;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02008164
Willy Tarreaud0a06d52022-05-18 15:07:19 +02008165 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretone3d5f9a2022-12-15 15:44:36 +01008166 return 0;
Willy Tarreau170b35b2022-05-05 09:09:15 +02008167
Remi Tricot-Le Bretone3d5f9a2022-12-15 15:44:36 +01008168end:
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01008169 ssl_sock_free_ocsp(ocsp);
Willy Tarreau170b35b2022-05-05 09:09:15 +02008170 appctx->svcctx = NULL;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02008171 return 1;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02008172}
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01008173
8174struct ocsp_cli_ctx {
8175 struct httpclient *hc;
8176 struct ckch_data *ckch_data;
8177 uint flags;
8178 uint do_update;
8179};
8180
8181const struct http_hdr ocsp_request_hdrs[] = {
8182 { IST("Content-Type"), IST("application/ocsp-request") },
8183 { IST_NULL, IST_NULL }
8184};
8185
8186void cli_ocsp_res_stline_cb(struct httpclient *hc)
8187{
8188 struct appctx *appctx = hc->caller;
8189 struct ocsp_cli_ctx *ctx;
8190
8191 if (!appctx)
8192 return;
8193
8194 ctx = appctx->svcctx;
8195 ctx->flags |= HC_F_RES_STLINE;
8196 appctx_wakeup(appctx);
8197}
8198
8199void cli_ocsp_res_headers_cb(struct httpclient *hc)
8200{
8201 struct appctx *appctx = hc->caller;
8202 struct ocsp_cli_ctx *ctx;
8203
8204 if (!appctx)
8205 return;
8206
8207 ctx = appctx->svcctx;
8208 ctx->flags |= HC_F_RES_HDR;
8209 appctx_wakeup(appctx);
8210}
8211
8212void cli_ocsp_res_body_cb(struct httpclient *hc)
8213{
8214 struct appctx *appctx = hc->caller;
8215 struct ocsp_cli_ctx *ctx;
8216
8217 if (!appctx)
8218 return;
8219
8220 ctx = appctx->svcctx;
8221 ctx->flags |= HC_F_RES_BODY;
8222 appctx_wakeup(appctx);
8223}
8224
8225void cli_ocsp_res_end_cb(struct httpclient *hc)
8226{
8227 struct appctx *appctx = hc->caller;
8228 struct ocsp_cli_ctx *ctx;
8229
8230 if (!appctx)
8231 return;
8232
8233 ctx = appctx->svcctx;
8234 ctx->flags |= HC_F_RES_END;
8235 appctx_wakeup(appctx);
8236}
8237
8238static int cli_parse_update_ocsp_response(char **args, char *payload, struct appctx *appctx, void *private)
8239{
8240 int errcode = 0;
8241 char *err = NULL;
8242 struct ckch_store *ckch_store = NULL;
8243 X509 *cert = NULL;
8244 struct ocsp_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
8245 struct httpclient *hc = NULL;
8246 struct buffer *req_url = NULL;
8247 struct buffer *req_body = NULL;
8248 OCSP_CERTID *certid = NULL;
8249
8250 if (!*args[3]) {
8251 memprintf(&err, "'update ssl ocsp-response' expects a filename\n");
8252 return cli_dynerr(appctx, err);
8253 }
8254
8255 req_url = alloc_trash_chunk();
8256 if (!req_url) {
8257 memprintf(&err, "%sCan't allocate memory\n", err ? err : "");
8258 errcode |= ERR_ALERT | ERR_FATAL;
8259 goto end;
8260 }
8261
8262 req_body = alloc_trash_chunk();
8263 if (!req_body) {
8264 memprintf(&err, "%sCan't allocate memory\n", err ? err : "");
8265 errcode |= ERR_ALERT | ERR_FATAL;
8266 goto end;
8267 }
8268
8269 /* The operations on the CKCH architecture are locked so we can
8270 * manipulate ckch_store and ckch_inst */
8271 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock)) {
8272 memprintf(&err, "%sCan't update the certificate!\nOperations on certificates are currently locked!\n", err ? err : "");
8273 errcode |= ERR_ALERT | ERR_FATAL;
8274 goto end;
8275 }
8276
8277 ckch_store = ckchs_lookup(args[3]);
8278
8279 if (!ckch_store) {
8280 memprintf(&err, "%sCkch_store not found!\n", err ? err : "");
8281 errcode |= ERR_ALERT | ERR_FATAL;
8282 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
8283 goto end;
8284 }
8285
8286 ctx->ckch_data = ckch_store->data;
8287
8288 cert = ckch_store->data->cert;
8289
8290 if (ssl_ocsp_get_uri_from_cert(cert, req_url, &err)) {
8291 errcode |= ERR_ALERT | ERR_FATAL;
8292 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
8293 goto end;
8294 }
8295
8296 certid = OCSP_cert_to_id(NULL, ctx->ckch_data->cert, ctx->ckch_data->ocsp_issuer);
8297 if (certid == NULL) {
8298 memprintf(&err, "%sOCSP_cert_to_id() error\n", err ? err : "");
8299 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
8300 goto end;
8301 }
8302
8303 /* From here on the lock is not needed anymore. */
8304 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
8305
8306 /* Create ocsp request */
8307 if (ssl_ocsp_create_request_details(certid, req_url, req_body, &err) != 0) {
8308 memprintf(&err, "%sCreate ocsp request error\n", err ? err : "");
8309 goto end;
8310 }
8311
8312 hc = httpclient_new(appctx, b_data(req_body) ? HTTP_METH_POST : HTTP_METH_GET, ist2(b_orig(req_url), b_data(req_url)));
8313 if (!hc) {
8314 memprintf(&err, "%sCan't allocate httpclient\n", err ? err : "");
8315 goto end;
8316 }
8317
8318 if (httpclient_req_gen(hc, hc->req.url, hc->req.meth, b_data(req_body) ? ocsp_request_hdrs : NULL,
8319 ist2(b_orig(req_body), b_data(req_body))) != ERR_NONE) {
8320 memprintf(&err, "%shttpclient_req_gen() error\n", err ? err : "");
8321 goto end;
8322 }
8323
8324 hc->ops.res_stline = cli_ocsp_res_stline_cb;
8325 hc->ops.res_headers = cli_ocsp_res_headers_cb;
8326 hc->ops.res_payload = cli_ocsp_res_body_cb;
8327 hc->ops.res_end = cli_ocsp_res_end_cb;
8328
8329 ctx->hc = hc; /* store the httpclient ptr in the applet */
8330 ctx->flags = 0;
8331
8332 if (!httpclient_start(hc)) {
8333 memprintf(&err, "%shttpclient_start() error\n", err ? err : "");
8334 goto end;
8335 }
8336
8337 free_trash_chunk(req_url);
8338
8339 return 0;
8340
8341end:
8342 free_trash_chunk(req_url);
8343
8344 if (errcode & ERR_CODE) {
8345 return cli_dynerr(appctx, memprintf(&err, "%sCan't send ocsp request for %s!\n", err ? err : "", args[3]));
8346 }
8347 return cli_dynmsg(appctx, LOG_NOTICE, err);
8348}
8349
8350static int cli_io_handler_update_ocsp_response(struct appctx *appctx)
8351{
8352 struct ocsp_cli_ctx *ctx = appctx->svcctx;
8353 struct httpclient *hc = ctx->hc;
8354
8355 if (ctx->flags & HC_F_RES_STLINE) {
8356 if (hc->res.status != 200) {
8357 chunk_printf(&trash, "OCSP response error (status %d)\n", hc->res.status);
8358 if (applet_putchk(appctx, &trash) == -1)
8359 goto more;
8360 goto end;
8361 }
8362 ctx->flags &= ~HC_F_RES_STLINE;
8363 }
8364
8365 if (ctx->flags & HC_F_RES_HDR) {
8366 struct http_hdr *hdr;
8367 int found = 0;
8368 /* Look for "Content-Type" header which should have
8369 * "application/ocsp-response" value. */
8370 for (hdr = hc->res.hdrs; isttest(hdr->v); hdr++) {
8371 if (isteqi(hdr->n, ist("Content-Type")) &&
8372 isteqi(hdr->v, ist("application/ocsp-response"))) {
8373 found = 1;
8374 break;
8375 }
8376 }
8377 if (!found) {
8378 fprintf(stderr, "Missing 'Content-Type: application/ocsp-response' header\n");
8379 goto end;
8380 }
8381 ctx->flags &= ~HC_F_RES_HDR;
8382 }
8383
8384 if (ctx->flags & HC_F_RES_BODY) {
8385 /* Wait until the full body is received and HC_F_RES_END flag is
8386 * set. */
8387 }
8388
8389 /* we must close only if F_END is the last flag */
8390 if (ctx->flags & HC_F_RES_END) {
8391 char *err = NULL;
8392
8393 if (ssl_ocsp_check_response(ctx->ckch_data->chain, ctx->ckch_data->ocsp_issuer, &hc->res.buf, &err)) {
8394 chunk_printf(&trash, "%s", err);
8395 if (applet_putchk(appctx, &trash) == -1)
8396 goto more;
8397 goto end;
8398 }
8399
8400 if (ssl_sock_update_ocsp_response(&hc->res.buf, &err) != 0) {
8401 chunk_printf(&trash, "%s", err);
8402 if (applet_putchk(appctx, &trash) == -1)
8403 goto more;
8404 goto end;
8405 }
8406
8407 chunk_reset(&trash);
8408
8409 if (ssl_ocsp_response_print(&hc->res.buf, &trash))
8410 goto end;
8411
8412 if (applet_putchk(appctx, &trash) == -1)
8413 goto more;
8414 ctx->flags &= ~HC_F_RES_BODY;
8415 ctx->flags &= ~HC_F_RES_END;
8416 goto end;
8417 }
8418
8419more:
8420 if (!ctx->flags)
8421 applet_have_no_more_data(appctx);
8422 return 0;
8423end:
8424 return 1;
8425}
8426
8427static void cli_release_update_ocsp_response(struct appctx *appctx)
8428{
8429 struct ocsp_cli_ctx *ctx = appctx->svcctx;
8430 struct httpclient *hc = ctx->hc;
8431
8432 /* Everything possible was printed on the CLI, we can destroy the client */
8433 httpclient_stop_and_destroy(hc);
8434
8435 return;
8436}
8437
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02008438#endif
8439
William Lallemand32af2032016-10-29 18:09:35 +02008440/* register cli keywords */
8441static struct cli_kw_list cli_kws = {{ },{
8442#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01008443 { { "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 },
8444 { { "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 +02008445#endif
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01008446 { { "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 +02008447
Remi Tricot-Le Bretoneeaa29b2022-12-20 11:11:07 +01008448 { { "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 },
8449#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
8450 { { "update", "ssl", "ocsp-response", NULL }, "update ssl ocsp-response <certfile> : send ocsp request and update stored ocsp response", cli_parse_update_ocsp_response, cli_io_handler_update_ocsp_response, cli_release_update_ocsp_response },
8451#endif
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02008452#ifdef HAVE_SSL_PROVIDERS
8453 { { "show", "ssl", "providers", NULL }, "show ssl providers : show loaded SSL providers", NULL, cli_io_handler_show_providers },
8454#endif
William Lallemand32af2032016-10-29 18:09:35 +02008455 { { NULL }, NULL, NULL, NULL }
8456}};
8457
Willy Tarreau0108d902018-11-25 19:14:37 +01008458INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02008459
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02008460/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02008461struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02008462 .snd_buf = ssl_sock_from_buf,
8463 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01008464 .subscribe = ssl_subscribe,
8465 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02008466 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02008467 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02008468 .rcv_pipe = NULL,
8469 .snd_pipe = NULL,
8470 .shutr = NULL,
8471 .shutw = ssl_sock_shutw,
8472 .close = ssl_sock_close,
8473 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01008474 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01008475 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01008476 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01008477 .prepare_srv = ssl_sock_prepare_srv_ctx,
8478 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01008479 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02008480 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01008481 .set_idle = ssl_set_idle,
8482 .set_used = ssl_set_used,
Willy Tarreaude827952022-04-11 10:43:28 +02008483 .get_ssl_sock_ctx = ssl_sock_get_ctx,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01008484 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01008485 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02008486};
8487
Olivier Houchardccaa7de2017-10-02 11:51:03 +02008488enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
8489 struct session *sess, struct stream *s, int flags)
8490{
8491 struct connection *conn;
8492
8493 conn = objt_conn(sess->origin);
8494
Willy Tarreaub52d4d22022-05-27 10:44:39 +02008495 if (conn) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02008496 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Willy Tarreaub52d4d22022-05-27 10:44:39 +02008497 sc_ep_set(s->scf, SE_FL_WAIT_FOR_HS);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02008498 s->req.flags |= CF_READ_NULL;
8499 return ACT_RET_YIELD;
8500 }
8501 }
8502 return (ACT_RET_CONT);
8503}
8504
8505static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
8506{
8507 rule->action_ptr = ssl_action_wait_for_hs;
8508
8509 return ACT_RET_PRS_OK;
8510}
8511
8512static struct action_kw_list http_req_actions = {ILH, {
8513 { "wait-for-handshake", ssl_parse_wait_for_hs },
8514 { /* END */ }
8515}};
8516
Willy Tarreau0108d902018-11-25 19:14:37 +01008517INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
8518
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05008519#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01008520
8521static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
8522{
8523 if (ptr) {
8524 chunk_destroy(ptr);
8525 free(ptr);
8526 }
8527}
8528
8529#endif
William Lallemand76b4a122020-08-04 17:41:39 +02008530
8531#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
8532static void ssl_sock_ocsp_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
8533{
8534 struct ocsp_cbk_arg *ocsp_arg;
8535
8536 if (ptr) {
8537 ocsp_arg = ptr;
8538
8539 if (ocsp_arg->is_single) {
8540 ssl_sock_free_ocsp(ocsp_arg->s_ocsp);
8541 ocsp_arg->s_ocsp = NULL;
8542 } else {
8543 int i;
8544
8545 for (i = 0; i < SSL_SOCK_NUM_KEYTYPES; i++) {
8546 ssl_sock_free_ocsp(ocsp_arg->m_ocsp[i]);
8547 ocsp_arg->m_ocsp[i] = NULL;
8548 }
8549 }
8550 free(ocsp_arg);
8551 }
8552}
8553#endif
8554
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01008555static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
8556{
Willy Tarreaubafbe012017-11-24 17:34:44 +01008557 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01008558}
William Lallemand7d42ef52020-07-06 11:41:30 +02008559
William Lallemand722180a2021-06-09 16:46:12 +02008560#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02008561static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
8562{
8563 struct ssl_keylog *keylog;
8564
8565 if (!ptr)
8566 return;
8567
8568 keylog = ptr;
8569
8570 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
8571 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
8572 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
8573 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
8574 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
8575 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
8576 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
8577 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
8578
8579 pool_free(pool_head_ssl_keylog, ptr);
8580}
8581#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01008582
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02008583static void ssl_sock_clt_crt_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
8584{
8585 if (!ptr)
8586 return;
8587
8588 X509_free((X509*)ptr);
8589}
8590
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01008591static void ssl_sock_clt_sni_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
8592{
8593 pool_free(ssl_sock_client_sni_pool, ptr);
8594}
8595
Willy Tarreau92faadf2012-10-10 23:04:25 +02008596static void __ssl_sock_init(void)
8597{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05008598#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02008599 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05008600 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05008601#endif
Emeric Brun46591952012-05-18 15:47:34 +02008602
Willy Tarreauef934602016-12-22 23:12:01 +01008603 if (global_ssl.listen_default_ciphers)
8604 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
8605 if (global_ssl.connect_default_ciphers)
8606 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05008607#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02008608 if (global_ssl.listen_default_ciphersuites)
8609 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
8610 if (global_ssl.connect_default_ciphersuites)
8611 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
8612#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01008613
Willy Tarreau13e14102016-12-22 20:25:26 +01008614 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02008615#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02008616 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08008617#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05008618#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02008619 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05008620 n = sk_SSL_COMP_num(cm);
8621 while (n--) {
8622 (void) sk_SSL_COMP_pop(cm);
8623 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05008624#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05008625
Willy Tarreau5db847a2019-05-09 14:13:35 +02008626#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02008627 ssl_locking_init();
8628#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05008629#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01008630 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
8631#endif
William Lallemand76b4a122020-08-04 17:41:39 +02008632
8633#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
8634 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
8635#endif
8636
Thierry FOURNIER28962c92018-06-17 21:37:05 +02008637 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02008638 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 +01008639#ifdef USE_QUIC
8640 ssl_qc_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
8641#endif /* USE_QUIC */
William Lallemand722180a2021-06-09 16:46:12 +02008642#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02008643 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
8644#endif
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02008645 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 +01008646 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 +02008647#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00008648 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00008649 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02008650#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01008651#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
8652 hap_register_post_check(tlskeys_finalize_config);
8653#endif
Willy Tarreau80713382018-11-26 10:19:54 +01008654
8655 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
8656 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
8657
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01008658 hap_register_post_deinit(ssl_free_global_issuers);
8659
Willy Tarreau80713382018-11-26 10:19:54 +01008660#ifndef OPENSSL_NO_DH
8661 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
8662 hap_register_post_deinit(ssl_free_dh);
8663#endif
William Lallemandd7bfbe22022-04-11 18:41:24 +02008664#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Willy Tarreau80713382018-11-26 10:19:54 +01008665 hap_register_post_deinit(ssl_free_engines);
8666#endif
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02008667#ifdef HAVE_SSL_PROVIDERS
8668 hap_register_post_deinit(ssl_unload_providers);
8669#endif
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01008670#if HA_OPENSSL_VERSION_NUMBER < 0x3000000fL
Willy Tarreau80713382018-11-26 10:19:54 +01008671 /* Load SSL string for the verbose & debug mode. */
8672 ERR_load_SSL_strings();
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01008673#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02008674 ha_meth = BIO_meth_new(0x666, "ha methods");
8675 BIO_meth_set_write(ha_meth, ha_ssl_write);
8676 BIO_meth_set_read(ha_meth, ha_ssl_read);
8677 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
8678 BIO_meth_set_create(ha_meth, ha_ssl_new);
8679 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
8680 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
8681 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02008682
8683 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02008684
Remi Tricot-Le Breton2b963642022-12-20 11:11:02 +01008685 HA_SPIN_INIT(&ocsp_tree_lock);
8686
Dragan Dosen9ac98092020-05-11 15:51:45 +02008687 /* Try to register dedicated SSL/TLS protocol message callbacks for
8688 * heartbleed attack (CVE-2014-0160) and clienthello.
8689 */
8690 hap_register_post_check(ssl_sock_register_msg_callbacks);
8691
Dragan Dosen1e7ed042020-05-08 18:30:00 +02008692 /* Try to free all callbacks that were registered by using
8693 * ssl_sock_register_msg_callback().
8694 */
8695 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01008696}
Willy Tarreau79367f92022-04-25 19:18:24 +02008697INITCALL0(STG_REGISTER, __ssl_sock_init);
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01008698
Willy Tarreau80713382018-11-26 10:19:54 +01008699/* Compute and register the version string */
8700static void ssl_register_build_options()
8701{
8702 char *ptr = NULL;
8703 int i;
8704
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008705 memprintf(&ptr, "Built with OpenSSL version : "
8706#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01008707 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008708#else /* OPENSSL_IS_BORINGSSL */
8709 OPENSSL_VERSION_TEXT
8710 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08008711 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02008712 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008713#endif
8714 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02008715#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008716 "no (library version too old)"
8717#elif defined(OPENSSL_NO_TLSEXT)
8718 "no (disabled via OPENSSL_NO_TLSEXT)"
8719#else
8720 "yes"
8721#endif
8722 "", ptr);
8723
8724 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
8725#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
8726 "yes"
8727#else
8728#ifdef OPENSSL_NO_TLSEXT
8729 "no (because of OPENSSL_NO_TLSEXT)"
8730#else
8731 "no (version might be too old, 0.9.8f min needed)"
8732#endif
8733#endif
8734 "", ptr);
8735
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02008736 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
8737 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
8738 if (methodVersions[i].option)
8739 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01008740
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02008741#ifdef HAVE_SSL_PROVIDERS
8742 {
8743 struct list provider_names;
8744 struct provider_name *name;
8745 LIST_INIT(&provider_names);
8746 ssl_provider_get_name_list(&provider_names);
8747
8748 memprintf(&ptr, "%s\nOpenSSL providers loaded :", ptr);
8749
8750 list_for_each_entry(name, &provider_names, list) {
8751 memprintf(&ptr, "%s %s", ptr, name->name);
8752 }
8753
8754 ssl_provider_clear_name_list(&provider_names);
8755 }
8756#endif
8757
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008758 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01008759}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008760
Willy Tarreau80713382018-11-26 10:19:54 +01008761INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02008762
William Lallemandd7bfbe22022-04-11 18:41:24 +02008763#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00008764void ssl_free_engines(void) {
8765 struct ssl_engine_list *wl, *wlb;
8766 /* free up engine list */
8767 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
8768 ENGINE_finish(wl->e);
8769 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02008770 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00008771 free(wl);
8772 }
8773}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02008774#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02008775
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02008776#ifdef HAVE_SSL_PROVIDERS
8777void ssl_unload_providers(void) {
8778 struct ssl_provider_list *prov, *provb;
8779 list_for_each_entry_safe(prov, provb, &openssl_providers, list) {
8780 OSSL_PROVIDER_unload(prov->provider);
8781 LIST_DELETE(&prov->list);
8782 free(prov);
8783 }
8784}
8785#endif
8786
Remi Gacogned3a23c32015-05-28 16:39:47 +02008787#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00008788void ssl_free_dh(void) {
8789 if (local_dh_1024) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008790 HASSL_DH_free(local_dh_1024);
Grant Zhang872f9c22017-01-21 01:10:18 +00008791 local_dh_1024 = NULL;
8792 }
8793 if (local_dh_2048) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008794 HASSL_DH_free(local_dh_2048);
Grant Zhang872f9c22017-01-21 01:10:18 +00008795 local_dh_2048 = NULL;
8796 }
8797 if (local_dh_4096) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008798 HASSL_DH_free(local_dh_4096);
Grant Zhang872f9c22017-01-21 01:10:18 +00008799 local_dh_4096 = NULL;
8800 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02008801 if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008802 HASSL_DH_free(global_dh);
Remi Gacogne47783ef2015-05-29 15:53:22 +02008803 global_dh = NULL;
8804 }
Grant Zhang872f9c22017-01-21 01:10:18 +00008805}
8806#endif
8807
Grant Zhang872f9c22017-01-21 01:10:18 +00008808static void __ssl_sock_deinit(void)
8809{
8810#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02008811 if (ssl_ctx_lru_tree) {
8812 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01008813 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02008814 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02008815#endif
8816
Willy Tarreau5db847a2019-05-09 14:13:35 +02008817#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02008818 ERR_remove_state(0);
8819 ERR_free_strings();
8820
8821 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08008822#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02008823
Willy Tarreau5db847a2019-05-09 14:13:35 +02008824#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02008825 CRYPTO_cleanup_all_ex_data();
8826#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02008827 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02008828}
Willy Tarreau79367f92022-04-25 19:18:24 +02008829REGISTER_POST_DEINIT(__ssl_sock_deinit);
Remi Gacogned3a23c32015-05-28 16:39:47 +02008830
William Dauchyf6370442020-11-14 19:25:33 +01008831
Emeric Brun46591952012-05-18 15:47:34 +02008832/*
8833 * Local variables:
8834 * c-indent-level: 8
8835 * c-basic-offset: 8
8836 * End:
8837 */