blob: db255fa9e1e136176e62706de053dac2ca829352 [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>
Frédéric Lécaille748ece62022-05-21 23:58:40 +020068#include <haproxy/quic_tp.h>
Willy Tarreau1e56f922020-06-04 23:20:13 +020069#include <haproxy/server.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020070#include <haproxy/shctx.h>
Willy Tarreau47d7f902020-06-04 14:25:47 +020071#include <haproxy/ssl_ckch.h>
Willy Tarreau52d88722020-06-04 14:29:23 +020072#include <haproxy/ssl_crtlist.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020073#include <haproxy/ssl_sock.h>
Willy Tarreaub2bd8652020-06-04 14:21:22 +020074#include <haproxy/ssl_utils.h>
Amaury Denoyelle9963fa72020-11-03 17:10:00 +010075#include <haproxy/stats.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020076#include <haproxy/stconn.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020077#include <haproxy/stream-t.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020078#include <haproxy/task.h>
Willy Tarreauc2f7c582020-06-02 18:15:32 +020079#include <haproxy/ticks.h>
Willy Tarreau92b4f132020-06-01 11:05:15 +020080#include <haproxy/time.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020081#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020082#include <haproxy/vars.h>
Frédéric Lécailleec216522020-11-23 14:33:30 +010083#include <haproxy/xprt_quic.h>
Tim Duesterhusd5fc8fc2021-09-11 17:51:13 +020084#include <haproxy/xxhash.h>
Remi Tricot-Le Breton2e7d1eb2022-01-11 10:11:10 +010085#include <haproxy/istbuf.h>
Emeric Brun46591952012-05-18 15:47:34 +020086
Emeric Brun46591952012-05-18 15:47:34 +020087
Willy Tarreau9356dac2019-05-10 09:22:53 +020088/* ***** READ THIS before adding code here! *****
89 *
90 * Due to API incompatibilities between multiple OpenSSL versions and their
91 * derivatives, it's often tempting to add macros to (re-)define certain
92 * symbols. Please do not do this here, and do it in common/openssl-compat.h
93 * exclusively so that the whole code consistently uses the same macros.
94 *
95 * Whenever possible if a macro is missing in certain versions, it's better
96 * to conditionally define it in openssl-compat.h than using lots of ifdefs.
97 */
98
Emeric Brunece0c332017-12-06 13:51:49 +010099int nb_engines = 0;
Emeric Brune1f38db2012-09-03 20:36:47 +0200100
William Lallemande0f3fd52020-02-25 14:53:06 +0100101static struct eb_root cert_issuer_tree = EB_ROOT; /* issuers tree from "issuers-chain-path" */
102
William Lallemand7fd8b452020-05-07 15:20:43 +0200103struct global_ssl global_ssl = {
Willy Tarreauef934602016-12-22 23:12:01 +0100104#ifdef LISTEN_DEFAULT_CIPHERS
105 .listen_default_ciphers = LISTEN_DEFAULT_CIPHERS,
106#endif
107#ifdef CONNECT_DEFAULT_CIPHERS
108 .connect_default_ciphers = CONNECT_DEFAULT_CIPHERS,
109#endif
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +0500110#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200111 .listen_default_ciphersuites = LISTEN_DEFAULT_CIPHERSUITES,
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200112 .connect_default_ciphersuites = CONNECT_DEFAULT_CIPHERSUITES,
113#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100114 .listen_default_ssloptions = BC_SSL_O_NONE,
115 .connect_default_ssloptions = SRV_SSL_O_NONE,
116
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +0200117 .listen_default_sslmethods.flags = MC_SSL_O_ALL,
118 .listen_default_sslmethods.min = CONF_TLSV_NONE,
119 .listen_default_sslmethods.max = CONF_TLSV_NONE,
120 .connect_default_sslmethods.flags = MC_SSL_O_ALL,
121 .connect_default_sslmethods.min = CONF_TLSV_NONE,
122 .connect_default_sslmethods.max = CONF_TLSV_NONE,
123
Willy Tarreauef934602016-12-22 23:12:01 +0100124#ifdef DEFAULT_SSL_MAX_RECORD
125 .max_record = DEFAULT_SSL_MAX_RECORD,
126#endif
Thomas Prückl10243932022-04-27 13:04:54 +0200127 .hard_max_record = 0,
Willy Tarreauef934602016-12-22 23:12:01 +0100128 .default_dh_param = SSL_DEFAULT_DH_PARAM,
129 .ctx_cache = DEFAULT_SSL_CTX_CACHE,
Marcin Deranek310a2602021-07-13 19:04:24 +0200130 .capture_buffer_size = 0,
William Lallemand3af48e72020-02-03 17:15:52 +0100131 .extra_files = SSL_GF_ALL,
William Lallemand8e8581e2020-10-20 17:36:46 +0200132 .extra_files_noext = 0,
William Lallemand722180a2021-06-09 16:46:12 +0200133#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200134 .keylog = 0
135#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100136};
137
Olivier Houcharda8955d52019-04-07 22:00:38 +0200138static BIO_METHOD *ha_meth;
139
Olivier Houchard66ab4982019-02-26 18:37:15 +0100140DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx_pool", sizeof(struct ssl_sock_ctx));
141
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100142DECLARE_STATIC_POOL(ssl_sock_client_sni_pool, "ssl_sock_client_sni_pool", TLSEXT_MAXLEN_host_name + 1);
143
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100144/* ssl stats module */
145enum {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100146 SSL_ST_SESS,
147 SSL_ST_REUSED_SESS,
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100148 SSL_ST_FAILED_HANDSHAKE,
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100149
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100150 SSL_ST_STATS_COUNT /* must be the last member of the enum */
151};
152
153static struct name_desc ssl_stats[] = {
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100154 [SSL_ST_SESS] = { .name = "ssl_sess",
155 .desc = "Total number of ssl sessions established" },
156 [SSL_ST_REUSED_SESS] = { .name = "ssl_reused_sess",
157 .desc = "Total number of ssl sessions reused" },
158 [SSL_ST_FAILED_HANDSHAKE] = { .name = "ssl_failed_handshake",
159 .desc = "Total number of failed handshake" },
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100160};
161
162static struct ssl_counters {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100163 long long sess;
164 long long reused_sess;
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100165 long long failed_handshake;
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100166} ssl_counters;
167
168static void ssl_fill_stats(void *data, struct field *stats)
169{
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100170 struct ssl_counters *counters = data;
171
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100172 stats[SSL_ST_SESS] = mkf_u64(FN_COUNTER, counters->sess);
173 stats[SSL_ST_REUSED_SESS] = mkf_u64(FN_COUNTER, counters->reused_sess);
174 stats[SSL_ST_FAILED_HANDSHAKE] = mkf_u64(FN_COUNTER, counters->failed_handshake);
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100175}
176
177static struct stats_module ssl_stats_module = {
178 .name = "ssl",
179 .fill_stats = ssl_fill_stats,
180 .stats = ssl_stats,
181 .stats_count = SSL_ST_STATS_COUNT,
182 .counters = &ssl_counters,
183 .counters_size = sizeof(ssl_counters),
184 .domain_flags = MK_STATS_PROXY_DOMAIN(STATS_PX_CAP_FE|STATS_PX_CAP_LI|STATS_PX_CAP_BE|STATS_PX_CAP_SRV),
185 .clearable = 1,
186};
187
188INITCALL1(STG_REGISTER, stats_register_module, &ssl_stats_module);
189
Willy Tarreaua9380522022-05-05 08:50:17 +0200190/* CLI context for "show tls-keys" */
191struct show_keys_ctx {
192 struct tls_keys_ref *next_ref; /* next reference to be dumped */
193 int names_only; /* non-zero = only show file names */
194 int next_index; /* next index to be dumped */
Willy Tarreaubd338642022-05-05 08:59:17 +0200195 int dump_entries; /* dump entries also */
Willy Tarreau9c5a38c2022-05-05 09:03:44 +0200196 enum {
197 SHOW_KEYS_INIT = 0,
198 SHOW_KEYS_LIST,
199 SHOW_KEYS_DONE,
200 } state; /* phase of the current dump */
Willy Tarreaua9380522022-05-05 08:50:17 +0200201};
202
Willy Tarreau691d5032021-01-20 14:55:01 +0100203/* ssl_sock_io_cb is exported to see it resolved in "show fd" */
Willy Tarreau144f84a2021-03-02 16:09:26 +0100204struct task *ssl_sock_io_cb(struct task *, void *, unsigned int);
Olivier Houchard000694c2019-05-23 14:45:12 +0200205static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
Olivier Houchardea8dd942019-05-20 14:02:16 +0200206
Olivier Houcharda8955d52019-04-07 22:00:38 +0200207/* Methods to implement OpenSSL BIO */
208static int ha_ssl_write(BIO *h, const char *buf, int num)
209{
210 struct buffer tmpbuf;
211 struct ssl_sock_ctx *ctx;
212 int ret;
213
214 ctx = BIO_get_data(h);
215 tmpbuf.size = num;
216 tmpbuf.area = (void *)(uintptr_t)buf;
217 tmpbuf.data = num;
218 tmpbuf.head = 0;
219 ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200220 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200221 BIO_set_retry_write(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200222 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200223 } else if (ret == 0)
224 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200225 return ret;
226}
227
228static int ha_ssl_gets(BIO *h, char *buf, int size)
229{
230
231 return 0;
232}
233
234static int ha_ssl_puts(BIO *h, const char *str)
235{
236
237 return ha_ssl_write(h, str, strlen(str));
238}
239
240static int ha_ssl_read(BIO *h, char *buf, int size)
241{
242 struct buffer tmpbuf;
243 struct ssl_sock_ctx *ctx;
244 int ret;
245
246 ctx = BIO_get_data(h);
247 tmpbuf.size = size;
248 tmpbuf.area = buf;
249 tmpbuf.data = 0;
250 tmpbuf.head = 0;
251 ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200252 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200253 BIO_set_retry_read(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200254 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200255 } else if (ret == 0)
256 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200257
258 return ret;
259}
260
261static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
262{
263 int ret = 0;
264 switch (cmd) {
265 case BIO_CTRL_DUP:
266 case BIO_CTRL_FLUSH:
267 ret = 1;
268 break;
269 }
270 return ret;
271}
272
273static int ha_ssl_new(BIO *h)
274{
275 BIO_set_init(h, 1);
276 BIO_set_data(h, NULL);
277 BIO_clear_flags(h, ~0);
278 return 1;
279}
280
281static int ha_ssl_free(BIO *data)
282{
283
284 return 1;
285}
286
287
Willy Tarreau5db847a2019-05-09 14:13:35 +0200288#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100289
Emeric Brun821bb9b2017-06-15 16:37:39 +0200290static HA_RWLOCK_T *ssl_rwlocks;
291
292
293unsigned long ssl_id_function(void)
294{
295 return (unsigned long)tid;
296}
297
298void ssl_locking_function(int mode, int n, const char * file, int line)
299{
300 if (mode & CRYPTO_LOCK) {
301 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100302 HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200303 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100304 HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200305 }
306 else {
307 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100308 HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200309 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100310 HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200311 }
312}
313
314static int ssl_locking_init(void)
315{
316 int i;
317
318 ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
319 if (!ssl_rwlocks)
320 return -1;
321
322 for (i = 0 ; i < CRYPTO_num_locks() ; i++)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100323 HA_RWLOCK_INIT(&ssl_rwlocks[i]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200324
325 CRYPTO_set_id_callback(ssl_id_function);
326 CRYPTO_set_locking_callback(ssl_locking_function);
327
328 return 0;
329}
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100330
Emeric Brun821bb9b2017-06-15 16:37:39 +0200331#endif
332
Willy Tarreauaf613e82020-06-05 08:40:51 +0200333__decl_thread(HA_SPINLOCK_T ckch_lock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200334
William Lallemandbc6ca7c2019-10-29 23:48:19 +0100335
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200336
337/* mimic what X509_STORE_load_locations do with store_ctx */
338static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
339{
Remi Tricot-Le Bretond75b99e2021-05-17 11:45:55 +0200340 X509_STORE *store = NULL;
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +0100341 struct cafile_entry *ca_e = ssl_store_get_cafile_entry(path, 0);
342 if (ca_e)
343 store = ca_e->ca_store;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200344 if (store_ctx && store) {
345 int i;
346 X509_OBJECT *obj;
347 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
348 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
349 obj = sk_X509_OBJECT_value(objs, i);
350 switch (X509_OBJECT_get_type(obj)) {
351 case X509_LU_X509:
352 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
353 break;
354 case X509_LU_CRL:
355 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
356 break;
357 default:
358 break;
359 }
360 }
361 return 1;
362 }
363 return 0;
364}
365
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500366/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200367static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
368{
369 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
370 return ssl_set_cert_crl_file(store_ctx, path);
371}
372
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200373/*
374 Extract CA_list from CA_file already in tree.
375 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
376 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
377*/
378static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
379{
380 struct ebmb_node *eb;
381 struct cafile_entry *ca_e;
382
383 eb = ebst_lookup(&cafile_tree, path);
384 if (!eb)
385 return NULL;
386 ca_e = ebmb_entry(eb, struct cafile_entry, node);
387
388 if (ca_e->ca_list == NULL) {
389 int i;
390 unsigned long key;
391 struct eb_root ca_name_tree = EB_ROOT;
392 struct eb64_node *node, *back;
393 struct {
394 struct eb64_node node;
395 X509_NAME *xname;
396 } *ca_name;
397 STACK_OF(X509_OBJECT) *objs;
398 STACK_OF(X509_NAME) *skn;
399 X509 *x;
400 X509_NAME *xn;
401
402 skn = sk_X509_NAME_new_null();
403 /* take x509 from cafile_tree */
404 objs = X509_STORE_get0_objects(ca_e->ca_store);
405 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
406 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
407 if (!x)
408 continue;
409 xn = X509_get_subject_name(x);
410 if (!xn)
411 continue;
412 /* Check for duplicates. */
413 key = X509_NAME_hash(xn);
414 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
415 node && ca_name == NULL;
416 node = eb64_next(node)) {
417 ca_name = container_of(node, typeof(*ca_name), node);
418 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
419 ca_name = NULL;
420 }
421 /* find a duplicate */
422 if (ca_name)
423 continue;
424 ca_name = calloc(1, sizeof *ca_name);
425 xn = X509_NAME_dup(xn);
426 if (!ca_name ||
427 !xn ||
428 !sk_X509_NAME_push(skn, xn)) {
429 free(ca_name);
430 X509_NAME_free(xn);
431 sk_X509_NAME_pop_free(skn, X509_NAME_free);
432 sk_X509_NAME_free(skn);
433 skn = NULL;
434 break;
435 }
436 ca_name->node.key = key;
437 ca_name->xname = xn;
438 eb64_insert(&ca_name_tree, &ca_name->node);
439 }
440 ca_e->ca_list = skn;
441 /* remove temporary ca_name tree */
442 node = eb64_first(&ca_name_tree);
443 while (node) {
444 ca_name = container_of(node, typeof(*ca_name), node);
445 back = eb64_next(node);
446 eb64_delete(node);
447 free(ca_name);
448 node = back;
449 }
450 }
451 return ca_e->ca_list;
452}
453
Willy Tarreauff882702021-04-10 17:23:00 +0200454struct pool_head *pool_head_ssl_capture __read_mostly = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200455int ssl_capture_ptr_index = -1;
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +0100456int ssl_app_data_index = -1;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +0100457#ifdef USE_QUIC
458int ssl_qc_app_data_index = -1;
459#endif /* USE_QUIC */
Willy Tarreauef934602016-12-22 23:12:01 +0100460
William Lallemand722180a2021-06-09 16:46:12 +0200461#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200462int ssl_keylog_index = -1;
Willy Tarreauff882702021-04-10 17:23:00 +0200463struct pool_head *pool_head_ssl_keylog __read_mostly = NULL;
464struct pool_head *pool_head_ssl_keylog_str __read_mostly = NULL;
William Lallemand7d42ef52020-07-06 11:41:30 +0200465#endif
466
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +0200467int ssl_client_crt_ref_index = -1;
468
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100469/* Used to store the client's SNI in case of ClientHello callback error */
470int ssl_client_sni_index = -1;
471
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200472#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
473struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
474#endif
475
William Lallemandd7bfbe22022-04-11 18:41:24 +0200476#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200477unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000478struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
479struct ssl_engine_list {
480 struct list list;
481 ENGINE *e;
482};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200483#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000484
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +0200485#ifdef HAVE_SSL_PROVIDERS
486struct list openssl_providers = LIST_HEAD_INIT(openssl_providers);
487struct ssl_provider_list {
488 struct list list;
489 OSSL_PROVIDER *provider;
490};
491#endif
492
Remi Gacogne8de54152014-07-15 11:36:40 +0200493#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200494static int ssl_dh_ptr_index = -1;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +0100495static HASSL_DH *global_dh = NULL;
496static HASSL_DH *local_dh_1024 = NULL;
497static HASSL_DH *local_dh_2048 = NULL;
498static HASSL_DH *local_dh_4096 = NULL;
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100499#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +0100500static DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100501#else
502static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey);
503#endif
Remi Gacogne8de54152014-07-15 11:36:40 +0200504#endif /* OPENSSL_NO_DH */
505
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100506#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200507/* X509V3 Extensions that will be added on generated certificates */
508#define X509V3_EXT_SIZE 5
509static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
510 "basicConstraints",
511 "nsComment",
512 "subjectKeyIdentifier",
513 "authorityKeyIdentifier",
514 "keyUsage",
515};
516static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
517 "CA:FALSE",
518 "\"OpenSSL Generated Certificate\"",
519 "hash",
520 "keyid,issuer:always",
521 "nonRepudiation,digitalSignature,keyEncipherment"
522};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200523/* LRU cache to store generated certificate */
524static struct lru64_head *ssl_ctx_lru_tree = NULL;
525static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200526static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100527__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200528
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200529#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
530
yanbzhube2774d2015-12-10 15:07:30 -0500531/* The order here matters for picking a default context,
532 * keep the most common keytype at the bottom of the list
533 */
534const char *SSL_SOCK_KEYTYPE_NAMES[] = {
535 "dsa",
536 "ecdsa",
537 "rsa"
538};
yanbzhube2774d2015-12-10 15:07:30 -0500539
William Lallemandc3cd35f2017-11-28 11:04:43 +0100540static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100541static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
542
Dragan Dosen9ac98092020-05-11 15:51:45 +0200543/* Dedicated callback functions for heartbeat and clienthello.
544 */
545#ifdef TLS1_RT_HEARTBEAT
546static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
547 int content_type, const void *buf, size_t len,
548 SSL *ssl);
549#endif
550static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
551 int content_type, const void *buf, size_t len,
552 SSL *ssl);
553
William Lallemand722180a2021-06-09 16:46:12 +0200554#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200555static void ssl_init_keylog(struct connection *conn, int write_p, int version,
556 int content_type, const void *buf, size_t len,
557 SSL *ssl);
558#endif
559
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200560/* List head of all registered SSL/TLS protocol message callbacks. */
561struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
562
563/* Registers the function <func> in order to be called on SSL/TLS protocol
564 * message processing. It will return 0 if the function <func> is not set
565 * or if it fails to allocate memory.
566 */
567int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
568{
569 struct ssl_sock_msg_callback *cbk;
570
571 if (!func)
572 return 0;
573
574 cbk = calloc(1, sizeof(*cbk));
575 if (!cbk) {
576 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
577 return 0;
578 }
579
580 cbk->func = func;
581
Willy Tarreau2b718102021-04-21 07:32:39 +0200582 LIST_APPEND(&ssl_sock_msg_callbacks, &cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200583
584 return 1;
585}
586
Dragan Dosen9ac98092020-05-11 15:51:45 +0200587/* Used to register dedicated SSL/TLS protocol message callbacks.
588 */
589static int ssl_sock_register_msg_callbacks(void)
590{
591#ifdef TLS1_RT_HEARTBEAT
592 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
593 return ERR_ABORT;
594#endif
Marcin Deranek310a2602021-07-13 19:04:24 +0200595 if (global_ssl.capture_buffer_size > 0) {
Dragan Dosen9ac98092020-05-11 15:51:45 +0200596 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
597 return ERR_ABORT;
598 }
William Lallemand722180a2021-06-09 16:46:12 +0200599#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200600 if (global_ssl.keylog > 0) {
601 if (!ssl_sock_register_msg_callback(ssl_init_keylog))
602 return ERR_ABORT;
603 }
604#endif
605
Christopher Fauletfc633b62020-11-06 15:24:23 +0100606 return ERR_NONE;
Dragan Dosen9ac98092020-05-11 15:51:45 +0200607}
608
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200609/* Used to free all SSL/TLS protocol message callbacks that were
610 * registered by using ssl_sock_register_msg_callback().
611 */
612static void ssl_sock_unregister_msg_callbacks(void)
613{
614 struct ssl_sock_msg_callback *cbk, *cbkback;
615
616 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +0200617 LIST_DELETE(&cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200618 free(cbk);
619 }
620}
621
Willy Tarreaude827952022-04-11 10:43:28 +0200622static struct ssl_sock_ctx *ssl_sock_get_ctx(struct connection *conn)
623{
624 if (!conn || conn->xprt != xprt_get(XPRT_SSL) || !conn->xprt_ctx)
625 return NULL;
626
627 return (struct ssl_sock_ctx *)conn->xprt_ctx;
628}
629
Dragan Doseneb607fe2020-05-11 17:17:06 +0200630SSL *ssl_sock_get_ssl_object(struct connection *conn)
631{
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200632 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dragan Doseneb607fe2020-05-11 17:17:06 +0200633
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200634 return ctx ? ctx->ssl : NULL;
Dragan Doseneb607fe2020-05-11 17:17:06 +0200635}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100636/*
637 * This function gives the detail of the SSL error. It is used only
638 * if the debug mode and the verbose mode are activated. It dump all
639 * the SSL error until the stack was empty.
640 */
641static forceinline void ssl_sock_dump_errors(struct connection *conn)
642{
643 unsigned long ret;
644
645 if (unlikely(global.mode & MODE_DEBUG)) {
646 while(1) {
Remi Tricot-Le Breton1effd9a2022-02-11 12:04:44 +0100647 const char *func = NULL;
648 ERR_peek_error_func(&func);
649
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100650 ret = ERR_get_error();
651 if (ret == 0)
652 return;
Willy Tarreau566cebc2021-03-02 19:32:39 +0100653 fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
Willy Tarreau0e9c2642022-04-11 18:01:28 +0200654 conn_fd(conn), ret,
Remi Tricot-Le Breton1effd9a2022-02-11 12:04:44 +0100655 func, ERR_reason_error_string(ret));
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100656 }
657 }
658}
659
yanbzhube2774d2015-12-10 15:07:30 -0500660
William Lallemandd7bfbe22022-04-11 18:41:24 +0200661#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200662int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000663{
664 int err_code = ERR_ABORT;
665 ENGINE *engine;
666 struct ssl_engine_list *el;
667
668 /* grab the structural reference to the engine */
669 engine = ENGINE_by_id(engine_id);
670 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100671 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000672 goto fail_get;
673 }
674
675 if (!ENGINE_init(engine)) {
676 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100677 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000678 goto fail_init;
679 }
680
681 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100682 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000683 goto fail_set_method;
684 }
685
686 el = calloc(1, sizeof(*el));
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200687 if (!el)
688 goto fail_alloc;
Grant Zhang872f9c22017-01-21 01:10:18 +0000689 el->e = engine;
Willy Tarreau2b718102021-04-21 07:32:39 +0200690 LIST_INSERT(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100691 nb_engines++;
692 if (global_ssl.async)
693 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000694 return 0;
695
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200696fail_alloc:
Grant Zhang872f9c22017-01-21 01:10:18 +0000697fail_set_method:
698 /* release the functional reference from ENGINE_init() */
699 ENGINE_finish(engine);
700
701fail_init:
702 /* release the structural reference from ENGINE_by_id() */
703 ENGINE_free(engine);
704
705fail_get:
706 return err_code;
707}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200708#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000709
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +0200710#ifdef HAVE_SSL_PROVIDERS
711int ssl_init_provider(const char *provider_name)
712{
713 int err_code = ERR_ABORT;
714 struct ssl_provider_list *prov = NULL;
715
716 prov = calloc(1, sizeof(*prov));
717 if (!prov) {
718 ha_alert("ssl-provider %s: memory allocation failure\n", provider_name);
719 goto error;
720 }
721
722 if ((prov->provider = OSSL_PROVIDER_load(NULL, provider_name)) == NULL) {
723 ha_alert("ssl-provider %s: unknown provider\n", provider_name);
724 goto error;
725 }
726
727 LIST_INSERT(&openssl_providers, &prov->list);
728
729 return 0;
730
731error:
732 ha_free(&prov);
733 return err_code;
734}
735#endif /* HAVE_SSL_PROVIDERS */
736
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +0500737#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +0200738/*
739 * openssl async fd handler
740 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200741void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000742{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200743 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000744
Emeric Brun3854e012017-05-17 20:42:48 +0200745 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000746 * to poll this fd until it is requested
747 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000748 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000749 fd_cant_recv(fd);
750
751 /* crypto engine is available, let's notify the associated
752 * connection that it can pursue its processing.
753 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200754 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000755}
756
Emeric Brun3854e012017-05-17 20:42:48 +0200757/*
758 * openssl async delayed SSL_free handler
759 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200760void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000761{
762 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200763 OSSL_ASYNC_FD all_fd[32];
764 size_t num_all_fds = 0;
765 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000766
Emeric Brun3854e012017-05-17 20:42:48 +0200767 /* We suppose that the async job for a same SSL *
768 * are serialized. So if we are awake it is
769 * because the running job has just finished
770 * and we can remove all async fds safely
771 */
772 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
773 if (num_all_fds > 32) {
774 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
775 return;
776 }
777
778 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
779 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200780 fd_stop_both(all_fd[i]);
Emeric Brun3854e012017-05-17 20:42:48 +0200781
782 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000783 SSL_free(ssl);
Willy Tarreau82531f62021-10-06 12:15:18 +0200784 _HA_ATOMIC_DEC(&global.sslconns);
Willy Tarreau4781b152021-04-06 13:53:36 +0200785 _HA_ATOMIC_DEC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000786}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000787/*
Emeric Brun3854e012017-05-17 20:42:48 +0200788 * function used to manage a returned SSL_ERROR_WANT_ASYNC
789 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000790 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200791static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000792{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100793 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200794 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200795 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000796 size_t num_add_fds = 0;
797 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200798 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000799
800 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
801 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200802 if (num_add_fds > 32 || num_del_fds > 32) {
803 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 +0000804 return;
805 }
806
Emeric Brun3854e012017-05-17 20:42:48 +0200807 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000808
Emeric Brun3854e012017-05-17 20:42:48 +0200809 /* We remove unused fds from the fdtab */
810 for (i=0 ; i < num_del_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200811 fd_stop_both(del_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000812
Emeric Brun3854e012017-05-17 20:42:48 +0200813 /* We add new fds to the fdtab */
814 for (i=0 ; i < num_add_fds ; i++) {
Olivier Houchardea8dd942019-05-20 14:02:16 +0200815 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000816 }
817
Emeric Brun3854e012017-05-17 20:42:48 +0200818 num_add_fds = 0;
819 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
820 if (num_add_fds > 32) {
821 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
822 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000823 }
Emeric Brun3854e012017-05-17 20:42:48 +0200824
825 /* We activate the polling for all known async fds */
826 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000827 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200828 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000829 /* To ensure that the fd cache won't be used
830 * We'll prefer to catch a real RD event
831 * because handling an EAGAIN on this fd will
832 * result in a context switch and also
833 * some engines uses a fd in blocking mode.
834 */
835 fd_cant_recv(add_fd[i]);
836 }
Emeric Brun3854e012017-05-17 20:42:48 +0200837
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000838}
839#endif
840
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200841#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 +0200842/*
843 * This function returns the number of seconds elapsed
844 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
845 * date presented un ASN1_GENERALIZEDTIME.
846 *
847 * In parsing error case, it returns -1.
848 */
849static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
850{
851 long epoch;
852 char *p, *end;
853 const unsigned short month_offset[12] = {
854 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
855 };
Remi Tricot-Le Bretona3a0cce2021-06-09 17:16:18 +0200856 unsigned long year, month;
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200857
858 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
859
860 p = (char *)d->data;
861 end = p + d->length;
862
863 if (end - p < 4) return -1;
864 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
865 p += 4;
866 if (end - p < 2) return -1;
867 month = 10 * (p[0] - '0') + p[1] - '0';
868 if (month < 1 || month > 12) return -1;
869 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
870 We consider leap years and the current month (<marsh or not) */
871 epoch = ( ((year - 1970) * 365)
872 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
873 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
874 + month_offset[month-1]
875 ) * 24 * 60 * 60;
876 p += 2;
877 if (end - p < 2) return -1;
878 /* Add the number of seconds of completed days of current month */
879 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
880 p += 2;
881 if (end - p < 2) return -1;
882 /* Add the completed hours of the current day */
883 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
884 p += 2;
885 if (end - p < 2) return -1;
886 /* Add the completed minutes of the current hour */
887 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
888 p += 2;
889 if (p == end) return -1;
890 /* Test if there is available seconds */
891 if (p[0] < '0' || p[0] > '9')
892 goto nosec;
893 if (end - p < 2) return -1;
894 /* Add the seconds of the current minute */
895 epoch += 10 * (p[0] - '0') + p[1] - '0';
896 p += 2;
897 if (p == end) return -1;
898 /* Ignore seconds float part if present */
899 if (p[0] == '.') {
900 do {
901 if (++p == end) return -1;
902 } while (p[0] >= '0' && p[0] <= '9');
903 }
904
905nosec:
906 if (p[0] == 'Z') {
907 if (end - p != 1) return -1;
908 return epoch;
909 }
910 else if (p[0] == '+') {
911 if (end - p != 5) return -1;
912 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700913 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 +0200914 }
915 else if (p[0] == '-') {
916 if (end - p != 5) return -1;
917 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700918 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 +0200919 }
920
921 return -1;
922}
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200923#endif
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200924
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200925#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
William Lallemand104a7a62019-10-14 14:14:59 +0200926/*
927 * struct alignment works here such that the key.key is the same as key_data
928 * Do not change the placement of key_data
929 */
930struct certificate_ocsp {
931 struct ebmb_node key;
932 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
Remi Tricot-Le Breton5aa1dce2021-06-10 13:51:12 +0200933 unsigned int key_length;
William Lallemand104a7a62019-10-14 14:14:59 +0200934 struct buffer response;
William Lallemand76b4a122020-08-04 17:41:39 +0200935 int refcount;
William Lallemand104a7a62019-10-14 14:14:59 +0200936 long expire;
937};
938
939struct ocsp_cbk_arg {
940 int is_single;
941 int single_kt;
942 union {
943 struct certificate_ocsp *s_ocsp;
944 /*
945 * m_ocsp will have multiple entries dependent on key type
946 * Entry 0 - DSA
947 * Entry 1 - ECDSA
948 * Entry 2 - RSA
949 */
950 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
951 };
952};
953
Emeric Brun1d3865b2014-06-20 15:37:32 +0200954static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200955
956/* This function starts to check if the OCSP response (in DER format) contained
957 * in chunk 'ocsp_response' is valid (else exits on error).
958 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
959 * contained in the OCSP Response and exits on error if no match.
960 * If it's a valid OCSP Response:
961 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
962 * pointed by 'ocsp'.
963 * If 'ocsp' is NULL, the function looks up into the OCSP response's
964 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
965 * from the response) and exits on error if not found. Finally, If an OCSP response is
966 * already present in the container, it will be overwritten.
967 *
968 * Note: OCSP response containing more than one OCSP Single response is not
969 * considered valid.
970 *
971 * Returns 0 on success, 1 in error case.
972 */
Willy Tarreau83061a82018-07-13 11:56:34 +0200973static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
974 struct certificate_ocsp *ocsp,
975 OCSP_CERTID *cid, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +0200976{
977 OCSP_RESPONSE *resp;
978 OCSP_BASICRESP *bs = NULL;
979 OCSP_SINGLERESP *sr;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200980 OCSP_CERTID *id;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200981 unsigned char *p = (unsigned char *) ocsp_response->area;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200982 int rc , count_sr;
Emeric Brun13a6b482014-06-20 15:44:34 +0200983 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200984 int reason;
985 int ret = 1;
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200986#ifdef HAVE_ASN1_TIME_TO_TM
987 struct tm nextupd_tm = {0};
988#endif
Emeric Brun4147b2e2014-06-16 18:36:30 +0200989
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200990 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
991 ocsp_response->data);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200992 if (!resp) {
993 memprintf(err, "Unable to parse OCSP response");
994 goto out;
995 }
996
997 rc = OCSP_response_status(resp);
998 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
999 memprintf(err, "OCSP response status not successful");
1000 goto out;
1001 }
1002
1003 bs = OCSP_response_get1_basic(resp);
1004 if (!bs) {
1005 memprintf(err, "Failed to get basic response from OCSP Response");
1006 goto out;
1007 }
1008
1009 count_sr = OCSP_resp_count(bs);
1010 if (count_sr > 1) {
1011 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
1012 goto out;
1013 }
1014
1015 sr = OCSP_resp_get0(bs, 0);
1016 if (!sr) {
1017 memprintf(err, "Failed to get OCSP single response");
1018 goto out;
1019 }
1020
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001021 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
1022
Emeric Brun4147b2e2014-06-16 18:36:30 +02001023 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
Emmanuel Hocdetef607052017-10-24 14:57:16 +02001024 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
Emmanuel Hocdet872085c2017-10-10 15:18:52 +02001025 memprintf(err, "OCSP single response: certificate status is unknown");
Emeric Brun4147b2e2014-06-16 18:36:30 +02001026 goto out;
1027 }
1028
Emeric Brun13a6b482014-06-20 15:44:34 +02001029 if (!nextupd) {
1030 memprintf(err, "OCSP single response: missing nextupdate");
1031 goto out;
1032 }
1033
Emeric Brunc8b27b62014-06-19 14:16:17 +02001034 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001035 if (!rc) {
1036 memprintf(err, "OCSP single response: no longer valid.");
1037 goto out;
1038 }
1039
1040 if (cid) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001041 if (OCSP_id_cmp(id, cid)) {
Emeric Brun4147b2e2014-06-16 18:36:30 +02001042 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
1043 goto out;
1044 }
1045 }
1046
1047 if (!ocsp) {
1048 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
1049 unsigned char *p;
1050
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001051 rc = i2d_OCSP_CERTID(id, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001052 if (!rc) {
1053 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
1054 goto out;
1055 }
1056
1057 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
1058 memprintf(err, "OCSP single response: Certificate ID too long");
1059 goto out;
1060 }
1061
1062 p = key;
1063 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001064 i2d_OCSP_CERTID(id, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001065 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
1066 if (!ocsp) {
1067 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
1068 goto out;
1069 }
1070 }
1071
1072 /* According to comments on "chunk_dup", the
1073 previous chunk buffer will be freed */
1074 if (!chunk_dup(&ocsp->response, ocsp_response)) {
1075 memprintf(err, "OCSP response: Memory allocation error");
1076 goto out;
1077 }
1078
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +02001079#ifdef HAVE_ASN1_TIME_TO_TM
1080 if (ASN1_TIME_to_tm(nextupd, &nextupd_tm) == 0) {
1081 memprintf(err, "OCSP single response: Invalid \"Next Update\" time");
1082 goto out;
1083 }
1084 ocsp->expire = my_timegm(&nextupd_tm) - OCSP_MAX_RESPONSE_TIME_SKEW;
1085#else
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001086 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
Remi Tricot-Le Bretona3a0cce2021-06-09 17:16:18 +02001087 if (ocsp->expire < 0) {
1088 memprintf(err, "OCSP single response: Invalid \"Next Update\" time");
1089 goto out;
1090 }
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +02001091#endif
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001092
Emeric Brun4147b2e2014-06-16 18:36:30 +02001093 ret = 0;
1094out:
Janusz Dziemidowicz8d710492017-03-08 16:59:41 +01001095 ERR_clear_error();
1096
Emeric Brun4147b2e2014-06-16 18:36:30 +02001097 if (bs)
1098 OCSP_BASICRESP_free(bs);
1099
1100 if (resp)
1101 OCSP_RESPONSE_free(resp);
1102
1103 return ret;
1104}
1105/*
1106 * External function use to update the OCSP response in the OCSP response's
1107 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
1108 * to update in DER format.
1109 *
1110 * Returns 0 on success, 1 in error case.
1111 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001112int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001113{
1114 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
1115}
1116
William Lallemand4a660132019-10-14 14:51:41 +02001117#endif
1118
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001119
1120/*
1121 * Initialize an HMAC context <hctx> using the <key> and <md> parameters.
1122 * Returns -1 in case of error, 1 otherwise.
1123 */
1124static int ssl_hmac_init(MAC_CTX *hctx, unsigned char *key, int key_len, const EVP_MD *md)
1125{
1126#ifdef HAVE_OSSL_PARAM
1127 OSSL_PARAM params[3];
1128
1129 params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, key, key_len);
1130 params[1] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, (char*)EVP_MD_name(md), 0);
1131 params[2] = OSSL_PARAM_construct_end();
1132 if (EVP_MAC_CTX_set_params(hctx, params) == 0)
1133 return -1; /* error in mac initialisation */
1134
1135#else
1136 HMAC_Init_ex(hctx, key, key_len, md, NULL);
1137#endif
1138 return 1;
1139}
1140
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001141#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +01001142
1143static 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 +01001144{
Christopher Faulet16f45c82018-02-16 11:23:49 +01001145 struct tls_keys_ref *ref;
Emeric Brun9e754772019-01-10 17:51:55 +01001146 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001147 struct connection *conn;
1148 int head;
1149 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001150 int ret = -1; /* error by default */
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001151
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001152 conn = SSL_get_ex_data(s, ssl_app_data_index);
Willy Tarreau07d94e42018-09-20 10:57:52 +02001153 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001154 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1155
1156 keys = ref->tlskeys;
1157 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001158
1159 if (enc) {
1160 memcpy(key_name, keys[head].name, 16);
1161
1162 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +01001163 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001164
Emeric Brun9e754772019-01-10 17:51:55 +01001165 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001166
Emeric Brun9e754772019-01-10 17:51:55 +01001167 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
1168 goto end;
1169
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001170 if (ssl_hmac_init(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
1171 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +01001172 ret = 1;
1173 }
1174 else if (ref->key_size_bits == 256 ) {
1175
1176 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
1177 goto end;
1178
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001179 if (ssl_hmac_init(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
1180 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +01001181 ret = 1;
1182 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001183 } else {
1184 for (i = 0; i < TLS_TICKETS_NO; i++) {
1185 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
1186 goto found;
1187 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01001188 ret = 0;
1189 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001190
Christopher Faulet16f45c82018-02-16 11:23:49 +01001191 found:
Emeric Brun9e754772019-01-10 17:51:55 +01001192 if (ref->key_size_bits == 128) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001193 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
1194 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +01001195 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
1196 goto end;
1197 /* 2 for key renewal, 1 if current key is still valid */
1198 ret = i ? 2 : 1;
1199 }
1200 else if (ref->key_size_bits == 256) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001201 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
1202 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +01001203 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
1204 goto end;
1205 /* 2 for key renewal, 1 if current key is still valid */
1206 ret = i ? 2 : 1;
1207 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001208 }
Emeric Brun9e754772019-01-10 17:51:55 +01001209
Christopher Faulet16f45c82018-02-16 11:23:49 +01001210 end:
1211 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1212 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001213}
1214
1215struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
1216{
1217 struct tls_keys_ref *ref;
1218
1219 list_for_each_entry(ref, &tlskeys_reference, list)
1220 if (ref->filename && strcmp(filename, ref->filename) == 0)
1221 return ref;
1222 return NULL;
1223}
1224
1225struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1226{
1227 struct tls_keys_ref *ref;
1228
1229 list_for_each_entry(ref, &tlskeys_reference, list)
1230 if (ref->unique_id == unique_id)
1231 return ref;
1232 return NULL;
1233}
1234
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001235/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001236 * match existing ones, this function returns -1
1237 * else it returns 0 on success.
1238 */
1239int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001240 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001241{
Emeric Brun9e754772019-01-10 17:51:55 +01001242 if (ref->key_size_bits == 128) {
1243 if (tlskey->data != sizeof(struct tls_sess_key_128))
1244 return -1;
1245 }
1246 else if (ref->key_size_bits == 256) {
1247 if (tlskey->data != sizeof(struct tls_sess_key_256))
1248 return -1;
1249 }
1250 else
1251 return -1;
1252
Christopher Faulet16f45c82018-02-16 11:23:49 +01001253 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001254 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1255 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001256 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1257 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001258
1259 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001260}
1261
Willy Tarreau83061a82018-07-13 11:56:34 +02001262int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001263{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001264 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1265
1266 if(!ref) {
1267 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1268 return 1;
1269 }
Emeric Brun9e754772019-01-10 17:51:55 +01001270 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1271 memprintf(err, "Invalid key size");
1272 return 1;
1273 }
1274
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001275 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001276}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001277
1278/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001279 * automatic ids. It's called just after the basic checks. It returns
1280 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001281 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001282static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001283{
1284 int i = 0;
1285 struct tls_keys_ref *ref, *ref2, *ref3;
1286 struct list tkr = LIST_HEAD_INIT(tkr);
1287
1288 list_for_each_entry(ref, &tlskeys_reference, list) {
1289 if (ref->unique_id == -1) {
1290 /* Look for the first free id. */
1291 while (1) {
1292 list_for_each_entry(ref2, &tlskeys_reference, list) {
1293 if (ref2->unique_id == i) {
1294 i++;
1295 break;
1296 }
1297 }
1298 if (&ref2->list == &tlskeys_reference)
1299 break;
1300 }
1301
1302 /* Uses the unique id and increment it for the next entry. */
1303 ref->unique_id = i;
1304 i++;
1305 }
1306 }
1307
1308 /* This sort the reference list by id. */
1309 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001310 LIST_DELETE(&ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001311 list_for_each_entry(ref3, &tkr, list) {
1312 if (ref->unique_id < ref3->unique_id) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001313 LIST_APPEND(&ref3->list, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001314 break;
1315 }
1316 }
1317 if (&ref3->list == &tkr)
Willy Tarreau2b718102021-04-21 07:32:39 +02001318 LIST_APPEND(&tkr, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001319 }
1320
1321 /* swap root */
Willy Tarreau2b718102021-04-21 07:32:39 +02001322 LIST_INSERT(&tkr, &tlskeys_reference);
1323 LIST_DELETE(&tkr);
Christopher Fauletfc633b62020-11-06 15:24:23 +01001324 return ERR_NONE;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001325}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001326#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1327
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001328#ifndef OPENSSL_NO_OCSP
William Lallemand76b4a122020-08-04 17:41:39 +02001329int ocsp_ex_index = -1;
1330
yanbzhube2774d2015-12-10 15:07:30 -05001331int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1332{
1333 switch (evp_keytype) {
1334 case EVP_PKEY_RSA:
1335 return 2;
1336 case EVP_PKEY_DSA:
1337 return 0;
1338 case EVP_PKEY_EC:
1339 return 1;
1340 }
1341
1342 return -1;
1343}
1344
Emeric Brun4147b2e2014-06-16 18:36:30 +02001345/*
1346 * Callback used to set OCSP status extension content in server hello.
1347 */
1348int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1349{
yanbzhube2774d2015-12-10 15:07:30 -05001350 struct certificate_ocsp *ocsp;
1351 struct ocsp_cbk_arg *ocsp_arg;
1352 char *ssl_buf;
William Lallemand76b4a122020-08-04 17:41:39 +02001353 SSL_CTX *ctx;
yanbzhube2774d2015-12-10 15:07:30 -05001354 EVP_PKEY *ssl_pkey;
1355 int key_type;
1356 int index;
1357
William Lallemand76b4a122020-08-04 17:41:39 +02001358 ctx = SSL_get_SSL_CTX(ssl);
1359 if (!ctx)
1360 return SSL_TLSEXT_ERR_NOACK;
1361
1362 ocsp_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
1363 if (!ocsp_arg)
1364 return SSL_TLSEXT_ERR_NOACK;
yanbzhube2774d2015-12-10 15:07:30 -05001365
1366 ssl_pkey = SSL_get_privatekey(ssl);
1367 if (!ssl_pkey)
1368 return SSL_TLSEXT_ERR_NOACK;
1369
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001370 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001371
1372 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1373 ocsp = ocsp_arg->s_ocsp;
1374 else {
1375 /* For multiple certs per context, we have to find the correct OCSP response based on
1376 * the certificate type
1377 */
1378 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1379
1380 if (index < 0)
1381 return SSL_TLSEXT_ERR_NOACK;
1382
1383 ocsp = ocsp_arg->m_ocsp[index];
1384
1385 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001386
1387 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001388 !ocsp->response.area ||
1389 !ocsp->response.data ||
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001390 (ocsp->expire < now.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001391 return SSL_TLSEXT_ERR_NOACK;
1392
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001393 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001394 if (!ssl_buf)
1395 return SSL_TLSEXT_ERR_NOACK;
1396
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001397 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
1398 SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001399
1400 return SSL_TLSEXT_ERR_OK;
1401}
1402
William Lallemand4a660132019-10-14 14:51:41 +02001403#endif
1404
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001405#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
William Lallemand76b4a122020-08-04 17:41:39 +02001406
1407
1408/*
1409 * Decrease the refcount of the struct ocsp_response and frees it if it's not
1410 * used anymore. Also removes it from the tree if free'd.
1411 */
1412static void ssl_sock_free_ocsp(struct certificate_ocsp *ocsp)
1413{
1414 if (!ocsp)
1415 return;
1416
1417 ocsp->refcount--;
1418 if (ocsp->refcount <= 0) {
1419 ebmb_delete(&ocsp->key);
1420 chunk_destroy(&ocsp->response);
1421 free(ocsp);
1422 }
1423}
1424
1425
Emeric Brun4147b2e2014-06-16 18:36:30 +02001426/*
1427 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001428 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1429 * status extension, the issuer's certificate is mandatory. It should be
1430 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001431 *
William Lallemand246c0242019-10-11 08:59:13 +02001432 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1433 * OCSP response. If file is empty or content is not a valid OCSP response,
1434 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1435 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001436 *
1437 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001438 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001439 */
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001440static int ssl_sock_load_ocsp(SSL_CTX *ctx, const struct cert_key_and_chain *ckch, STACK_OF(X509) *chain)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001441{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001442 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001443 OCSP_CERTID *cid = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001444 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001445 struct certificate_ocsp *ocsp = NULL, *iocsp;
1446 char *warn = NULL;
1447 unsigned char *p;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001448 void (*callback) (void);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001449
Emeric Brun4147b2e2014-06-16 18:36:30 +02001450
William Lallemand246c0242019-10-11 08:59:13 +02001451 x = ckch->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001452 if (!x)
1453 goto out;
1454
William Lallemand246c0242019-10-11 08:59:13 +02001455 issuer = ckch->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001456 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1457 if (chain) {
1458 /* check if one of the certificate of the chain is the issuer */
1459 for (i = 0; i < sk_X509_num(chain); i++) {
1460 X509 *ti = sk_X509_value(chain, i);
1461 if (X509_check_issued(ti, x) == X509_V_OK) {
1462 issuer = ti;
1463 break;
1464 }
1465 }
1466 }
William Lallemand246c0242019-10-11 08:59:13 +02001467 if (!issuer)
1468 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001469
1470 cid = OCSP_cert_to_id(0, x, issuer);
1471 if (!cid)
1472 goto out;
1473
1474 i = i2d_OCSP_CERTID(cid, NULL);
1475 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1476 goto out;
1477
Vincent Bernat02779b62016-04-03 13:48:43 +02001478 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001479 if (!ocsp)
1480 goto out;
1481
1482 p = ocsp->key_data;
Remi Tricot-Le Breton5aa1dce2021-06-10 13:51:12 +02001483 ocsp->key_length = i2d_OCSP_CERTID(cid, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001484
1485 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1486 if (iocsp == ocsp)
1487 ocsp = NULL;
1488
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001489#ifndef SSL_CTX_get_tlsext_status_cb
1490# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1491 *cb = (void (*) (void))ctx->tlsext_status_cb;
1492#endif
1493 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1494
1495 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001496 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001497 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001498
William Lallemanda560c062020-07-31 11:43:20 +02001499 cb_arg = calloc(1, sizeof(*cb_arg));
1500 if (!cb_arg)
1501 goto out;
1502
yanbzhube2774d2015-12-10 15:07:30 -05001503 cb_arg->is_single = 1;
1504 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001505 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001506
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001507 pkey = X509_get_pubkey(x);
1508 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1509 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001510
1511 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001512 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 */
1513
yanbzhube2774d2015-12-10 15:07:30 -05001514 } else {
1515 /*
1516 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1517 * Update that cb_arg with the new cert's staple
1518 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001519 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001520 struct certificate_ocsp *tmp_ocsp;
1521 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001522 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001523 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001524
William Lallemand76b4a122020-08-04 17:41:39 +02001525 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001526
1527 /*
1528 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1529 * the order of operations below matter, take care when changing it
1530 */
1531 tmp_ocsp = cb_arg->s_ocsp;
1532 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1533 cb_arg->s_ocsp = NULL;
1534 cb_arg->m_ocsp[index] = tmp_ocsp;
1535 cb_arg->is_single = 0;
1536 cb_arg->single_kt = 0;
1537
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001538 pkey = X509_get_pubkey(x);
1539 key_type = EVP_PKEY_base_id(pkey);
1540 EVP_PKEY_free(pkey);
1541
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001542 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001543 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001544 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001545 iocsp->refcount++;
1546 }
yanbzhube2774d2015-12-10 15:07:30 -05001547 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001548
1549 ret = 0;
1550
1551 warn = NULL;
William Lallemand86e4d632020-08-07 00:44:32 +02001552 if (ssl_sock_load_ocsp_response(ckch->ocsp_response, iocsp, cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001553 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001554 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001555 }
1556
1557out:
Emeric Brun4147b2e2014-06-16 18:36:30 +02001558 if (cid)
1559 OCSP_CERTID_free(cid);
1560
1561 if (ocsp)
1562 free(ocsp);
1563
1564 if (warn)
1565 free(warn);
1566
Emeric Brun4147b2e2014-06-16 18:36:30 +02001567 return ret;
1568}
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001569#endif
1570
1571#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001572static int ssl_sock_load_ocsp(SSL_CTX *ctx, const struct cert_key_and_chain *ckch, STACK_OF(X509) *chain)
Emmanuel Hocdet2c32d8f2017-05-22 14:58:00 +02001573{
William Lallemand4a660132019-10-14 14:51:41 +02001574 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 +02001575}
1576#endif
1577
William Lallemand4a660132019-10-14 14:51:41 +02001578
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001579#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001580
1581#define CT_EXTENSION_TYPE 18
1582
William Lallemand03c331c2020-05-13 10:10:01 +02001583int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001584
1585int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1586{
Willy Tarreau83061a82018-07-13 11:56:34 +02001587 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001588
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001589 *out = (unsigned char *) sctl->area;
1590 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001591
1592 return 1;
1593}
1594
1595int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1596{
1597 return 1;
1598}
1599
William Lallemanda17f4112019-10-10 15:16:44 +02001600static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001601{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001602 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001603
William Lallemanda17f4112019-10-10 15:16:44 +02001604 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 +01001605 goto out;
1606
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001607 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1608
1609 ret = 0;
1610
1611out:
1612 return ret;
1613}
1614
1615#endif
1616
Emeric Brune1f38db2012-09-03 20:36:47 +02001617void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1618{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001619 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001620#ifdef USE_QUIC
1621 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1622#endif /* USE_QUIC */
1623 struct ssl_sock_ctx *ctx = NULL;
1624
Emeric Brund8b2bb52014-01-28 15:43:53 +01001625 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001626 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001627
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001628 if (conn)
Willy Tarreau939b0bf2022-04-11 11:29:11 +02001629 ctx = conn_get_ssl_sock_ctx(conn);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001630#ifdef USE_QUIC
1631 else if (qc)
1632 ctx = qc->xprt_ctx;
1633#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01001634
1635 if (!ctx) {
1636 /* must never happen */
1637 ABORT_NOW();
1638 return;
1639 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001640
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001641#ifndef SSL_OP_NO_RENEGOTIATION
1642 /* Please note that BoringSSL defines this macro to zero so don't
1643 * change this to #if and do not assign a default value to this macro!
1644 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001645 if (where & SSL_CB_HANDSHAKE_START) {
1646 /* Disable renegotiation (CVE-2009-3555) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001647 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 +02001648 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001649 conn->err_code = CO_ER_SSL_RENEG;
1650 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001651 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001652#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001653
1654 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001655 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001656 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001657 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001658 consider that the buffering was activated,
1659 so we rise the output buffer size from 4k
1660 to 16k */
1661 write_bio = SSL_get_wbio(ssl);
1662 if (write_bio != SSL_get_rbio(ssl)) {
1663 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001664 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001665 }
1666 }
1667 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001668}
1669
Emeric Brune64aef12012-09-21 13:15:06 +02001670/* Callback is called for each certificate of the chain during a verify
1671 ok is set to 1 if preverify detect no error on current certificate.
1672 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001673int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001674{
1675 SSL *ssl;
1676 struct connection *conn;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001677 struct ssl_sock_ctx *ctx;
Emeric Brun81c00f02012-09-21 14:31:21 +02001678 int err, depth;
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001679 X509 *client_crt;
1680 STACK_OF(X509) *certs;
Emeric Brune64aef12012-09-21 13:15:06 +02001681
1682 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001683 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001684 client_crt = SSL_get_ex_data(ssl, ssl_client_crt_ref_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001685
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02001686 ctx = __conn_get_ssl_sock_ctx(conn);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001687 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001688
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001689 depth = X509_STORE_CTX_get_error_depth(x_store);
1690 err = X509_STORE_CTX_get_error(x_store);
1691
Emeric Brun81c00f02012-09-21 14:31:21 +02001692 if (ok) /* no errors */
1693 return ok;
1694
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001695 /* Keep a reference to the client's certificate in order to be able to
1696 * dump some fetches values in a log even when the verification process
1697 * fails. */
1698 if (depth == 0) {
1699 X509_free(client_crt);
1700 client_crt = X509_STORE_CTX_get0_cert(x_store);
1701 if (client_crt) {
1702 X509_up_ref(client_crt);
1703 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
1704 }
1705 }
1706 else {
1707 /* An error occurred on a CA certificate of the certificate
1708 * chain, we might never call this verify callback on the client
1709 * certificate's depth (which is 0) so we try to store the
1710 * reference right now. */
Remi Tricot-Le Bretonf95c2952021-08-20 09:51:23 +02001711 certs = X509_STORE_CTX_get1_chain(x_store);
1712 if (certs) {
1713 client_crt = sk_X509_value(certs, 0);
1714 if (client_crt) {
1715 X509_up_ref(client_crt);
1716 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001717 }
1718 sk_X509_pop_free(certs, X509_free);
1719 }
1720 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001721
1722 /* check if CA error needs to be ignored */
1723 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001724 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1725 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1726 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001727 }
1728
Willy Tarreau731248f2020-02-04 14:02:02 +01001729 if (err < 64 && __objt_listener(conn->target)->bind_conf->ca_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001730 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001731 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001732 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001733 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001734
Willy Tarreau20879a02012-12-03 16:32:10 +01001735 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001736 return 0;
1737 }
1738
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001739 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1740 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001741
Emeric Brun81c00f02012-09-21 14:31:21 +02001742 /* check if certificate error needs to be ignored */
Willy Tarreau731248f2020-02-04 14:02:02 +01001743 if (err < 64 && __objt_listener(conn->target)->bind_conf->crt_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001744 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001745 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001746 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001747 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001748
Willy Tarreau20879a02012-12-03 16:32:10 +01001749 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001750 return 0;
Emeric Brune64aef12012-09-21 13:15:06 +02001751}
1752
Dragan Dosen9ac98092020-05-11 15:51:45 +02001753#ifdef TLS1_RT_HEARTBEAT
1754static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1755 int content_type, const void *buf, size_t len,
1756 SSL *ssl)
1757{
1758 /* test heartbeat received (write_p is set to 0
1759 for a received record) */
1760 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02001761 struct ssl_sock_ctx *ctx = __conn_get_ssl_sock_ctx(conn);
Dragan Dosen9ac98092020-05-11 15:51:45 +02001762 const unsigned char *p = buf;
1763 unsigned int payload;
1764
1765 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1766
1767 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1768 if (*p != TLS1_HB_REQUEST)
1769 return;
1770
1771 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1772 goto kill_it;
1773
1774 payload = (p[1] * 256) + p[2];
1775 if (3 + payload + 16 <= len)
1776 return; /* OK no problem */
1777 kill_it:
1778 /* We have a clear heartbleed attack (CVE-2014-0160), the
1779 * advertised payload is larger than the advertised packet
1780 * length, so we have garbage in the buffer between the
1781 * payload and the end of the buffer (p+len). We can't know
1782 * if the SSL stack is patched, and we don't know if we can
1783 * safely wipe out the area between p+3+len and payload.
1784 * So instead, we prevent the response from being sent by
1785 * setting the max_send_fragment to 0 and we report an SSL
1786 * error, which will kill this connection. It will be reported
1787 * above as SSL_ERROR_SSL while an other handshake failure with
1788 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1789 */
1790 ssl->max_send_fragment = 0;
1791 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1792 }
1793}
1794#endif
1795
1796static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1797 int content_type, const void *buf, size_t len,
1798 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001799{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001800 struct ssl_capture *capture;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001801 uchar *msg;
1802 uchar *end;
1803 uchar *extensions_end;
1804 uchar *ec_start = NULL;
1805 uchar *ec_formats_start = NULL;
1806 uchar *list_end;
1807 ushort protocol_version;
1808 ushort extension_id;
1809 ushort ec_len = 0;
1810 uchar ec_formats_len = 0;
1811 int offset = 0;
1812 int rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001813
1814 /* This function is called for "from client" and "to server"
1815 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001816 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001817 */
1818
1819 /* "write_p" is set to 0 is the bytes are received messages,
1820 * otherwise it is set to 1.
1821 */
1822 if (write_p != 0)
1823 return;
1824
1825 /* content_type contains the type of message received or sent
1826 * according with the SSL/TLS protocol spec. This message is
1827 * encoded with one byte. The value 256 (two bytes) is used
1828 * for designing the SSL/TLS record layer. According with the
1829 * rfc6101, the expected message (other than 256) are:
1830 * - change_cipher_spec(20)
1831 * - alert(21)
1832 * - handshake(22)
1833 * - application_data(23)
1834 * - (255)
1835 * We are interessed by the handshake and specially the client
1836 * hello.
1837 */
1838 if (content_type != 22)
1839 return;
1840
1841 /* The message length is at least 4 bytes, containing the
1842 * message type and the message length.
1843 */
1844 if (len < 4)
1845 return;
1846
1847 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001848 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001849 * - hello_request(0)
1850 * - client_hello(1)
1851 * - server_hello(2)
1852 * - certificate(11)
1853 * - server_key_exchange (12)
1854 * - certificate_request(13)
1855 * - server_hello_done(14)
1856 * We are interested by the client hello.
1857 */
1858 msg = (unsigned char *)buf;
1859 if (msg[0] != 1)
1860 return;
1861
1862 /* Next three bytes are the length of the message. The total length
1863 * must be this decoded length + 4. If the length given as argument
1864 * is not the same, we abort the protocol dissector.
1865 */
1866 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1867 if (len < rec_len + 4)
1868 return;
1869 msg += 4;
1870 end = msg + rec_len;
1871 if (end < msg)
1872 return;
1873
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001874 /* Expect 2 bytes for protocol version
1875 * (1 byte for major and 1 byte for minor)
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001876 */
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001877 if (msg + 2 > end)
1878 return;
1879 protocol_version = (msg[0] << 8) + msg[1];
1880 msg += 2;
1881
1882 /* Expect the random, composed by 4 bytes for the unix time and
1883 * 28 bytes for unix payload. So we jump 4 + 28.
1884 */
1885 msg += 4 + 28;
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001886 if (msg > end)
1887 return;
1888
1889 /* Next, is session id:
1890 * if present, we have to jump by length + 1 for the size information
1891 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001892 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001893 if (msg[0] > 0)
1894 msg += msg[0];
1895 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001896 if (msg > end)
1897 return;
1898
1899 /* Next two bytes are the ciphersuite length. */
1900 if (msg + 2 > end)
1901 return;
1902 rec_len = (msg[0] << 8) + msg[1];
1903 msg += 2;
1904 if (msg + rec_len > end || msg + rec_len < msg)
1905 return;
1906
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001907 capture = pool_zalloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001908 if (!capture)
1909 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001910 /* Compute the xxh64 of the ciphersuite. */
1911 capture->xxh64 = XXH64(msg, rec_len, 0);
1912
1913 /* Capture the ciphersuite. */
Marcin Deranek310a2602021-07-13 19:04:24 +02001914 capture->ciphersuite_len = MIN(global_ssl.capture_buffer_size, rec_len);
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001915 capture->ciphersuite_offset = 0;
1916 memcpy(capture->data, msg, capture->ciphersuite_len);
1917 msg += rec_len;
1918 offset += capture->ciphersuite_len;
1919
1920 /* Initialize other data */
1921 capture->protocol_version = protocol_version;
1922
1923 /* Next, compression methods:
1924 * if present, we have to jump by length + 1 for the size information
1925 * if not present, we have to jump by 1 only
1926 */
1927 if (msg[0] > 0)
1928 msg += msg[0];
1929 msg += 1;
1930 if (msg > end)
1931 goto store_capture;
1932
1933 /* We reached extensions */
1934 if (msg + 2 > end)
1935 goto store_capture;
1936 rec_len = (msg[0] << 8) + msg[1];
1937 msg += 2;
1938 if (msg + rec_len > end || msg + rec_len < msg)
1939 goto store_capture;
1940 extensions_end = msg + rec_len;
1941 capture->extensions_offset = offset;
1942
1943 /* Parse each extension */
1944 while (msg + 4 < extensions_end) {
1945 /* Add 2 bytes of extension_id */
Marcin Deranek310a2602021-07-13 19:04:24 +02001946 if (global_ssl.capture_buffer_size >= offset + 2) {
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001947 capture->data[offset++] = msg[0];
1948 capture->data[offset++] = msg[1];
1949 capture->extensions_len += 2;
1950 }
1951 else
1952 break;
1953 extension_id = (msg[0] << 8) + msg[1];
1954 /* Length of the extension */
1955 rec_len = (msg[2] << 8) + msg[3];
1956
1957 /* Expect 2 bytes extension id + 2 bytes extension size */
1958 msg += 2 + 2;
1959 if (msg + rec_len > extensions_end || msg + rec_len < msg)
1960 goto store_capture;
1961 /* TLS Extensions
1962 * https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml */
1963 if (extension_id == 0x000a) {
1964 /* Elliptic Curves:
1965 * https://www.rfc-editor.org/rfc/rfc8422.html
1966 * https://www.rfc-editor.org/rfc/rfc7919.html */
1967 list_end = msg + rec_len;
1968 if (msg + 2 > list_end)
1969 goto store_capture;
1970 rec_len = (msg[0] << 8) + msg[1];
1971 msg += 2;
1972
1973 if (msg + rec_len > list_end || msg + rec_len < msg)
1974 goto store_capture;
1975 /* Store location/size of the list */
1976 ec_start = msg;
1977 ec_len = rec_len;
1978 }
1979 else if (extension_id == 0x000b) {
1980 /* Elliptic Curves Point Formats:
1981 * https://www.rfc-editor.org/rfc/rfc8422.html */
1982 list_end = msg + rec_len;
1983 if (msg + 1 > list_end)
1984 goto store_capture;
1985 rec_len = msg[0];
1986 msg += 1;
1987
1988 if (msg + rec_len > list_end || msg + rec_len < msg)
1989 goto store_capture;
1990 /* Store location/size of the list */
1991 ec_formats_start = msg;
1992 ec_formats_len = rec_len;
1993 }
1994 msg += rec_len;
1995 }
1996
1997 if (ec_start) {
1998 rec_len = ec_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001999 if (offset + rec_len > global_ssl.capture_buffer_size)
2000 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02002001 memcpy(capture->data + offset, ec_start, rec_len);
2002 capture->ec_offset = offset;
2003 capture->ec_len = rec_len;
2004 offset += rec_len;
2005 }
2006 if (ec_formats_start) {
2007 rec_len = ec_formats_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02002008 if (offset + rec_len > global_ssl.capture_buffer_size)
2009 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02002010 memcpy(capture->data + offset, ec_formats_start, rec_len);
2011 capture->ec_formats_offset = offset;
2012 capture->ec_formats_len = rec_len;
2013 offset += rec_len;
2014 }
Emmanuel Hocdete3804742017-03-08 11:07:10 +01002015
Marcin Deranek769fd2e2021-07-12 14:16:55 +02002016 store_capture:
Emmanuel Hocdete3804742017-03-08 11:07:10 +01002017 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01002018}
William Lallemand7d42ef52020-07-06 11:41:30 +02002019
2020
William Lallemand722180a2021-06-09 16:46:12 +02002021#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02002022static void ssl_init_keylog(struct connection *conn, int write_p, int version,
2023 int content_type, const void *buf, size_t len,
2024 SSL *ssl)
2025{
2026 struct ssl_keylog *keylog;
2027
2028 if (SSL_get_ex_data(ssl, ssl_keylog_index))
2029 return;
2030
Willy Tarreauf208ac02021-03-22 21:10:12 +01002031 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02002032 if (!keylog)
2033 return;
2034
William Lallemand7d42ef52020-07-06 11:41:30 +02002035 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
2036 pool_free(pool_head_ssl_keylog, keylog);
2037 return;
2038 }
2039}
2040#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01002041
Emeric Brun29f037d2014-04-25 19:05:36 +02002042/* Callback is called for ssl protocol analyse */
2043void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
2044{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02002045 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2046 struct ssl_sock_msg_callback *cbk;
2047
Dragan Dosen1e7ed042020-05-08 18:30:00 +02002048 /* Try to call all callback functions that were registered by using
2049 * ssl_sock_register_msg_callback().
2050 */
2051 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
2052 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
2053 }
Emeric Brun29f037d2014-04-25 19:05:36 +02002054}
2055
Bernard Spil13c53f82018-02-15 13:34:58 +01002056#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01002057static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
2058 const unsigned char *in, unsigned int inlen,
2059 void *arg)
2060{
2061 struct server *srv = arg;
2062
2063 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
2064 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
2065 return SSL_TLSEXT_ERR_OK;
2066 return SSL_TLSEXT_ERR_NOACK;
2067}
2068#endif
2069
2070#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02002071/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002072 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02002073 */
2074static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
2075 unsigned int *len, void *arg)
2076{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002077 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02002078
2079 *data = (const unsigned char *)conf->npn_str;
2080 *len = conf->npn_len;
2081 return SSL_TLSEXT_ERR_OK;
2082}
2083#endif
2084
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002085#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02002086/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002087 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02002088 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002089static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
2090 unsigned char *outlen,
2091 const unsigned char *server,
2092 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02002093{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002094 struct ssl_bind_conf *conf = arg;
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002095#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002096 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002097#endif
Willy Tarreauab861d32013-04-02 02:30:41 +02002098
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002099 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
2100 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01002101#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002102 if (qc)
2103 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01002104#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002105 return SSL_TLSEXT_ERR_NOACK;
2106 }
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002107
2108#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002109 if (qc && !quic_set_app_ops(qc, *out, *outlen)) {
2110 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002111 return SSL_TLSEXT_ERR_NOACK;
2112 }
2113#endif
2114
Willy Tarreauab861d32013-04-02 02:30:41 +02002115 return SSL_TLSEXT_ERR_OK;
2116}
2117#endif
2118
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02002119#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002120#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002121
Shimi Gersneradabbfe2020-08-23 13:58:13 +03002122/* Configure a DNS SAN extenion on a certificate. */
2123int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
2124 int failure = 0;
2125 X509_EXTENSION *san_ext = NULL;
2126 CONF *conf = NULL;
2127 struct buffer *san_name = get_trash_chunk();
2128
2129 conf = NCONF_new(NULL);
2130 if (!conf) {
2131 failure = 1;
2132 goto cleanup;
2133 }
2134
2135 /* Build an extension based on the DNS entry above */
2136 chunk_appendf(san_name, "DNS:%s", servername);
2137 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
2138 if (!san_ext) {
2139 failure = 1;
2140 goto cleanup;
2141 }
2142
2143 /* Add the extension */
2144 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
2145 failure = 1;
2146 goto cleanup;
2147 }
2148
2149 /* Success */
2150 failure = 0;
2151
2152cleanup:
2153 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
2154 if (NULL != conf) NCONF_free(conf);
2155
2156 return failure;
2157}
2158
Christopher Faulet30548802015-06-11 13:39:32 +02002159/* Create a X509 certificate with the specified servername and serial. This
2160 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02002161static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002162ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002163{
Shimi Gersner5846c492020-08-23 13:58:12 +03002164 X509 *cacert = bind_conf->ca_sign_ckch->cert;
2165 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002166 SSL_CTX *ssl_ctx = NULL;
2167 X509 *newcrt = NULL;
2168 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002169 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002170 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002171 X509_NAME *name;
2172 const EVP_MD *digest;
2173 X509V3_CTX ctx;
2174 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002175 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002176
Christopher Faulet48a83322017-07-28 16:56:09 +02002177 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05002178#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002179 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
2180#else
2181 tmp_ssl = SSL_new(bind_conf->default_ctx);
2182 if (tmp_ssl)
2183 pkey = SSL_get_privatekey(tmp_ssl);
2184#endif
2185 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002186 goto mkcert_error;
2187
2188 /* Create the certificate */
2189 if (!(newcrt = X509_new()))
2190 goto mkcert_error;
2191
2192 /* Set version number for the certificate (X509v3) and the serial
2193 * number */
2194 if (X509_set_version(newcrt, 2L) != 1)
2195 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02002196 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002197
2198 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08002199 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
2200 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02002201 goto mkcert_error;
2202
2203 /* set public key in the certificate */
2204 if (X509_set_pubkey(newcrt, pkey) != 1)
2205 goto mkcert_error;
2206
2207 /* Set issuer name from the CA */
2208 if (!(name = X509_get_subject_name(cacert)))
2209 goto mkcert_error;
2210 if (X509_set_issuer_name(newcrt, name) != 1)
2211 goto mkcert_error;
2212
2213 /* Set the subject name using the same, but the CN */
2214 name = X509_NAME_dup(name);
2215 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
2216 (const unsigned char *)servername,
2217 -1, -1, 0) != 1) {
2218 X509_NAME_free(name);
2219 goto mkcert_error;
2220 }
2221 if (X509_set_subject_name(newcrt, name) != 1) {
2222 X509_NAME_free(name);
2223 goto mkcert_error;
2224 }
2225 X509_NAME_free(name);
2226
2227 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002228 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002229 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
2230 for (i = 0; i < X509V3_EXT_SIZE; i++) {
2231 X509_EXTENSION *ext;
2232
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002233 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02002234 goto mkcert_error;
2235 if (!X509_add_ext(newcrt, ext, -1)) {
2236 X509_EXTENSION_free(ext);
2237 goto mkcert_error;
2238 }
2239 X509_EXTENSION_free(ext);
2240 }
2241
Shimi Gersneradabbfe2020-08-23 13:58:13 +03002242 /* Add SAN extension */
2243 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
2244 goto mkcert_error;
2245 }
2246
Christopher Faulet31af49d2015-06-09 17:29:50 +02002247 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002248
2249 key_type = EVP_PKEY_base_id(capkey);
2250
2251 if (key_type == EVP_PKEY_DSA)
2252 digest = EVP_sha1();
2253 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002254 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002255 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02002256 digest = EVP_sha256();
2257 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05002258#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02002259 int nid;
2260
2261 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
2262 goto mkcert_error;
2263 if (!(digest = EVP_get_digestbynid(nid)))
2264 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02002265#else
2266 goto mkcert_error;
2267#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02002268 }
2269
Christopher Faulet31af49d2015-06-09 17:29:50 +02002270 if (!(X509_sign(newcrt, capkey, digest)))
2271 goto mkcert_error;
2272
2273 /* Create and set the new SSL_CTX */
2274 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
2275 goto mkcert_error;
2276 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
2277 goto mkcert_error;
2278 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
2279 goto mkcert_error;
2280 if (!SSL_CTX_check_private_key(ssl_ctx))
2281 goto mkcert_error;
2282
Shimi Gersner5846c492020-08-23 13:58:12 +03002283 /* Build chaining the CA cert and the rest of the chain, keep these order */
2284#if defined(SSL_CTX_add1_chain_cert)
2285 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
2286 goto mkcert_error;
2287 }
2288
2289 if (bind_conf->ca_sign_ckch->chain) {
2290 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2291 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2292 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2293 goto mkcert_error;
2294 }
2295 }
2296 }
2297#endif
2298
Christopher Faulet31af49d2015-06-09 17:29:50 +02002299 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002300
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002301#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002302#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002303 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002304#else
2305 ssl_sock_set_tmp_dh_from_pkey(ssl_ctx, pkey);
2306#endif
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002307#endif
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002308
2309#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
2310#if defined(SSL_CTX_set1_curves_list)
2311 {
2312 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
2313 if (!SSL_CTX_set1_curves_list(ssl_ctx, ecdhe))
2314 goto end;
2315 }
2316#endif
2317#else
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002318#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2319 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002320 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002321 EC_KEY *ecc;
2322 int nid;
2323
2324 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2325 goto end;
2326 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2327 goto end;
2328 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2329 EC_KEY_free(ecc);
2330 }
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002331#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
2332#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002333 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002334 return ssl_ctx;
2335
2336 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002337 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002338 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002339 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2340 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002341 return NULL;
2342}
2343
Christopher Faulet7969a332015-10-09 11:15:03 +02002344
Christopher Faulet30548802015-06-11 13:39:32 +02002345/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002346 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002347SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002348ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002349{
2350 struct lru64 *lru = NULL;
2351
2352 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002353 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002354 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002355 if (lru && lru->domain) {
2356 if (ssl)
2357 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002358 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002359 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002360 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002361 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002362 }
2363 return NULL;
2364}
2365
Emeric Brun821bb9b2017-06-15 16:37:39 +02002366/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2367 * function is not thread-safe, it should only be used to check if a certificate
2368 * exists in the lru cache (with no warranty it will not be removed by another
2369 * thread). It is kept for backward compatibility. */
2370SSL_CTX *
2371ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2372{
2373 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2374}
2375
Christopher Fauletd2cab922015-07-28 16:03:47 +02002376/* Set a certificate int the LRU cache used to store generated
2377 * certificate. Return 0 on success, otherwise -1 */
2378int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002379ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002380{
2381 struct lru64 *lru = NULL;
2382
2383 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002384 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002385 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002386 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002387 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002388 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002389 }
Christopher Faulet30548802015-06-11 13:39:32 +02002390 if (lru->domain && lru->data)
2391 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002392 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002393 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002394 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002395 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002396 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002397}
2398
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002399/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002400unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002401ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002402{
2403 return XXH32(data, len, ssl_ctx_lru_seed);
2404}
2405
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002406/* Generate a cert and immediately assign it to the SSL session so that the cert's
2407 * refcount is maintained regardless of the cert's presence in the LRU cache.
2408 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002409static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002410ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002411{
Shimi Gersner5846c492020-08-23 13:58:12 +03002412 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002413 SSL_CTX *ssl_ctx = NULL;
2414 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002415 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002416
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002417 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002418 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002419 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002420 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002421 if (lru && lru->domain)
2422 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002423 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002424 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002425 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002426 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002427 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002428 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002429 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002430 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002431 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002432 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002433 SSL_set_SSL_CTX(ssl, ssl_ctx);
2434 /* No LRU cache, this CTX will be released as soon as the session dies */
2435 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002436 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002437 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002438 return 0;
2439}
2440static int
2441ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2442{
2443 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002444 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002445
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002446 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002447 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002448 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002449 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002450 }
2451 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002452}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002453#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002454
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002455#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002456
2457static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002458{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002459#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002460 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002461 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2462#endif
2463}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002464static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2465 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002466 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2467}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002468static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002469#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002470 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002471 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2472#endif
2473}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002474static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002475#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002476 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002477 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2478#endif
2479}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002480/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002481static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2482/* Unusable in this context. */
2483static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2484static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2485static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2486static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2487static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002488#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002489
2490static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2491 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002492 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2493}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002494static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2495 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2496 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2497}
2498static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2499 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002500 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2501}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002502static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2503 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2504 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2505}
2506static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2507 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002508 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2509}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002510static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2511 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2512 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2513}
2514static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2515 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002516 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2517}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002518static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2519 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2520 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2521}
2522static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002523#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002524 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002525 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2526#endif
2527}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002528static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002529#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002530 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2531 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002532#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002533}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002534#endif
2535static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2536static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002537
William Lallemand7fd8b452020-05-07 15:20:43 +02002538struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002539 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2540 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2541 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2542 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2543 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2544 {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 +02002545};
2546
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002547static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2548{
2549 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2550 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2551 SSL_set_SSL_CTX(ssl, ctx);
2552}
2553
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002554#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002555
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002556int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002557{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002558 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002559 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002560
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002561 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || (s->options & BC_O_GENERATE_CERTS))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002562 return SSL_TLSEXT_ERR_OK;
2563 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002564}
2565
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002566#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002567int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002568{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002569 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002570#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002571int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002572{
2573#endif
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002574 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2575#ifdef USE_QUIC
2576 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2577#endif /* USE_QUIC */
2578 struct bind_conf *s = NULL;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002579 const uint8_t *extension_data;
2580 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002581 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002582
2583 char *wildp = NULL;
2584 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002585 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002586 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002587 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002588 int i;
2589
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002590 if (conn)
2591 s = __objt_listener(conn->target)->bind_conf;
2592#ifdef USE_QUIC
2593 else if (qc)
2594 s = qc->li->bind_conf;
2595#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01002596
2597 if (!s) {
2598 /* must never happen */
2599 ABORT_NOW();
2600 return 0;
2601 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002602
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002603#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002604 if (qc) {
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002605 /* Look for the QUIC transport parameters. */
2606#ifdef OPENSSL_IS_BORINGSSL
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002607 if (!SSL_early_callback_ctx_extension_get(ctx, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002608 &extension_data, &extension_len))
2609#else
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002610 if (!SSL_client_hello_get0_ext(ssl, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002611 &extension_data, &extension_len))
2612#endif
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002613 {
2614 /* This is not redundant. It we only return 0 without setting
2615 * <*al>, this has as side effect to generate another TLS alert
2616 * which would be set after calling quic_set_tls_alert().
2617 */
2618 *al = SSL_AD_MISSING_EXTENSION;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002619 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002620 return 0;
2621 }
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002622
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002623 if (!quic_transport_params_store(qc, 0, extension_data,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002624 extension_data + extension_len))
2625 goto abort;
2626 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002627#endif /* USE_QUIC */
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002628
Olivier Houchard9679ac92017-10-27 14:58:08 +02002629 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002630 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002631#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002632 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2633 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002634#else
2635 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2636#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002637 /*
2638 * The server_name extension was given too much extensibility when it
2639 * was written, so parsing the normal case is a bit complex.
2640 */
2641 size_t len;
2642 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002643 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002644 /* Extract the length of the supplied list of names. */
2645 len = (*extension_data++) << 8;
2646 len |= *extension_data++;
2647 if (len + 2 != extension_len)
2648 goto abort;
2649 /*
2650 * The list in practice only has a single element, so we only consider
2651 * the first one.
2652 */
2653 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2654 goto abort;
2655 extension_len = len - 1;
2656 /* Now we can finally pull out the byte array with the actual hostname. */
2657 if (extension_len <= 2)
2658 goto abort;
2659 len = (*extension_data++) << 8;
2660 len |= *extension_data++;
2661 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2662 || memchr(extension_data, 0, len) != NULL)
2663 goto abort;
2664 servername = extension_data;
2665 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002666 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002667#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002668 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002669 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002670 }
2671#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002672 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002673 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002674 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002675 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002676 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002677 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002678 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002679 goto abort;
2680 }
2681
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002682 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002683#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002684 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002685#else
2686 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2687#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002688 uint8_t sign;
2689 size_t len;
2690 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002691 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002692 len = (*extension_data++) << 8;
2693 len |= *extension_data++;
2694 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002695 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002696 if (len % 2 != 0)
2697 goto abort;
2698 for (; len > 0; len -= 2) {
2699 extension_data++; /* hash */
2700 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002701 switch (sign) {
2702 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002703 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002704 break;
2705 case TLSEXT_signature_ecdsa:
2706 has_ecdsa_sig = 1;
2707 break;
2708 default:
2709 continue;
2710 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002711 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002712 break;
2713 }
2714 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002715 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002716 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002717 }
2718 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002719 const SSL_CIPHER *cipher;
2720 size_t len;
2721 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002722 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002723#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002724 len = ctx->cipher_suites_len;
2725 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002726#else
2727 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2728#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002729 if (len % 2 != 0)
2730 goto abort;
2731 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002732#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002733 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002734 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002735#else
2736 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2737#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002738 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002739 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002740 break;
2741 }
2742 }
2743 }
2744
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002745 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002746 trash.area[i] = tolower(servername[i]);
2747 if (!wildp && (trash.area[i] == '.'))
2748 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002749 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002750 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002751
William Lallemand150bfa82019-09-19 17:12:49 +02002752 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002753
William Lallemand94bd3192020-08-14 14:43:35 +02002754 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2755 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002756 for (i = 0; i < 2; i++) {
2757 if (i == 0) /* lookup in full qualified names */
2758 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002759 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002760 node = ebst_lookup(&s->sni_w_ctx, wildp);
2761 else
2762 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002763
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002764 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002765
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002766 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002767 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002768 struct sni_ctx *sni, *sni_tmp;
2769 int skip = 0;
2770
2771 if (i == 1 && wildp) { /* wildcard */
2772 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2773 sni = container_of(n, struct sni_ctx, name);
2774 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002775 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002776 skip = 1;
2777 break;
2778 }
2779 }
2780 if (skip)
2781 continue;
2782 }
2783
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002784 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002785 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002786 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002787 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002788 break;
2789 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002790 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002791 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002792 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002793 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002794 if (!node_anonymous)
2795 node_anonymous = n;
2796 break;
2797 }
2798 }
2799 }
William Lallemand94bd3192020-08-14 14:43:35 +02002800 }
2801 /* Once the certificates are found, select them depending on what is
2802 * supported in the client and by key_signature priority order: EDSA >
2803 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002804 if (has_ecdsa_sig && node_ecdsa)
2805 node = node_ecdsa;
2806 else if (has_rsa_sig && node_rsa)
2807 node = node_rsa;
2808 else if (node_anonymous)
2809 node = node_anonymous;
2810 else if (node_ecdsa)
2811 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2812 else
2813 node = node_rsa; /* no rsa signature case (far far away) */
2814
William Lallemand94bd3192020-08-14 14:43:35 +02002815 if (node) {
2816 /* switch ctx */
2817 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2818 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2819 if (conf) {
2820 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2821 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2822 if (conf->early_data)
2823 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002824 }
William Lallemand94bd3192020-08-14 14:43:35 +02002825 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2826 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002827 }
William Lallemand150bfa82019-09-19 17:12:49 +02002828
William Lallemand02010472019-10-18 11:02:19 +02002829 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002830#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002831 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002832 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002833 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002834 }
2835#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002836 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002837 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002838 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002839 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002840 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
William Lallemand7980dff2021-11-18 17:46:26 +01002841 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002842 }
William Lallemand7980dff2021-11-18 17:46:26 +01002843
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01002844 /* We are about to raise an handshake error so the servername extension
2845 * callback will never be called and the SNI will never be stored in the
2846 * SSL context. In order for the ssl_fc_sni sample fetch to still work
2847 * in such a case, we store the SNI ourselves as an ex_data information
2848 * in the SSL context.
2849 */
2850 {
2851 char *client_sni = pool_alloc(ssl_sock_client_sni_pool);
2852 if (client_sni) {
2853 strncpy(client_sni, trash.area, TLSEXT_MAXLEN_host_name);
2854 client_sni[TLSEXT_MAXLEN_host_name] = '\0';
2855 SSL_set_ex_data(ssl, ssl_client_sni_index, client_sni);
2856 }
2857 }
2858
William Lallemand7980dff2021-11-18 17:46:26 +01002859 /* other cases fallback on abort, if strict-sni is set but no node was found */
2860
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002861 abort:
2862 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002863 if (conn)
2864 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002865#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002866 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002867#else
2868 *al = SSL_AD_UNRECOGNIZED_NAME;
2869 return 0;
2870#endif
William Lallemand7980dff2021-11-18 17:46:26 +01002871
2872allow_early:
2873#ifdef OPENSSL_IS_BORINGSSL
2874 if (allow_early)
2875 SSL_set_early_data_enabled(ssl, 1);
2876#else
2877 if (!allow_early)
2878 SSL_set_max_early_data(ssl, 0);
2879#endif
2880 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002881}
2882
William Lallemand002e2062021-11-18 15:25:16 +01002883#else /* ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002884
Emeric Brunfc0421f2012-09-07 17:30:07 +02002885/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2886 * warning when no match is found, which implies the default (first) cert
2887 * will keep being used.
2888 */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002889static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002890{
2891 const char *servername;
2892 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002893 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002894 struct bind_conf *s = priv;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002895 int i;
2896 (void)al; /* shut gcc stupid warning */
2897
2898 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002899 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002900#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002901 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002902 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002903#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002904 if (s->strict_sni)
2905 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002906 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002907 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002908 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002909 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002910 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002911
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002912 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002913 if (!servername[i])
2914 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002915 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002916 if (!wildp && (trash.area[i] == '.'))
2917 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002918 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002919 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002920
William Lallemand150bfa82019-09-19 17:12:49 +02002921 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002922 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002923 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002924 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2925 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002926 if (!container_of(n, struct sni_ctx, name)->neg) {
2927 node = n;
2928 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002929 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002930 }
2931 if (!node && wildp) {
2932 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002933 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2934 /* lookup a not neg filter */
2935 if (!container_of(n, struct sni_ctx, name)->neg) {
2936 node = n;
2937 break;
2938 }
2939 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002940 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002941 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002942#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002943 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(servername, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002944 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002945 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002946 return SSL_TLSEXT_ERR_OK;
2947 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002948#endif
William Lallemand21724f02019-11-04 17:56:13 +01002949 if (s->strict_sni) {
2950 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002951 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002952 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002953 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002954 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002955 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002956 }
2957
2958 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002959 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002960 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002961 return SSL_TLSEXT_ERR_OK;
2962}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002963#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002964#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2965
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002966#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002967
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002968static inline HASSL_DH *ssl_new_dh_fromdata(BIGNUM *p, BIGNUM *g)
2969{
2970#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2971 OSSL_PARAM_BLD *tmpl = NULL;
2972 OSSL_PARAM *params = NULL;
2973 EVP_PKEY_CTX *ctx = NULL;
2974 EVP_PKEY *pkey = NULL;
2975
2976 if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
2977 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
2978 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)
2979 || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
2980 goto end;
2981 }
2982 ctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2983 if (ctx == NULL
2984 || !EVP_PKEY_fromdata_init(ctx)
2985 || !EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params)) {
2986 goto end;
2987 }
2988
2989end:
2990 EVP_PKEY_CTX_free(ctx);
2991 OSSL_PARAM_free(params);
2992 OSSL_PARAM_BLD_free(tmpl);
2993 return pkey;
2994#else
2995
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002996 HASSL_DH *dh = DH_new();
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002997
2998 if (!dh)
2999 return NULL;
3000
3001 DH_set0_pqg(dh, p, NULL, g);
3002
3003 return dh;
3004#endif
3005}
3006
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02003007#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003008static inline HASSL_DH *ssl_get_dh_by_nid(int nid)
3009{
3010#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3011 OSSL_PARAM params[2];
3012 EVP_PKEY *pkey = NULL;
3013 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
3014 const char *named_group = NULL;
3015
3016 if (!pctx)
3017 goto end;
3018
3019 named_group = OBJ_nid2ln(nid);
3020
3021 if (!named_group)
3022 goto end;
3023
3024 params[0] = OSSL_PARAM_construct_utf8_string("group", (char*)named_group, 0);
3025 params[1] = OSSL_PARAM_construct_end();
3026
3027 if (EVP_PKEY_keygen_init(pctx) && EVP_PKEY_CTX_set_params(pctx, params))
3028 EVP_PKEY_generate(pctx, &pkey);
3029
3030end:
3031 EVP_PKEY_CTX_free(pctx);
3032 return pkey;
3033#else
3034
3035 HASSL_DH *dh = NULL;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003036 dh = DH_new_by_nid(nid);
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003037 return dh;
3038#endif
3039}
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02003040#endif
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003041
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01003042
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003043static HASSL_DH * ssl_get_dh_1024(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003044{
Remi Gacogned3a341a2015-05-29 16:26:17 +02003045 static unsigned char dh1024_p[]={
3046 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
3047 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
3048 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
3049 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
3050 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
3051 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
3052 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
3053 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
3054 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
3055 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
3056 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
3057 };
3058 static unsigned char dh1024_g[]={
3059 0x02,
3060 };
3061
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003062 BIGNUM *p;
3063 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02003064
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003065 HASSL_DH *dh = NULL;
3066
3067 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
3068 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
3069
3070 if (p && g)
3071 dh = ssl_new_dh_fromdata(p, g);
3072
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003073 return dh;
3074}
3075
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003076static HASSL_DH *ssl_get_dh_2048(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003077{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003078#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02003079 static unsigned char dh2048_p[]={
3080 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
3081 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
3082 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
3083 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
3084 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
3085 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
3086 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
3087 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
3088 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
3089 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
3090 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
3091 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
3092 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
3093 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
3094 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
3095 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
3096 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
3097 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
3098 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
3099 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
3100 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
3101 0xB7,0x1F,0x77,0xF3,
3102 };
3103 static unsigned char dh2048_g[]={
3104 0x02,
3105 };
3106
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003107 BIGNUM *p;
3108 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02003109
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003110 HASSL_DH *dh = NULL;
3111
3112 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
3113 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
3114
3115 if (p && g)
3116 dh = ssl_new_dh_fromdata(p, g);
3117
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003118 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003119#else
3120 return ssl_get_dh_by_nid(NID_ffdhe2048);
3121#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003122}
3123
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003124static HASSL_DH *ssl_get_dh_4096(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003125{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003126#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02003127 static unsigned char dh4096_p[]={
3128 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
3129 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
3130 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
3131 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
3132 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
3133 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
3134 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
3135 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
3136 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
3137 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
3138 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
3139 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
3140 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
3141 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
3142 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
3143 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
3144 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
3145 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
3146 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
3147 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
3148 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
3149 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
3150 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
3151 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
3152 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
3153 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
3154 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
3155 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
3156 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
3157 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
3158 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
3159 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
3160 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
3161 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
3162 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
3163 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
3164 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
3165 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
3166 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
3167 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
3168 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
3169 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
3170 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003171 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02003172 static unsigned char dh4096_g[]={
3173 0x02,
3174 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003175
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003176 BIGNUM *p;
3177 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02003178
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003179 HASSL_DH *dh = NULL;
3180
3181 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
3182 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
3183
3184 if (p && g)
3185 dh = ssl_new_dh_fromdata(p, g);
3186
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003187 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003188#else
3189 return ssl_get_dh_by_nid(NID_ffdhe4096);
3190#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003191}
3192
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003193static HASSL_DH *ssl_get_tmp_dh(EVP_PKEY *pkey)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003194{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003195 HASSL_DH *dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003196 int type;
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003197 int keylen = 0;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003198
3199 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003200
3201 /* The keylen supplied by OpenSSL can only be 512 or 1024.
3202 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
3203 */
3204 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
3205 keylen = EVP_PKEY_bits(pkey);
3206 }
3207
Willy Tarreauef934602016-12-22 23:12:01 +01003208 if (keylen > global_ssl.default_dh_param) {
3209 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003210 }
3211
Remi Gacogned3a341a2015-05-29 16:26:17 +02003212 if (keylen >= 4096) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003213 if (!local_dh_4096)
3214 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02003215 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003216 }
3217 else if (keylen >= 2048) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003218 if (!local_dh_2048)
3219 local_dh_2048 = ssl_get_dh_2048();
Remi Gacogne8de54152014-07-15 11:36:40 +02003220 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003221 }
3222 else {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003223 if (!local_dh_1024)
3224 local_dh_1024 = ssl_get_dh_1024();
Remi Gacogne8de54152014-07-15 11:36:40 +02003225 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003226 }
3227
3228 return dh;
3229}
3230
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003231#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003232/* Returns Diffie-Hellman parameters matching the private key length
3233 but not exceeding global_ssl.default_dh_param */
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003234static HASSL_DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003235{
3236 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
3237
3238 return ssl_get_tmp_dh(pkey);
3239}
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003240#endif
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003241
Remi Tricot-Le Breton846eda92022-02-11 12:04:50 +01003242static int ssl_sock_set_tmp_dh(SSL_CTX *ctx, HASSL_DH *dh)
3243{
3244#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
3245 return SSL_CTX_set_tmp_dh(ctx, dh);
3246#else
3247 int retval = 0;
3248 HASSL_DH_up_ref(dh);
3249
3250 retval = SSL_CTX_set0_tmp_dh_pkey(ctx, dh);
3251
3252 if (!retval)
3253 HASSL_DH_free(dh);
3254
3255 return retval;
3256#endif
3257}
3258
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003259#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3260static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey)
3261{
3262 HASSL_DH *dh = NULL;
3263 if (pkey && (dh = ssl_get_tmp_dh(pkey))) {
3264 HASSL_DH_up_ref(dh);
3265 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dh))
3266 HASSL_DH_free(dh);
3267 }
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003268}
3269#endif
3270
Remi Tricot-Le Breton09ebb332022-02-11 12:04:48 +01003271HASSL_DH *ssl_sock_get_dh_from_bio(BIO *bio)
3272{
3273#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3274 HASSL_DH *dh = NULL;
3275 OSSL_DECODER_CTX *dctx = NULL;
3276 const char *format = "PEM";
3277 const char *keytype = "DH";
3278
3279 dctx = OSSL_DECODER_CTX_new_for_pkey(&dh, format, NULL, keytype,
3280 OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
3281 NULL, NULL);
3282
3283 if (dctx == NULL || OSSL_DECODER_CTX_get_num_decoders(dctx) == 0)
3284 goto end;
3285
3286 /* The DH parameters might not be the first section found in the PEM
3287 * file so we need to iterate over all of them until we find the right
3288 * one.
3289 */
3290 while (!BIO_eof(bio) && !dh)
3291 OSSL_DECODER_from_bio(dctx, bio);
3292
3293end:
3294 OSSL_DECODER_CTX_free(dctx);
3295 return dh;
3296#else
3297 HASSL_DH *dh = NULL;
3298
3299 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3300
3301 return dh;
3302#endif
3303}
3304
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003305static HASSL_DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003306{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003307 HASSL_DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02003308 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003309
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003310 if (in == NULL)
3311 goto end;
3312
Remi Gacogne47783ef2015-05-29 15:53:22 +02003313 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003314 goto end;
3315
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003316 dh = ssl_sock_get_dh_from_bio(in);
Remi Gacogne47783ef2015-05-29 15:53:22 +02003317
3318end:
3319 if (in)
3320 BIO_free(in);
3321
Emeric Brune1b4ed42018-08-16 15:14:12 +02003322 ERR_clear_error();
3323
Remi Gacogne47783ef2015-05-29 15:53:22 +02003324 return dh;
3325}
3326
3327int ssl_sock_load_global_dh_param_from_file(const char *filename)
3328{
3329 global_dh = ssl_sock_get_dh_from_file(filename);
3330
3331 if (global_dh) {
3332 return 0;
3333 }
3334
3335 return -1;
3336}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003337#endif
3338
William Lallemand9117de92019-10-04 00:29:42 +02003339/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02003340static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02003341 struct bind_conf *s, struct ssl_bind_conf *conf,
3342 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003343{
3344 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003345 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003346
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003347 if (*name == '!') {
3348 neg = 1;
3349 name++;
3350 }
3351 if (*name == '*') {
3352 wild = 1;
3353 name++;
3354 }
3355 /* !* filter is a nop */
3356 if (neg && wild)
3357 return order;
3358 if (*name) {
3359 int j, len;
3360 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003361 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02003362 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003363 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02003364 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003365 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003366
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003367 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02003368 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02003369 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003370 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02003371 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003372 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003373 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003374 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003375 sc->order = order++;
3376 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02003377 sc->wild = wild;
3378 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01003379 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02003380 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003381 }
3382 return order;
3383}
3384
William Lallemand6af03992019-07-23 15:00:54 +02003385/*
William Lallemand1d29c742019-10-04 00:53:29 +02003386 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
3387 * This function can't return an error.
3388 *
3389 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
3390 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003391void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02003392{
3393
3394 struct sni_ctx *sc0, *sc0b, *sc1;
3395 struct ebmb_node *node;
3396
3397 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
3398
3399 /* ignore if sc0 was already inserted in a tree */
3400 if (sc0->name.node.leaf_p)
3401 continue;
3402
3403 /* Check for duplicates. */
3404 if (sc0->wild)
3405 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
3406 else
3407 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
3408
3409 for (; node; node = ebmb_next_dup(node)) {
3410 sc1 = ebmb_entry(node, struct sni_ctx, name);
3411 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
3412 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
3413 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02003414 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02003415 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003416 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02003417 break;
William Lallemand1d29c742019-10-04 00:53:29 +02003418 }
3419 }
3420
3421 /* if duplicate, ignore the insertion */
3422 if (!sc0)
3423 continue;
3424
3425 if (sc0->wild)
3426 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
3427 else
3428 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003429 }
William Lallemand21724f02019-11-04 17:56:13 +01003430
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003431 /* replace the default_ctx if required with the instance's ctx. */
3432 if (ckch_inst->is_default) {
3433 SSL_CTX_free(bind_conf->default_ctx);
3434 SSL_CTX_up_ref(ckch_inst->ctx);
3435 bind_conf->default_ctx = ckch_inst->ctx;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003436 bind_conf->default_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02003437 }
3438}
3439
3440/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003441 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02003442 */
William Lallemande3af8fb2019-10-08 11:36:53 +02003443struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02003444
William Lallemand2954c472020-03-06 21:54:13 +01003445/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02003446struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02003447
Emeric Brun7a883362019-10-17 13:27:40 +02003448/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003449 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02003450 * DH parameter is loaded into the SSL_CTX and if there is no
3451 * DH parameter available in ckchs nor in global, the default
3452 * DH parameters are applied on the SSL_CTX.
3453 * Returns a bitfield containing the flags:
3454 * ERR_FATAL in any fatal error case
3455 * ERR_ALERT if a reason of the error is availabine in err
3456 * ERR_WARN if a warning is available into err
3457 * The value 0 means there is no error nor warning and
3458 * the operation succeed.
3459 */
William Lallemandfa892222019-07-23 16:06:08 +02003460#ifndef OPENSSL_NO_DH
Emeric Brun7a883362019-10-17 13:27:40 +02003461static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct cert_key_and_chain *ckch,
3462 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02003463{
Emeric Brun7a883362019-10-17 13:27:40 +02003464 int ret = 0;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003465 HASSL_DH *dh = NULL;
William Lallemandfa892222019-07-23 16:06:08 +02003466
William Lallemanda8c73742019-07-31 18:31:34 +02003467 if (ckch && ckch->dh) {
William Lallemandfa892222019-07-23 16:06:08 +02003468 dh = ckch->dh;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003469 if (!ssl_sock_set_tmp_dh(ctx, dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003470 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
3471 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003472 memprintf(err, "%s, DH ciphers won't be available.\n",
3473 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003474 ret |= ERR_WARN;
3475 goto end;
3476 }
William Lallemandfa892222019-07-23 16:06:08 +02003477
3478 if (ssl_dh_ptr_index >= 0) {
3479 /* store a pointer to the DH params to avoid complaining about
3480 ssl-default-dh-param not being set for this SSL_CTX */
3481 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
3482 }
3483 }
3484 else if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003485 if (!ssl_sock_set_tmp_dh(ctx, global_dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003486 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
3487 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003488 memprintf(err, "%s, DH ciphers won't be available.\n",
3489 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003490 ret |= ERR_WARN;
3491 goto end;
3492 }
William Lallemandfa892222019-07-23 16:06:08 +02003493 }
3494 else {
3495 /* Clear openssl global errors stack */
3496 ERR_clear_error();
3497
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003498 /* We do not want DHE ciphers to be added to the cipher list
3499 * unless there is an explicit global dh option in the conf.
3500 */
3501 if (global_ssl.default_dh_param) {
3502 if (global_ssl.default_dh_param <= 1024) {
3503 /* we are limited to DH parameter of 1024 bits anyway */
3504 if (local_dh_1024 == NULL)
3505 local_dh_1024 = ssl_get_dh_1024();
William Lallemandfa892222019-07-23 16:06:08 +02003506
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003507 if (local_dh_1024 == NULL) {
3508 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3509 err && *err ? *err : "", path);
3510 ret |= ERR_ALERT | ERR_FATAL;
3511 goto end;
3512 }
William Lallemandfa892222019-07-23 16:06:08 +02003513
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003514 if (!ssl_sock_set_tmp_dh(ctx, local_dh_1024)) {
3515 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3516 err && *err ? *err : "", path);
3517 memprintf(err, "%s, DH ciphers won't be available.\n",
3518 err && *err ? *err : "");
3519 ret |= ERR_WARN;
3520 goto end;
3521 }
Emeric Bruna9363eb2019-10-17 14:53:03 +02003522 }
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003523 else {
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003524#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003525 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003526#else
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003527 ssl_sock_set_tmp_dh_from_pkey(ctx, ckch ? ckch->key : NULL);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003528#endif
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003529 }
William Lallemandfa892222019-07-23 16:06:08 +02003530 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003531 }
3532
William Lallemandf9568fc2019-10-16 18:27:58 +02003533end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003534 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003535 return ret;
3536}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003537#endif
William Lallemandfa892222019-07-23 16:06:08 +02003538
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003539
3540/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003541 * Returns a bitfield containing the flags:
3542 * ERR_FATAL in any fatal error case
3543 * ERR_ALERT if the reason of the error is available in err
3544 * ERR_WARN if a warning is available into err
3545 * The value 0 means there is no error nor warning and
3546 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003547 */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003548static int ssl_sock_load_cert_chain(const char *path, const struct cert_key_and_chain *ckch,
3549 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003550{
Emeric Bruna96b5822019-10-17 13:25:14 +02003551 int errcode = 0;
3552
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003553 if (find_chain == NULL) {
3554 errcode |= ERR_FATAL;
3555 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003556 }
3557
3558 if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
3559 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
3560 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003561 errcode |= ERR_ALERT | ERR_FATAL;
3562 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003563 }
3564
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003565 if (ckch->chain) {
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003566 *find_chain = ckch->chain;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003567 } else {
3568 /* Find Certificate Chain in global */
3569 struct issuer_chain *issuer;
Emmanuel Hocdetef87e0a2020-03-23 11:29:11 +01003570 issuer = ssl_get0_issuer_chain(ckch->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003571 if (issuer)
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003572 *find_chain = issuer->chain;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003573 }
William Lallemand85888572020-02-27 14:48:35 +01003574
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003575 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003576 /* always put a null chain stack in the SSL_CTX so it does not
3577 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003578 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003579 }
3580
William Lallemandf187ce62020-06-02 18:27:20 +02003581 /* Load all certs in the ckch into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003582#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003583 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand935d8292020-08-12 20:02:10 +02003584 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'. Make sure you are linking against Openssl >= 1.0.2.\n",
3585 err && *err ? *err : "", path);
3586 errcode |= ERR_ALERT | ERR_FATAL;
3587 goto end;
3588 }
William Lallemandf187ce62020-06-02 18:27:20 +02003589#else
3590 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003591 X509 *ca;
William Lallemandf187ce62020-06-02 18:27:20 +02003592 STACK_OF(X509) *chain;
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003593 chain = X509_chain_up_ref(*find_chain);
William Lallemandf187ce62020-06-02 18:27:20 +02003594 while ((ca = sk_X509_shift(chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003595 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003596 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3597 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003598 X509_free(ca);
3599 sk_X509_pop_free(chain, X509_free);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003600 errcode |= ERR_ALERT | ERR_FATAL;
3601 goto end;
3602 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003603 }
William Lallemandf187ce62020-06-02 18:27:20 +02003604#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003605
William Lallemand9a1d8392020-08-10 17:28:23 +02003606#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003607 /* remove the Root CA from the SSL_CTX if the option is activated */
3608 if (global_ssl.skip_self_issued_ca) {
3609 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3610 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3611 err && *err ? *err : "", path);
3612 errcode |= ERR_ALERT | ERR_FATAL;
3613 goto end;
3614 }
3615 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003616#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003617
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003618end:
3619 return errcode;
3620}
3621
3622
3623/* Loads the info in ckch into ctx
3624 * Returns a bitfield containing the flags:
3625 * ERR_FATAL in any fatal error case
3626 * ERR_ALERT if the reason of the error is available in err
3627 * ERR_WARN if a warning is available into err
3628 * The value 0 means there is no error nor warning and
3629 * the operation succeed.
3630 */
3631static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
3632{
3633 int errcode = 0;
3634 STACK_OF(X509) *find_chain = NULL;
3635
3636 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3637 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3638 err && *err ? *err : "", path);
3639 errcode |= ERR_ALERT | ERR_FATAL;
3640 return errcode;
3641 }
3642
3643 /* Load certificate chain */
3644 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3645 if (errcode & ERR_CODE)
3646 goto end;
3647
William Lallemandfa892222019-07-23 16:06:08 +02003648#ifndef OPENSSL_NO_DH
3649 /* store a NULL pointer to indicate we have not yet loaded
3650 a custom DH param file */
3651 if (ssl_dh_ptr_index >= 0) {
3652 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3653 }
3654
Emeric Brun7a883362019-10-17 13:27:40 +02003655 errcode |= ssl_sock_load_dh_params(ctx, ckch, path, err);
3656 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003657 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3658 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003659 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003660 }
3661#endif
3662
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003663#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemanda17f4112019-10-10 15:16:44 +02003664 if (sctl_ex_index >= 0 && ckch->sctl) {
3665 if (ssl_sock_load_sctl(ctx, ckch->sctl) < 0) {
3666 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003667 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003668 errcode |= ERR_ALERT | ERR_FATAL;
3669 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003670 }
3671 }
3672#endif
3673
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003674#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
William Lallemand246c0242019-10-11 08:59:13 +02003675 /* Load OCSP Info into context */
3676 if (ckch->ocsp_response) {
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01003677 if (ssl_sock_load_ocsp(ctx, ckch, find_chain) < 0) {
Tim Duesterhus93128532019-11-23 23:45:10 +01003678 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",
3679 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003680 errcode |= ERR_ALERT | ERR_FATAL;
3681 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003682 }
3683 }
William Lallemand246c0242019-10-11 08:59:13 +02003684#endif
3685
Emeric Bruna96b5822019-10-17 13:25:14 +02003686 end:
3687 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003688}
3689
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003690
3691/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
3692 * Returns a bitfield containing the flags:
3693 * ERR_FATAL in any fatal error case
3694 * ERR_ALERT if the reason of the error is available in err
3695 * ERR_WARN if a warning is available into err
3696 * The value 0 means there is no error nor warning and
3697 * the operation succeed.
3698 */
3699static int ssl_sock_put_srv_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch,
3700 SSL_CTX *ctx, char **err)
3701{
3702 int errcode = 0;
3703 STACK_OF(X509) *find_chain = NULL;
3704
3705 /* Load the private key */
3706 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3707 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3708 err && *err ? *err : "", path);
3709 errcode |= ERR_ALERT | ERR_FATAL;
3710 }
3711
3712 /* Load certificate chain */
3713 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3714 if (errcode & ERR_CODE)
3715 goto end;
3716
3717 if (SSL_CTX_check_private_key(ctx) <= 0) {
3718 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3719 err && *err ? *err : "", path);
3720 errcode |= ERR_ALERT | ERR_FATAL;
3721 }
3722
3723end:
3724 return errcode;
3725}
3726
3727
William Lallemand614ca0d2019-10-07 13:52:11 +02003728/*
3729 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003730 *
3731 * Returns a bitfield containing the flags:
3732 * ERR_FATAL in any fatal error case
3733 * ERR_ALERT if the reason of the error is available in err
3734 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003735 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003736int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003737 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003738{
William Lallemandc9402072019-05-15 15:33:54 +02003739 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003740 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003741 int order = 0;
3742 X509_NAME *xname;
3743 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003744 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003745 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003746#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3747 STACK_OF(GENERAL_NAME) *names;
3748#endif
William Lallemand36b84632019-07-18 19:28:17 +02003749 struct cert_key_and_chain *ckch;
William Lallemand614ca0d2019-10-07 13:52:11 +02003750 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003751 int errcode = 0;
3752
3753 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003754
William Lallemande3af8fb2019-10-08 11:36:53 +02003755 if (!ckchs || !ckchs->ckch)
Emeric Brun054563d2019-10-17 13:16:58 +02003756 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003757
William Lallemande3af8fb2019-10-08 11:36:53 +02003758 ckch = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003759
William Lallemandc9402072019-05-15 15:33:54 +02003760 ctx = SSL_CTX_new(SSLv23_server_method());
3761 if (!ctx) {
3762 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3763 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003764 errcode |= ERR_ALERT | ERR_FATAL;
3765 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003766 }
3767
Emeric Bruna96b5822019-10-17 13:25:14 +02003768 errcode |= ssl_sock_put_ckch_into_ctx(path, ckch, ctx, err);
3769 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003770 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003771
3772 ckch_inst = ckch_inst_new();
3773 if (!ckch_inst) {
3774 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3775 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003776 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003777 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003778 }
3779
William Lallemand36b84632019-07-18 19:28:17 +02003780 pkey = X509_get_pubkey(ckch->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003781 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003782 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003783 switch(EVP_PKEY_base_id(pkey)) {
3784 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003785 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003786 break;
3787 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003788 kinfo.sig = TLSEXT_signature_ecdsa;
3789 break;
3790 case EVP_PKEY_DSA:
3791 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003792 break;
3793 }
3794 EVP_PKEY_free(pkey);
3795 }
3796
Emeric Brun50bcecc2013-04-22 13:05:23 +02003797 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003798 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003799 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 +02003800 if (order < 0) {
3801 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003802 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003803 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003804 }
3805 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003806 }
3807 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003808#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand36b84632019-07-18 19:28:17 +02003809 names = X509_get_ext_d2i(ckch->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003810 if (names) {
3811 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3812 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3813 if (name->type == GEN_DNS) {
3814 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003815 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003816 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003817 if (order < 0) {
3818 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003819 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003820 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003821 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003822 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003823 }
3824 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003825 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003826 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003827#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand36b84632019-07-18 19:28:17 +02003828 xname = X509_get_subject_name(ckch->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003829 i = -1;
3830 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3831 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003832 ASN1_STRING *value;
3833
3834 value = X509_NAME_ENTRY_get_data(entry);
3835 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003836 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003837 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003838 if (order < 0) {
3839 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003840 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003841 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003842 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003843 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003844 }
3845 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003846 /* we must not free the SSL_CTX anymore below, since it's already in
3847 * the tree, so it will be discovered and cleaned in time.
3848 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003849
Emeric Brunfc0421f2012-09-07 17:30:07 +02003850#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003851 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003852 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3853 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003854 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003855 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003856 }
3857#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003858 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003859 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003860 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003861 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003862 SSL_CTX_up_ref(ctx);
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003863 bind_conf->default_inst = ckch_inst;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003864 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003865
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003866 /* Always keep a reference to the newly constructed SSL_CTX in the
3867 * instance. This way if the instance has no SNIs, the SSL_CTX will
3868 * still be linked. */
3869 SSL_CTX_up_ref(ctx);
3870 ckch_inst->ctx = ctx;
3871
William Lallemand9117de92019-10-04 00:29:42 +02003872 /* everything succeed, the ckch instance can be used */
3873 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003874 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003875 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003876
William Lallemand02e19a52020-04-08 16:11:26 +02003877 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3878
Emeric Brun054563d2019-10-17 13:16:58 +02003879 *ckchi = ckch_inst;
3880 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003881
3882error:
3883 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003884 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003885 if (ckch_inst->is_default)
3886 SSL_CTX_free(ctx);
3887
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003888 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003889 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003890 }
William Lallemandd9199372019-10-04 15:37:05 +02003891 SSL_CTX_free(ctx);
3892
Emeric Brun054563d2019-10-17 13:16:58 +02003893 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003894}
3895
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003896
3897/*
3898 * This function allocate a ckch_inst that will be used on the backend side
3899 * (server line)
3900 *
3901 * Returns a bitfield containing the flags:
3902 * ERR_FATAL in any fatal error case
3903 * ERR_ALERT if the reason of the error is available in err
3904 * ERR_WARN if a warning is available into err
3905 */
3906int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01003907 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003908{
3909 SSL_CTX *ctx;
3910 struct cert_key_and_chain *ckch;
3911 struct ckch_inst *ckch_inst = NULL;
3912 int errcode = 0;
3913
3914 *ckchi = NULL;
3915
3916 if (!ckchs || !ckchs->ckch)
3917 return ERR_FATAL;
3918
3919 ckch = ckchs->ckch;
3920
3921 ctx = SSL_CTX_new(SSLv23_client_method());
3922 if (!ctx) {
3923 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3924 err && *err ? *err : "", path);
3925 errcode |= ERR_ALERT | ERR_FATAL;
3926 goto error;
3927 }
3928
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003929 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, ckch, ctx, err);
3930 if (errcode & ERR_CODE)
3931 goto error;
3932
3933 ckch_inst = ckch_inst_new();
3934 if (!ckch_inst) {
3935 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3936 err && *err ? *err : "", path);
3937 errcode |= ERR_ALERT | ERR_FATAL;
3938 goto error;
3939 }
3940
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003941 /* everything succeed, the ckch instance can be used */
3942 ckch_inst->bind_conf = NULL;
3943 ckch_inst->ssl_conf = NULL;
3944 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01003945 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003946 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003947
3948 *ckchi = ckch_inst;
3949 return errcode;
3950
3951error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003952 SSL_CTX_free(ctx);
3953
3954 return errcode;
3955}
3956
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003957/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003958static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3959 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003960 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003961{
Emeric Brun054563d2019-10-17 13:16:58 +02003962 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003963
3964 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003965 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 +02003966
Emeric Brun054563d2019-10-17 13:16:58 +02003967 if (errcode & ERR_CODE)
3968 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003969
William Lallemand24bde432020-03-09 16:48:43 +01003970 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003971
3972 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003973 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003974 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003975}
3976
William Lallemanddb26e2b2021-01-26 12:01:46 +01003977/* This function generates a <struct ckch_inst *> for a <struct server *>, and
3978 * fill the SSL_CTX of the server.
3979 *
3980 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003981static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01003982 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003983{
3984 int errcode = 0;
3985
3986 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01003987 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003988
3989 if (errcode & ERR_CODE)
3990 return errcode;
3991
William Lallemanddb26e2b2021-01-26 12:01:46 +01003992 (*ckch_inst)->server = server;
3993 /* Keep the reference to the SSL_CTX in the server. */
3994 SSL_CTX_up_ref((*ckch_inst)->ctx);
3995 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003996 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003997 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003998 return errcode;
3999}
4000
William Lallemand6be66ec2020-03-06 22:26:32 +01004001
William Lallemand4c68bba2020-03-30 18:45:10 +02004002
4003
4004/* Make sure openssl opens /dev/urandom before the chroot. The work is only
4005 * done once. Zero is returned if the operation fails. No error is returned
4006 * if the random is said as not implemented, because we expect that openssl
4007 * will use another method once needed.
4008 */
Amaury Denoyellec593bcd2021-05-19 15:35:29 +02004009int ssl_initialize_random(void)
William Lallemand4c68bba2020-03-30 18:45:10 +02004010{
4011 unsigned char random;
4012 static int random_initialized = 0;
4013
4014 if (!random_initialized && RAND_bytes(&random, 1) != 0)
4015 random_initialized = 1;
4016
4017 return random_initialized;
4018}
4019
William Lallemand2954c472020-03-06 21:54:13 +01004020/* Load a crt-list file, this is done in 2 parts:
4021 * - store the content of the file in a crtlist structure with crtlist_entry structures
4022 * - generate the instances by iterating on entries in the crtlist struct
4023 *
4024 * Nothing is locked there, this function is used in the configuration parser.
4025 *
4026 * Returns a set of ERR_* flags possibly with an error in <err>.
4027 */
William Lallemand6be66ec2020-03-06 22:26:32 +01004028int 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 +01004029{
4030 struct crtlist *crtlist = NULL;
4031 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02004032 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01004033 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01004034 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02004035 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01004036
William Lallemand79d31ec2020-03-25 15:10:49 +01004037 bind_conf_node = malloc(sizeof(*bind_conf_node));
4038 if (!bind_conf_node) {
4039 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
4040 cfgerr |= ERR_FATAL | ERR_ALERT;
4041 goto error;
4042 }
4043 bind_conf_node->next = NULL;
4044 bind_conf_node->bind_conf = bind_conf;
4045
William Lallemand41ca9302020-04-08 13:15:18 +02004046 /* strip trailing slashes, including first one */
4047 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
4048 *end = 0;
4049
William Lallemand2954c472020-03-06 21:54:13 +01004050 /* look for an existing crtlist or create one */
4051 eb = ebst_lookup(&crtlists_tree, file);
4052 if (eb) {
4053 crtlist = ebmb_entry(eb, struct crtlist, node);
4054 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01004055 /* load a crt-list OR a directory */
4056 if (dir)
4057 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
4058 else
4059 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
4060
William Lallemand2954c472020-03-06 21:54:13 +01004061 if (!(cfgerr & ERR_CODE))
4062 ebst_insert(&crtlists_tree, &crtlist->node);
4063 }
4064
4065 if (cfgerr & ERR_CODE) {
4066 cfgerr |= ERR_FATAL | ERR_ALERT;
4067 goto error;
4068 }
4069
4070 /* generates ckch instance from the crtlist_entry */
4071 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
4072 struct ckch_store *store;
4073 struct ckch_inst *ckch_inst = NULL;
4074
4075 store = entry->node.key;
4076 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
4077 if (cfgerr & ERR_CODE) {
4078 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
4079 goto error;
4080 }
Willy Tarreau2b718102021-04-21 07:32:39 +02004081 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02004082 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01004083 }
William Lallemand2954c472020-03-06 21:54:13 +01004084
William Lallemand79d31ec2020-03-25 15:10:49 +01004085 /* add the bind_conf to the list */
4086 bind_conf_node->next = crtlist->bind_conf;
4087 crtlist->bind_conf = bind_conf_node;
4088
William Lallemand2954c472020-03-06 21:54:13 +01004089 return cfgerr;
4090error:
4091 {
William Lallemand49398312020-03-30 17:01:33 +02004092 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01004093 struct ckch_inst *inst, *s_inst;
4094
William Lallemand49398312020-03-30 17:01:33 +02004095 lastentry = entry; /* which entry we tried to generate last */
4096 if (lastentry) {
4097 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
4098 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
4099 break;
4100
4101 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01004102
William Lallemand49398312020-03-30 17:01:33 +02004103 /* this was not generated for this bind_conf, skip */
4104 if (inst->bind_conf != bind_conf)
4105 continue;
4106
William Lallemandd9d5d1b2020-04-09 16:31:05 +02004107 /* free the sni_ctx and instance */
4108 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02004109 }
William Lallemand2954c472020-03-06 21:54:13 +01004110 }
William Lallemand2954c472020-03-06 21:54:13 +01004111 }
William Lallemand79d31ec2020-03-25 15:10:49 +01004112 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01004113 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01004114 return cfgerr;
4115}
4116
William Lallemand06b22a82020-03-16 14:45:55 +01004117/* Returns a set of ERR_* flags possibly with an error in <err>. */
4118int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
4119{
4120 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01004121 int cfgerr = 0;
4122 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01004123 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01004124 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01004125
4126 if ((ckchs = ckchs_lookup(path))) {
4127 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01004128 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
4129 found++;
4130 } else if (stat(path, &buf) == 0) {
4131 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01004132 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02004133 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01004134 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01004135 cfgerr |= ERR_ALERT | ERR_FATAL;
4136 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01004137 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01004138 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01004139 }
4140 } else {
4141 /* stat failed, could be a bundle */
4142 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02004143 char fp[MAXPATHLEN+1] = {0};
4144 int n = 0;
4145
4146 /* Load all possible certs and keys in separate ckch_store */
4147 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
4148 struct stat buf;
4149 int ret;
4150
4151 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
4152 if (ret > sizeof(fp))
4153 continue;
4154
4155 if ((ckchs = ckchs_lookup(fp))) {
4156 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01004157 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02004158 } else {
4159 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01004160 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02004161 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02004162 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01004163 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02004164 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
4165 }
4166 }
4167 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01004168#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
4169 if (found) {
4170 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
4171 err && *err ? *err : "", path);
4172 cfgerr |= ERR_ALERT | ERR_FATAL;
4173 }
4174#endif
William Lallemand06b22a82020-03-16 14:45:55 +01004175 }
4176 }
William Lallemand06ce84a2020-11-20 15:36:13 +01004177 if (!found) {
4178 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
4179 err && *err ? *err : "", path, strerror(errno));
4180 cfgerr |= ERR_ALERT | ERR_FATAL;
4181 }
William Lallemand06b22a82020-03-16 14:45:55 +01004182
4183 return cfgerr;
4184}
4185
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004186
4187/* Create a full ssl context and ckch instance that will be used for a specific
4188 * backend server (server configuration line).
4189 * Returns a set of ERR_* flags possibly with an error in <err>.
4190 */
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004191int 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 +01004192{
4193 struct stat buf;
4194 int cfgerr = 0;
4195 struct ckch_store *ckchs;
4196 int found = 0; /* did we found a file to load ? */
4197
4198 if ((ckchs = ckchs_lookup(path))) {
4199 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01004200 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004201 found++;
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004202 } else {
4203 if (!create_if_none) {
4204 memprintf(err, "%sunable to stat SSL certificate '%s'.\n",
4205 err && *err ? *err : "", path);
4206 cfgerr |= ERR_ALERT | ERR_FATAL;
4207 goto out;
4208 }
4209
4210 if (stat(path, &buf) == 0) {
4211 /* We do not manage directories on backend side. */
4212 if (S_ISDIR(buf.st_mode) == 0) {
4213 ++found;
4214 ckchs = ckchs_load_cert_file(path, err);
4215 if (!ckchs)
4216 cfgerr |= ERR_ALERT | ERR_FATAL;
4217 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
4218 }
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004219 }
4220 }
4221 if (!found) {
4222 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
4223 err && *err ? *err : "", path, strerror(errno));
4224 cfgerr |= ERR_ALERT | ERR_FATAL;
4225 }
4226
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004227out:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004228 return cfgerr;
4229}
4230
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004231/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004232static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004233ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004234{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004235 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004236 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004237 SSL_OP_ALL | /* all known workarounds for bugs */
4238 SSL_OP_NO_SSLv2 |
4239 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02004240 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02004241 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004242 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02004243 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004244 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004245 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004246 SSL_MODE_ENABLE_PARTIAL_WRITE |
4247 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004248 SSL_MODE_RELEASE_BUFFERS |
4249 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004250 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004251 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004252 int flags = MC_SSL_O_ALL;
4253 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02004254 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004255
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004256 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004257 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004258
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004259 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004260 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
4261 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4262 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004263 else
4264 flags = conf_ssl_methods->flags;
4265
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004266 min = conf_ssl_methods->min;
4267 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02004268
4269 /* default minimum is TLSV12, */
4270 if (!min) {
4271 if (!max || (max >= default_min_ver)) {
4272 min = default_min_ver;
4273 } else {
4274 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). "
4275 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
4276 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
4277 min = max;
4278 }
4279 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004280 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004281 if (min)
4282 flags |= (methodVersions[min].flag - 1);
4283 if (max)
4284 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004285 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004286 min = max = CONF_TLSV_NONE;
4287 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004288 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004289 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004290 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004291 if (min) {
4292 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004293 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
4294 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4295 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
4296 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004297 hole = 0;
4298 }
4299 max = i;
4300 }
4301 else {
4302 min = max = i;
4303 }
4304 }
4305 else {
4306 if (min)
4307 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004308 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004309 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004310 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4311 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004312 cfgerr += 1;
4313 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004314 /* save real min/max in bind_conf */
4315 conf_ssl_methods->min = min;
4316 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004317
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004318#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004319 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004320 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004321 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004322 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004323 else
William Lallemandd0712f32020-06-11 17:34:00 +02004324 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
4325 /* clear every version flags in case SSL_CTX_new()
4326 * returns an SSL_CTX with disabled versions */
4327 SSL_CTX_clear_options(ctx, methodVersions[i].option);
4328
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004329 if (flags & methodVersions[i].flag)
4330 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02004331
4332 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004333#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004334 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004335 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4336 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02004337#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004338
4339 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
4340 options |= SSL_OP_NO_TICKET;
4341 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
4342 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08004343
4344#ifdef SSL_OP_NO_RENEGOTIATION
4345 options |= SSL_OP_NO_RENEGOTIATION;
4346#endif
4347
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004348 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004349
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004350#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004351 if (global_ssl.async)
4352 mode |= SSL_MODE_ASYNC;
4353#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004354 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004355 if (global_ssl.life_time)
4356 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004357
4358#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
4359#ifdef OPENSSL_IS_BORINGSSL
4360 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
4361 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Ilya Shipitsine9ff8992020-01-19 12:20:14 +05004362#elif defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01004363 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01004364 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02004365 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
4366 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004367#else
4368 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004369#endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02004370 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004371#endif
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004372 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004373}
4374
William Lallemand4f45bb92017-10-30 20:08:51 +01004375
4376static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
4377{
4378 if (first == block) {
4379 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4380 if (first->len > 0)
4381 sh_ssl_sess_tree_delete(sh_ssl_sess);
4382 }
4383}
4384
4385/* return first block from sh_ssl_sess */
4386static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
4387{
4388 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
4389
4390}
4391
4392/* store a session into the cache
4393 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
4394 * data: asn1 encoded session
4395 * data_len: asn1 encoded session length
4396 * Returns 1 id session was stored (else 0)
4397 */
4398static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
4399{
4400 struct shared_block *first;
4401 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
4402
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004403 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01004404 if (!first) {
4405 /* Could not retrieve enough free blocks to store that session */
4406 return 0;
4407 }
4408
4409 /* STORE the key in the first elem */
4410 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4411 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
4412 first->len = sizeof(struct sh_ssl_sess_hdr);
4413
4414 /* it returns the already existing node
4415 or current node if none, never returns null */
4416 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
4417 if (oldsh_ssl_sess != sh_ssl_sess) {
4418 /* NOTE: Row couldn't be in use because we lock read & write function */
4419 /* release the reserved row */
4420 shctx_row_dec_hot(ssl_shctx, first);
4421 /* replace the previous session already in the tree */
4422 sh_ssl_sess = oldsh_ssl_sess;
4423 /* ignore the previous session data, only use the header */
4424 first = sh_ssl_sess_first_block(sh_ssl_sess);
4425 shctx_row_inc_hot(ssl_shctx, first);
4426 first->len = sizeof(struct sh_ssl_sess_hdr);
4427 }
4428
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004429 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01004430 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004431 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01004432 }
4433
4434 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004435
4436 return 1;
4437}
William Lallemanded0b5ad2017-10-30 19:36:36 +01004438
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004439/* SSL callback used when a new session is created while connecting to a server */
4440static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4441{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004442 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004443 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004444
Willy Tarreau07d94e42018-09-20 10:57:52 +02004445 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004446
William Lallemand3ce6eed2021-02-08 10:43:44 +01004447 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4448 * one cache per thread, it only prevents to flush it from the CLI in
4449 * another thread */
4450
Olivier Houcharde6060c52017-11-16 17:42:52 +01004451 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4452 int len;
4453 unsigned char *ptr;
William Lallemande18d4e82021-11-17 02:59:21 +01004454 const char *sni;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004455
Olivier Houcharde6060c52017-11-16 17:42:52 +01004456 len = i2d_SSL_SESSION(sess, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01004457 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004458 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004459 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4460 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4461 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004462 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
4463 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004464 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4465 }
4466 if (s->ssl_ctx.reused_sess[tid].ptr) {
4467 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4468 &ptr);
4469 }
William Lallemande18d4e82021-11-17 02:59:21 +01004470
4471 if (s->ssl_ctx.reused_sess[tid].sni) {
4472 /* if the new sni is empty or isn' t the same as the old one */
4473 if ((!sni) || strcmp(s->ssl_ctx.reused_sess[tid].sni, sni) != 0) {
4474 ha_free(&s->ssl_ctx.reused_sess[tid].sni);
4475 if (sni)
4476 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4477 }
4478 } else if (sni) {
4479 /* if there wasn't an old sni but there is a new one */
4480 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4481 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004482 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004483 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004484 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004485 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004486 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004487 }
4488
4489 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004490}
4491
Olivier Houcharde6060c52017-11-16 17:42:52 +01004492
William Lallemanded0b5ad2017-10-30 19:36:36 +01004493/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004494int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004495{
4496 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4497 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4498 unsigned char *p;
4499 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004500 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004501 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004502
4503 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004504 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004505 * note: SSL_SESSION_set1_id is using
4506 * a memcpy so we need to use a different pointer
4507 * than sid_data or sid_ctx_data to avoid valgrind
4508 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004509 */
4510
4511 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004512
4513 /* copy value in an other buffer */
4514 memcpy(encid, sid_data, sid_length);
4515
4516 /* pad with 0 */
4517 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4518 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4519
4520 /* force length to zero to avoid ASN1 encoding */
4521 SSL_SESSION_set1_id(sess, encid, 0);
4522
4523 /* force length to zero to avoid ASN1 encoding */
4524 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004525
4526 /* check if buffer is large enough for the ASN1 encoded session */
4527 data_len = i2d_SSL_SESSION(sess, NULL);
4528 if (data_len > SHSESS_MAX_DATA_LEN)
4529 goto err;
4530
4531 p = encsess;
4532
4533 /* process ASN1 session encoding before the lock */
4534 i2d_SSL_SESSION(sess, &p);
4535
William Lallemanded0b5ad2017-10-30 19:36:36 +01004536
William Lallemanda3c77cf2017-10-30 23:44:40 +01004537 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004538 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004539 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004540 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004541err:
4542 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004543 SSL_SESSION_set1_id(sess, encid, sid_length);
4544 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004545
4546 return 0; /* do not increment session reference count */
4547}
4548
4549/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004550SSL_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 +01004551{
William Lallemand4f45bb92017-10-30 20:08:51 +01004552 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004553 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4554 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004555 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004556 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004557
Willy Tarreau4c19e992021-06-15 16:39:22 +02004558 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004559
4560 /* allow the session to be freed automatically by openssl */
4561 *do_copy = 0;
4562
4563 /* tree key is zeros padded sessionid */
4564 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4565 memcpy(tmpkey, key, key_len);
4566 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4567 key = tmpkey;
4568 }
4569
4570 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004571 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004572
4573 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004574 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4575 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004576 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004577 shctx_unlock(ssl_shctx);
Willy Tarreau4c19e992021-06-15 16:39:22 +02004578 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004579 return NULL;
4580 }
4581
William Lallemand4f45bb92017-10-30 20:08:51 +01004582 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4583 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004584
William Lallemand4f45bb92017-10-30 20:08:51 +01004585 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 +01004586
William Lallemanda3c77cf2017-10-30 23:44:40 +01004587 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004588
4589 /* decode ASN1 session */
4590 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004591 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004592 /* Reset session id and session id contenxt */
4593 if (sess) {
4594 SSL_SESSION_set1_id(sess, key, key_len);
4595 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4596 }
4597
4598 return sess;
4599}
4600
William Lallemand4f45bb92017-10-30 20:08:51 +01004601
William Lallemanded0b5ad2017-10-30 19:36:36 +01004602/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004603void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004604{
William Lallemand4f45bb92017-10-30 20:08:51 +01004605 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004606 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4607 unsigned int sid_length;
4608 const unsigned char *sid_data;
4609 (void)ctx;
4610
4611 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4612 /* tree key is zeros padded sessionid */
4613 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4614 memcpy(tmpkey, sid_data, sid_length);
4615 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4616 sid_data = tmpkey;
4617 }
4618
William Lallemanda3c77cf2017-10-30 23:44:40 +01004619 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004620
4621 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004622 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4623 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004624 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004625 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004626 }
4627
4628 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004629 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004630}
4631
4632/* Set session cache mode to server and disable openssl internal cache.
4633 * Set shared cache callbacks on an ssl context.
4634 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004635void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004636{
4637 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4638
4639 if (!ssl_shctx) {
4640 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4641 return;
4642 }
4643
4644 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4645 SSL_SESS_CACHE_NO_INTERNAL |
4646 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4647
4648 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004649 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4650 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4651 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004652}
William Lallemand7d42ef52020-07-06 11:41:30 +02004653
4654/*
4655 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4656 *
4657 * The format is:
4658 * * <Label> <space> <ClientRandom> <space> <Secret>
4659 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4660 */
4661
William Lallemand722180a2021-06-09 16:46:12 +02004662#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004663void SSL_CTX_keylog(const SSL *ssl, const char *line)
4664{
4665 struct ssl_keylog *keylog;
4666 char *lastarg = NULL;
4667 char *dst = NULL;
4668
4669 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4670 if (!keylog)
4671 return;
4672
4673 lastarg = strrchr(line, ' ');
4674 if (lastarg == NULL || ++lastarg == NULL)
4675 return;
4676
4677 dst = pool_alloc(pool_head_ssl_keylog_str);
4678 if (!dst)
4679 return;
4680
4681 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4682 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4683
4684 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4685 if (keylog->client_random)
4686 goto error;
4687 keylog->client_random = dst;
4688
4689 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4690 if (keylog->client_early_traffic_secret)
4691 goto error;
4692 keylog->client_early_traffic_secret = dst;
4693
4694 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4695 if(keylog->client_handshake_traffic_secret)
4696 goto error;
4697 keylog->client_handshake_traffic_secret = dst;
4698
4699 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4700 if (keylog->server_handshake_traffic_secret)
4701 goto error;
4702 keylog->server_handshake_traffic_secret = dst;
4703
4704 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4705 if (keylog->client_traffic_secret_0)
4706 goto error;
4707 keylog->client_traffic_secret_0 = dst;
4708
4709 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4710 if (keylog->server_traffic_secret_0)
4711 goto error;
4712 keylog->server_traffic_secret_0 = dst;
4713
4714 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4715 if (keylog->early_exporter_secret)
4716 goto error;
4717 keylog->early_exporter_secret = dst;
4718
4719 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4720 if (keylog->exporter_secret)
4721 goto error;
4722 keylog->exporter_secret = dst;
4723 } else {
4724 goto error;
4725 }
4726
4727 return;
4728
4729error:
4730 pool_free(pool_head_ssl_keylog_str, dst);
4731
4732 return;
4733}
4734#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004735
William Lallemand8b453912019-11-21 15:48:10 +01004736/*
4737 * This function applies the SSL configuration on a SSL_CTX
4738 * It returns an error code and fills the <err> buffer
4739 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004740static 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 +01004741{
4742 struct proxy *curproxy = bind_conf->frontend;
4743 int cfgerr = 0;
4744 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004745 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004746 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004747#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004748 const char *conf_ciphersuites;
4749#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004750 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004751
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004752 if (ssl_conf) {
4753 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4754 int i, min, max;
4755 int flags = MC_SSL_O_ALL;
4756
4757 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004758 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4759 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004760 if (min)
4761 flags |= (methodVersions[min].flag - 1);
4762 if (max)
4763 flags |= ~((methodVersions[max].flag << 1) - 1);
4764 min = max = CONF_TLSV_NONE;
4765 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4766 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4767 if (min)
4768 max = i;
4769 else
4770 min = max = i;
4771 }
4772 /* save real min/max */
4773 conf_ssl_methods->min = min;
4774 conf_ssl_methods->max = max;
4775 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004776 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4777 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004778 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004779 }
4780 }
4781
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004782 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004783 case SSL_SOCK_VERIFY_NONE:
4784 verify = SSL_VERIFY_NONE;
4785 break;
4786 case SSL_SOCK_VERIFY_OPTIONAL:
4787 verify = SSL_VERIFY_PEER;
4788 break;
4789 case SSL_SOCK_VERIFY_REQUIRED:
4790 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4791 break;
4792 }
4793 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4794 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004795 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 +01004796 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 +01004797 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 +01004798 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004799 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004800 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004801 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004802 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004803 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004804 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004805 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4806 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4807 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4808 cfgerr |= ERR_ALERT | ERR_FATAL;
4809 }
4810 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004811 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004812 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 +02004813 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004814 }
Emeric Brun850efd52014-01-29 12:24:34 +01004815 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004816 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4817 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004818 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004819 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004820#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004821 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004822 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4823
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004824 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004825 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4826 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004827 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004828 }
Emeric Brun561e5742012-10-02 15:20:55 +02004829 else {
4830 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4831 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004832 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004833#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004834 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004835 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004836#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004837 if(bind_conf->keys_ref) {
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +01004838 if (!SSL_CTX_set_tlsext_ticket_key_evp_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004839 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4840 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004841 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004842 }
4843 }
4844#endif
4845
William Lallemand4f45bb92017-10-30 20:08:51 +01004846 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004847 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4848 if (conf_ciphers &&
4849 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004850 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4851 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004852 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004853 }
4854
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004855#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004856 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4857 if (conf_ciphersuites &&
4858 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004859 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4860 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004861 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004862 }
4863#endif
4864
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004865#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02004866 if (!local_dh_1024)
4867 local_dh_1024 = ssl_get_dh_1024();
4868 if (!local_dh_2048)
4869 local_dh_2048 = ssl_get_dh_2048();
4870 if (!local_dh_4096)
4871 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02004872#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004873
Emeric Brunfc0421f2012-09-07 17:30:07 +02004874 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004875#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004876 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004877#endif
William Lallemand722180a2021-06-09 16:46:12 +02004878#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004879 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
4880#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004881
Bernard Spil13c53f82018-02-15 13:34:58 +01004882#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004883 ssl_conf_cur = NULL;
4884 if (ssl_conf && ssl_conf->npn_str)
4885 ssl_conf_cur = ssl_conf;
4886 else if (bind_conf->ssl_conf.npn_str)
4887 ssl_conf_cur = &bind_conf->ssl_conf;
4888 if (ssl_conf_cur)
4889 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004890#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004891#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004892 ssl_conf_cur = NULL;
4893 if (ssl_conf && ssl_conf->alpn_str)
4894 ssl_conf_cur = ssl_conf;
4895 else if (bind_conf->ssl_conf.alpn_str)
4896 ssl_conf_cur = &bind_conf->ssl_conf;
4897 if (ssl_conf_cur)
4898 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004899#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004900#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004901 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4902 if (conf_curves) {
4903 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004904 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4905 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004906 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004907 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004908 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004909 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004910#endif /* defined(SSL_CTX_set1_curves_list) */
4911
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004912 if (!conf_curves) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004913#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004914#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004915 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004916 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4917 NULL);
4918
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004919 if (ecdhe && SSL_CTX_set1_curves_list(ctx, ecdhe) == 0) {
4920 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4921 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
4922 cfgerr |= ERR_ALERT | ERR_FATAL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02004923 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004924#endif /* defined(SSL_CTX_set1_curves_list) */
Olivier Houchardc2aae742017-09-22 18:26:28 +02004925#else
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004926#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
4927 int i;
4928 EC_KEY *ecdh;
4929
Olivier Houchardc2aae742017-09-22 18:26:28 +02004930 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4931 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4932 ECDHE_DEFAULT_CURVE);
Emeric Brun2b58d042012-09-20 17:10:03 +02004933
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004934 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004935 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004936 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 +01004937 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004938 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004939 }
4940 else {
4941 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4942 EC_KEY_free(ecdh);
4943 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004944#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
4945#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Emeric Brun2b58d042012-09-20 17:10:03 +02004946 }
Emeric Brun2b58d042012-09-20 17:10:03 +02004947
Emeric Brunfc0421f2012-09-07 17:30:07 +02004948 return cfgerr;
4949}
4950
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004951
4952/*
4953 * Prepare the SSL_CTX based on the bind line configuration.
4954 * Since the CA file loading is made depending on the verify option of the bind
4955 * line, the link between the SSL_CTX and the CA file tree entry is made here.
4956 * If we want to create a link between the CA file entry and the corresponding
4957 * ckch instance (for CA file hot update), it needs to be done after
4958 * ssl_sock_prepare_ctx.
4959 * Returns 0 in case of success.
4960 */
4961int ssl_sock_prep_ctx_and_inst(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
4962 SSL_CTX *ctx, struct ckch_inst *ckch_inst, char **err)
4963{
4964 int errcode = 0;
4965
4966 errcode |= ssl_sock_prepare_ctx(bind_conf, ssl_conf, ctx, err);
4967 if (!errcode && ckch_inst)
4968 ckch_inst_add_cafile_link(ckch_inst, bind_conf, ssl_conf, NULL);
4969
4970 return errcode;
4971}
4972
Evan Broderbe554312013-06-27 00:05:25 -07004973static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4974{
4975 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4976 size_t prefixlen, suffixlen;
4977
4978 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004979 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004980 return 1;
4981
Evan Broderbe554312013-06-27 00:05:25 -07004982 /* The rest of this logic is based on RFC 6125, section 6.4.3
4983 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4984
Emeric Bruna848dae2013-10-08 11:27:28 +02004985 pattern_wildcard = NULL;
4986 pattern_left_label_end = pattern;
4987 while (*pattern_left_label_end != '.') {
4988 switch (*pattern_left_label_end) {
4989 case 0:
4990 /* End of label not found */
4991 return 0;
4992 case '*':
4993 /* If there is more than one wildcards */
4994 if (pattern_wildcard)
4995 return 0;
4996 pattern_wildcard = pattern_left_label_end;
4997 break;
4998 }
4999 pattern_left_label_end++;
5000 }
5001
5002 /* If it's not trivial and there is no wildcard, it can't
5003 * match */
5004 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07005005 return 0;
5006
5007 /* Make sure all labels match except the leftmost */
5008 hostname_left_label_end = strchr(hostname, '.');
5009 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02005010 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07005011 return 0;
5012
5013 /* Make sure the leftmost label of the hostname is long enough
5014 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02005015 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07005016 return 0;
5017
5018 /* Finally compare the string on either side of the
5019 * wildcard */
5020 prefixlen = pattern_wildcard - pattern;
5021 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02005022 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
5023 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07005024 return 0;
5025
5026 return 1;
5027}
5028
5029static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
5030{
5031 SSL *ssl;
5032 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005033 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02005034 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02005035 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07005036
5037 int depth;
5038 X509 *cert;
5039 STACK_OF(GENERAL_NAME) *alt_names;
5040 int i;
5041 X509_NAME *cert_subject;
5042 char *str;
5043
5044 if (ok == 0)
5045 return ok;
5046
5047 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02005048 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02005049 ssl_ctx = __conn_get_ssl_sock_ctx(conn);
Evan Broderbe554312013-06-27 00:05:25 -07005050
Willy Tarreauad92a9a2017-07-28 11:38:41 +02005051 /* We're checking if the provided hostnames match the desired one. The
5052 * desired hostname comes from the SNI we presented if any, or if not
5053 * provided then it may have been explicitly stated using a "verifyhost"
5054 * directive. If neither is set, we don't care about the name so the
5055 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02005056 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005057 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02005058 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02005059 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02005060 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02005061 if (!servername)
5062 return ok;
5063 }
Evan Broderbe554312013-06-27 00:05:25 -07005064
5065 /* We only need to verify the CN on the actual server cert,
5066 * not the indirect CAs */
5067 depth = X509_STORE_CTX_get_error_depth(ctx);
5068 if (depth != 0)
5069 return ok;
5070
5071 /* At this point, the cert is *not* OK unless we can find a
5072 * hostname match */
5073 ok = 0;
5074
5075 cert = X509_STORE_CTX_get_current_cert(ctx);
5076 /* It seems like this might happen if verify peer isn't set */
5077 if (!cert)
5078 return ok;
5079
5080 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
5081 if (alt_names) {
5082 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
5083 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
5084 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005085#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02005086 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
5087#else
Evan Broderbe554312013-06-27 00:05:25 -07005088 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02005089#endif
Evan Broderbe554312013-06-27 00:05:25 -07005090 ok = ssl_sock_srv_hostcheck(str, servername);
5091 OPENSSL_free(str);
5092 }
5093 }
5094 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02005095 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07005096 }
5097
5098 cert_subject = X509_get_subject_name(cert);
5099 i = -1;
5100 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
5101 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005102 ASN1_STRING *value;
5103 value = X509_NAME_ENTRY_get_data(entry);
5104 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07005105 ok = ssl_sock_srv_hostcheck(str, servername);
5106 OPENSSL_free(str);
5107 }
5108 }
5109
Willy Tarreau71d058c2017-07-26 20:09:56 +02005110 /* report the mismatch and indicate if SNI was used or not */
5111 if (!ok && !conn->err_code)
5112 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07005113 return ok;
5114}
5115
Emeric Brun94324a42012-10-11 14:00:19 +02005116/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01005117int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02005118{
5119 int cfgerr = 0;
William Lallemand2c776f12021-12-28 18:47:17 +01005120 SSL_CTX *ctx;
Willy Tarreaufce03112015-01-15 21:32:40 +01005121 /* Automatic memory computations need to know we use SSL there */
5122 global.ssl_used_backend = 1;
5123
5124 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02005125 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005126 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005127 ha_alert("out of memory.\n");
Emeric Brun821bb9b2017-06-15 16:37:39 +02005128 cfgerr++;
5129 return cfgerr;
5130 }
5131 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01005132 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02005133 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02005134
William Lallemand2c776f12021-12-28 18:47:17 +01005135 if (srv->ssl_ctx.client_crt) {
5136 const int create_if_none = srv->flags & SRV_F_DYNAMIC ? 0 : 1;
5137 char *err = NULL;
5138 int err_code = 0;
5139
5140 /* If there is a crt keyword there, the SSL_CTX will be created here. */
5141 err_code = ssl_sock_load_srv_cert(srv->ssl_ctx.client_crt, srv, create_if_none, &err);
5142 if (err_code != ERR_NONE) {
5143 if ((err_code & ERR_WARN) && !(err_code & ERR_ALERT))
5144 ha_warning("%s", err);
5145 else
5146 ha_alert("%s", err);
5147
5148 if (err_code & (ERR_FATAL|ERR_ABORT))
5149 cfgerr++;
5150 }
5151 ha_free(&err);
5152 }
5153
5154 ctx = srv->ssl_ctx.ctx;
5155
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005156 /* The context will be uninitialized if there wasn't any "cert" option
5157 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005158 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005159 ctx = SSL_CTX_new(SSLv23_client_method());
5160 if (!ctx) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005161 ha_alert("unable to allocate ssl context.\n");
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005162 cfgerr++;
5163 return cfgerr;
5164 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005165
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005166 srv->ssl_ctx.ctx = ctx;
5167 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005168
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005169 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 +01005170
5171 return cfgerr;
5172}
5173
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005174/* Initialize an SSL context that will be used on the backend side.
5175 * Returns an error count.
5176 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005177static int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005178{
5179 struct proxy *curproxy = srv->proxy;
5180 int cfgerr = 0;
5181 long options =
5182 SSL_OP_ALL | /* all known workarounds for bugs */
5183 SSL_OP_NO_SSLv2 |
5184 SSL_OP_NO_COMPRESSION;
5185 long mode =
5186 SSL_MODE_ENABLE_PARTIAL_WRITE |
5187 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
5188 SSL_MODE_RELEASE_BUFFERS |
5189 SSL_MODE_SMALL_BUFFERS;
5190 int verify = SSL_VERIFY_NONE;
5191 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
5192 int i, min, max, hole;
5193 int flags = MC_SSL_O_ALL;
5194
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005195 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005196 ha_warning("no-sslv3/no-tlsv1x are ignored for this server. "
5197 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n");
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005198 else
5199 flags = conf_ssl_methods->flags;
5200
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005201 /* Real min and max should be determinate with configuration and openssl's capabilities */
5202 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005203 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005204 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005205 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005206
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005207 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005208 min = max = CONF_TLSV_NONE;
5209 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005210 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005211 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005212 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005213 if (min) {
5214 if (hole) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005215 ha_warning("%s '%s': SSL/TLS versions range not contiguous for server '%s'. "
Christopher Faulet767a84b2017-11-24 16:50:31 +01005216 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
5217 proxy_type_str(curproxy), curproxy->id, srv->id,
5218 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005219 hole = 0;
5220 }
5221 max = i;
5222 }
5223 else {
5224 min = max = i;
5225 }
5226 }
5227 else {
5228 if (min)
5229 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005230 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005231 if (!min) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005232 ha_alert("%s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01005233 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005234 cfgerr += 1;
5235 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005236
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005237#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005238 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08005239 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005240 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005241 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005242 else
5243 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
5244 if (flags & methodVersions[i].flag)
5245 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005246#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005247 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005248 methodVersions[min].ctx_set_version(ctx, SET_MIN);
5249 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005250#endif
5251
5252 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
5253 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005254 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005255
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005256#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005257 if (global_ssl.async)
5258 mode |= SSL_MODE_ASYNC;
5259#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005260 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005261
Emeric Brun850efd52014-01-29 12:24:34 +01005262 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
5263 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01005264 switch (srv->ssl_ctx.verify) {
5265 case SSL_SOCK_VERIFY_NONE:
5266 verify = SSL_VERIFY_NONE;
5267 break;
5268 case SSL_SOCK_VERIFY_REQUIRED:
5269 verify = SSL_VERIFY_PEER;
5270 break;
5271 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005272 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02005273 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01005274 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02005275 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02005276 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005277 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005278 ha_alert("unable to set CA file '%s'.\n",
5279 srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005280 cfgerr++;
5281 }
5282 }
Emeric Brun850efd52014-01-29 12:24:34 +01005283 else {
5284 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005285 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 +01005286 else
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005287 ha_alert("verify is enabled but no CA file specified.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01005288 cfgerr++;
5289 }
Emeric Brunef42d922012-10-11 16:11:36 +02005290#ifdef X509_V_FLAG_CRL_CHECK
5291 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005292 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02005293
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01005294 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005295 ha_alert("unable to configure CRL file '%s'.\n",
5296 srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005297 cfgerr++;
5298 }
5299 else {
5300 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5301 }
5302 }
5303#endif
5304 }
5305
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005306 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5307 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02005308 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005309 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005310 ha_alert("unable to set SSL cipher list to '%s'.\n",
5311 srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02005312 cfgerr++;
5313 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005314
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05005315#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005316 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005317 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005318 ha_alert("unable to set TLS 1.3 cipher suites to '%s'.\n",
5319 srv->ssl_ctx.ciphersuites);
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005320 cfgerr++;
5321 }
5322#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01005323#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
5324 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005325 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01005326#endif
5327#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5328 if (srv->ssl_ctx.alpn_str)
5329 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
5330#endif
5331
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005332
5333 return cfgerr;
5334}
5335
5336/*
5337 * Prepare the frontend's SSL_CTX based on the server line configuration.
5338 * Since the CA file loading is made depending on the verify option of the
5339 * server line, the link between the SSL_CTX and the CA file tree entry is
5340 * made here.
5341 * If we want to create a link between the CA file entry and the corresponding
5342 * ckch instance (for CA file hot update), it needs to be done after
5343 * ssl_sock_prepare_srv_ssl_ctx.
5344 * Returns an error count.
5345 */
5346int ssl_sock_prep_srv_ctx_and_inst(const struct server *srv, SSL_CTX *ctx,
5347 struct ckch_inst *ckch_inst)
5348{
5349 int cfgerr = 0;
5350
5351 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, ctx);
5352 if (!cfgerr && ckch_inst)
5353 ckch_inst_add_cafile_link(ckch_inst, NULL, NULL, srv);
Emeric Brun94324a42012-10-11 14:00:19 +02005354
5355 return cfgerr;
5356}
5357
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005358
Frédéric Lécailleec216522020-11-23 14:33:30 +01005359/*
5360 * Create an initial CTX used to start the SSL connections.
5361 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
5362 * Returns 0 if succeeded, or something >0 if not.
5363 */
5364#ifdef USE_QUIC
5365static int ssl_initial_ctx(struct bind_conf *bind_conf)
5366{
5367 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
5368 return ssl_quic_initial_ctx(bind_conf);
5369 else
5370 return ssl_sock_initial_ctx(bind_conf);
5371}
5372#else
5373static int ssl_initial_ctx(struct bind_conf *bind_conf)
5374{
5375 return ssl_sock_initial_ctx(bind_conf);
5376}
5377#endif
5378
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005379/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005380 * be NULL, in which case nothing is done. Returns the number of errors
5381 * encountered.
5382 */
Willy Tarreau03209342016-12-22 17:08:28 +01005383int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005384{
5385 struct ebmb_node *node;
5386 struct sni_ctx *sni;
5387 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01005388 int errcode = 0;
5389 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02005390
Willy Tarreaufce03112015-01-15 21:32:40 +01005391 /* Automatic memory computations need to know we use SSL there */
5392 global.ssl_used_frontend = 1;
5393
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005394 /* Create initial_ctx used to start the ssl connection before do switchctx */
5395 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01005396 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005397 /* It should not be necessary to call this function, but it's
5398 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01005399 to initial_ctx in ssl_initial_ctx. */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005400 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, NULL, bind_conf->initial_ctx, NULL, &errmsg);
5401 }
5402 if (bind_conf->default_ctx) {
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005403 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 +01005404 }
Emeric Brun0bed9942014-10-30 19:25:24 +01005405
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005406 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005407 while (node) {
5408 sni = ebmb_entry(node, struct sni_ctx, name);
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005409 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005410 /* only initialize the CTX on its first occurrence and
5411 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005412 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
5413 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005414 node = ebmb_next(node);
5415 }
5416
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005417 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005418 while (node) {
5419 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01005420 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005421 /* only initialize the CTX on its first occurrence and
5422 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005423 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005424 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005425 node = ebmb_next(node);
5426 }
William Lallemand8b453912019-11-21 15:48:10 +01005427
5428 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005429 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005430 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005431 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005432 err++;
5433 }
5434
5435 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005436 return err;
5437}
5438
Willy Tarreau55d37912016-12-21 23:38:39 +01005439/* Prepares all the contexts for a bind_conf and allocates the shared SSL
5440 * context if needed. Returns < 0 on error, 0 on success. The warnings and
5441 * alerts are directly emitted since the rest of the stack does it below.
5442 */
5443int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
5444{
5445 struct proxy *px = bind_conf->frontend;
5446 int alloc_ctx;
5447 int err;
5448
Willy Tarreau11ba4042022-05-20 15:56:32 +02005449 if (!(bind_conf->options & BC_O_USE_SSL)) {
Willy Tarreau55d37912016-12-21 23:38:39 +01005450 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005451 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
5452 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01005453 }
5454 return 0;
5455 }
5456 if (!bind_conf->default_ctx) {
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005457 if (bind_conf->strict_sni && !(bind_conf->options & BC_O_GENERATE_CERTS)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005458 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5459 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005460 }
5461 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005462 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5463 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005464 return -1;
5465 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005466 }
William Lallemandc61c0b32017-12-04 18:46:39 +01005467 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005468 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02005469 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
Willy Tarreau91358592021-06-15 08:08:04 +02005470 sizeof(*sh_ssl_sess_tree), (global.nbthread > 1));
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02005471 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005472 if (alloc_ctx == SHCTX_E_INIT_LOCK)
5473 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");
5474 else
5475 ha_alert("Unable to allocate SSL session cache.\n");
5476 return -1;
5477 }
5478 /* free block callback */
5479 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5480 /* init the root tree within the extra space */
5481 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5482 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01005483 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005484 err = 0;
5485 /* initialize all certificate contexts */
5486 err += ssl_sock_prepare_all_ctx(bind_conf);
5487
5488 /* initialize CA variables if the certificates generation is enabled */
5489 err += ssl_sock_load_ca(bind_conf);
5490
5491 return -err;
5492}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005493
William Lallemand231610a2021-12-30 11:25:43 +01005494/* release ssl context allocated for servers. Most of the field free here
5495 * must also be allocated in srv_ssl_settings_cpy() */
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005496void ssl_sock_free_srv_ctx(struct server *srv)
5497{
Olivier Houchardc7566002018-11-20 23:33:50 +01005498#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
William Lallemand231610a2021-12-30 11:25:43 +01005499 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005500#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005501#ifdef OPENSSL_NPN_NEGOTIATED
William Lallemand231610a2021-12-30 11:25:43 +01005502 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005503#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005504 if (srv->ssl_ctx.reused_sess) {
5505 int i;
5506
William Lallemande18d4e82021-11-17 02:59:21 +01005507 for (i = 0; i < global.nbthread; i++) {
Willy Tarreaue709e822021-02-26 21:06:32 +01005508 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
William Lallemande18d4e82021-11-17 02:59:21 +01005509 ha_free(&srv->ssl_ctx.reused_sess[i].sni);
5510 }
Willy Tarreaue709e822021-02-26 21:06:32 +01005511 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005512 }
5513
Willy Tarreaue709e822021-02-26 21:06:32 +01005514 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005515 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005516 srv->ssl_ctx.ctx = NULL;
5517 }
William Lallemand231610a2021-12-30 11:25:43 +01005518
5519 ha_free(&srv->ssl_ctx.ca_file);
5520 ha_free(&srv->ssl_ctx.crl_file);
5521 ha_free(&srv->ssl_ctx.client_crt);
5522 ha_free(&srv->ssl_ctx.verify_host);
5523#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5524 ha_free(&srv->sni_expr);
William Lallemand43c2ce42022-03-16 17:48:19 +01005525 release_sample_expr(srv->ssl_ctx.sni);
5526 srv->ssl_ctx.sni = NULL;
William Lallemand231610a2021-12-30 11:25:43 +01005527#endif
5528 ha_free(&srv->ssl_ctx.ciphers);
5529#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
5530 ha_free(&srv->ssl_ctx.ciphersuites);
5531#endif
William Lallemande69563f2021-12-30 14:45:19 +01005532 /* If there is a certificate we must unlink the ckch instance */
5533 ckch_inst_free(srv->ssl_ctx.inst);
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005534}
5535
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005536/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005537 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5538 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005539void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005540{
5541 struct ebmb_node *node, *back;
5542 struct sni_ctx *sni;
5543
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005544 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005545 while (node) {
5546 sni = ebmb_entry(node, struct sni_ctx, name);
5547 back = ebmb_next(node);
5548 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005549 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005550 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005551 free(sni);
5552 node = back;
5553 }
5554
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005555 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005556 while (node) {
5557 sni = ebmb_entry(node, struct sni_ctx, name);
5558 back = ebmb_next(node);
5559 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005560 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005561 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005562 free(sni);
5563 node = back;
5564 }
William Lallemandb2408692020-06-24 09:54:29 +02005565
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005566 SSL_CTX_free(bind_conf->initial_ctx);
5567 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005568 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005569 bind_conf->default_ctx = NULL;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005570 bind_conf->default_inst = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005571 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005572}
William Lallemandb2408692020-06-24 09:54:29 +02005573
5574
5575void ssl_sock_deinit()
5576{
5577 crtlist_deinit(); /* must be free'd before the ckchs */
5578 ckch_deinit();
5579}
5580REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005581
Willy Tarreau795cdab2016-12-22 17:30:54 +01005582/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5583void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5584{
5585 ssl_sock_free_ca(bind_conf);
5586 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005587 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005588 free(bind_conf->ca_sign_file);
5589 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005590 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005591 free(bind_conf->keys_ref->filename);
5592 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005593 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005594 free(bind_conf->keys_ref);
5595 }
5596 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005597 bind_conf->ca_sign_pass = NULL;
5598 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005599}
5600
Christopher Faulet31af49d2015-06-09 17:29:50 +02005601/* Load CA cert file and private key used to generate certificates */
5602int
Willy Tarreau03209342016-12-22 17:08:28 +01005603ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005604{
Willy Tarreau03209342016-12-22 17:08:28 +01005605 struct proxy *px = bind_conf->frontend;
Shimi Gersner5846c492020-08-23 13:58:12 +03005606 struct cert_key_and_chain *ckch = NULL;
5607 int ret = 0;
5608 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005609
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005610 if (!(bind_conf->options & BC_O_GENERATE_CERTS))
Shimi Gersner5846c492020-08-23 13:58:12 +03005611 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005612
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005613#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005614 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005615 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005616 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005617 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005618 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005619#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005620
Christopher Faulet31af49d2015-06-09 17:29:50 +02005621 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005622 ha_alert("Proxy '%s': cannot enable certificate generation, "
5623 "no CA certificate File configured at [%s:%d].\n",
5624 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005625 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005626 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005627
Shimi Gersner5846c492020-08-23 13:58:12 +03005628 /* Allocate cert structure */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02005629 ckch = calloc(1, sizeof(*ckch));
Shimi Gersner5846c492020-08-23 13:58:12 +03005630 if (!ckch) {
5631 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5632 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5633 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005634 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005635
5636 /* Try to parse file */
5637 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, ckch, &err)) {
5638 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5639 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005640 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005641 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005642 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005643
5644 /* Fail if missing cert or pkey */
5645 if ((!ckch->cert) || (!ckch->key)) {
5646 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5647 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5648 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005649 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005650
Shimi Gersner5846c492020-08-23 13:58:12 +03005651 /* Final assignment to bind */
5652 bind_conf->ca_sign_ckch = ckch;
5653 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005654
Shimi Gersner5846c492020-08-23 13:58:12 +03005655 failed:
5656 if (ckch) {
5657 ssl_sock_free_cert_key_and_chain_contents(ckch);
5658 free(ckch);
5659 }
5660
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005661 bind_conf->options &= ~BC_O_GENERATE_CERTS;
Shimi Gersner5846c492020-08-23 13:58:12 +03005662 ret++;
5663 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005664}
5665
5666/* Release CA cert and private key used to generate certificated */
5667void
5668ssl_sock_free_ca(struct bind_conf *bind_conf)
5669{
Shimi Gersner5846c492020-08-23 13:58:12 +03005670 if (bind_conf->ca_sign_ckch) {
5671 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005672 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005673 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005674}
5675
Emeric Brun46591952012-05-18 15:47:34 +02005676/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005677 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5678 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5679 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5680 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005681 * 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 +01005682 * as parameters to this function.
5683 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5684 * CO_ER_SSL_NO_MEM.
5685 */
5686int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5687 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5688{
5689 int retry = 1;
5690
5691 retry:
5692 /* Alloc a new SSL session. */
5693 *ssl = SSL_new(ssl_ctx);
5694 if (!*ssl) {
5695 if (!retry--)
5696 goto err;
5697
5698 pool_gc(NULL);
5699 goto retry;
5700 }
5701
5702 *bio = BIO_new(bio_meth);
5703 if (!*bio) {
5704 SSL_free(*ssl);
5705 *ssl = NULL;
5706 if (!retry--)
5707 goto err;
5708
5709 pool_gc(NULL);
5710 goto retry;
5711 }
5712
5713 BIO_set_data(*bio, ctx);
5714 SSL_set_bio(*ssl, *bio, *bio);
5715
5716 /* set connection pointer. */
5717 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5718 SSL_free(*ssl);
5719 *ssl = NULL;
5720 if (!retry--)
5721 goto err;
5722
5723 pool_gc(NULL);
5724 goto retry;
5725 }
5726
5727 return 0;
5728
5729 err:
5730 conn->err_code = CO_ER_SSL_NO_MEM;
5731 return -1;
5732}
5733
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005734/* This function is called when all the XPRT have been initialized. We can
5735 * now attempt to start the SSL handshake.
5736 */
5737static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5738{
5739 struct ssl_sock_ctx *ctx = xprt_ctx;
5740
5741 if (ctx->xprt->start) {
5742 int ret;
5743
5744 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5745 if (ret < 0)
5746 return ret;
5747 }
5748 tasklet_wakeup(ctx->wait_event.tasklet);
5749
5750 return 0;
5751}
5752
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005753/*
Emeric Brun46591952012-05-18 15:47:34 +02005754 * This function is called if SSL * context is not yet allocated. The function
5755 * is designed to be called before any other data-layer operation and sets the
5756 * handshake flag on the connection. It is safe to call it multiple times.
5757 * It returns 0 on success and -1 in error case.
5758 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005759static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005760{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005761 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005762 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005763 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005764 return 0;
5765
Olivier Houchard66ab4982019-02-26 18:37:15 +01005766 ctx = pool_alloc(ssl_sock_ctx_pool);
5767 if (!ctx) {
5768 conn->err_code = CO_ER_SSL_NO_MEM;
5769 return -1;
5770 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005771 ctx->wait_event.tasklet = tasklet_new();
5772 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005773 conn->err_code = CO_ER_SSL_NO_MEM;
5774 pool_free(ssl_sock_ctx_pool, ctx);
5775 return -1;
5776 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005777 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5778 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005779 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005780 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005781 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005782 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005783 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005784 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005785 ctx->xprt_st = 0;
5786 ctx->xprt_ctx = NULL;
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005787 ctx->error_code = 0;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005788
5789 /* Only work with sockets for now, this should be adapted when we'll
5790 * add QUIC support.
5791 */
5792 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005793 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005794 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5795 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005796 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005797
Willy Tarreau82531f62021-10-06 12:15:18 +02005798 if (global.maxsslconn && global.sslconns >= global.maxsslconn) {
Willy Tarreau20879a02012-12-03 16:32:10 +01005799 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005800 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005801 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005802
Emeric Brun46591952012-05-18 15:47:34 +02005803 /* If it is in client mode initiate SSL session
5804 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005805 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005806 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5807 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005808 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005809
Olivier Houchard66ab4982019-02-26 18:37:15 +01005810 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005811 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005812 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5813 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5814 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 +01005815 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005816 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005817 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005818 } else if (sess) {
5819 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005820 }
5821 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005822 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005823
Emeric Brun46591952012-05-18 15:47:34 +02005824 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005825 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005826
Willy Tarreau82531f62021-10-06 12:15:18 +02005827 _HA_ATOMIC_INC(&global.sslconns);
5828 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005829 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005830 return 0;
5831 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005832 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005833 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005834
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005835 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5836 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005837 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005838
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005839#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005840 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005841 b_alloc(&ctx->early_buf);
5842 SSL_set_max_early_data(ctx->ssl,
5843 /* Only allow early data if we managed to allocate
5844 * a buffer.
5845 */
5846 (!b_is_null(&ctx->early_buf)) ?
5847 global.tune.bufsize - global.tune.maxrewrite : 0);
5848 }
5849#endif
5850
Olivier Houchard66ab4982019-02-26 18:37:15 +01005851 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005852
Emeric Brun46591952012-05-18 15:47:34 +02005853 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005854 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005855#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005856 if (bc->ssl_conf.early_data)
5857 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005858#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005859
Willy Tarreau82531f62021-10-06 12:15:18 +02005860 _HA_ATOMIC_INC(&global.sslconns);
5861 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005862 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005863 return 0;
5864 }
5865 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005866 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005867err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005868 if (ctx && ctx->wait_event.tasklet)
5869 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005870 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005871 return -1;
5872}
5873
5874
5875/* This is the callback which is used when an SSL handshake is pending. It
5876 * updates the FD status if it wants some polling before being called again.
5877 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5878 * otherwise it returns non-zero and removes itself from the connection's
5879 * flags (the bit is provided in <flag> by the caller).
5880 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005881static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005882{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005883 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Emeric Brun46591952012-05-18 15:47:34 +02005884 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005885 struct ssl_counters *counters = NULL;
5886 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005887 struct listener *li;
5888 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005889 socklen_t lskerr;
5890 int skerr;
5891
Emeric Brun46591952012-05-18 15:47:34 +02005892
Willy Tarreau3c728722014-01-23 13:50:42 +01005893 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005894 return 0;
5895
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005896 /* get counters */
5897 switch (obj_type(conn->target)) {
5898 case OBJ_TYPE_LISTENER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005899 li = __objt_listener(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005900 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5901 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5902 &ssl_stats_module);
5903 break;
5904
5905 case OBJ_TYPE_SERVER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005906 srv = __objt_server(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005907 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5908 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5909 &ssl_stats_module);
5910 break;
5911
5912 default:
5913 break;
5914 }
5915
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005916 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005917 goto out_error;
5918
Willy Tarreau06300382021-02-02 15:42:25 +01005919 /* don't start calculating a handshake on a dead connection */
5920 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5921 goto out_error;
5922
5923 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5924 * status from the lower layers, so let's check the FD directly. Ideally
5925 * the xprt layers should provide some status indicating their knowledge
5926 * of shutdowns or error.
5927 */
Willy Tarreau07ecfc52022-04-11 18:07:03 +02005928 BUG_ON(conn->flags & CO_FL_FDLESS);
5929
Willy Tarreau06300382021-02-02 15:42:25 +01005930 skerr = 0;
5931 lskerr = sizeof(skerr);
5932 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5933 skerr != 0)
5934 goto out_error;
5935
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005936#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005937 /*
5938 * Check if we have early data. If we do, we have to read them
5939 * before SSL_do_handshake() is called, And there's no way to
5940 * detect early data, except to try to read them
5941 */
5942 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005943 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005944
Olivier Houchard54907bb2019-12-19 15:02:39 +01005945 while (1) {
5946 ret = SSL_read_early_data(ctx->ssl,
5947 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5948 &read_data);
5949 if (ret == SSL_READ_EARLY_DATA_ERROR)
5950 goto check_error;
5951 if (read_data > 0) {
5952 conn->flags |= CO_FL_EARLY_DATA;
5953 b_add(&ctx->early_buf, read_data);
5954 }
5955 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5956 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5957 if (!b_data(&ctx->early_buf))
5958 b_free(&ctx->early_buf);
5959 break;
5960 }
5961 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005962 }
5963#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005964 /* If we use SSL_do_handshake to process a reneg initiated by
5965 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5966 * Usually SSL_write and SSL_read are used and process implicitly
5967 * the reneg handshake.
5968 * Here we use SSL_peek as a workaround for reneg.
5969 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005970 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005971 char c;
5972
Olivier Houchard66ab4982019-02-26 18:37:15 +01005973 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005974 if (ret <= 0) {
5975 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005976 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005977
Emeric Brun674b7432012-11-08 19:21:55 +01005978 if (ret == SSL_ERROR_WANT_WRITE) {
5979 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005980 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005981 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005982 return 0;
5983 }
5984 else if (ret == SSL_ERROR_WANT_READ) {
5985 /* handshake may have been completed but we have
5986 * no more data to read.
5987 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005988 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005989 ret = 1;
5990 goto reneg_ok;
5991 }
5992 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005993 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005994 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005995 return 0;
5996 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005997#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005998 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005999 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006000 return 0;
6001 }
6002#endif
Emeric Brun674b7432012-11-08 19:21:55 +01006003 else if (ret == SSL_ERROR_SYSCALL) {
6004 /* if errno is null, then connection was successfully established */
6005 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
6006 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01006007 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02006008#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
6009 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006010 conn->err_code = CO_ER_SSL_HANDSHAKE;
6011#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006012 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02006013#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02006014 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006015 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006016 empty_handshake = state == TLS_ST_BEFORE;
6017#else
Lukas Tribus49799162019-07-08 14:29:15 +02006018 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
6019 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006020#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006021 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02006022 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006023 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006024 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6025 else
6026 conn->err_code = CO_ER_SSL_EMPTY;
6027 }
6028 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006029 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006030 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6031 else
6032 conn->err_code = CO_ER_SSL_ABORT;
6033 }
6034 }
6035 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006036 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006037 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01006038 else
Emeric Brun29f037d2014-04-25 19:05:36 +02006039 conn->err_code = CO_ER_SSL_HANDSHAKE;
6040 }
Lukas Tribus49799162019-07-08 14:29:15 +02006041#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01006042 }
Emeric Brun674b7432012-11-08 19:21:55 +01006043 goto out_error;
6044 }
6045 else {
6046 /* Fail on all other handshake errors */
6047 /* Note: OpenSSL may leave unread bytes in the socket's
6048 * buffer, causing an RST to be emitted upon close() on
6049 * TCP sockets. We first try to drain possibly pending
6050 * data to avoid this as much as possible.
6051 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01006052 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01006053 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006054 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02006055 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01006056 goto out_error;
6057 }
6058 }
6059 /* read some data: consider handshake completed */
6060 goto reneg_ok;
6061 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006062 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006063check_error:
Emeric Brun46591952012-05-18 15:47:34 +02006064 if (ret != 1) {
6065 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006066 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006067
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02006068 if (!ctx->error_code)
6069 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton7c6898e2021-07-29 09:45:51 +02006070
Emeric Brun46591952012-05-18 15:47:34 +02006071 if (ret == SSL_ERROR_WANT_WRITE) {
6072 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02006073 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02006074 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02006075 return 0;
6076 }
6077 else if (ret == SSL_ERROR_WANT_READ) {
6078 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02006079 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02006080 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6081 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02006082 return 0;
6083 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006084#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006085 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006086 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006087 return 0;
6088 }
6089#endif
Willy Tarreau89230192012-09-28 20:22:13 +02006090 else if (ret == SSL_ERROR_SYSCALL) {
6091 /* if errno is null, then connection was successfully established */
6092 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
6093 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006094 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02006095#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
6096 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006097 conn->err_code = CO_ER_SSL_HANDSHAKE;
6098#else
6099 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02006100#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02006101 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006102 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006103 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006104#else
Lukas Tribus49799162019-07-08 14:29:15 +02006105 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
6106 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006107#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006108 if (empty_handshake) {
6109 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006110 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006111 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6112 else
6113 conn->err_code = CO_ER_SSL_EMPTY;
6114 }
6115 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006116 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006117 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6118 else
6119 conn->err_code = CO_ER_SSL_ABORT;
6120 }
Emeric Brun29f037d2014-04-25 19:05:36 +02006121 }
6122 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006123 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006124 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6125 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006126 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02006127 }
Lukas Tribus49799162019-07-08 14:29:15 +02006128#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02006129 }
Willy Tarreau89230192012-09-28 20:22:13 +02006130 goto out_error;
6131 }
Emeric Brun46591952012-05-18 15:47:34 +02006132 else {
6133 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02006134 /* Note: OpenSSL may leave unread bytes in the socket's
6135 * buffer, causing an RST to be emitted upon close() on
6136 * TCP sockets. We first try to drain possibly pending
6137 * data to avoid this as much as possible.
6138 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01006139 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01006140 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006141 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02006142 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006143 goto out_error;
6144 }
6145 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006146#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01006147 else {
6148 /*
6149 * If the server refused the early data, we have to send a
6150 * 425 to the client, as we no longer have the data to sent
6151 * them again.
6152 */
6153 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006154 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006155 conn->err_code = CO_ER_SSL_EARLY_FAILED;
6156 goto out_error;
6157 }
6158 }
6159 }
6160#endif
6161
Emeric Brun46591952012-05-18 15:47:34 +02006162
Emeric Brun674b7432012-11-08 19:21:55 +01006163reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00006164
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006165#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006166 /* ASYNC engine API doesn't support moving read/write
6167 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006168 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00006169 */
6170 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006171 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006172#endif
Emeric Brun46591952012-05-18 15:47:34 +02006173 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006174 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02006175 if (objt_server(conn->target)) {
6176 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
6177 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
6178 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02006179 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02006180 else {
6181 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
6182 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
6183 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
6184 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006185
Willy Tarreau42995282020-11-06 13:19:18 +01006186 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006187 HA_ATOMIC_INC(&counters->sess);
6188 HA_ATOMIC_INC(&counters_px->sess);
Willy Tarreau42995282020-11-06 13:19:18 +01006189 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006190 }
Willy Tarreau42995282020-11-06 13:19:18 +01006191 else if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006192 HA_ATOMIC_INC(&counters->reused_sess);
6193 HA_ATOMIC_INC(&counters_px->reused_sess);
Emeric Brun46591952012-05-18 15:47:34 +02006194 }
6195
6196 /* The connection is now established at both layers, it's time to leave */
6197 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
6198 return 1;
6199
6200 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006201 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006202 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006203 ERR_clear_error();
6204
Emeric Brun9fa89732012-10-04 17:09:56 +02006205 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01006206 if (objt_server(conn->target)) {
6207 struct server *s = __objt_server(conn->target);
6208 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
6209 * one cache per thread, it only prevents to flush it from the CLI in
6210 * another thread */
6211
6212 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01006213 if (s->ssl_ctx.reused_sess[tid].ptr)
6214 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01006215 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02006216 }
6217
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006218 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006219 HA_ATOMIC_INC(&counters->failed_handshake);
6220 HA_ATOMIC_INC(&counters_px->failed_handshake);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006221 }
6222
Emeric Brun46591952012-05-18 15:47:34 +02006223 /* Fail on all other handshake errors */
6224 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01006225 if (!conn->err_code)
6226 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006227 return 0;
6228}
6229
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006230/* Called from the upper layer, to subscribe <es> to events <event_type>. The
6231 * event subscriber <es> is not allowed to change from a previous call as long
6232 * as at least one event is still subscribed. The <event_type> must only be a
6233 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
6234 * unless the transport layer was already released.
6235 */
6236static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006237{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006238 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006239
Olivier Houchard0ff28652019-06-24 18:57:39 +02006240 if (!ctx)
6241 return -1;
6242
Willy Tarreau113d52b2020-01-10 09:20:26 +01006243 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006244 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006245
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006246 ctx->subs = es;
6247 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006248
6249 /* we may have to subscribe to lower layers for new events */
6250 event_type &= ~ctx->wait_event.events;
6251 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
6252 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006253 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006254}
6255
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006256/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
6257 * The <es> pointer is not allowed to differ from the one passed to the
6258 * subscribe() call. It always returns zero.
6259 */
6260static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006261{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006262 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006263
Willy Tarreau113d52b2020-01-10 09:20:26 +01006264 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006265 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006266
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006267 es->events &= ~event_type;
6268 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01006269 ctx->subs = NULL;
6270
6271 /* If we subscribed, and we're not doing the handshake,
6272 * then we subscribed because the upper layer asked for it,
6273 * as the upper layer is no longer interested, we can
6274 * unsubscribe too.
6275 */
6276 event_type &= ctx->wait_event.events;
6277 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
6278 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006279
6280 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006281}
6282
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006283/* The connection has been taken over, so destroy the old tasklet and create
6284 * a new one. The original thread ID must be passed into orig_tid
6285 * It should be called with the takeover lock for the old thread held.
6286 * Returns 0 on success, and -1 on failure
6287 */
6288static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
6289{
6290 struct ssl_sock_ctx *ctx = xprt_ctx;
6291 struct tasklet *tl = tasklet_new();
6292
6293 if (!tl)
6294 return -1;
6295
6296 ctx->wait_event.tasklet->context = NULL;
6297 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
6298 ctx->wait_event.tasklet = tl;
6299 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
6300 ctx->wait_event.tasklet->context = ctx;
6301 return 0;
6302}
6303
Willy Tarreau41491682021-03-02 17:29:56 +01006304/* notify the next xprt that the connection is about to become idle and that it
6305 * may be stolen at any time after the function returns and that any tasklet in
6306 * the chain must be careful before dereferencing its context.
6307 */
6308static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
6309{
6310 struct ssl_sock_ctx *ctx = xprt_ctx;
6311
6312 if (!ctx || !ctx->wait_event.tasklet)
6313 return;
6314
6315 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6316 if (ctx->xprt)
6317 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
6318}
6319
6320/* notify the next xprt that the connection is not idle anymore and that it may
6321 * not be stolen before the next xprt_set_idle().
6322 */
6323static void ssl_set_used(struct connection *conn, void *xprt_ctx)
6324{
6325 struct ssl_sock_ctx *ctx = xprt_ctx;
6326
6327 if (!ctx || !ctx->wait_event.tasklet)
6328 return;
6329
6330 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6331 if (ctx->xprt)
6332 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
6333}
6334
Olivier Houchard2e055482019-05-27 19:50:12 +02006335/* Use the provided XPRT as an underlying XPRT, and provide the old one.
6336 * Returns 0 on success, and non-zero on failure.
6337 */
6338static 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)
6339{
6340 struct ssl_sock_ctx *ctx = xprt_ctx;
6341
6342 if (oldxprt_ops != NULL)
6343 *oldxprt_ops = ctx->xprt;
6344 if (oldxprt_ctx != NULL)
6345 *oldxprt_ctx = ctx->xprt_ctx;
6346 ctx->xprt = toadd_ops;
6347 ctx->xprt_ctx = toadd_ctx;
6348 return 0;
6349}
6350
Olivier Houchard5149b592019-05-23 17:47:36 +02006351/* Remove the specified xprt. If if it our underlying XPRT, remove it and
6352 * return 0, otherwise just call the remove_xprt method from the underlying
6353 * XPRT.
6354 */
6355static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
6356{
6357 struct ssl_sock_ctx *ctx = xprt_ctx;
6358
6359 if (ctx->xprt_ctx == toremove_ctx) {
6360 ctx->xprt_ctx = newctx;
6361 ctx->xprt = newops;
6362 return 0;
6363 }
6364 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
6365}
6366
Willy Tarreau144f84a2021-03-02 16:09:26 +01006367struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02006368{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006369 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006370 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006371 struct connection *conn;
6372 int conn_in_list;
6373 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006374
Willy Tarreau41491682021-03-02 17:29:56 +01006375 if (state & TASK_F_USR1) {
6376 /* the tasklet was idling on an idle connection, it might have
6377 * been stolen, let's be careful!
6378 */
6379 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6380 if (tl->context == NULL) {
6381 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6382 tasklet_free(tl);
6383 return NULL;
6384 }
6385 conn = ctx->conn;
6386 conn_in_list = conn->flags & CO_FL_LIST_MASK;
6387 if (conn_in_list)
6388 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006389 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01006390 } else {
6391 conn = ctx->conn;
6392 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006393 }
Willy Tarreau41491682021-03-02 17:29:56 +01006394
Olivier Houchardea8dd942019-05-20 14:02:16 +02006395 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01006396 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006397 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006398 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
6399 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01006400 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006401 }
6402 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006403 /* If we had an error, or the handshake is done and I/O is available,
6404 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01006405 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02006406 * we can't be sure conn_fd_handler() will be called again.
6407 */
6408 if ((ctx->conn->flags & CO_FL_ERROR) ||
6409 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006410 int woke = 0;
6411
6412 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006413 if (ctx->subs) {
6414 tasklet_wakeup(ctx->subs->tasklet);
6415 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006416 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006417 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006418 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006419
Olivier Houchardea8dd942019-05-20 14:02:16 +02006420 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01006421 * upper layers know. If we have no mux, create it,
6422 * and once we have a mux, call its wake method if we didn't
6423 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02006424 */
6425 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01006426 if (!ctx->conn->mux)
6427 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006428 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006429 ret = ctx->conn->mux->wake(ctx->conn);
6430 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006431 }
6432 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006433#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006434 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006435 else if (b_data(&ctx->early_buf) && ctx->subs &&
6436 ctx->subs->events & SUB_RETRY_RECV) {
6437 tasklet_wakeup(ctx->subs->tasklet);
6438 ctx->subs->events &= ~SUB_RETRY_RECV;
6439 if (!ctx->subs->events)
6440 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01006441 }
6442#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006443leave:
6444 if (!ret && conn_in_list) {
6445 struct server *srv = objt_server(conn->target);
6446
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006447 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006448 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau430bf4a2021-03-04 09:45:32 +01006449 ebmb_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006450 else
Willy Tarreau430bf4a2021-03-04 09:45:32 +01006451 ebmb_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006452 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006453 }
Willy Tarreau74163142021-03-13 11:30:19 +01006454 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006455}
6456
Emeric Brun46591952012-05-18 15:47:34 +02006457/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01006458 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02006459 * buffer wraps, in which case a second call may be performed. The connection's
6460 * flags are updated with whatever special event is detected (error, read0,
6461 * empty). The caller is responsible for taking care of those events and
6462 * avoiding the call if inappropriate. The function does not call the
6463 * connection's polling update function, so the caller is responsible for this.
6464 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006465static 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 +02006466{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006467 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02006468 ssize_t ret;
6469 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02006470
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006471 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006472 goto out_error;
6473
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006474#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006475 if (b_data(&ctx->early_buf)) {
6476 try = b_contig_space(buf);
6477 if (try > b_data(&ctx->early_buf))
6478 try = b_data(&ctx->early_buf);
6479 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
6480 b_add(buf, try);
6481 b_del(&ctx->early_buf, try);
6482 if (b_data(&ctx->early_buf) == 0)
6483 b_free(&ctx->early_buf);
6484 return try;
6485 }
6486#endif
6487
Willy Tarreau911db9b2020-01-23 16:27:54 +01006488 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006489 /* a handshake was requested */
6490 return 0;
6491
Emeric Brun46591952012-05-18 15:47:34 +02006492 /* read the largest possible block. For this, we perform only one call
6493 * to recv() unless the buffer wraps and we exactly fill the first hunk,
6494 * in which case we accept to do it once again. A new attempt is made on
6495 * EINTR too.
6496 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01006497 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006498
Willy Tarreau591d4452018-06-15 17:21:00 +02006499 try = b_contig_space(buf);
6500 if (!try)
6501 break;
6502
Willy Tarreauabf08d92014-01-14 11:31:27 +01006503 if (try > count)
6504 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02006505
Olivier Houchard66ab4982019-02-26 18:37:15 +01006506 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02006507
Emeric Brune1f38db2012-09-03 20:36:47 +02006508 if (conn->flags & CO_FL_ERROR) {
6509 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006510 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006511 }
Emeric Brun46591952012-05-18 15:47:34 +02006512 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006513 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006514 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006515 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006516 }
Emeric Brun46591952012-05-18 15:47:34 +02006517 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006518 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006519 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006520 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006521 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006522 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006523#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006524 /* Async mode can be re-enabled, because we're leaving data state.*/
6525 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006526 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006527#endif
Emeric Brun46591952012-05-18 15:47:34 +02006528 break;
6529 }
6530 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006531 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006532 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6533 SUB_RETRY_RECV,
6534 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006535 /* handshake is running, and it may need to re-enable read */
6536 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006537#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006538 /* Async mode can be re-enabled, because we're leaving data state.*/
6539 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006540 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006541#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006542 break;
6543 }
Emeric Brun46591952012-05-18 15:47:34 +02006544 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006545 } else if (ret == SSL_ERROR_ZERO_RETURN)
6546 goto read0;
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006547 else if (ret == SSL_ERROR_SSL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006548 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6549 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006550 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006551 conn->err_code = CO_ERR_SSL_FATAL;
6552 }
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006553 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6554 * stack before shutting down the connection for
6555 * reading. */
Willy Tarreauacef5e22022-04-25 20:32:15 +02006556 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN || errno == EWOULDBLOCK))
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006557 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006558 /* otherwise it's a real error */
6559 goto out_error;
6560 }
6561 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006562 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006563 return done;
6564
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006565 clear_ssl_error:
6566 /* Clear openssl global errors stack */
6567 ssl_sock_dump_errors(conn);
6568 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006569 read0:
6570 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006571 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006572
Emeric Brun46591952012-05-18 15:47:34 +02006573 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006574 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006575 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006576 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006577 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006578 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006579}
6580
6581
Willy Tarreau787db9a2018-06-14 18:31:46 +02006582/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6583 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6584 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006585 * Only one call to send() is performed, unless the buffer wraps, in which case
6586 * a second call may be performed. The connection's flags are updated with
6587 * whatever special event is detected (error, empty). The caller is responsible
6588 * for taking care of those events and avoiding the call if inappropriate. The
6589 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006590 * is responsible for this. The buffer's output is not adjusted, it's up to the
6591 * caller to take care of this. It's up to the caller to update the buffer's
6592 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006593 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006594static 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 +02006595{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006596 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006597 ssize_t ret;
6598 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006599
6600 done = 0;
6601
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006602 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006603 goto out_error;
6604
Willy Tarreau911db9b2020-01-23 16:27:54 +01006605 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006606 /* a handshake was requested */
6607 return 0;
6608
6609 /* send the largest possible block. For this we perform only one call
6610 * to send() unless the buffer wraps and we exactly fill the first hunk,
6611 * in which case we accept to do it once again.
6612 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006613 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006614#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006615 size_t written_data;
6616#endif
6617
Willy Tarreau787db9a2018-06-14 18:31:46 +02006618 try = b_contig_data(buf, done);
6619 if (try > count)
6620 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006621
Thomas Prückl10243932022-04-27 13:04:54 +02006622 if (global_ssl.hard_max_record && try > global_ssl.hard_max_record)
6623 try = global_ssl.hard_max_record;
6624
Willy Tarreau7bed9452014-02-02 02:00:24 +01006625 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006626 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006627 global_ssl.max_record && try > global_ssl.max_record) {
6628 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006629 }
6630 else {
6631 /* we need to keep the information about the fact that
6632 * we're not limiting the upcoming send(), because if it
6633 * fails, we'll have to retry with at least as many data.
6634 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006635 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006636 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006637
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006638#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006639 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006640 unsigned int max_early;
6641
Olivier Houchard522eea72017-11-03 16:27:47 +01006642 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006643 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006644 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006645 if (SSL_get0_session(ctx->ssl))
6646 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006647 else
6648 max_early = 0;
6649 }
6650
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006651 if (try + ctx->sent_early_data > max_early) {
6652 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006653 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006654 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006655 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006656 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006657 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006658 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006659 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006660 if (ret == 1) {
6661 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006662 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006663 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006664 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006665 /* Initiate the handshake, now */
6666 tasklet_wakeup(ctx->wait_event.tasklet);
6667 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006668
Olivier Houchardc2aae742017-09-22 18:26:28 +02006669 }
6670
6671 } else
6672#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006673 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006674
Emeric Brune1f38db2012-09-03 20:36:47 +02006675 if (conn->flags & CO_FL_ERROR) {
6676 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006677 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006678 }
Emeric Brun46591952012-05-18 15:47:34 +02006679 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006680 /* A send succeeded, so we can consider ourself connected */
6681 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006682 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006683 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006684 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006685 }
6686 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006687 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006688
Emeric Brun46591952012-05-18 15:47:34 +02006689 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006690 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006691 /* handshake is running, and it may need to re-enable write */
6692 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006693 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006694#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006695 /* Async mode can be re-enabled, because we're leaving data state.*/
6696 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006697 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006698#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006699 break;
6700 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006701
Emeric Brun46591952012-05-18 15:47:34 +02006702 break;
6703 }
6704 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006705 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006706 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006707 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6708 SUB_RETRY_RECV,
6709 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006710#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006711 /* Async mode can be re-enabled, because we're leaving data state.*/
6712 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006713 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006714#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006715 break;
6716 }
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006717 else if (ret == SSL_ERROR_SSL || ret == SSL_ERROR_SYSCALL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006718 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6719
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02006720 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006721 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006722 conn->err_code = CO_ERR_SSL_FATAL;
6723 }
Emeric Brun46591952012-05-18 15:47:34 +02006724 goto out_error;
6725 }
6726 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006727 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006728 return done;
6729
6730 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006731 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006732 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006733 ERR_clear_error();
6734
Emeric Brun46591952012-05-18 15:47:34 +02006735 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006736 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006737}
6738
Willy Tarreau832e2422021-05-13 10:11:03 +02006739void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006740
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006741 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006742
Olivier Houchardea8dd942019-05-20 14:02:16 +02006743
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006744 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006745 if (ctx->wait_event.events != 0)
6746 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6747 ctx->wait_event.events,
6748 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006749 if (ctx->subs) {
6750 ctx->subs->events = 0;
6751 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006752 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006753
Olivier Houchard692c1d02019-05-23 18:41:47 +02006754 if (ctx->xprt->close)
6755 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006756#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006757 if (global_ssl.async) {
6758 OSSL_ASYNC_FD all_fd[32], afd;
6759 size_t num_all_fds = 0;
6760 int i;
6761
Olivier Houchard66ab4982019-02-26 18:37:15 +01006762 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006763 if (num_all_fds > 32) {
6764 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6765 return;
6766 }
6767
Olivier Houchard66ab4982019-02-26 18:37:15 +01006768 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006769
6770 /* If an async job is pending, we must try to
6771 to catch the end using polling before calling
6772 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006773 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006774 for (i=0 ; i < num_all_fds ; i++) {
6775 /* switch on an handler designed to
6776 * handle the SSL_free
6777 */
6778 afd = all_fd[i];
6779 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006780 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006781 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006782 /* To ensure that the fd cache won't be used
6783 * and we'll catch a real RD event.
6784 */
6785 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006786 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006787 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006788 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006789 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006790 return;
6791 }
Emeric Brun3854e012017-05-17 20:42:48 +02006792 /* Else we can remove the fds from the fdtab
6793 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006794 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006795 * because the fd is owned by the engine.
6796 * the engine is responsible to close
6797 */
6798 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +02006799 fd_stop_both(all_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006800 }
6801#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006802 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006803 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006804 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006805 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau82531f62021-10-06 12:15:18 +02006806 _HA_ATOMIC_DEC(&global.sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006807 }
Emeric Brun46591952012-05-18 15:47:34 +02006808}
6809
6810/* This function tries to perform a clean shutdown on an SSL connection, and in
6811 * any case, flags the connection as reusable if no handshake was in progress.
6812 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006813static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006814{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006815 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006816
Willy Tarreau911db9b2020-01-23 16:27:54 +01006817 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006818 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006819 if (!clean)
6820 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006821 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006822 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006823 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006824 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006825 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006826 ERR_clear_error();
6827 }
Emeric Brun46591952012-05-18 15:47:34 +02006828}
6829
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006830
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006831/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006832int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6833{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006834 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemandd4f946c2019-12-05 10:26:40 +01006835 X509 *crt;
6836
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006837 if (!ctx)
William Lallemandd4f946c2019-12-05 10:26:40 +01006838 return 0;
William Lallemandd4f946c2019-12-05 10:26:40 +01006839 crt = SSL_get_certificate(ctx->ssl);
6840 if (!crt)
6841 return 0;
6842
6843 return cert_get_pkey_algo(crt, out);
6844}
6845
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006846/* used for ppv2 cert signature (can be used for logging) */
6847const char *ssl_sock_get_cert_sig(struct connection *conn)
6848{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006849 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006850
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006851 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6852 X509 *crt;
6853
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006854 if (!ctx)
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006855 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006856 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006857 if (!crt)
6858 return NULL;
6859 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6860 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6861}
6862
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006863/* used for ppv2 authority */
6864const char *ssl_sock_get_sni(struct connection *conn)
6865{
6866#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006867 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006868
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006869 if (!ctx)
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006870 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006871 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006872#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006873 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006874#endif
6875}
6876
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006877/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006878const char *ssl_sock_get_cipher_name(struct connection *conn)
6879{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006880 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006881
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006882 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006883 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006884 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006885}
6886
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006887/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006888const char *ssl_sock_get_proto_version(struct connection *conn)
6889{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006890 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006891
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006892 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006893 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006894 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006895}
6896
Olivier Houchardab28a322018-12-21 19:45:40 +01006897void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6898{
6899#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006900 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006901
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006902 if (!ctx)
Olivier Houcharde488ea82019-06-28 14:10:33 +02006903 return;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006904 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006905#endif
6906}
6907
Willy Tarreau119a4082016-12-22 21:58:38 +01006908/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6909 * to disable SNI.
6910 */
Willy Tarreau63076412015-07-10 11:33:32 +02006911void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6912{
6913#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006914 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemande18d4e82021-11-17 02:59:21 +01006915 struct server *s;
Willy Tarreau119a4082016-12-22 21:58:38 +01006916 char *prev_name;
6917
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006918 if (!ctx)
Willy Tarreau63076412015-07-10 11:33:32 +02006919 return;
Willy Tarreau77bfa662021-12-23 11:12:13 +01006920
6921 BUG_ON(!(conn->flags & CO_FL_WAIT_L6_CONN));
6922 BUG_ON(!(conn->flags & CO_FL_SSL_WAIT_HS));
6923
William Lallemande18d4e82021-11-17 02:59:21 +01006924 s = __objt_server(conn->target);
Willy Tarreau63076412015-07-10 11:33:32 +02006925
Willy Tarreau119a4082016-12-22 21:58:38 +01006926 /* if the SNI changes, we must destroy the reusable context so that a
William Lallemande18d4e82021-11-17 02:59:21 +01006927 * new connection will present a new SNI. compare with the SNI
6928 * previously stored in the reused_sess */
6929 /* the RWLOCK is used to ensure that we are not trying to flush the
6930 * cache from the CLI */
6931
6932 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
6933 prev_name = s->ssl_ctx.reused_sess[tid].sni;
Willy Tarreau119a4082016-12-22 21:58:38 +01006934 if ((!prev_name && hostname) ||
6935 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006936 SSL_set_session(ctx->ssl, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01006937 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau119a4082016-12-22 21:58:38 +01006938
Olivier Houchard66ab4982019-02-26 18:37:15 +01006939 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006940#endif
6941}
6942
Emeric Brun0abf8362014-06-24 18:26:41 +02006943/* Extract peer certificate's common name into the chunk dest
6944 * Returns
6945 * the len of the extracted common name
6946 * or 0 if no CN found in DN
6947 * or -1 on error case (i.e. no peer certificate)
6948 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006949int ssl_sock_get_remote_common_name(struct connection *conn,
6950 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006951{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006952 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
David Safb76832014-05-08 23:42:08 -04006953 X509 *crt = NULL;
6954 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006955 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006956 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006957 .area = (char *)&find_cn,
6958 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006959 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006960 int result = -1;
David Safb76832014-05-08 23:42:08 -04006961
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006962 if (!ctx)
Emeric Brun0abf8362014-06-24 18:26:41 +02006963 goto out;
David Safb76832014-05-08 23:42:08 -04006964
6965 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006966 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006967 if (!crt)
6968 goto out;
6969
6970 name = X509_get_subject_name(crt);
6971 if (!name)
6972 goto out;
David Safb76832014-05-08 23:42:08 -04006973
Emeric Brun0abf8362014-06-24 18:26:41 +02006974 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6975out:
David Safb76832014-05-08 23:42:08 -04006976 if (crt)
6977 X509_free(crt);
6978
6979 return result;
6980}
6981
Dave McCowan328fb582014-07-30 10:39:13 -04006982/* returns 1 if client passed a certificate for this session, 0 if not */
6983int ssl_sock_get_cert_used_sess(struct connection *conn)
6984{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006985 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dave McCowan328fb582014-07-30 10:39:13 -04006986 X509 *crt = NULL;
6987
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006988 if (!ctx)
Dave McCowan328fb582014-07-30 10:39:13 -04006989 return 0;
6990
6991 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006992 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006993 if (!crt)
6994 return 0;
6995
6996 X509_free(crt);
6997 return 1;
6998}
6999
7000/* returns 1 if client passed a certificate for this connection, 0 if not */
7001int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04007002{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007003 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01007004
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007005 if (!ctx)
David Safb76832014-05-08 23:42:08 -04007006 return 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01007007 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04007008}
7009
7010/* returns result from SSL verify */
7011unsigned int ssl_sock_get_verify_result(struct connection *conn)
7012{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007013 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01007014
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007015 if (!ctx)
David Safb76832014-05-08 23:42:08 -04007016 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Olivier Houchard66ab4982019-02-26 18:37:15 +01007017 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04007018}
7019
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007020/* Returns the application layer protocol name in <str> and <len> when known.
7021 * Zero is returned if the protocol name was not found, otherwise non-zero is
7022 * returned. The string is allocated in the SSL context and doesn't have to be
7023 * freed by the caller. NPN is also checked if available since older versions
7024 * of openssl (1.0.1) which are more common in field only support this one.
7025 */
Amaury Denoyelle71e588c2021-11-12 11:23:29 +01007026int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007027{
Olivier Houchard66ab4982019-02-26 18:37:15 +01007028#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
7029 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01007030 struct ssl_sock_ctx *ctx = xprt_ctx;
7031 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007032 return 0;
7033
7034 *str = NULL;
7035
7036#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01007037 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007038 if (*str)
7039 return 1;
7040#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01007041#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01007042 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007043 if (*str)
7044 return 1;
7045#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01007046#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007047 return 0;
7048}
7049
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007050/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02007051int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007052{
7053 X509 *ca;
7054 X509_NAME *name = NULL;
7055 ASN1_OCTET_STRING *skid = NULL;
7056 STACK_OF(X509) *chain = NULL;
7057 struct issuer_chain *issuer;
7058 struct eb64_node *node;
7059 char *path;
7060 u64 key;
7061 int ret = 0;
7062
7063 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
7064 if (chain == NULL) {
7065 chain = sk_X509_new_null();
7066 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
7067 name = X509_get_subject_name(ca);
7068 }
7069 if (!sk_X509_push(chain, ca)) {
7070 X509_free(ca);
7071 goto end;
7072 }
7073 }
7074 if (!chain) {
7075 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
7076 goto end;
7077 }
7078 if (!skid) {
7079 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
7080 goto end;
7081 }
7082 if (!name) {
7083 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
7084 goto end;
7085 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01007086 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01007087 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007088 issuer = container_of(node, typeof(*issuer), node);
7089 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
7090 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
7091 goto end;
7092 }
7093 }
7094 issuer = calloc(1, sizeof *issuer);
7095 path = strdup(fp);
7096 if (!issuer || !path) {
7097 free(issuer);
7098 free(path);
7099 goto end;
7100 }
7101 issuer->node.key = key;
7102 issuer->path = path;
7103 issuer->chain = chain;
7104 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01007105 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007106 ret = 1;
7107 end:
7108 if (skid)
7109 ASN1_OCTET_STRING_free(skid);
7110 if (chain)
7111 sk_X509_pop_free(chain, X509_free);
7112 return ret;
7113}
7114
William Lallemandda8584c2020-05-14 10:14:37 +02007115 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007116{
7117 AUTHORITY_KEYID *akid;
7118 struct issuer_chain *issuer = NULL;
7119
7120 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01007121 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007122 struct eb64_node *node;
7123 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01007124 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007125 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
7126 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
7127 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
7128 issuer = ti;
7129 break;
7130 }
7131 }
7132 AUTHORITY_KEYID_free(akid);
7133 }
7134 return issuer;
7135}
7136
William Lallemanddad31052020-05-14 17:47:32 +02007137void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007138{
7139 struct eb64_node *node, *back;
7140 struct issuer_chain *issuer;
7141
William Lallemande0f3fd52020-02-25 14:53:06 +01007142 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007143 while (node) {
7144 issuer = container_of(node, typeof(*issuer), node);
7145 back = eb64_next(node);
7146 eb64_delete(node);
7147 free(issuer->path);
7148 sk_X509_pop_free(issuer->chain, X509_free);
7149 free(issuer);
7150 node = back;
7151 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007152}
7153
William Lallemandd7bfbe22022-04-11 18:41:24 +02007154#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007155static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01007156 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007157
Emeric Brun3854e012017-05-17 20:42:48 +02007158 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01007159 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007160 err_code = ERR_ABORT;
7161 }
7162 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01007163}
Willy Tarreau9ceda382016-12-21 23:13:03 +01007164#endif
7165
Willy Tarreaude5675a2021-01-20 14:41:29 +01007166/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007167 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01007168 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01007169static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01007170{
7171 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007172 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007173
7174 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007175 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007176
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007177 if (sctx->conn != conn) {
7178 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
7179 ret = 1;
7180 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01007181 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
7182
7183 if (sctx->xprt) {
7184 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
7185 if (sctx->xprt_ctx)
7186 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
7187 }
7188
7189 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007190
7191 /* as soon as a shutdown is reported the lower layer unregisters its
7192 * subscriber, so the situations below are transient and rare enough to
7193 * be reported as suspicious. In any case they shouldn't last.
7194 */
7195 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
7196 ret = 1;
7197 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
7198 ret = 1;
7199
Willy Tarreaude5675a2021-01-20 14:41:29 +01007200 chunk_appendf(&trash, " .subs=%p", sctx->subs);
7201 if (sctx->subs) {
7202 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007203 if (sctx->subs->tasklet->calls >= 1000000)
7204 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007205 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
7206 sctx->subs->tasklet->calls,
7207 sctx->subs->tasklet->context);
7208 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
7209 chunk_appendf(&trash, ")");
7210 }
7211 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
7212 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007213 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007214}
7215
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007216#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02007217/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007218 * each reference. The variable <ref> must point to the current node's list
7219 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02007220 */
William Lallemand32af2032016-10-29 18:09:35 +02007221static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007222struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02007223{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007224 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007225 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02007226
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007227 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007228 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007229 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02007230
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007231 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02007232}
7233
7234static inline
7235struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
7236{
7237 int id;
7238 char *error;
7239
7240 /* If the reference starts by a '#', this is numeric id. */
7241 if (reference[0] == '#') {
7242 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
7243 id = strtol(reference + 1, &error, 10);
7244 if (*error != '\0')
7245 return NULL;
7246
7247 /* Perform the unique id lookup. */
7248 return tlskeys_ref_lookupid(id);
7249 }
7250
7251 /* Perform the string lookup. */
7252 return tlskeys_ref_lookup(reference);
7253}
7254#endif
7255
7256
7257#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7258
Willy Tarreaua9380522022-05-05 08:50:17 +02007259/* dumps all tls keys. Relies on the show_keys_ctx context from the appctx. */
Willy Tarreaubd338642022-05-05 08:59:17 +02007260static int cli_io_handler_tlskeys_files(struct appctx *appctx)
7261{
Willy Tarreaua9380522022-05-05 08:50:17 +02007262 struct show_keys_ctx *ctx = appctx->svcctx;
William Lallemand32af2032016-10-29 18:09:35 +02007263
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007264 switch (ctx->state) {
7265 case SHOW_KEYS_INIT:
William Lallemand32af2032016-10-29 18:09:35 +02007266 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08007267 * quit the function with returning 0. The function is called
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007268 * later and restart at the state "SHOW_KEYS_INIT".
William Lallemand32af2032016-10-29 18:09:35 +02007269 */
7270 chunk_reset(&trash);
7271
Willy Tarreaubd338642022-05-05 08:59:17 +02007272 if (ctx->dump_entries)
William Lallemand32af2032016-10-29 18:09:35 +02007273 chunk_appendf(&trash, "# id secret\n");
7274 else
7275 chunk_appendf(&trash, "# id (file)\n");
7276
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007277 if (applet_putchk(appctx, &trash) == -1)
William Lallemand32af2032016-10-29 18:09:35 +02007278 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007279
William Lallemand32af2032016-10-29 18:09:35 +02007280 /* Now, we start the browsing of the references lists.
7281 * Note that the following call to LIST_ELEM return bad pointer. The only
7282 * available field of this pointer is <list>. It is used with the function
7283 * tlskeys_list_get_next() for retruning the first available entry
7284 */
Willy Tarreaua9380522022-05-05 08:50:17 +02007285 if (ctx->next_ref == NULL)
7286 ctx->next_ref = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007287
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007288 ctx->state = SHOW_KEYS_LIST;
William Lallemand32af2032016-10-29 18:09:35 +02007289 /* fall through */
7290
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007291 case SHOW_KEYS_LIST:
Willy Tarreaua9380522022-05-05 08:50:17 +02007292 while (ctx->next_ref) {
7293 struct tls_keys_ref *ref = ctx->next_ref;
William Lallemand32af2032016-10-29 18:09:35 +02007294
7295 chunk_reset(&trash);
Willy Tarreaubd338642022-05-05 08:59:17 +02007296 if (ctx->dump_entries && ctx->next_index == 0)
William Lallemand32af2032016-10-29 18:09:35 +02007297 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007298
Willy Tarreaua9380522022-05-05 08:50:17 +02007299 if (ctx->next_index == 0)
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007300 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
7301
Willy Tarreaubd338642022-05-05 08:59:17 +02007302 if (ctx->dump_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01007303 int head;
7304
7305 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
7306 head = ref->tls_ticket_enc_index;
Willy Tarreaua9380522022-05-05 08:50:17 +02007307 while (ctx->next_index < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02007308 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02007309
7310 chunk_reset(t2);
7311 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01007312 if (ref->key_size_bits == 128) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007313 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007314 sizeof(struct tls_sess_key_128),
7315 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007316 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007317 t2->area);
7318 }
7319 else if (ref->key_size_bits == 256) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007320 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007321 sizeof(struct tls_sess_key_256),
7322 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007323 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007324 t2->area);
7325 }
7326 else {
7327 /* This case should never happen */
Willy Tarreaua9380522022-05-05 08:50:17 +02007328 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, ctx->next_index);
Emeric Brun9e754772019-01-10 17:51:55 +01007329 }
William Lallemand32af2032016-10-29 18:09:35 +02007330
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007331 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007332 /* let's try again later from this stream. We add ourselves into
7333 * this stream's users so that it can remove us upon termination.
7334 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01007335 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
William Lallemand32af2032016-10-29 18:09:35 +02007336 return 0;
7337 }
Willy Tarreaua9380522022-05-05 08:50:17 +02007338 ctx->next_index++;
William Lallemand32af2032016-10-29 18:09:35 +02007339 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01007340 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaua9380522022-05-05 08:50:17 +02007341 ctx->next_index = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007342 }
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007343 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007344 /* let's try again later from this stream. We add ourselves into
7345 * this stream's users so that it can remove us upon termination.
7346 */
William Lallemand32af2032016-10-29 18:09:35 +02007347 return 0;
7348 }
7349
Willy Tarreaua9380522022-05-05 08:50:17 +02007350 if (ctx->names_only == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02007351 break;
7352
7353 /* get next list entry and check the end of the list */
Willy Tarreaua9380522022-05-05 08:50:17 +02007354 ctx->next_ref = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007355 }
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007356 ctx->state = SHOW_KEYS_DONE;
William Lallemand32af2032016-10-29 18:09:35 +02007357 /* fall through */
7358
7359 default:
William Lallemand32af2032016-10-29 18:09:35 +02007360 return 1;
7361 }
7362 return 0;
7363}
7364
Willy Tarreaua9380522022-05-05 08:50:17 +02007365/* Prepares a "show_keys_ctx" and sets the appropriate io_handler if needed */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007366static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007367{
Willy Tarreaua9380522022-05-05 08:50:17 +02007368 struct show_keys_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
7369
William Lallemand32af2032016-10-29 18:09:35 +02007370 /* no parameter, shows only file list */
7371 if (!*args[2]) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007372 ctx->names_only = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007373 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007374 }
7375
7376 if (args[2][0] == '*') {
7377 /* list every TLS ticket keys */
Willy Tarreaua9380522022-05-05 08:50:17 +02007378 ctx->names_only = 1;
William Lallemand32af2032016-10-29 18:09:35 +02007379 } else {
Willy Tarreaua9380522022-05-05 08:50:17 +02007380 ctx->next_ref = tlskeys_ref_lookup_ref(args[2]);
7381 if (!ctx->next_ref)
Willy Tarreau9d008692019-08-09 11:21:01 +02007382 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02007383 }
Willy Tarreaubd338642022-05-05 08:59:17 +02007384
7385 ctx->dump_entries = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007386 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007387}
7388
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007389static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007390{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007391 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02007392 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007393
William Lallemand32af2032016-10-29 18:09:35 +02007394 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02007395 if (!*args[3] || !*args[4])
7396 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 +02007397
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007398 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02007399 if (!ref)
7400 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02007401
Willy Tarreau1c913e42018-08-22 05:26:57 +02007402 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02007403 if (ret < 0)
7404 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01007405
Willy Tarreau1c913e42018-08-22 05:26:57 +02007406 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02007407 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
7408 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007409
Willy Tarreau9d008692019-08-09 11:21:01 +02007410 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02007411}
William Lallemandd4f946c2019-12-05 10:26:40 +01007412#endif
William Lallemand419e6342020-04-08 12:05:39 +02007413
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007414static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007415{
7416#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
7417 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02007418 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02007419
7420 if (!payload)
7421 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02007422
7423 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02007424 if (!*payload)
7425 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02007426
7427 /* remove \r and \n from the payload */
7428 for (i = 0, j = 0; payload[i]; i++) {
7429 if (payload[i] == '\r' || payload[i] == '\n')
7430 continue;
7431 payload[j++] = payload[i];
7432 }
7433 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007434
Willy Tarreau1c913e42018-08-22 05:26:57 +02007435 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02007436 if (ret < 0)
7437 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007438
Willy Tarreau1c913e42018-08-22 05:26:57 +02007439 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02007440 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02007441 if (err)
7442 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
7443 else
7444 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007445 }
Willy Tarreau9d008692019-08-09 11:21:01 +02007446
7447 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02007448#else
Willy Tarreau9d008692019-08-09 11:21:01 +02007449 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 +02007450#endif
7451
Elliot Otchet71f82972020-01-15 08:12:14 -05007452}
7453
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007454
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007455#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 +02007456static int cli_io_handler_show_ocspresponse_detail(struct appctx *appctx);
7457#endif
7458
Willy Tarreau170b35b2022-05-05 09:09:15 +02007459/* parsing function for 'show ssl ocsp-response [id]'. If an entry is forced,
7460 * it's set into appctx->svcctx.
7461 */
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007462static int cli_parse_show_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
7463{
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007464#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 +02007465 if (*args[3]) {
7466 struct certificate_ocsp *ocsp = NULL;
7467 char *key = NULL;
7468 int key_length = 0;
7469
7470 if (strlen(args[3]) > OCSP_MAX_CERTID_ASN1_LENGTH*2) {
7471 return cli_err(appctx, "'show ssl ocsp-response' received a too big key.\n");
7472 }
7473
7474 if (parse_binary(args[3], &key, &key_length, NULL)) {
7475
7476 char full_key[OCSP_MAX_CERTID_ASN1_LENGTH] = {};
7477 memcpy(full_key, key, key_length);
7478
7479 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, full_key, OCSP_MAX_CERTID_ASN1_LENGTH);
7480 }
7481 if (key)
7482 ha_free(&key);
7483
7484 if (!ocsp) {
7485 return cli_err(appctx, "Certificate ID does not match any certificate.\n");
7486 }
7487
Willy Tarreau170b35b2022-05-05 09:09:15 +02007488 appctx->svcctx = ocsp;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007489 appctx->io_handler = cli_io_handler_show_ocspresponse_detail;
7490 }
7491
7492 return 0;
7493
7494#else
7495 return cli_err(appctx, "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n");
7496#endif
7497}
7498
7499
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007500#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 +02007501/*
7502 * This function dumps the details of an OCSP_CERTID. It is based on
7503 * ocsp_certid_print in OpenSSL.
7504 */
7505static inline int ocsp_certid_print(BIO *bp, OCSP_CERTID *certid, int indent)
7506{
7507 ASN1_OCTET_STRING *piNameHash = NULL;
7508 ASN1_OCTET_STRING *piKeyHash = NULL;
7509 ASN1_INTEGER *pSerial = NULL;
7510
7511 if (OCSP_id_get0_info(&piNameHash, NULL, &piKeyHash, &pSerial, certid)) {
7512
7513 BIO_printf(bp, "%*sCertificate ID:\n", indent, "");
7514 indent += 2;
Remi Tricot-Le Bretoncc750ef2021-12-17 18:53:23 +01007515 BIO_printf(bp, "%*sIssuer Name Hash: ", indent, "");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007516 i2a_ASN1_STRING(bp, piNameHash, 0);
7517 BIO_printf(bp, "\n%*sIssuer Key Hash: ", indent, "");
7518 i2a_ASN1_STRING(bp, piKeyHash, 0);
7519 BIO_printf(bp, "\n%*sSerial Number: ", indent, "");
7520 i2a_ASN1_INTEGER(bp, pSerial);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007521 }
7522 return 1;
7523}
7524#endif
7525
7526/*
7527 * IO handler of "show ssl ocsp-response". The command taking a specific ID
7528 * is managed in cli_io_handler_show_ocspresponse_detail.
Willy Tarreau170b35b2022-05-05 09:09:15 +02007529 * The current entry is taken from appctx->svcctx.
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007530 */
7531static int cli_io_handler_show_ocspresponse(struct appctx *appctx)
7532{
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007533#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 +02007534 struct buffer *trash = alloc_trash_chunk();
7535 struct buffer *tmp = NULL;
7536 struct ebmb_node *node;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007537 struct certificate_ocsp *ocsp = NULL;
7538 BIO *bio = NULL;
7539 int write = -1;
7540
7541 if (trash == NULL)
7542 return 1;
7543
7544 tmp = alloc_trash_chunk();
7545 if (!tmp)
7546 goto end;
7547
7548 if ((bio = BIO_new(BIO_s_mem())) == NULL)
7549 goto end;
7550
Willy Tarreau170b35b2022-05-05 09:09:15 +02007551 if (!appctx->svcctx) {
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007552 chunk_appendf(trash, "# Certificate IDs\n");
7553 node = ebmb_first(&cert_ocsp_tree);
7554 } else {
Willy Tarreau170b35b2022-05-05 09:09:15 +02007555 node = &((struct certificate_ocsp *)appctx->svcctx)->key;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007556 }
7557
7558 while (node) {
7559 OCSP_CERTID *certid = NULL;
7560 const unsigned char *p = NULL;
7561 int i;
7562
7563 ocsp = ebmb_entry(node, struct certificate_ocsp, key);
7564
7565 /* Dump the key in hexadecimal */
7566 chunk_appendf(trash, "Certificate ID key : ");
7567 for (i = 0; i < ocsp->key_length; ++i) {
7568 chunk_appendf(trash, "%02x", ocsp->key_data[i]);
7569 }
7570 chunk_appendf(trash, "\n");
7571
7572 p = ocsp->key_data;
7573
7574 /* Decode the certificate ID (serialized into the key). */
7575 d2i_OCSP_CERTID(&certid, &p, ocsp->key_length);
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007576 if (!certid)
7577 goto end;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007578
7579 /* Dump the CERTID info */
7580 ocsp_certid_print(bio, certid, 1);
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007581 OCSP_CERTID_free(certid);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007582 write = BIO_read(bio, tmp->area, tmp->size-1);
Remi Tricot-Le Bretoncc750ef2021-12-17 18:53:23 +01007583 /* strip trailing LFs */
7584 while (write > 0 && tmp->area[write-1] == '\n')
7585 write--;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007586 tmp->area[write] = '\0';
7587
7588 chunk_appendf(trash, "%s\n", tmp->area);
7589
7590 node = ebmb_next(node);
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007591 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007592 goto yield;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007593 }
7594
7595end:
Willy Tarreau170b35b2022-05-05 09:09:15 +02007596 appctx->svcctx = NULL;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007597 if (trash)
7598 free_trash_chunk(trash);
7599 if (tmp)
7600 free_trash_chunk(tmp);
7601 if (bio)
7602 BIO_free(bio);
7603 return 1;
7604
7605yield:
7606
7607 if (trash)
7608 free_trash_chunk(trash);
7609 if (tmp)
7610 free_trash_chunk(tmp);
7611 if (bio)
7612 BIO_free(bio);
Willy Tarreau170b35b2022-05-05 09:09:15 +02007613 appctx->svcctx = ocsp;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007614 return 0;
7615#else
7616 return cli_err(appctx, "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n");
7617#endif
7618}
7619
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007620#ifdef HAVE_SSL_PROVIDERS
7621struct provider_name {
7622 const char *name;
7623 struct list list;
7624};
7625
7626
7627static int ssl_provider_get_name_cb(OSSL_PROVIDER *provider, void *cbdata)
7628{
7629 struct list *provider_names = cbdata;
7630 struct provider_name *item = NULL;
7631 const char *name = OSSL_PROVIDER_get0_name(provider);
7632
7633 if (!provider_names)
7634 return 0;
7635
7636 item = calloc(1, sizeof(*item));
7637
7638 if (!item)
7639 return 0;
7640
7641 item->name = name;
7642 LIST_APPEND(provider_names, &item->list);
7643
7644 return 1;
7645}
7646
7647static void ssl_provider_get_name_list(struct list *provider_names)
7648{
7649 if (!provider_names)
7650 return;
7651
7652 OSSL_PROVIDER_do_all(NULL, ssl_provider_get_name_cb, provider_names);
7653}
7654
7655static void ssl_provider_clear_name_list(struct list *provider_names)
7656{
7657 struct provider_name *item = NULL, *item_s = NULL;
7658
7659 if (provider_names) {
7660 list_for_each_entry_safe(item, item_s, provider_names, list) {
7661 LIST_DELETE(&item->list);
7662 free(item);
7663 }
7664 }
7665}
7666
7667static int cli_io_handler_show_providers(struct appctx *appctx)
7668{
7669 struct buffer *trash = get_trash_chunk();
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007670 struct list provider_names;
7671 struct provider_name *name;
7672
7673 LIST_INIT(&provider_names);
7674
7675 chunk_appendf(trash, "Loaded providers : \n");
7676
7677 ssl_provider_get_name_list(&provider_names);
7678
7679 list_for_each_entry(name, &provider_names, list) {
7680 chunk_appendf(trash, "\t- %s\n", name->name);
7681 }
7682
7683 ssl_provider_clear_name_list(&provider_names);
7684
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007685 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007686 goto yield;
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007687
7688 return 1;
7689
7690yield:
7691 return 0;
7692}
7693#endif
7694
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007695
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007696#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 +02007697/*
7698 * Dump the details about an OCSP response in DER format stored in
7699 * <ocsp_response> into buffer <out>.
7700 * Returns 0 in case of success.
7701 */
7702int ssl_ocsp_response_print(struct buffer *ocsp_response, struct buffer *out)
7703{
7704 BIO *bio = NULL;
7705 int write = -1;
7706 OCSP_RESPONSE *resp;
7707 const unsigned char *p;
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01007708 int retval = -1;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007709
7710 if (!ocsp_response)
7711 return -1;
7712
7713 if ((bio = BIO_new(BIO_s_mem())) == NULL)
7714 return -1;
7715
7716 p = (const unsigned char*)ocsp_response->area;
7717
7718 resp = d2i_OCSP_RESPONSE(NULL, &p, ocsp_response->data);
7719 if (!resp) {
7720 chunk_appendf(out, "Unable to parse OCSP response");
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007721 goto end;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007722 }
7723
7724 if (OCSP_RESPONSE_print(bio, resp, 0) != 0) {
Remi Tricot-Le Breton2e7d1eb2022-01-11 10:11:10 +01007725 struct buffer *trash = get_trash_chunk();
7726 struct ist ist_block = IST_NULL;
7727 struct ist ist_double_lf = IST_NULL;
7728 static struct ist double_lf = IST("\n\n");
7729
7730 write = BIO_read(bio, trash->area, trash->size - 1);
Remi Tricot-Le Breton1b01b7f2022-02-16 15:17:09 +01007731 if (write <= 0)
7732 goto end;
Remi Tricot-Le Breton2e7d1eb2022-01-11 10:11:10 +01007733 trash->data = write;
7734
7735 /* Look for empty lines in the 'trash' buffer and add a space to
7736 * the beginning to avoid having empty lines in the output
7737 * (without changing the appearance of the information
7738 * displayed).
7739 */
7740 ist_block = ist2(b_orig(trash), b_data(trash));
7741
7742 ist_double_lf = istist(ist_block, double_lf);
7743
7744 while (istlen(ist_double_lf)) {
7745 /* istptr(ist_double_lf) points to the first \n of a
7746 * \n\n pattern.
7747 */
7748 uint empty_line_offset = istptr(ist_double_lf) + 1 - istptr(ist_block);
7749
7750 /* Write up to the first '\n' of the "\n\n" pattern into
7751 * the output buffer.
7752 */
7753 b_putblk(out, istptr(ist_block), empty_line_offset);
7754 /* Add an extra space. */
7755 b_putchr(out, ' ');
7756
7757 /* Keep looking for empty lines in the rest of the data. */
7758 ist_block = istadv(ist_block, empty_line_offset);
7759
7760 ist_double_lf = istist(ist_block, double_lf);
7761 }
7762
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01007763 retval = (b_istput(out, ist_block) <= 0);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007764 }
7765
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007766end:
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007767 if (bio)
7768 BIO_free(bio);
7769
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007770 OCSP_RESPONSE_free(resp);
7771
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01007772 return retval;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007773}
7774
7775/*
7776 * Dump the details of the OCSP response of ID <ocsp_certid> into buffer <out>.
7777 * Returns 0 in case of success.
7778 */
7779int ssl_get_ocspresponse_detail(unsigned char *ocsp_certid, struct buffer *out)
7780{
7781 struct certificate_ocsp *ocsp;
7782
7783 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, ocsp_certid, OCSP_MAX_CERTID_ASN1_LENGTH);
7784 if (!ocsp)
7785 return -1;
7786
7787 return ssl_ocsp_response_print(&ocsp->response, out);
7788}
7789
7790
Willy Tarreau170b35b2022-05-05 09:09:15 +02007791/* IO handler of details "show ssl ocsp-response <id>".
7792 * The current entry is taken from appctx->svcctx.
7793 */
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007794static int cli_io_handler_show_ocspresponse_detail(struct appctx *appctx)
7795{
7796 struct buffer *trash = alloc_trash_chunk();
Willy Tarreau170b35b2022-05-05 09:09:15 +02007797 struct certificate_ocsp *ocsp = appctx->svcctx;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007798
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007799 if (trash == NULL)
7800 return 1;
7801
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01007802 if (ssl_ocsp_response_print(&ocsp->response, trash)) {
7803 free_trash_chunk(trash);
7804 return 1;
7805 }
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007806
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007807 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007808 goto yield;
Willy Tarreau170b35b2022-05-05 09:09:15 +02007809
7810 appctx->svcctx = NULL;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007811 if (trash)
7812 free_trash_chunk(trash);
7813 return 1;
7814
7815yield:
7816 if (trash)
7817 free_trash_chunk(trash);
7818
7819 return 0;
7820}
7821#endif
7822
William Lallemand32af2032016-10-29 18:09:35 +02007823/* register cli keywords */
7824static struct cli_kw_list cli_kws = {{ },{
7825#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Willy Tarreaubd338642022-05-05 08:59:17 +02007826 { { "show", "tls-keys", NULL }, "show tls-keys [id|*] : show tls keys references or dump tls ticket keys when id specified", cli_parse_show_tlskeys, cli_io_handler_tlskeys_files },
Willy Tarreaub205bfd2021-05-07 11:38:37 +02007827 { { "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 +02007828#endif
Willy Tarreaub205bfd2021-05-07 11:38:37 +02007829 { { "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 +02007830
7831 { { "show", "ssl", "ocsp-response", NULL },"show ssl ocsp-response [id] : display the IDs of the OCSP responses used in memory, or the details of a single OCSP response", cli_parse_show_ocspresponse, cli_io_handler_show_ocspresponse, NULL },
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007832#ifdef HAVE_SSL_PROVIDERS
7833 { { "show", "ssl", "providers", NULL }, "show ssl providers : show loaded SSL providers", NULL, cli_io_handler_show_providers },
7834#endif
William Lallemand32af2032016-10-29 18:09:35 +02007835 { { NULL }, NULL, NULL, NULL }
7836}};
7837
Willy Tarreau0108d902018-11-25 19:14:37 +01007838INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02007839
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02007840/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02007841struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02007842 .snd_buf = ssl_sock_from_buf,
7843 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01007844 .subscribe = ssl_subscribe,
7845 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02007846 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02007847 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02007848 .rcv_pipe = NULL,
7849 .snd_pipe = NULL,
7850 .shutr = NULL,
7851 .shutw = ssl_sock_shutw,
7852 .close = ssl_sock_close,
7853 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01007854 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01007855 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01007856 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01007857 .prepare_srv = ssl_sock_prepare_srv_ctx,
7858 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007859 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02007860 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01007861 .set_idle = ssl_set_idle,
7862 .set_used = ssl_set_used,
Willy Tarreaude827952022-04-11 10:43:28 +02007863 .get_ssl_sock_ctx = ssl_sock_get_ctx,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01007864 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01007865 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02007866};
7867
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007868enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
7869 struct session *sess, struct stream *s, int flags)
7870{
7871 struct connection *conn;
7872
7873 conn = objt_conn(sess->origin);
7874
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007875 if (conn) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007876 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007877 sc_ep_set(s->scf, SE_FL_WAIT_FOR_HS);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007878 s->req.flags |= CF_READ_NULL;
7879 return ACT_RET_YIELD;
7880 }
7881 }
7882 return (ACT_RET_CONT);
7883}
7884
7885static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
7886{
7887 rule->action_ptr = ssl_action_wait_for_hs;
7888
7889 return ACT_RET_PRS_OK;
7890}
7891
7892static struct action_kw_list http_req_actions = {ILH, {
7893 { "wait-for-handshake", ssl_parse_wait_for_hs },
7894 { /* END */ }
7895}};
7896
Willy Tarreau0108d902018-11-25 19:14:37 +01007897INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
7898
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007899#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007900
7901static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7902{
7903 if (ptr) {
7904 chunk_destroy(ptr);
7905 free(ptr);
7906 }
7907}
7908
7909#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007910
7911#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7912static void ssl_sock_ocsp_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7913{
7914 struct ocsp_cbk_arg *ocsp_arg;
7915
7916 if (ptr) {
7917 ocsp_arg = ptr;
7918
7919 if (ocsp_arg->is_single) {
7920 ssl_sock_free_ocsp(ocsp_arg->s_ocsp);
7921 ocsp_arg->s_ocsp = NULL;
7922 } else {
7923 int i;
7924
7925 for (i = 0; i < SSL_SOCK_NUM_KEYTYPES; i++) {
7926 ssl_sock_free_ocsp(ocsp_arg->m_ocsp[i]);
7927 ocsp_arg->m_ocsp[i] = NULL;
7928 }
7929 }
7930 free(ocsp_arg);
7931 }
7932}
7933#endif
7934
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007935static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7936{
Willy Tarreaubafbe012017-11-24 17:34:44 +01007937 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007938}
William Lallemand7d42ef52020-07-06 11:41:30 +02007939
William Lallemand722180a2021-06-09 16:46:12 +02007940#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007941static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7942{
7943 struct ssl_keylog *keylog;
7944
7945 if (!ptr)
7946 return;
7947
7948 keylog = ptr;
7949
7950 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7951 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7952 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7953 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7954 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7955 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7956 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7957 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7958
7959 pool_free(pool_head_ssl_keylog, ptr);
7960}
7961#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007962
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007963static void ssl_sock_clt_crt_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7964{
7965 if (!ptr)
7966 return;
7967
7968 X509_free((X509*)ptr);
7969}
7970
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01007971static void ssl_sock_clt_sni_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7972{
7973 pool_free(ssl_sock_client_sni_pool, ptr);
7974}
7975
Willy Tarreau92faadf2012-10-10 23:04:25 +02007976static void __ssl_sock_init(void)
7977{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007978#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007979 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007980 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007981#endif
Emeric Brun46591952012-05-18 15:47:34 +02007982
Willy Tarreauef934602016-12-22 23:12:01 +01007983 if (global_ssl.listen_default_ciphers)
7984 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7985 if (global_ssl.connect_default_ciphers)
7986 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007987#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007988 if (global_ssl.listen_default_ciphersuites)
7989 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7990 if (global_ssl.connect_default_ciphersuites)
7991 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7992#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007993
Willy Tarreau13e14102016-12-22 20:25:26 +01007994 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007995#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007996 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007997#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007998#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007999 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05008000 n = sk_SSL_COMP_num(cm);
8001 while (n--) {
8002 (void) sk_SSL_COMP_pop(cm);
8003 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05008004#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05008005
Willy Tarreau5db847a2019-05-09 14:13:35 +02008006#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02008007 ssl_locking_init();
8008#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05008009#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01008010 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
8011#endif
William Lallemand76b4a122020-08-04 17:41:39 +02008012
8013#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
8014 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
8015#endif
8016
Thierry FOURNIER28962c92018-06-17 21:37:05 +02008017 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02008018 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 +01008019#ifdef USE_QUIC
8020 ssl_qc_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
8021#endif /* USE_QUIC */
William Lallemand722180a2021-06-09 16:46:12 +02008022#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02008023 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
8024#endif
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02008025 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 +01008026 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 +02008027#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00008028 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00008029 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02008030#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01008031#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
8032 hap_register_post_check(tlskeys_finalize_config);
8033#endif
Willy Tarreau80713382018-11-26 10:19:54 +01008034
8035 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
8036 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
8037
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01008038 hap_register_post_deinit(ssl_free_global_issuers);
8039
Willy Tarreau80713382018-11-26 10:19:54 +01008040#ifndef OPENSSL_NO_DH
8041 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
8042 hap_register_post_deinit(ssl_free_dh);
8043#endif
William Lallemandd7bfbe22022-04-11 18:41:24 +02008044#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Willy Tarreau80713382018-11-26 10:19:54 +01008045 hap_register_post_deinit(ssl_free_engines);
8046#endif
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02008047#ifdef HAVE_SSL_PROVIDERS
8048 hap_register_post_deinit(ssl_unload_providers);
8049#endif
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01008050#if HA_OPENSSL_VERSION_NUMBER < 0x3000000fL
Willy Tarreau80713382018-11-26 10:19:54 +01008051 /* Load SSL string for the verbose & debug mode. */
8052 ERR_load_SSL_strings();
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01008053#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02008054 ha_meth = BIO_meth_new(0x666, "ha methods");
8055 BIO_meth_set_write(ha_meth, ha_ssl_write);
8056 BIO_meth_set_read(ha_meth, ha_ssl_read);
8057 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
8058 BIO_meth_set_create(ha_meth, ha_ssl_new);
8059 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
8060 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
8061 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02008062
8063 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02008064
Dragan Dosen9ac98092020-05-11 15:51:45 +02008065 /* Try to register dedicated SSL/TLS protocol message callbacks for
8066 * heartbleed attack (CVE-2014-0160) and clienthello.
8067 */
8068 hap_register_post_check(ssl_sock_register_msg_callbacks);
8069
Dragan Dosen1e7ed042020-05-08 18:30:00 +02008070 /* Try to free all callbacks that were registered by using
8071 * ssl_sock_register_msg_callback().
8072 */
8073 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01008074}
Willy Tarreau79367f92022-04-25 19:18:24 +02008075INITCALL0(STG_REGISTER, __ssl_sock_init);
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01008076
Willy Tarreau80713382018-11-26 10:19:54 +01008077/* Compute and register the version string */
8078static void ssl_register_build_options()
8079{
8080 char *ptr = NULL;
8081 int i;
8082
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008083 memprintf(&ptr, "Built with OpenSSL version : "
8084#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01008085 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008086#else /* OPENSSL_IS_BORINGSSL */
8087 OPENSSL_VERSION_TEXT
8088 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08008089 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02008090 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008091#endif
8092 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02008093#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008094 "no (library version too old)"
8095#elif defined(OPENSSL_NO_TLSEXT)
8096 "no (disabled via OPENSSL_NO_TLSEXT)"
8097#else
8098 "yes"
8099#endif
8100 "", ptr);
8101
8102 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
8103#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
8104 "yes"
8105#else
8106#ifdef OPENSSL_NO_TLSEXT
8107 "no (because of OPENSSL_NO_TLSEXT)"
8108#else
8109 "no (version might be too old, 0.9.8f min needed)"
8110#endif
8111#endif
8112 "", ptr);
8113
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02008114 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
8115 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
8116 if (methodVersions[i].option)
8117 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01008118
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02008119#ifdef HAVE_SSL_PROVIDERS
8120 {
8121 struct list provider_names;
8122 struct provider_name *name;
8123 LIST_INIT(&provider_names);
8124 ssl_provider_get_name_list(&provider_names);
8125
8126 memprintf(&ptr, "%s\nOpenSSL providers loaded :", ptr);
8127
8128 list_for_each_entry(name, &provider_names, list) {
8129 memprintf(&ptr, "%s %s", ptr, name->name);
8130 }
8131
8132 ssl_provider_clear_name_list(&provider_names);
8133 }
8134#endif
8135
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008136 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01008137}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008138
Willy Tarreau80713382018-11-26 10:19:54 +01008139INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02008140
William Lallemandd7bfbe22022-04-11 18:41:24 +02008141#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00008142void ssl_free_engines(void) {
8143 struct ssl_engine_list *wl, *wlb;
8144 /* free up engine list */
8145 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
8146 ENGINE_finish(wl->e);
8147 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02008148 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00008149 free(wl);
8150 }
8151}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02008152#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02008153
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02008154#ifdef HAVE_SSL_PROVIDERS
8155void ssl_unload_providers(void) {
8156 struct ssl_provider_list *prov, *provb;
8157 list_for_each_entry_safe(prov, provb, &openssl_providers, list) {
8158 OSSL_PROVIDER_unload(prov->provider);
8159 LIST_DELETE(&prov->list);
8160 free(prov);
8161 }
8162}
8163#endif
8164
Remi Gacogned3a23c32015-05-28 16:39:47 +02008165#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00008166void ssl_free_dh(void) {
8167 if (local_dh_1024) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008168 HASSL_DH_free(local_dh_1024);
Grant Zhang872f9c22017-01-21 01:10:18 +00008169 local_dh_1024 = NULL;
8170 }
8171 if (local_dh_2048) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008172 HASSL_DH_free(local_dh_2048);
Grant Zhang872f9c22017-01-21 01:10:18 +00008173 local_dh_2048 = NULL;
8174 }
8175 if (local_dh_4096) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008176 HASSL_DH_free(local_dh_4096);
Grant Zhang872f9c22017-01-21 01:10:18 +00008177 local_dh_4096 = NULL;
8178 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02008179 if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008180 HASSL_DH_free(global_dh);
Remi Gacogne47783ef2015-05-29 15:53:22 +02008181 global_dh = NULL;
8182 }
Grant Zhang872f9c22017-01-21 01:10:18 +00008183}
8184#endif
8185
Grant Zhang872f9c22017-01-21 01:10:18 +00008186static void __ssl_sock_deinit(void)
8187{
8188#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02008189 if (ssl_ctx_lru_tree) {
8190 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01008191 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02008192 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02008193#endif
8194
Willy Tarreau5db847a2019-05-09 14:13:35 +02008195#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02008196 ERR_remove_state(0);
8197 ERR_free_strings();
8198
8199 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08008200#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02008201
Willy Tarreau5db847a2019-05-09 14:13:35 +02008202#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02008203 CRYPTO_cleanup_all_ex_data();
8204#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02008205 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02008206}
Willy Tarreau79367f92022-04-25 19:18:24 +02008207REGISTER_POST_DEINIT(__ssl_sock_deinit);
Remi Gacogned3a23c32015-05-28 16:39:47 +02008208
William Dauchyf6370442020-11-14 19:25:33 +01008209
Emeric Brun46591952012-05-18 15:47:34 +02008210/*
8211 * Local variables:
8212 * c-indent-level: 8
8213 * c-basic-offset: 8
8214 * End:
8215 */