blob: 01c5bc910ff961eb756bfa3a51e6b2864b939296 [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écaille301425b2022-06-14 17:40:39 +02002624 extension_data + extension_len) ||
2625 !qc_conn_finalize(qc, 0))
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002626 goto abort;
2627 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002628#endif /* USE_QUIC */
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002629
Olivier Houchard9679ac92017-10-27 14:58:08 +02002630 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002631 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002632#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002633 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2634 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002635#else
2636 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2637#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002638 /*
2639 * The server_name extension was given too much extensibility when it
2640 * was written, so parsing the normal case is a bit complex.
2641 */
2642 size_t len;
2643 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002644 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002645 /* Extract the length of the supplied list of names. */
2646 len = (*extension_data++) << 8;
2647 len |= *extension_data++;
2648 if (len + 2 != extension_len)
2649 goto abort;
2650 /*
2651 * The list in practice only has a single element, so we only consider
2652 * the first one.
2653 */
2654 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2655 goto abort;
2656 extension_len = len - 1;
2657 /* Now we can finally pull out the byte array with the actual hostname. */
2658 if (extension_len <= 2)
2659 goto abort;
2660 len = (*extension_data++) << 8;
2661 len |= *extension_data++;
2662 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2663 || memchr(extension_data, 0, len) != NULL)
2664 goto abort;
2665 servername = extension_data;
2666 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002667 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002668#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002669 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002670 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002671 }
2672#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002673 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002674 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002675 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002676 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002677 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002678 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002679 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002680 goto abort;
2681 }
2682
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002683 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002684#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002685 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002686#else
2687 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2688#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002689 uint8_t sign;
2690 size_t len;
2691 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002692 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002693 len = (*extension_data++) << 8;
2694 len |= *extension_data++;
2695 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002696 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002697 if (len % 2 != 0)
2698 goto abort;
2699 for (; len > 0; len -= 2) {
2700 extension_data++; /* hash */
2701 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002702 switch (sign) {
2703 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002704 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002705 break;
2706 case TLSEXT_signature_ecdsa:
2707 has_ecdsa_sig = 1;
2708 break;
2709 default:
2710 continue;
2711 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002712 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002713 break;
2714 }
2715 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002716 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002717 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002718 }
2719 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002720 const SSL_CIPHER *cipher;
2721 size_t len;
2722 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002723 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002724#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002725 len = ctx->cipher_suites_len;
2726 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002727#else
2728 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2729#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002730 if (len % 2 != 0)
2731 goto abort;
2732 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002733#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002734 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002735 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002736#else
2737 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2738#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002739 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002740 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002741 break;
2742 }
2743 }
2744 }
2745
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002746 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002747 trash.area[i] = tolower(servername[i]);
2748 if (!wildp && (trash.area[i] == '.'))
2749 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002750 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002751 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002752
William Lallemand150bfa82019-09-19 17:12:49 +02002753 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002754
William Lallemand94bd3192020-08-14 14:43:35 +02002755 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2756 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002757 for (i = 0; i < 2; i++) {
2758 if (i == 0) /* lookup in full qualified names */
2759 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002760 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002761 node = ebst_lookup(&s->sni_w_ctx, wildp);
2762 else
2763 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002764
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002765 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002766
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002767 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002768 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002769 struct sni_ctx *sni, *sni_tmp;
2770 int skip = 0;
2771
2772 if (i == 1 && wildp) { /* wildcard */
2773 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2774 sni = container_of(n, struct sni_ctx, name);
2775 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002776 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002777 skip = 1;
2778 break;
2779 }
2780 }
2781 if (skip)
2782 continue;
2783 }
2784
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002785 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002786 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002787 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002788 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002789 break;
2790 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002791 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002792 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002793 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002794 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002795 if (!node_anonymous)
2796 node_anonymous = n;
2797 break;
2798 }
2799 }
2800 }
William Lallemand94bd3192020-08-14 14:43:35 +02002801 }
2802 /* Once the certificates are found, select them depending on what is
2803 * supported in the client and by key_signature priority order: EDSA >
2804 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002805 if (has_ecdsa_sig && node_ecdsa)
2806 node = node_ecdsa;
2807 else if (has_rsa_sig && node_rsa)
2808 node = node_rsa;
2809 else if (node_anonymous)
2810 node = node_anonymous;
2811 else if (node_ecdsa)
2812 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2813 else
2814 node = node_rsa; /* no rsa signature case (far far away) */
2815
William Lallemand94bd3192020-08-14 14:43:35 +02002816 if (node) {
2817 /* switch ctx */
2818 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2819 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2820 if (conf) {
2821 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2822 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2823 if (conf->early_data)
2824 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002825 }
William Lallemand94bd3192020-08-14 14:43:35 +02002826 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2827 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002828 }
William Lallemand150bfa82019-09-19 17:12:49 +02002829
William Lallemand02010472019-10-18 11:02:19 +02002830 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002831#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002832 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002833 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002834 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002835 }
2836#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002837 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002838 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002839 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002840 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002841 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
William Lallemand7980dff2021-11-18 17:46:26 +01002842 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002843 }
William Lallemand7980dff2021-11-18 17:46:26 +01002844
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01002845 /* We are about to raise an handshake error so the servername extension
2846 * callback will never be called and the SNI will never be stored in the
2847 * SSL context. In order for the ssl_fc_sni sample fetch to still work
2848 * in such a case, we store the SNI ourselves as an ex_data information
2849 * in the SSL context.
2850 */
2851 {
2852 char *client_sni = pool_alloc(ssl_sock_client_sni_pool);
2853 if (client_sni) {
2854 strncpy(client_sni, trash.area, TLSEXT_MAXLEN_host_name);
2855 client_sni[TLSEXT_MAXLEN_host_name] = '\0';
2856 SSL_set_ex_data(ssl, ssl_client_sni_index, client_sni);
2857 }
2858 }
2859
William Lallemand7980dff2021-11-18 17:46:26 +01002860 /* other cases fallback on abort, if strict-sni is set but no node was found */
2861
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002862 abort:
2863 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002864 if (conn)
2865 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002866#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002867 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002868#else
2869 *al = SSL_AD_UNRECOGNIZED_NAME;
2870 return 0;
2871#endif
William Lallemand7980dff2021-11-18 17:46:26 +01002872
2873allow_early:
2874#ifdef OPENSSL_IS_BORINGSSL
2875 if (allow_early)
2876 SSL_set_early_data_enabled(ssl, 1);
2877#else
2878 if (!allow_early)
2879 SSL_set_max_early_data(ssl, 0);
2880#endif
2881 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002882}
2883
William Lallemand002e2062021-11-18 15:25:16 +01002884#else /* ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002885
Emeric Brunfc0421f2012-09-07 17:30:07 +02002886/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2887 * warning when no match is found, which implies the default (first) cert
2888 * will keep being used.
2889 */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002890static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002891{
2892 const char *servername;
2893 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002894 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002895 struct bind_conf *s = priv;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002896 int i;
2897 (void)al; /* shut gcc stupid warning */
2898
2899 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002900 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002901#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002902 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate_from_conn(s, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002903 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002904#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002905 if (s->strict_sni)
2906 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002907 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002908 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002909 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002910 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002911 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002912
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002913 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002914 if (!servername[i])
2915 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002916 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002917 if (!wildp && (trash.area[i] == '.'))
2918 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002919 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002920 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002921
William Lallemand150bfa82019-09-19 17:12:49 +02002922 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002923 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002924 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002925 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2926 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002927 if (!container_of(n, struct sni_ctx, name)->neg) {
2928 node = n;
2929 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002930 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002931 }
2932 if (!node && wildp) {
2933 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002934 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2935 /* lookup a not neg filter */
2936 if (!container_of(n, struct sni_ctx, name)->neg) {
2937 node = n;
2938 break;
2939 }
2940 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002941 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002942 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002943#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02002944 if (s->options & BC_O_GENERATE_CERTS && ssl_sock_generate_certificate(servername, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002945 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002946 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002947 return SSL_TLSEXT_ERR_OK;
2948 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002949#endif
William Lallemand21724f02019-11-04 17:56:13 +01002950 if (s->strict_sni) {
2951 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002952 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002953 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002954 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002955 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002956 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002957 }
2958
2959 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002960 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002961 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002962 return SSL_TLSEXT_ERR_OK;
2963}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002964#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002965#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2966
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002967#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002968
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002969static inline HASSL_DH *ssl_new_dh_fromdata(BIGNUM *p, BIGNUM *g)
2970{
2971#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2972 OSSL_PARAM_BLD *tmpl = NULL;
2973 OSSL_PARAM *params = NULL;
2974 EVP_PKEY_CTX *ctx = NULL;
2975 EVP_PKEY *pkey = NULL;
2976
2977 if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
2978 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
2979 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)
2980 || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
2981 goto end;
2982 }
2983 ctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2984 if (ctx == NULL
2985 || !EVP_PKEY_fromdata_init(ctx)
2986 || !EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params)) {
2987 goto end;
2988 }
2989
2990end:
2991 EVP_PKEY_CTX_free(ctx);
2992 OSSL_PARAM_free(params);
2993 OSSL_PARAM_BLD_free(tmpl);
2994 return pkey;
2995#else
2996
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002997 HASSL_DH *dh = DH_new();
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002998
2999 if (!dh)
3000 return NULL;
3001
3002 DH_set0_pqg(dh, p, NULL, g);
3003
3004 return dh;
3005#endif
3006}
3007
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02003008#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003009static inline HASSL_DH *ssl_get_dh_by_nid(int nid)
3010{
3011#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3012 OSSL_PARAM params[2];
3013 EVP_PKEY *pkey = NULL;
3014 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
3015 const char *named_group = NULL;
3016
3017 if (!pctx)
3018 goto end;
3019
3020 named_group = OBJ_nid2ln(nid);
3021
3022 if (!named_group)
3023 goto end;
3024
3025 params[0] = OSSL_PARAM_construct_utf8_string("group", (char*)named_group, 0);
3026 params[1] = OSSL_PARAM_construct_end();
3027
3028 if (EVP_PKEY_keygen_init(pctx) && EVP_PKEY_CTX_set_params(pctx, params))
3029 EVP_PKEY_generate(pctx, &pkey);
3030
3031end:
3032 EVP_PKEY_CTX_free(pctx);
3033 return pkey;
3034#else
3035
3036 HASSL_DH *dh = NULL;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003037 dh = DH_new_by_nid(nid);
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003038 return dh;
3039#endif
3040}
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02003041#endif
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003042
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01003043
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003044static HASSL_DH * ssl_get_dh_1024(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003045{
Remi Gacogned3a341a2015-05-29 16:26:17 +02003046 static unsigned char dh1024_p[]={
3047 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
3048 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
3049 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
3050 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
3051 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
3052 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
3053 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
3054 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
3055 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
3056 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
3057 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
3058 };
3059 static unsigned char dh1024_g[]={
3060 0x02,
3061 };
3062
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003063 BIGNUM *p;
3064 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02003065
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003066 HASSL_DH *dh = NULL;
3067
3068 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
3069 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
3070
3071 if (p && g)
3072 dh = ssl_new_dh_fromdata(p, g);
3073
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003074 return dh;
3075}
3076
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003077static HASSL_DH *ssl_get_dh_2048(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003078{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003079#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02003080 static unsigned char dh2048_p[]={
3081 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
3082 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
3083 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
3084 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
3085 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
3086 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
3087 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
3088 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
3089 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
3090 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
3091 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
3092 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
3093 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
3094 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
3095 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
3096 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
3097 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
3098 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
3099 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
3100 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
3101 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
3102 0xB7,0x1F,0x77,0xF3,
3103 };
3104 static unsigned char dh2048_g[]={
3105 0x02,
3106 };
3107
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003108 BIGNUM *p;
3109 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02003110
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003111 HASSL_DH *dh = NULL;
3112
3113 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
3114 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
3115
3116 if (p && g)
3117 dh = ssl_new_dh_fromdata(p, g);
3118
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003119 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003120#else
3121 return ssl_get_dh_by_nid(NID_ffdhe2048);
3122#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003123}
3124
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003125static HASSL_DH *ssl_get_dh_4096(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003126{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003127#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02003128 static unsigned char dh4096_p[]={
3129 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
3130 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
3131 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
3132 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
3133 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
3134 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
3135 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
3136 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
3137 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
3138 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
3139 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
3140 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
3141 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
3142 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
3143 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
3144 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
3145 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
3146 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
3147 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
3148 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
3149 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
3150 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
3151 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
3152 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
3153 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
3154 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
3155 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
3156 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
3157 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
3158 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
3159 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
3160 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
3161 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
3162 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
3163 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
3164 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
3165 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
3166 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
3167 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
3168 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
3169 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
3170 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
3171 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003172 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02003173 static unsigned char dh4096_g[]={
3174 0x02,
3175 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003176
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003177 BIGNUM *p;
3178 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02003179
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003180 HASSL_DH *dh = NULL;
3181
3182 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
3183 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
3184
3185 if (p && g)
3186 dh = ssl_new_dh_fromdata(p, g);
3187
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003188 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003189#else
3190 return ssl_get_dh_by_nid(NID_ffdhe4096);
3191#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003192}
3193
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003194static HASSL_DH *ssl_get_tmp_dh(EVP_PKEY *pkey)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003195{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003196 HASSL_DH *dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003197 int type;
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003198 int keylen = 0;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003199
3200 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003201
3202 /* The keylen supplied by OpenSSL can only be 512 or 1024.
3203 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
3204 */
3205 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
3206 keylen = EVP_PKEY_bits(pkey);
3207 }
3208
Willy Tarreauef934602016-12-22 23:12:01 +01003209 if (keylen > global_ssl.default_dh_param) {
3210 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003211 }
3212
Remi Gacogned3a341a2015-05-29 16:26:17 +02003213 if (keylen >= 4096) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003214 if (!local_dh_4096)
3215 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02003216 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003217 }
3218 else if (keylen >= 2048) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003219 if (!local_dh_2048)
3220 local_dh_2048 = ssl_get_dh_2048();
Remi Gacogne8de54152014-07-15 11:36:40 +02003221 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003222 }
3223 else {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003224 if (!local_dh_1024)
3225 local_dh_1024 = ssl_get_dh_1024();
Remi Gacogne8de54152014-07-15 11:36:40 +02003226 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003227 }
3228
3229 return dh;
3230}
3231
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003232#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003233/* Returns Diffie-Hellman parameters matching the private key length
3234 but not exceeding global_ssl.default_dh_param */
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003235static HASSL_DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003236{
3237 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
3238
3239 return ssl_get_tmp_dh(pkey);
3240}
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003241#endif
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003242
Remi Tricot-Le Breton846eda92022-02-11 12:04:50 +01003243static int ssl_sock_set_tmp_dh(SSL_CTX *ctx, HASSL_DH *dh)
3244{
3245#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
3246 return SSL_CTX_set_tmp_dh(ctx, dh);
3247#else
3248 int retval = 0;
3249 HASSL_DH_up_ref(dh);
3250
3251 retval = SSL_CTX_set0_tmp_dh_pkey(ctx, dh);
3252
3253 if (!retval)
3254 HASSL_DH_free(dh);
3255
3256 return retval;
3257#endif
3258}
3259
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003260#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3261static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey)
3262{
3263 HASSL_DH *dh = NULL;
3264 if (pkey && (dh = ssl_get_tmp_dh(pkey))) {
3265 HASSL_DH_up_ref(dh);
3266 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dh))
3267 HASSL_DH_free(dh);
3268 }
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003269}
3270#endif
3271
Remi Tricot-Le Breton09ebb332022-02-11 12:04:48 +01003272HASSL_DH *ssl_sock_get_dh_from_bio(BIO *bio)
3273{
3274#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3275 HASSL_DH *dh = NULL;
3276 OSSL_DECODER_CTX *dctx = NULL;
3277 const char *format = "PEM";
3278 const char *keytype = "DH";
3279
3280 dctx = OSSL_DECODER_CTX_new_for_pkey(&dh, format, NULL, keytype,
3281 OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
3282 NULL, NULL);
3283
3284 if (dctx == NULL || OSSL_DECODER_CTX_get_num_decoders(dctx) == 0)
3285 goto end;
3286
3287 /* The DH parameters might not be the first section found in the PEM
3288 * file so we need to iterate over all of them until we find the right
3289 * one.
3290 */
3291 while (!BIO_eof(bio) && !dh)
3292 OSSL_DECODER_from_bio(dctx, bio);
3293
3294end:
3295 OSSL_DECODER_CTX_free(dctx);
3296 return dh;
3297#else
3298 HASSL_DH *dh = NULL;
3299
3300 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3301
3302 return dh;
3303#endif
3304}
3305
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003306static HASSL_DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003307{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003308 HASSL_DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02003309 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003310
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003311 if (in == NULL)
3312 goto end;
3313
Remi Gacogne47783ef2015-05-29 15:53:22 +02003314 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003315 goto end;
3316
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003317 dh = ssl_sock_get_dh_from_bio(in);
Remi Gacogne47783ef2015-05-29 15:53:22 +02003318
3319end:
3320 if (in)
3321 BIO_free(in);
3322
Emeric Brune1b4ed42018-08-16 15:14:12 +02003323 ERR_clear_error();
3324
Remi Gacogne47783ef2015-05-29 15:53:22 +02003325 return dh;
3326}
3327
3328int ssl_sock_load_global_dh_param_from_file(const char *filename)
3329{
3330 global_dh = ssl_sock_get_dh_from_file(filename);
3331
3332 if (global_dh) {
3333 return 0;
3334 }
3335
3336 return -1;
3337}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003338#endif
3339
William Lallemand9117de92019-10-04 00:29:42 +02003340/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02003341static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02003342 struct bind_conf *s, struct ssl_bind_conf *conf,
3343 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003344{
3345 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003346 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003347
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003348 if (*name == '!') {
3349 neg = 1;
3350 name++;
3351 }
3352 if (*name == '*') {
3353 wild = 1;
3354 name++;
3355 }
3356 /* !* filter is a nop */
3357 if (neg && wild)
3358 return order;
3359 if (*name) {
3360 int j, len;
3361 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003362 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02003363 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003364 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02003365 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003366 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003367
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003368 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02003369 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02003370 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003371 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02003372 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003373 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003374 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003375 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003376 sc->order = order++;
3377 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02003378 sc->wild = wild;
3379 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01003380 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02003381 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003382 }
3383 return order;
3384}
3385
William Lallemand6af03992019-07-23 15:00:54 +02003386/*
William Lallemand1d29c742019-10-04 00:53:29 +02003387 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
3388 * This function can't return an error.
3389 *
3390 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
3391 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003392void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02003393{
3394
3395 struct sni_ctx *sc0, *sc0b, *sc1;
3396 struct ebmb_node *node;
3397
3398 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
3399
3400 /* ignore if sc0 was already inserted in a tree */
3401 if (sc0->name.node.leaf_p)
3402 continue;
3403
3404 /* Check for duplicates. */
3405 if (sc0->wild)
3406 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
3407 else
3408 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
3409
3410 for (; node; node = ebmb_next_dup(node)) {
3411 sc1 = ebmb_entry(node, struct sni_ctx, name);
3412 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
3413 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
3414 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02003415 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02003416 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003417 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02003418 break;
William Lallemand1d29c742019-10-04 00:53:29 +02003419 }
3420 }
3421
3422 /* if duplicate, ignore the insertion */
3423 if (!sc0)
3424 continue;
3425
3426 if (sc0->wild)
3427 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
3428 else
3429 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003430 }
William Lallemand21724f02019-11-04 17:56:13 +01003431
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003432 /* replace the default_ctx if required with the instance's ctx. */
3433 if (ckch_inst->is_default) {
3434 SSL_CTX_free(bind_conf->default_ctx);
3435 SSL_CTX_up_ref(ckch_inst->ctx);
3436 bind_conf->default_ctx = ckch_inst->ctx;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003437 bind_conf->default_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02003438 }
3439}
3440
3441/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003442 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02003443 */
William Lallemande3af8fb2019-10-08 11:36:53 +02003444struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02003445
William Lallemand2954c472020-03-06 21:54:13 +01003446/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02003447struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02003448
Emeric Brun7a883362019-10-17 13:27:40 +02003449/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003450 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02003451 * DH parameter is loaded into the SSL_CTX and if there is no
3452 * DH parameter available in ckchs nor in global, the default
3453 * DH parameters are applied on the SSL_CTX.
3454 * Returns a bitfield containing the flags:
3455 * ERR_FATAL in any fatal error case
3456 * ERR_ALERT if a reason of the error is availabine in err
3457 * ERR_WARN if a warning is available into err
3458 * The value 0 means there is no error nor warning and
3459 * the operation succeed.
3460 */
William Lallemandfa892222019-07-23 16:06:08 +02003461#ifndef OPENSSL_NO_DH
Emeric Brun7a883362019-10-17 13:27:40 +02003462static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct cert_key_and_chain *ckch,
3463 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02003464{
Emeric Brun7a883362019-10-17 13:27:40 +02003465 int ret = 0;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003466 HASSL_DH *dh = NULL;
William Lallemandfa892222019-07-23 16:06:08 +02003467
William Lallemanda8c73742019-07-31 18:31:34 +02003468 if (ckch && ckch->dh) {
William Lallemandfa892222019-07-23 16:06:08 +02003469 dh = ckch->dh;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003470 if (!ssl_sock_set_tmp_dh(ctx, dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003471 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
3472 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003473 memprintf(err, "%s, DH ciphers won't be available.\n",
3474 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003475 ret |= ERR_WARN;
3476 goto end;
3477 }
William Lallemandfa892222019-07-23 16:06:08 +02003478
3479 if (ssl_dh_ptr_index >= 0) {
3480 /* store a pointer to the DH params to avoid complaining about
3481 ssl-default-dh-param not being set for this SSL_CTX */
3482 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
3483 }
3484 }
3485 else if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003486 if (!ssl_sock_set_tmp_dh(ctx, global_dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003487 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
3488 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003489 memprintf(err, "%s, DH ciphers won't be available.\n",
3490 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003491 ret |= ERR_WARN;
3492 goto end;
3493 }
William Lallemandfa892222019-07-23 16:06:08 +02003494 }
3495 else {
3496 /* Clear openssl global errors stack */
3497 ERR_clear_error();
3498
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003499 /* We do not want DHE ciphers to be added to the cipher list
3500 * unless there is an explicit global dh option in the conf.
3501 */
3502 if (global_ssl.default_dh_param) {
3503 if (global_ssl.default_dh_param <= 1024) {
3504 /* we are limited to DH parameter of 1024 bits anyway */
3505 if (local_dh_1024 == NULL)
3506 local_dh_1024 = ssl_get_dh_1024();
William Lallemandfa892222019-07-23 16:06:08 +02003507
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003508 if (local_dh_1024 == NULL) {
3509 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3510 err && *err ? *err : "", path);
3511 ret |= ERR_ALERT | ERR_FATAL;
3512 goto end;
3513 }
William Lallemandfa892222019-07-23 16:06:08 +02003514
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003515 if (!ssl_sock_set_tmp_dh(ctx, local_dh_1024)) {
3516 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3517 err && *err ? *err : "", path);
3518 memprintf(err, "%s, DH ciphers won't be available.\n",
3519 err && *err ? *err : "");
3520 ret |= ERR_WARN;
3521 goto end;
3522 }
Emeric Bruna9363eb2019-10-17 14:53:03 +02003523 }
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003524 else {
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003525#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003526 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003527#else
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003528 ssl_sock_set_tmp_dh_from_pkey(ctx, ckch ? ckch->key : NULL);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003529#endif
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003530 }
William Lallemandfa892222019-07-23 16:06:08 +02003531 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003532 }
3533
William Lallemandf9568fc2019-10-16 18:27:58 +02003534end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003535 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003536 return ret;
3537}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003538#endif
William Lallemandfa892222019-07-23 16:06:08 +02003539
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003540
3541/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003542 * Returns a bitfield containing the flags:
3543 * ERR_FATAL in any fatal error case
3544 * ERR_ALERT if the reason of the error is available in err
3545 * ERR_WARN if a warning is available into err
3546 * The value 0 means there is no error nor warning and
3547 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003548 */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003549static int ssl_sock_load_cert_chain(const char *path, const struct cert_key_and_chain *ckch,
3550 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003551{
Emeric Bruna96b5822019-10-17 13:25:14 +02003552 int errcode = 0;
3553
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003554 if (find_chain == NULL) {
3555 errcode |= ERR_FATAL;
3556 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003557 }
3558
3559 if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
3560 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
3561 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003562 errcode |= ERR_ALERT | ERR_FATAL;
3563 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003564 }
3565
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003566 if (ckch->chain) {
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003567 *find_chain = ckch->chain;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003568 } else {
3569 /* Find Certificate Chain in global */
3570 struct issuer_chain *issuer;
Emmanuel Hocdetef87e0a2020-03-23 11:29:11 +01003571 issuer = ssl_get0_issuer_chain(ckch->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003572 if (issuer)
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003573 *find_chain = issuer->chain;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003574 }
William Lallemand85888572020-02-27 14:48:35 +01003575
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003576 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003577 /* always put a null chain stack in the SSL_CTX so it does not
3578 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003579 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003580 }
3581
William Lallemandf187ce62020-06-02 18:27:20 +02003582 /* Load all certs in the ckch into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003583#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003584 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand935d8292020-08-12 20:02:10 +02003585 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'. Make sure you are linking against Openssl >= 1.0.2.\n",
3586 err && *err ? *err : "", path);
3587 errcode |= ERR_ALERT | ERR_FATAL;
3588 goto end;
3589 }
William Lallemandf187ce62020-06-02 18:27:20 +02003590#else
3591 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003592 X509 *ca;
William Lallemandf187ce62020-06-02 18:27:20 +02003593 STACK_OF(X509) *chain;
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003594 chain = X509_chain_up_ref(*find_chain);
William Lallemandf187ce62020-06-02 18:27:20 +02003595 while ((ca = sk_X509_shift(chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003596 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003597 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3598 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003599 X509_free(ca);
3600 sk_X509_pop_free(chain, X509_free);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003601 errcode |= ERR_ALERT | ERR_FATAL;
3602 goto end;
3603 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003604 }
William Lallemandf187ce62020-06-02 18:27:20 +02003605#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003606
William Lallemand9a1d8392020-08-10 17:28:23 +02003607#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003608 /* remove the Root CA from the SSL_CTX if the option is activated */
3609 if (global_ssl.skip_self_issued_ca) {
3610 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3611 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3612 err && *err ? *err : "", path);
3613 errcode |= ERR_ALERT | ERR_FATAL;
3614 goto end;
3615 }
3616 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003617#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003618
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003619end:
3620 return errcode;
3621}
3622
3623
3624/* Loads the info in ckch into ctx
3625 * Returns a bitfield containing the flags:
3626 * ERR_FATAL in any fatal error case
3627 * ERR_ALERT if the reason of the error is available in err
3628 * ERR_WARN if a warning is available into err
3629 * The value 0 means there is no error nor warning and
3630 * the operation succeed.
3631 */
3632static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
3633{
3634 int errcode = 0;
3635 STACK_OF(X509) *find_chain = NULL;
3636
3637 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3638 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3639 err && *err ? *err : "", path);
3640 errcode |= ERR_ALERT | ERR_FATAL;
3641 return errcode;
3642 }
3643
3644 /* Load certificate chain */
3645 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3646 if (errcode & ERR_CODE)
3647 goto end;
3648
William Lallemandfa892222019-07-23 16:06:08 +02003649#ifndef OPENSSL_NO_DH
3650 /* store a NULL pointer to indicate we have not yet loaded
3651 a custom DH param file */
3652 if (ssl_dh_ptr_index >= 0) {
3653 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3654 }
3655
Emeric Brun7a883362019-10-17 13:27:40 +02003656 errcode |= ssl_sock_load_dh_params(ctx, ckch, path, err);
3657 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003658 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3659 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003660 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003661 }
3662#endif
3663
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003664#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemanda17f4112019-10-10 15:16:44 +02003665 if (sctl_ex_index >= 0 && ckch->sctl) {
3666 if (ssl_sock_load_sctl(ctx, ckch->sctl) < 0) {
3667 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003668 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003669 errcode |= ERR_ALERT | ERR_FATAL;
3670 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003671 }
3672 }
3673#endif
3674
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003675#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
William Lallemand246c0242019-10-11 08:59:13 +02003676 /* Load OCSP Info into context */
3677 if (ckch->ocsp_response) {
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01003678 if (ssl_sock_load_ocsp(ctx, ckch, find_chain) < 0) {
Tim Duesterhus93128532019-11-23 23:45:10 +01003679 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",
3680 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003681 errcode |= ERR_ALERT | ERR_FATAL;
3682 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003683 }
3684 }
William Lallemand246c0242019-10-11 08:59:13 +02003685#endif
3686
Emeric Bruna96b5822019-10-17 13:25:14 +02003687 end:
3688 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003689}
3690
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003691
3692/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
3693 * Returns a bitfield containing the flags:
3694 * ERR_FATAL in any fatal error case
3695 * ERR_ALERT if the reason of the error is available in err
3696 * ERR_WARN if a warning is available into err
3697 * The value 0 means there is no error nor warning and
3698 * the operation succeed.
3699 */
3700static int ssl_sock_put_srv_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch,
3701 SSL_CTX *ctx, char **err)
3702{
3703 int errcode = 0;
3704 STACK_OF(X509) *find_chain = NULL;
3705
3706 /* Load the private key */
3707 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3708 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3709 err && *err ? *err : "", path);
3710 errcode |= ERR_ALERT | ERR_FATAL;
3711 }
3712
3713 /* Load certificate chain */
3714 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3715 if (errcode & ERR_CODE)
3716 goto end;
3717
3718 if (SSL_CTX_check_private_key(ctx) <= 0) {
3719 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3720 err && *err ? *err : "", path);
3721 errcode |= ERR_ALERT | ERR_FATAL;
3722 }
3723
3724end:
3725 return errcode;
3726}
3727
3728
William Lallemand614ca0d2019-10-07 13:52:11 +02003729/*
3730 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003731 *
3732 * Returns a bitfield containing the flags:
3733 * ERR_FATAL in any fatal error case
3734 * ERR_ALERT if the reason of the error is available in err
3735 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003736 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003737int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003738 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003739{
William Lallemandc9402072019-05-15 15:33:54 +02003740 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003741 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003742 int order = 0;
3743 X509_NAME *xname;
3744 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003745 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003746 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003747#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3748 STACK_OF(GENERAL_NAME) *names;
3749#endif
William Lallemand36b84632019-07-18 19:28:17 +02003750 struct cert_key_and_chain *ckch;
William Lallemand614ca0d2019-10-07 13:52:11 +02003751 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003752 int errcode = 0;
3753
3754 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003755
William Lallemande3af8fb2019-10-08 11:36:53 +02003756 if (!ckchs || !ckchs->ckch)
Emeric Brun054563d2019-10-17 13:16:58 +02003757 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003758
William Lallemande3af8fb2019-10-08 11:36:53 +02003759 ckch = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003760
William Lallemandc9402072019-05-15 15:33:54 +02003761 ctx = SSL_CTX_new(SSLv23_server_method());
3762 if (!ctx) {
3763 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3764 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003765 errcode |= ERR_ALERT | ERR_FATAL;
3766 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003767 }
3768
Emeric Bruna96b5822019-10-17 13:25:14 +02003769 errcode |= ssl_sock_put_ckch_into_ctx(path, ckch, ctx, err);
3770 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003771 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003772
3773 ckch_inst = ckch_inst_new();
3774 if (!ckch_inst) {
3775 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3776 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003777 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003778 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003779 }
3780
William Lallemand36b84632019-07-18 19:28:17 +02003781 pkey = X509_get_pubkey(ckch->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003782 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003783 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003784 switch(EVP_PKEY_base_id(pkey)) {
3785 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003786 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003787 break;
3788 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003789 kinfo.sig = TLSEXT_signature_ecdsa;
3790 break;
3791 case EVP_PKEY_DSA:
3792 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003793 break;
3794 }
3795 EVP_PKEY_free(pkey);
3796 }
3797
Emeric Brun50bcecc2013-04-22 13:05:23 +02003798 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003799 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003800 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 +02003801 if (order < 0) {
3802 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003803 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003804 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003805 }
3806 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003807 }
3808 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003809#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand36b84632019-07-18 19:28:17 +02003810 names = X509_get_ext_d2i(ckch->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003811 if (names) {
3812 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3813 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3814 if (name->type == GEN_DNS) {
3815 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003816 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003817 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003818 if (order < 0) {
3819 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003820 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003821 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003822 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003823 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003824 }
3825 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003826 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003827 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003828#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand36b84632019-07-18 19:28:17 +02003829 xname = X509_get_subject_name(ckch->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003830 i = -1;
3831 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3832 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003833 ASN1_STRING *value;
3834
3835 value = X509_NAME_ENTRY_get_data(entry);
3836 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003837 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003838 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003839 if (order < 0) {
3840 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003841 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003842 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003843 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003844 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003845 }
3846 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003847 /* we must not free the SSL_CTX anymore below, since it's already in
3848 * the tree, so it will be discovered and cleaned in time.
3849 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003850
Emeric Brunfc0421f2012-09-07 17:30:07 +02003851#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003852 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003853 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3854 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003855 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003856 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003857 }
3858#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003859 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003860 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003861 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003862 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003863 SSL_CTX_up_ref(ctx);
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003864 bind_conf->default_inst = ckch_inst;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003865 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003866
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003867 /* Always keep a reference to the newly constructed SSL_CTX in the
3868 * instance. This way if the instance has no SNIs, the SSL_CTX will
3869 * still be linked. */
3870 SSL_CTX_up_ref(ctx);
3871 ckch_inst->ctx = ctx;
3872
William Lallemand9117de92019-10-04 00:29:42 +02003873 /* everything succeed, the ckch instance can be used */
3874 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003875 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003876 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003877
William Lallemand02e19a52020-04-08 16:11:26 +02003878 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3879
Emeric Brun054563d2019-10-17 13:16:58 +02003880 *ckchi = ckch_inst;
3881 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003882
3883error:
3884 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003885 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003886 if (ckch_inst->is_default)
3887 SSL_CTX_free(ctx);
3888
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003889 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003890 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003891 }
William Lallemandd9199372019-10-04 15:37:05 +02003892 SSL_CTX_free(ctx);
3893
Emeric Brun054563d2019-10-17 13:16:58 +02003894 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003895}
3896
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003897
3898/*
3899 * This function allocate a ckch_inst that will be used on the backend side
3900 * (server line)
3901 *
3902 * Returns a bitfield containing the flags:
3903 * ERR_FATAL in any fatal error case
3904 * ERR_ALERT if the reason of the error is available in err
3905 * ERR_WARN if a warning is available into err
3906 */
3907int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01003908 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003909{
3910 SSL_CTX *ctx;
3911 struct cert_key_and_chain *ckch;
3912 struct ckch_inst *ckch_inst = NULL;
3913 int errcode = 0;
3914
3915 *ckchi = NULL;
3916
3917 if (!ckchs || !ckchs->ckch)
3918 return ERR_FATAL;
3919
3920 ckch = ckchs->ckch;
3921
3922 ctx = SSL_CTX_new(SSLv23_client_method());
3923 if (!ctx) {
3924 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3925 err && *err ? *err : "", path);
3926 errcode |= ERR_ALERT | ERR_FATAL;
3927 goto error;
3928 }
3929
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003930 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, ckch, ctx, err);
3931 if (errcode & ERR_CODE)
3932 goto error;
3933
3934 ckch_inst = ckch_inst_new();
3935 if (!ckch_inst) {
3936 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3937 err && *err ? *err : "", path);
3938 errcode |= ERR_ALERT | ERR_FATAL;
3939 goto error;
3940 }
3941
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003942 /* everything succeed, the ckch instance can be used */
3943 ckch_inst->bind_conf = NULL;
3944 ckch_inst->ssl_conf = NULL;
3945 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01003946 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003947 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003948
3949 *ckchi = ckch_inst;
3950 return errcode;
3951
3952error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003953 SSL_CTX_free(ctx);
3954
3955 return errcode;
3956}
3957
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003958/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003959static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3960 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003961 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003962{
Emeric Brun054563d2019-10-17 13:16:58 +02003963 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003964
3965 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003966 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 +02003967
Emeric Brun054563d2019-10-17 13:16:58 +02003968 if (errcode & ERR_CODE)
3969 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003970
William Lallemand24bde432020-03-09 16:48:43 +01003971 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003972
3973 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003974 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003975 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003976}
3977
William Lallemanddb26e2b2021-01-26 12:01:46 +01003978/* This function generates a <struct ckch_inst *> for a <struct server *>, and
3979 * fill the SSL_CTX of the server.
3980 *
3981 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003982static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01003983 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003984{
3985 int errcode = 0;
3986
3987 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01003988 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003989
3990 if (errcode & ERR_CODE)
3991 return errcode;
3992
William Lallemanddb26e2b2021-01-26 12:01:46 +01003993 (*ckch_inst)->server = server;
3994 /* Keep the reference to the SSL_CTX in the server. */
3995 SSL_CTX_up_ref((*ckch_inst)->ctx);
3996 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003997 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003998 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003999 return errcode;
4000}
4001
William Lallemand6be66ec2020-03-06 22:26:32 +01004002
William Lallemand4c68bba2020-03-30 18:45:10 +02004003
4004
4005/* Make sure openssl opens /dev/urandom before the chroot. The work is only
4006 * done once. Zero is returned if the operation fails. No error is returned
4007 * if the random is said as not implemented, because we expect that openssl
4008 * will use another method once needed.
4009 */
Amaury Denoyellec593bcd2021-05-19 15:35:29 +02004010int ssl_initialize_random(void)
William Lallemand4c68bba2020-03-30 18:45:10 +02004011{
4012 unsigned char random;
4013 static int random_initialized = 0;
4014
4015 if (!random_initialized && RAND_bytes(&random, 1) != 0)
4016 random_initialized = 1;
4017
4018 return random_initialized;
4019}
4020
William Lallemand2954c472020-03-06 21:54:13 +01004021/* Load a crt-list file, this is done in 2 parts:
4022 * - store the content of the file in a crtlist structure with crtlist_entry structures
4023 * - generate the instances by iterating on entries in the crtlist struct
4024 *
4025 * Nothing is locked there, this function is used in the configuration parser.
4026 *
4027 * Returns a set of ERR_* flags possibly with an error in <err>.
4028 */
William Lallemand6be66ec2020-03-06 22:26:32 +01004029int 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 +01004030{
4031 struct crtlist *crtlist = NULL;
4032 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02004033 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01004034 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01004035 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02004036 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01004037
William Lallemand79d31ec2020-03-25 15:10:49 +01004038 bind_conf_node = malloc(sizeof(*bind_conf_node));
4039 if (!bind_conf_node) {
4040 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
4041 cfgerr |= ERR_FATAL | ERR_ALERT;
4042 goto error;
4043 }
4044 bind_conf_node->next = NULL;
4045 bind_conf_node->bind_conf = bind_conf;
4046
William Lallemand41ca9302020-04-08 13:15:18 +02004047 /* strip trailing slashes, including first one */
4048 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
4049 *end = 0;
4050
William Lallemand2954c472020-03-06 21:54:13 +01004051 /* look for an existing crtlist or create one */
4052 eb = ebst_lookup(&crtlists_tree, file);
4053 if (eb) {
4054 crtlist = ebmb_entry(eb, struct crtlist, node);
4055 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01004056 /* load a crt-list OR a directory */
4057 if (dir)
4058 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
4059 else
4060 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
4061
William Lallemand2954c472020-03-06 21:54:13 +01004062 if (!(cfgerr & ERR_CODE))
4063 ebst_insert(&crtlists_tree, &crtlist->node);
4064 }
4065
4066 if (cfgerr & ERR_CODE) {
4067 cfgerr |= ERR_FATAL | ERR_ALERT;
4068 goto error;
4069 }
4070
4071 /* generates ckch instance from the crtlist_entry */
4072 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
4073 struct ckch_store *store;
4074 struct ckch_inst *ckch_inst = NULL;
4075
4076 store = entry->node.key;
4077 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
4078 if (cfgerr & ERR_CODE) {
4079 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
4080 goto error;
4081 }
Willy Tarreau2b718102021-04-21 07:32:39 +02004082 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02004083 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01004084 }
William Lallemand2954c472020-03-06 21:54:13 +01004085
William Lallemand79d31ec2020-03-25 15:10:49 +01004086 /* add the bind_conf to the list */
4087 bind_conf_node->next = crtlist->bind_conf;
4088 crtlist->bind_conf = bind_conf_node;
4089
William Lallemand2954c472020-03-06 21:54:13 +01004090 return cfgerr;
4091error:
4092 {
William Lallemand49398312020-03-30 17:01:33 +02004093 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01004094 struct ckch_inst *inst, *s_inst;
4095
William Lallemand49398312020-03-30 17:01:33 +02004096 lastentry = entry; /* which entry we tried to generate last */
4097 if (lastentry) {
4098 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
4099 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
4100 break;
4101
4102 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01004103
William Lallemand49398312020-03-30 17:01:33 +02004104 /* this was not generated for this bind_conf, skip */
4105 if (inst->bind_conf != bind_conf)
4106 continue;
4107
William Lallemandd9d5d1b2020-04-09 16:31:05 +02004108 /* free the sni_ctx and instance */
4109 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02004110 }
William Lallemand2954c472020-03-06 21:54:13 +01004111 }
William Lallemand2954c472020-03-06 21:54:13 +01004112 }
William Lallemand79d31ec2020-03-25 15:10:49 +01004113 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01004114 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01004115 return cfgerr;
4116}
4117
William Lallemand06b22a82020-03-16 14:45:55 +01004118/* Returns a set of ERR_* flags possibly with an error in <err>. */
4119int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
4120{
4121 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01004122 int cfgerr = 0;
4123 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01004124 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01004125 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01004126
4127 if ((ckchs = ckchs_lookup(path))) {
4128 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01004129 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
4130 found++;
4131 } else if (stat(path, &buf) == 0) {
4132 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01004133 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02004134 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01004135 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01004136 cfgerr |= ERR_ALERT | ERR_FATAL;
4137 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01004138 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01004139 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01004140 }
4141 } else {
4142 /* stat failed, could be a bundle */
4143 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02004144 char fp[MAXPATHLEN+1] = {0};
4145 int n = 0;
4146
4147 /* Load all possible certs and keys in separate ckch_store */
4148 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
4149 struct stat buf;
4150 int ret;
4151
4152 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
4153 if (ret > sizeof(fp))
4154 continue;
4155
4156 if ((ckchs = ckchs_lookup(fp))) {
4157 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01004158 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02004159 } else {
4160 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01004161 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02004162 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02004163 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01004164 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02004165 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
4166 }
4167 }
4168 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01004169#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
4170 if (found) {
4171 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
4172 err && *err ? *err : "", path);
4173 cfgerr |= ERR_ALERT | ERR_FATAL;
4174 }
4175#endif
William Lallemand06b22a82020-03-16 14:45:55 +01004176 }
4177 }
William Lallemand06ce84a2020-11-20 15:36:13 +01004178 if (!found) {
4179 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
4180 err && *err ? *err : "", path, strerror(errno));
4181 cfgerr |= ERR_ALERT | ERR_FATAL;
4182 }
William Lallemand06b22a82020-03-16 14:45:55 +01004183
4184 return cfgerr;
4185}
4186
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004187
4188/* Create a full ssl context and ckch instance that will be used for a specific
4189 * backend server (server configuration line).
4190 * Returns a set of ERR_* flags possibly with an error in <err>.
4191 */
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004192int 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 +01004193{
4194 struct stat buf;
4195 int cfgerr = 0;
4196 struct ckch_store *ckchs;
4197 int found = 0; /* did we found a file to load ? */
4198
4199 if ((ckchs = ckchs_lookup(path))) {
4200 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01004201 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004202 found++;
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004203 } else {
4204 if (!create_if_none) {
4205 memprintf(err, "%sunable to stat SSL certificate '%s'.\n",
4206 err && *err ? *err : "", path);
4207 cfgerr |= ERR_ALERT | ERR_FATAL;
4208 goto out;
4209 }
4210
4211 if (stat(path, &buf) == 0) {
4212 /* We do not manage directories on backend side. */
4213 if (S_ISDIR(buf.st_mode) == 0) {
4214 ++found;
4215 ckchs = ckchs_load_cert_file(path, err);
4216 if (!ckchs)
4217 cfgerr |= ERR_ALERT | ERR_FATAL;
4218 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
4219 }
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004220 }
4221 }
4222 if (!found) {
4223 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
4224 err && *err ? *err : "", path, strerror(errno));
4225 cfgerr |= ERR_ALERT | ERR_FATAL;
4226 }
4227
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004228out:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004229 return cfgerr;
4230}
4231
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004232/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004233static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004234ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004235{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004236 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004237 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004238 SSL_OP_ALL | /* all known workarounds for bugs */
4239 SSL_OP_NO_SSLv2 |
4240 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02004241 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02004242 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004243 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02004244 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004245 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004246 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004247 SSL_MODE_ENABLE_PARTIAL_WRITE |
4248 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004249 SSL_MODE_RELEASE_BUFFERS |
4250 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004251 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004252 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004253 int flags = MC_SSL_O_ALL;
4254 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02004255 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004256
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004257 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004258 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004259
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004260 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004261 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
4262 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4263 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004264 else
4265 flags = conf_ssl_methods->flags;
4266
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004267 min = conf_ssl_methods->min;
4268 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02004269
4270 /* default minimum is TLSV12, */
4271 if (!min) {
4272 if (!max || (max >= default_min_ver)) {
4273 min = default_min_ver;
4274 } else {
4275 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). "
4276 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
4277 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
4278 min = max;
4279 }
4280 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004281 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004282 if (min)
4283 flags |= (methodVersions[min].flag - 1);
4284 if (max)
4285 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004286 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004287 min = max = CONF_TLSV_NONE;
4288 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004289 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004290 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004291 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004292 if (min) {
4293 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004294 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
4295 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4296 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
4297 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004298 hole = 0;
4299 }
4300 max = i;
4301 }
4302 else {
4303 min = max = i;
4304 }
4305 }
4306 else {
4307 if (min)
4308 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004309 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004310 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004311 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4312 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004313 cfgerr += 1;
4314 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004315 /* save real min/max in bind_conf */
4316 conf_ssl_methods->min = min;
4317 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004318
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004319#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004320 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004321 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004322 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004323 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004324 else
William Lallemandd0712f32020-06-11 17:34:00 +02004325 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
4326 /* clear every version flags in case SSL_CTX_new()
4327 * returns an SSL_CTX with disabled versions */
4328 SSL_CTX_clear_options(ctx, methodVersions[i].option);
4329
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004330 if (flags & methodVersions[i].flag)
4331 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02004332
4333 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004334#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004335 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004336 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4337 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02004338#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004339
4340 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
4341 options |= SSL_OP_NO_TICKET;
4342 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
4343 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08004344
4345#ifdef SSL_OP_NO_RENEGOTIATION
4346 options |= SSL_OP_NO_RENEGOTIATION;
4347#endif
4348
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004349 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004350
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004351#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004352 if (global_ssl.async)
4353 mode |= SSL_MODE_ASYNC;
4354#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004355 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004356 if (global_ssl.life_time)
4357 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004358
4359#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
4360#ifdef OPENSSL_IS_BORINGSSL
4361 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
4362 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Ilya Shipitsine9ff8992020-01-19 12:20:14 +05004363#elif defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01004364 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01004365 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02004366 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
4367 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004368#else
4369 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004370#endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02004371 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004372#endif
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004373 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004374}
4375
William Lallemand4f45bb92017-10-30 20:08:51 +01004376
4377static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
4378{
4379 if (first == block) {
4380 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4381 if (first->len > 0)
4382 sh_ssl_sess_tree_delete(sh_ssl_sess);
4383 }
4384}
4385
4386/* return first block from sh_ssl_sess */
4387static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
4388{
4389 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
4390
4391}
4392
4393/* store a session into the cache
4394 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
4395 * data: asn1 encoded session
4396 * data_len: asn1 encoded session length
4397 * Returns 1 id session was stored (else 0)
4398 */
4399static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
4400{
4401 struct shared_block *first;
4402 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
4403
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004404 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01004405 if (!first) {
4406 /* Could not retrieve enough free blocks to store that session */
4407 return 0;
4408 }
4409
4410 /* STORE the key in the first elem */
4411 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4412 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
4413 first->len = sizeof(struct sh_ssl_sess_hdr);
4414
4415 /* it returns the already existing node
4416 or current node if none, never returns null */
4417 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
4418 if (oldsh_ssl_sess != sh_ssl_sess) {
4419 /* NOTE: Row couldn't be in use because we lock read & write function */
4420 /* release the reserved row */
4421 shctx_row_dec_hot(ssl_shctx, first);
4422 /* replace the previous session already in the tree */
4423 sh_ssl_sess = oldsh_ssl_sess;
4424 /* ignore the previous session data, only use the header */
4425 first = sh_ssl_sess_first_block(sh_ssl_sess);
4426 shctx_row_inc_hot(ssl_shctx, first);
4427 first->len = sizeof(struct sh_ssl_sess_hdr);
4428 }
4429
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004430 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01004431 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004432 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01004433 }
4434
4435 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004436
4437 return 1;
4438}
William Lallemanded0b5ad2017-10-30 19:36:36 +01004439
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004440/* SSL callback used when a new session is created while connecting to a server */
4441static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4442{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004443 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004444 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004445
Willy Tarreau07d94e42018-09-20 10:57:52 +02004446 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004447
William Lallemand3ce6eed2021-02-08 10:43:44 +01004448 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4449 * one cache per thread, it only prevents to flush it from the CLI in
4450 * another thread */
4451
Olivier Houcharde6060c52017-11-16 17:42:52 +01004452 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4453 int len;
4454 unsigned char *ptr;
William Lallemande18d4e82021-11-17 02:59:21 +01004455 const char *sni;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004456
Olivier Houcharde6060c52017-11-16 17:42:52 +01004457 len = i2d_SSL_SESSION(sess, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01004458 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004459 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004460 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4461 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4462 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004463 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
4464 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004465 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4466 }
4467 if (s->ssl_ctx.reused_sess[tid].ptr) {
4468 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4469 &ptr);
4470 }
William Lallemande18d4e82021-11-17 02:59:21 +01004471
4472 if (s->ssl_ctx.reused_sess[tid].sni) {
4473 /* if the new sni is empty or isn' t the same as the old one */
4474 if ((!sni) || strcmp(s->ssl_ctx.reused_sess[tid].sni, sni) != 0) {
4475 ha_free(&s->ssl_ctx.reused_sess[tid].sni);
4476 if (sni)
4477 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4478 }
4479 } else if (sni) {
4480 /* if there wasn't an old sni but there is a new one */
4481 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4482 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004483 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004484 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004485 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004486 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004487 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004488 }
4489
4490 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004491}
4492
Olivier Houcharde6060c52017-11-16 17:42:52 +01004493
William Lallemanded0b5ad2017-10-30 19:36:36 +01004494/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004495int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004496{
4497 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4498 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4499 unsigned char *p;
4500 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004501 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004502 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004503
4504 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004505 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004506 * note: SSL_SESSION_set1_id is using
4507 * a memcpy so we need to use a different pointer
4508 * than sid_data or sid_ctx_data to avoid valgrind
4509 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004510 */
4511
4512 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004513
4514 /* copy value in an other buffer */
4515 memcpy(encid, sid_data, sid_length);
4516
4517 /* pad with 0 */
4518 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4519 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4520
4521 /* force length to zero to avoid ASN1 encoding */
4522 SSL_SESSION_set1_id(sess, encid, 0);
4523
4524 /* force length to zero to avoid ASN1 encoding */
4525 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004526
4527 /* check if buffer is large enough for the ASN1 encoded session */
4528 data_len = i2d_SSL_SESSION(sess, NULL);
4529 if (data_len > SHSESS_MAX_DATA_LEN)
4530 goto err;
4531
4532 p = encsess;
4533
4534 /* process ASN1 session encoding before the lock */
4535 i2d_SSL_SESSION(sess, &p);
4536
William Lallemanded0b5ad2017-10-30 19:36:36 +01004537
William Lallemanda3c77cf2017-10-30 23:44:40 +01004538 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004539 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004540 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004541 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004542err:
4543 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004544 SSL_SESSION_set1_id(sess, encid, sid_length);
4545 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004546
4547 return 0; /* do not increment session reference count */
4548}
4549
4550/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004551SSL_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 +01004552{
William Lallemand4f45bb92017-10-30 20:08:51 +01004553 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004554 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4555 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004556 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004557 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004558
Willy Tarreau4c19e992021-06-15 16:39:22 +02004559 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004560
4561 /* allow the session to be freed automatically by openssl */
4562 *do_copy = 0;
4563
4564 /* tree key is zeros padded sessionid */
4565 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4566 memcpy(tmpkey, key, key_len);
4567 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4568 key = tmpkey;
4569 }
4570
4571 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004572 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004573
4574 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004575 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4576 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004577 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004578 shctx_unlock(ssl_shctx);
Willy Tarreau4c19e992021-06-15 16:39:22 +02004579 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004580 return NULL;
4581 }
4582
William Lallemand4f45bb92017-10-30 20:08:51 +01004583 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4584 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004585
William Lallemand4f45bb92017-10-30 20:08:51 +01004586 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 +01004587
William Lallemanda3c77cf2017-10-30 23:44:40 +01004588 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004589
4590 /* decode ASN1 session */
4591 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004592 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004593 /* Reset session id and session id contenxt */
4594 if (sess) {
4595 SSL_SESSION_set1_id(sess, key, key_len);
4596 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4597 }
4598
4599 return sess;
4600}
4601
William Lallemand4f45bb92017-10-30 20:08:51 +01004602
William Lallemanded0b5ad2017-10-30 19:36:36 +01004603/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004604void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004605{
William Lallemand4f45bb92017-10-30 20:08:51 +01004606 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004607 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4608 unsigned int sid_length;
4609 const unsigned char *sid_data;
4610 (void)ctx;
4611
4612 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4613 /* tree key is zeros padded sessionid */
4614 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4615 memcpy(tmpkey, sid_data, sid_length);
4616 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4617 sid_data = tmpkey;
4618 }
4619
William Lallemanda3c77cf2017-10-30 23:44:40 +01004620 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004621
4622 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004623 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4624 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004625 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004626 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004627 }
4628
4629 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004630 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004631}
4632
4633/* Set session cache mode to server and disable openssl internal cache.
4634 * Set shared cache callbacks on an ssl context.
4635 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004636void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004637{
4638 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4639
4640 if (!ssl_shctx) {
4641 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4642 return;
4643 }
4644
4645 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4646 SSL_SESS_CACHE_NO_INTERNAL |
4647 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4648
4649 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004650 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4651 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4652 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004653}
William Lallemand7d42ef52020-07-06 11:41:30 +02004654
4655/*
4656 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4657 *
4658 * The format is:
4659 * * <Label> <space> <ClientRandom> <space> <Secret>
4660 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4661 */
4662
William Lallemand722180a2021-06-09 16:46:12 +02004663#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004664void SSL_CTX_keylog(const SSL *ssl, const char *line)
4665{
4666 struct ssl_keylog *keylog;
4667 char *lastarg = NULL;
4668 char *dst = NULL;
4669
4670 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4671 if (!keylog)
4672 return;
4673
4674 lastarg = strrchr(line, ' ');
4675 if (lastarg == NULL || ++lastarg == NULL)
4676 return;
4677
4678 dst = pool_alloc(pool_head_ssl_keylog_str);
4679 if (!dst)
4680 return;
4681
4682 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4683 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4684
4685 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4686 if (keylog->client_random)
4687 goto error;
4688 keylog->client_random = dst;
4689
4690 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4691 if (keylog->client_early_traffic_secret)
4692 goto error;
4693 keylog->client_early_traffic_secret = dst;
4694
4695 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4696 if(keylog->client_handshake_traffic_secret)
4697 goto error;
4698 keylog->client_handshake_traffic_secret = dst;
4699
4700 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4701 if (keylog->server_handshake_traffic_secret)
4702 goto error;
4703 keylog->server_handshake_traffic_secret = dst;
4704
4705 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4706 if (keylog->client_traffic_secret_0)
4707 goto error;
4708 keylog->client_traffic_secret_0 = dst;
4709
4710 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4711 if (keylog->server_traffic_secret_0)
4712 goto error;
4713 keylog->server_traffic_secret_0 = dst;
4714
4715 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4716 if (keylog->early_exporter_secret)
4717 goto error;
4718 keylog->early_exporter_secret = dst;
4719
4720 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4721 if (keylog->exporter_secret)
4722 goto error;
4723 keylog->exporter_secret = dst;
4724 } else {
4725 goto error;
4726 }
4727
4728 return;
4729
4730error:
4731 pool_free(pool_head_ssl_keylog_str, dst);
4732
4733 return;
4734}
4735#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004736
William Lallemand8b453912019-11-21 15:48:10 +01004737/*
4738 * This function applies the SSL configuration on a SSL_CTX
4739 * It returns an error code and fills the <err> buffer
4740 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004741static 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 +01004742{
4743 struct proxy *curproxy = bind_conf->frontend;
4744 int cfgerr = 0;
4745 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004746 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004747 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004748#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004749 const char *conf_ciphersuites;
4750#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004751 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004752
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004753 if (ssl_conf) {
4754 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4755 int i, min, max;
4756 int flags = MC_SSL_O_ALL;
4757
4758 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004759 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4760 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004761 if (min)
4762 flags |= (methodVersions[min].flag - 1);
4763 if (max)
4764 flags |= ~((methodVersions[max].flag << 1) - 1);
4765 min = max = CONF_TLSV_NONE;
4766 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4767 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4768 if (min)
4769 max = i;
4770 else
4771 min = max = i;
4772 }
4773 /* save real min/max */
4774 conf_ssl_methods->min = min;
4775 conf_ssl_methods->max = max;
4776 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004777 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4778 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004779 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004780 }
4781 }
4782
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004783 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004784 case SSL_SOCK_VERIFY_NONE:
4785 verify = SSL_VERIFY_NONE;
4786 break;
4787 case SSL_SOCK_VERIFY_OPTIONAL:
4788 verify = SSL_VERIFY_PEER;
4789 break;
4790 case SSL_SOCK_VERIFY_REQUIRED:
4791 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4792 break;
4793 }
4794 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4795 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004796 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 +01004797 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 +01004798 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 +01004799 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004800 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004801 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004802 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004803 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004804 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004805 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004806 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4807 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4808 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4809 cfgerr |= ERR_ALERT | ERR_FATAL;
4810 }
4811 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004812 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004813 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 +02004814 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004815 }
Emeric Brun850efd52014-01-29 12:24:34 +01004816 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004817 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4818 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004819 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004820 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004821#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004822 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004823 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4824
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004825 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004826 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4827 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004828 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004829 }
Emeric Brun561e5742012-10-02 15:20:55 +02004830 else {
4831 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4832 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004833 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004834#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004835 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004836 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004837#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004838 if(bind_conf->keys_ref) {
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +01004839 if (!SSL_CTX_set_tlsext_ticket_key_evp_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004840 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4841 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004842 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004843 }
4844 }
4845#endif
4846
William Lallemand4f45bb92017-10-30 20:08:51 +01004847 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004848 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4849 if (conf_ciphers &&
4850 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004851 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4852 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004853 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004854 }
4855
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004856#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004857 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4858 if (conf_ciphersuites &&
4859 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004860 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4861 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004862 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004863 }
4864#endif
4865
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004866#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02004867 if (!local_dh_1024)
4868 local_dh_1024 = ssl_get_dh_1024();
4869 if (!local_dh_2048)
4870 local_dh_2048 = ssl_get_dh_2048();
4871 if (!local_dh_4096)
4872 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02004873#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004874
Emeric Brunfc0421f2012-09-07 17:30:07 +02004875 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004876#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004877 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004878#endif
William Lallemand722180a2021-06-09 16:46:12 +02004879#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004880 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
4881#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004882
Bernard Spil13c53f82018-02-15 13:34:58 +01004883#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004884 ssl_conf_cur = NULL;
4885 if (ssl_conf && ssl_conf->npn_str)
4886 ssl_conf_cur = ssl_conf;
4887 else if (bind_conf->ssl_conf.npn_str)
4888 ssl_conf_cur = &bind_conf->ssl_conf;
4889 if (ssl_conf_cur)
4890 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004891#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004892#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004893 ssl_conf_cur = NULL;
4894 if (ssl_conf && ssl_conf->alpn_str)
4895 ssl_conf_cur = ssl_conf;
4896 else if (bind_conf->ssl_conf.alpn_str)
4897 ssl_conf_cur = &bind_conf->ssl_conf;
4898 if (ssl_conf_cur)
4899 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004900#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004901#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004902 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4903 if (conf_curves) {
4904 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004905 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4906 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004907 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004908 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004909 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004910 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004911#endif /* defined(SSL_CTX_set1_curves_list) */
4912
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004913 if (!conf_curves) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004914#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004915#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004916 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004917 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4918 NULL);
4919
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004920 if (ecdhe && SSL_CTX_set1_curves_list(ctx, ecdhe) == 0) {
4921 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4922 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
4923 cfgerr |= ERR_ALERT | ERR_FATAL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02004924 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004925#endif /* defined(SSL_CTX_set1_curves_list) */
Olivier Houchardc2aae742017-09-22 18:26:28 +02004926#else
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004927#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
4928 int i;
4929 EC_KEY *ecdh;
4930
Olivier Houchardc2aae742017-09-22 18:26:28 +02004931 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4932 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4933 ECDHE_DEFAULT_CURVE);
Emeric Brun2b58d042012-09-20 17:10:03 +02004934
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004935 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004936 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004937 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 +01004938 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004939 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004940 }
4941 else {
4942 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4943 EC_KEY_free(ecdh);
4944 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004945#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
4946#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Emeric Brun2b58d042012-09-20 17:10:03 +02004947 }
Emeric Brun2b58d042012-09-20 17:10:03 +02004948
Emeric Brunfc0421f2012-09-07 17:30:07 +02004949 return cfgerr;
4950}
4951
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004952
4953/*
4954 * Prepare the SSL_CTX based on the bind line configuration.
4955 * Since the CA file loading is made depending on the verify option of the bind
4956 * line, the link between the SSL_CTX and the CA file tree entry is made here.
4957 * If we want to create a link between the CA file entry and the corresponding
4958 * ckch instance (for CA file hot update), it needs to be done after
4959 * ssl_sock_prepare_ctx.
4960 * Returns 0 in case of success.
4961 */
4962int ssl_sock_prep_ctx_and_inst(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
4963 SSL_CTX *ctx, struct ckch_inst *ckch_inst, char **err)
4964{
4965 int errcode = 0;
4966
4967 errcode |= ssl_sock_prepare_ctx(bind_conf, ssl_conf, ctx, err);
4968 if (!errcode && ckch_inst)
4969 ckch_inst_add_cafile_link(ckch_inst, bind_conf, ssl_conf, NULL);
4970
4971 return errcode;
4972}
4973
Evan Broderbe554312013-06-27 00:05:25 -07004974static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4975{
4976 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4977 size_t prefixlen, suffixlen;
4978
4979 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004980 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004981 return 1;
4982
Evan Broderbe554312013-06-27 00:05:25 -07004983 /* The rest of this logic is based on RFC 6125, section 6.4.3
4984 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4985
Emeric Bruna848dae2013-10-08 11:27:28 +02004986 pattern_wildcard = NULL;
4987 pattern_left_label_end = pattern;
4988 while (*pattern_left_label_end != '.') {
4989 switch (*pattern_left_label_end) {
4990 case 0:
4991 /* End of label not found */
4992 return 0;
4993 case '*':
4994 /* If there is more than one wildcards */
4995 if (pattern_wildcard)
4996 return 0;
4997 pattern_wildcard = pattern_left_label_end;
4998 break;
4999 }
5000 pattern_left_label_end++;
5001 }
5002
5003 /* If it's not trivial and there is no wildcard, it can't
5004 * match */
5005 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07005006 return 0;
5007
5008 /* Make sure all labels match except the leftmost */
5009 hostname_left_label_end = strchr(hostname, '.');
5010 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02005011 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07005012 return 0;
5013
5014 /* Make sure the leftmost label of the hostname is long enough
5015 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02005016 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07005017 return 0;
5018
5019 /* Finally compare the string on either side of the
5020 * wildcard */
5021 prefixlen = pattern_wildcard - pattern;
5022 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02005023 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
5024 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07005025 return 0;
5026
5027 return 1;
5028}
5029
5030static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
5031{
5032 SSL *ssl;
5033 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005034 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02005035 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02005036 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07005037
5038 int depth;
5039 X509 *cert;
5040 STACK_OF(GENERAL_NAME) *alt_names;
5041 int i;
5042 X509_NAME *cert_subject;
5043 char *str;
5044
5045 if (ok == 0)
5046 return ok;
5047
5048 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02005049 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02005050 ssl_ctx = __conn_get_ssl_sock_ctx(conn);
Evan Broderbe554312013-06-27 00:05:25 -07005051
Willy Tarreauad92a9a2017-07-28 11:38:41 +02005052 /* We're checking if the provided hostnames match the desired one. The
5053 * desired hostname comes from the SNI we presented if any, or if not
5054 * provided then it may have been explicitly stated using a "verifyhost"
5055 * directive. If neither is set, we don't care about the name so the
5056 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02005057 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005058 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02005059 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02005060 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02005061 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02005062 if (!servername)
5063 return ok;
5064 }
Evan Broderbe554312013-06-27 00:05:25 -07005065
5066 /* We only need to verify the CN on the actual server cert,
5067 * not the indirect CAs */
5068 depth = X509_STORE_CTX_get_error_depth(ctx);
5069 if (depth != 0)
5070 return ok;
5071
5072 /* At this point, the cert is *not* OK unless we can find a
5073 * hostname match */
5074 ok = 0;
5075
5076 cert = X509_STORE_CTX_get_current_cert(ctx);
5077 /* It seems like this might happen if verify peer isn't set */
5078 if (!cert)
5079 return ok;
5080
5081 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
5082 if (alt_names) {
5083 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
5084 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
5085 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005086#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02005087 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
5088#else
Evan Broderbe554312013-06-27 00:05:25 -07005089 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02005090#endif
Evan Broderbe554312013-06-27 00:05:25 -07005091 ok = ssl_sock_srv_hostcheck(str, servername);
5092 OPENSSL_free(str);
5093 }
5094 }
5095 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02005096 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07005097 }
5098
5099 cert_subject = X509_get_subject_name(cert);
5100 i = -1;
5101 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
5102 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005103 ASN1_STRING *value;
5104 value = X509_NAME_ENTRY_get_data(entry);
5105 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07005106 ok = ssl_sock_srv_hostcheck(str, servername);
5107 OPENSSL_free(str);
5108 }
5109 }
5110
Willy Tarreau71d058c2017-07-26 20:09:56 +02005111 /* report the mismatch and indicate if SNI was used or not */
5112 if (!ok && !conn->err_code)
5113 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07005114 return ok;
5115}
5116
Emeric Brun94324a42012-10-11 14:00:19 +02005117/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01005118int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02005119{
5120 int cfgerr = 0;
William Lallemand2c776f12021-12-28 18:47:17 +01005121 SSL_CTX *ctx;
Willy Tarreaufce03112015-01-15 21:32:40 +01005122 /* Automatic memory computations need to know we use SSL there */
5123 global.ssl_used_backend = 1;
5124
5125 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02005126 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005127 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005128 ha_alert("out of memory.\n");
Emeric Brun821bb9b2017-06-15 16:37:39 +02005129 cfgerr++;
5130 return cfgerr;
5131 }
5132 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01005133 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02005134 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02005135
William Lallemand2c776f12021-12-28 18:47:17 +01005136 if (srv->ssl_ctx.client_crt) {
5137 const int create_if_none = srv->flags & SRV_F_DYNAMIC ? 0 : 1;
5138 char *err = NULL;
5139 int err_code = 0;
5140
5141 /* If there is a crt keyword there, the SSL_CTX will be created here. */
5142 err_code = ssl_sock_load_srv_cert(srv->ssl_ctx.client_crt, srv, create_if_none, &err);
5143 if (err_code != ERR_NONE) {
5144 if ((err_code & ERR_WARN) && !(err_code & ERR_ALERT))
5145 ha_warning("%s", err);
5146 else
5147 ha_alert("%s", err);
5148
5149 if (err_code & (ERR_FATAL|ERR_ABORT))
5150 cfgerr++;
5151 }
5152 ha_free(&err);
5153 }
5154
5155 ctx = srv->ssl_ctx.ctx;
5156
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005157 /* The context will be uninitialized if there wasn't any "cert" option
5158 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005159 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005160 ctx = SSL_CTX_new(SSLv23_client_method());
5161 if (!ctx) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005162 ha_alert("unable to allocate ssl context.\n");
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005163 cfgerr++;
5164 return cfgerr;
5165 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005166
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005167 srv->ssl_ctx.ctx = ctx;
5168 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005169
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005170 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 +01005171
5172 return cfgerr;
5173}
5174
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005175/* Initialize an SSL context that will be used on the backend side.
5176 * Returns an error count.
5177 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005178static int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005179{
5180 struct proxy *curproxy = srv->proxy;
5181 int cfgerr = 0;
5182 long options =
5183 SSL_OP_ALL | /* all known workarounds for bugs */
5184 SSL_OP_NO_SSLv2 |
5185 SSL_OP_NO_COMPRESSION;
5186 long mode =
5187 SSL_MODE_ENABLE_PARTIAL_WRITE |
5188 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
5189 SSL_MODE_RELEASE_BUFFERS |
5190 SSL_MODE_SMALL_BUFFERS;
5191 int verify = SSL_VERIFY_NONE;
5192 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
5193 int i, min, max, hole;
5194 int flags = MC_SSL_O_ALL;
5195
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005196 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005197 ha_warning("no-sslv3/no-tlsv1x are ignored for this server. "
5198 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n");
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005199 else
5200 flags = conf_ssl_methods->flags;
5201
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005202 /* Real min and max should be determinate with configuration and openssl's capabilities */
5203 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005204 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005205 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005206 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005207
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005208 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005209 min = max = CONF_TLSV_NONE;
5210 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005211 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005212 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005213 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005214 if (min) {
5215 if (hole) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005216 ha_warning("%s '%s': SSL/TLS versions range not contiguous for server '%s'. "
Christopher Faulet767a84b2017-11-24 16:50:31 +01005217 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
5218 proxy_type_str(curproxy), curproxy->id, srv->id,
5219 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005220 hole = 0;
5221 }
5222 max = i;
5223 }
5224 else {
5225 min = max = i;
5226 }
5227 }
5228 else {
5229 if (min)
5230 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005231 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005232 if (!min) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005233 ha_alert("%s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01005234 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005235 cfgerr += 1;
5236 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005237
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005238#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005239 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08005240 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005241 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005242 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005243 else
5244 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
5245 if (flags & methodVersions[i].flag)
5246 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005247#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005248 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005249 methodVersions[min].ctx_set_version(ctx, SET_MIN);
5250 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005251#endif
5252
5253 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
5254 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005255 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005256
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005257#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005258 if (global_ssl.async)
5259 mode |= SSL_MODE_ASYNC;
5260#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005261 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005262
Emeric Brun850efd52014-01-29 12:24:34 +01005263 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
5264 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01005265 switch (srv->ssl_ctx.verify) {
5266 case SSL_SOCK_VERIFY_NONE:
5267 verify = SSL_VERIFY_NONE;
5268 break;
5269 case SSL_SOCK_VERIFY_REQUIRED:
5270 verify = SSL_VERIFY_PEER;
5271 break;
5272 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005273 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02005274 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01005275 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02005276 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02005277 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005278 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005279 ha_alert("unable to set CA file '%s'.\n",
5280 srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005281 cfgerr++;
5282 }
5283 }
Emeric Brun850efd52014-01-29 12:24:34 +01005284 else {
5285 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005286 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 +01005287 else
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005288 ha_alert("verify is enabled but no CA file specified.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01005289 cfgerr++;
5290 }
Emeric Brunef42d922012-10-11 16:11:36 +02005291#ifdef X509_V_FLAG_CRL_CHECK
5292 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005293 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02005294
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01005295 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005296 ha_alert("unable to configure CRL file '%s'.\n",
5297 srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005298 cfgerr++;
5299 }
5300 else {
5301 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5302 }
5303 }
5304#endif
5305 }
5306
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005307 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5308 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02005309 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005310 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005311 ha_alert("unable to set SSL cipher list to '%s'.\n",
5312 srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02005313 cfgerr++;
5314 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005315
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05005316#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005317 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005318 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005319 ha_alert("unable to set TLS 1.3 cipher suites to '%s'.\n",
5320 srv->ssl_ctx.ciphersuites);
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005321 cfgerr++;
5322 }
5323#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01005324#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
5325 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005326 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01005327#endif
5328#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5329 if (srv->ssl_ctx.alpn_str)
5330 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
5331#endif
5332
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005333
5334 return cfgerr;
5335}
5336
5337/*
5338 * Prepare the frontend's SSL_CTX based on the server line configuration.
5339 * Since the CA file loading is made depending on the verify option of the
5340 * server line, the link between the SSL_CTX and the CA file tree entry is
5341 * made here.
5342 * If we want to create a link between the CA file entry and the corresponding
5343 * ckch instance (for CA file hot update), it needs to be done after
5344 * ssl_sock_prepare_srv_ssl_ctx.
5345 * Returns an error count.
5346 */
5347int ssl_sock_prep_srv_ctx_and_inst(const struct server *srv, SSL_CTX *ctx,
5348 struct ckch_inst *ckch_inst)
5349{
5350 int cfgerr = 0;
5351
5352 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, ctx);
5353 if (!cfgerr && ckch_inst)
5354 ckch_inst_add_cafile_link(ckch_inst, NULL, NULL, srv);
Emeric Brun94324a42012-10-11 14:00:19 +02005355
5356 return cfgerr;
5357}
5358
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005359
Frédéric Lécailleec216522020-11-23 14:33:30 +01005360/*
5361 * Create an initial CTX used to start the SSL connections.
5362 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
5363 * Returns 0 if succeeded, or something >0 if not.
5364 */
5365#ifdef USE_QUIC
5366static int ssl_initial_ctx(struct bind_conf *bind_conf)
5367{
5368 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
5369 return ssl_quic_initial_ctx(bind_conf);
5370 else
5371 return ssl_sock_initial_ctx(bind_conf);
5372}
5373#else
5374static int ssl_initial_ctx(struct bind_conf *bind_conf)
5375{
5376 return ssl_sock_initial_ctx(bind_conf);
5377}
5378#endif
5379
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005380/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005381 * be NULL, in which case nothing is done. Returns the number of errors
5382 * encountered.
5383 */
Willy Tarreau03209342016-12-22 17:08:28 +01005384int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005385{
5386 struct ebmb_node *node;
5387 struct sni_ctx *sni;
5388 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01005389 int errcode = 0;
5390 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02005391
Willy Tarreaufce03112015-01-15 21:32:40 +01005392 /* Automatic memory computations need to know we use SSL there */
5393 global.ssl_used_frontend = 1;
5394
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005395 /* Create initial_ctx used to start the ssl connection before do switchctx */
5396 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01005397 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005398 /* It should not be necessary to call this function, but it's
5399 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01005400 to initial_ctx in ssl_initial_ctx. */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005401 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, NULL, bind_conf->initial_ctx, NULL, &errmsg);
5402 }
5403 if (bind_conf->default_ctx) {
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005404 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 +01005405 }
Emeric Brun0bed9942014-10-30 19:25:24 +01005406
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005407 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005408 while (node) {
5409 sni = ebmb_entry(node, struct sni_ctx, name);
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005410 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005411 /* only initialize the CTX on its first occurrence and
5412 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005413 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
5414 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005415 node = ebmb_next(node);
5416 }
5417
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005418 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005419 while (node) {
5420 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01005421 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005422 /* only initialize the CTX on its first occurrence and
5423 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005424 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005425 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005426 node = ebmb_next(node);
5427 }
William Lallemand8b453912019-11-21 15:48:10 +01005428
5429 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005430 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005431 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005432 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005433 err++;
5434 }
5435
5436 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005437 return err;
5438}
5439
Willy Tarreau55d37912016-12-21 23:38:39 +01005440/* Prepares all the contexts for a bind_conf and allocates the shared SSL
5441 * context if needed. Returns < 0 on error, 0 on success. The warnings and
5442 * alerts are directly emitted since the rest of the stack does it below.
5443 */
5444int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
5445{
5446 struct proxy *px = bind_conf->frontend;
5447 int alloc_ctx;
5448 int err;
5449
Willy Tarreau11ba4042022-05-20 15:56:32 +02005450 if (!(bind_conf->options & BC_O_USE_SSL)) {
Willy Tarreau55d37912016-12-21 23:38:39 +01005451 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005452 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
5453 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01005454 }
5455 return 0;
5456 }
5457 if (!bind_conf->default_ctx) {
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005458 if (bind_conf->strict_sni && !(bind_conf->options & BC_O_GENERATE_CERTS)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005459 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5460 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005461 }
5462 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005463 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5464 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005465 return -1;
5466 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005467 }
William Lallemandc61c0b32017-12-04 18:46:39 +01005468 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005469 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02005470 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
Willy Tarreau91358592021-06-15 08:08:04 +02005471 sizeof(*sh_ssl_sess_tree), (global.nbthread > 1));
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02005472 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005473 if (alloc_ctx == SHCTX_E_INIT_LOCK)
5474 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");
5475 else
5476 ha_alert("Unable to allocate SSL session cache.\n");
5477 return -1;
5478 }
5479 /* free block callback */
5480 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5481 /* init the root tree within the extra space */
5482 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5483 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01005484 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005485 err = 0;
5486 /* initialize all certificate contexts */
5487 err += ssl_sock_prepare_all_ctx(bind_conf);
5488
5489 /* initialize CA variables if the certificates generation is enabled */
5490 err += ssl_sock_load_ca(bind_conf);
5491
5492 return -err;
5493}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005494
William Lallemand231610a2021-12-30 11:25:43 +01005495/* release ssl context allocated for servers. Most of the field free here
5496 * must also be allocated in srv_ssl_settings_cpy() */
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005497void ssl_sock_free_srv_ctx(struct server *srv)
5498{
Olivier Houchardc7566002018-11-20 23:33:50 +01005499#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
William Lallemand231610a2021-12-30 11:25:43 +01005500 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005501#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005502#ifdef OPENSSL_NPN_NEGOTIATED
William Lallemand231610a2021-12-30 11:25:43 +01005503 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005504#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005505 if (srv->ssl_ctx.reused_sess) {
5506 int i;
5507
William Lallemande18d4e82021-11-17 02:59:21 +01005508 for (i = 0; i < global.nbthread; i++) {
Willy Tarreaue709e822021-02-26 21:06:32 +01005509 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
William Lallemande18d4e82021-11-17 02:59:21 +01005510 ha_free(&srv->ssl_ctx.reused_sess[i].sni);
5511 }
Willy Tarreaue709e822021-02-26 21:06:32 +01005512 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005513 }
5514
Willy Tarreaue709e822021-02-26 21:06:32 +01005515 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005516 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005517 srv->ssl_ctx.ctx = NULL;
5518 }
William Lallemand231610a2021-12-30 11:25:43 +01005519
5520 ha_free(&srv->ssl_ctx.ca_file);
5521 ha_free(&srv->ssl_ctx.crl_file);
5522 ha_free(&srv->ssl_ctx.client_crt);
5523 ha_free(&srv->ssl_ctx.verify_host);
5524#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5525 ha_free(&srv->sni_expr);
William Lallemand43c2ce42022-03-16 17:48:19 +01005526 release_sample_expr(srv->ssl_ctx.sni);
5527 srv->ssl_ctx.sni = NULL;
William Lallemand231610a2021-12-30 11:25:43 +01005528#endif
5529 ha_free(&srv->ssl_ctx.ciphers);
5530#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
5531 ha_free(&srv->ssl_ctx.ciphersuites);
5532#endif
William Lallemande69563f2021-12-30 14:45:19 +01005533 /* If there is a certificate we must unlink the ckch instance */
5534 ckch_inst_free(srv->ssl_ctx.inst);
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005535}
5536
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005537/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005538 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5539 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005540void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005541{
5542 struct ebmb_node *node, *back;
5543 struct sni_ctx *sni;
5544
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005545 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005546 while (node) {
5547 sni = ebmb_entry(node, struct sni_ctx, name);
5548 back = ebmb_next(node);
5549 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005550 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005551 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005552 free(sni);
5553 node = back;
5554 }
5555
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005556 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005557 while (node) {
5558 sni = ebmb_entry(node, struct sni_ctx, name);
5559 back = ebmb_next(node);
5560 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005561 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005562 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005563 free(sni);
5564 node = back;
5565 }
William Lallemandb2408692020-06-24 09:54:29 +02005566
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005567 SSL_CTX_free(bind_conf->initial_ctx);
5568 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005569 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005570 bind_conf->default_ctx = NULL;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005571 bind_conf->default_inst = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005572 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005573}
William Lallemandb2408692020-06-24 09:54:29 +02005574
5575
5576void ssl_sock_deinit()
5577{
5578 crtlist_deinit(); /* must be free'd before the ckchs */
5579 ckch_deinit();
5580}
5581REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005582
Willy Tarreau795cdab2016-12-22 17:30:54 +01005583/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5584void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5585{
5586 ssl_sock_free_ca(bind_conf);
5587 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005588 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005589 free(bind_conf->ca_sign_file);
5590 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005591 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005592 free(bind_conf->keys_ref->filename);
5593 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005594 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005595 free(bind_conf->keys_ref);
5596 }
5597 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005598 bind_conf->ca_sign_pass = NULL;
5599 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005600}
5601
Christopher Faulet31af49d2015-06-09 17:29:50 +02005602/* Load CA cert file and private key used to generate certificates */
5603int
Willy Tarreau03209342016-12-22 17:08:28 +01005604ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005605{
Willy Tarreau03209342016-12-22 17:08:28 +01005606 struct proxy *px = bind_conf->frontend;
Shimi Gersner5846c492020-08-23 13:58:12 +03005607 struct cert_key_and_chain *ckch = NULL;
5608 int ret = 0;
5609 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005610
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005611 if (!(bind_conf->options & BC_O_GENERATE_CERTS))
Shimi Gersner5846c492020-08-23 13:58:12 +03005612 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005613
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005614#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005615 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005616 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005617 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005618 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005619 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005620#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005621
Christopher Faulet31af49d2015-06-09 17:29:50 +02005622 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005623 ha_alert("Proxy '%s': cannot enable certificate generation, "
5624 "no CA certificate File configured at [%s:%d].\n",
5625 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005626 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005627 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005628
Shimi Gersner5846c492020-08-23 13:58:12 +03005629 /* Allocate cert structure */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02005630 ckch = calloc(1, sizeof(*ckch));
Shimi Gersner5846c492020-08-23 13:58:12 +03005631 if (!ckch) {
5632 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5633 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5634 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005635 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005636
5637 /* Try to parse file */
5638 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, ckch, &err)) {
5639 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5640 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005641 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005642 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005643 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005644
5645 /* Fail if missing cert or pkey */
5646 if ((!ckch->cert) || (!ckch->key)) {
5647 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5648 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5649 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005650 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005651
Shimi Gersner5846c492020-08-23 13:58:12 +03005652 /* Final assignment to bind */
5653 bind_conf->ca_sign_ckch = ckch;
5654 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005655
Shimi Gersner5846c492020-08-23 13:58:12 +03005656 failed:
5657 if (ckch) {
5658 ssl_sock_free_cert_key_and_chain_contents(ckch);
5659 free(ckch);
5660 }
5661
Willy Tarreau1ea6e6a2022-05-20 16:03:18 +02005662 bind_conf->options &= ~BC_O_GENERATE_CERTS;
Shimi Gersner5846c492020-08-23 13:58:12 +03005663 ret++;
5664 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005665}
5666
5667/* Release CA cert and private key used to generate certificated */
5668void
5669ssl_sock_free_ca(struct bind_conf *bind_conf)
5670{
Shimi Gersner5846c492020-08-23 13:58:12 +03005671 if (bind_conf->ca_sign_ckch) {
5672 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005673 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005674 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005675}
5676
Emeric Brun46591952012-05-18 15:47:34 +02005677/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005678 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5679 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5680 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5681 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005682 * 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 +01005683 * as parameters to this function.
5684 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5685 * CO_ER_SSL_NO_MEM.
5686 */
5687int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5688 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5689{
5690 int retry = 1;
5691
5692 retry:
5693 /* Alloc a new SSL session. */
5694 *ssl = SSL_new(ssl_ctx);
5695 if (!*ssl) {
5696 if (!retry--)
5697 goto err;
5698
5699 pool_gc(NULL);
5700 goto retry;
5701 }
5702
5703 *bio = BIO_new(bio_meth);
5704 if (!*bio) {
5705 SSL_free(*ssl);
5706 *ssl = NULL;
5707 if (!retry--)
5708 goto err;
5709
5710 pool_gc(NULL);
5711 goto retry;
5712 }
5713
5714 BIO_set_data(*bio, ctx);
5715 SSL_set_bio(*ssl, *bio, *bio);
5716
5717 /* set connection pointer. */
5718 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5719 SSL_free(*ssl);
5720 *ssl = NULL;
5721 if (!retry--)
5722 goto err;
5723
5724 pool_gc(NULL);
5725 goto retry;
5726 }
5727
5728 return 0;
5729
5730 err:
5731 conn->err_code = CO_ER_SSL_NO_MEM;
5732 return -1;
5733}
5734
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005735/* This function is called when all the XPRT have been initialized. We can
5736 * now attempt to start the SSL handshake.
5737 */
5738static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5739{
5740 struct ssl_sock_ctx *ctx = xprt_ctx;
5741
5742 if (ctx->xprt->start) {
5743 int ret;
5744
5745 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5746 if (ret < 0)
5747 return ret;
5748 }
5749 tasklet_wakeup(ctx->wait_event.tasklet);
5750
5751 return 0;
5752}
5753
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005754/*
Emeric Brun46591952012-05-18 15:47:34 +02005755 * This function is called if SSL * context is not yet allocated. The function
5756 * is designed to be called before any other data-layer operation and sets the
5757 * handshake flag on the connection. It is safe to call it multiple times.
5758 * It returns 0 on success and -1 in error case.
5759 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005760static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005761{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005762 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005763 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005764 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005765 return 0;
5766
Olivier Houchard66ab4982019-02-26 18:37:15 +01005767 ctx = pool_alloc(ssl_sock_ctx_pool);
5768 if (!ctx) {
5769 conn->err_code = CO_ER_SSL_NO_MEM;
5770 return -1;
5771 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005772 ctx->wait_event.tasklet = tasklet_new();
5773 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005774 conn->err_code = CO_ER_SSL_NO_MEM;
5775 pool_free(ssl_sock_ctx_pool, ctx);
5776 return -1;
5777 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005778 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5779 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005780 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005781 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005782 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005783 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005784 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005785 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005786 ctx->xprt_st = 0;
5787 ctx->xprt_ctx = NULL;
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005788 ctx->error_code = 0;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005789
5790 /* Only work with sockets for now, this should be adapted when we'll
5791 * add QUIC support.
5792 */
5793 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005794 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005795 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5796 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005797 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005798
Willy Tarreau82531f62021-10-06 12:15:18 +02005799 if (global.maxsslconn && global.sslconns >= global.maxsslconn) {
Willy Tarreau20879a02012-12-03 16:32:10 +01005800 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005801 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005802 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005803
Emeric Brun46591952012-05-18 15:47:34 +02005804 /* If it is in client mode initiate SSL session
5805 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005806 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005807 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5808 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005809 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005810
Olivier Houchard66ab4982019-02-26 18:37:15 +01005811 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005812 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005813 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5814 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5815 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 +01005816 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005817 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005818 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005819 } else if (sess) {
5820 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005821 }
5822 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005823 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005824
Emeric Brun46591952012-05-18 15:47:34 +02005825 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005826 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005827
Willy Tarreau82531f62021-10-06 12:15:18 +02005828 _HA_ATOMIC_INC(&global.sslconns);
5829 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005830 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005831 return 0;
5832 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005833 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005834 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005835
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005836 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5837 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005838 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005839
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005840#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005841 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005842 b_alloc(&ctx->early_buf);
5843 SSL_set_max_early_data(ctx->ssl,
5844 /* Only allow early data if we managed to allocate
5845 * a buffer.
5846 */
5847 (!b_is_null(&ctx->early_buf)) ?
5848 global.tune.bufsize - global.tune.maxrewrite : 0);
5849 }
5850#endif
5851
Olivier Houchard66ab4982019-02-26 18:37:15 +01005852 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005853
Emeric Brun46591952012-05-18 15:47:34 +02005854 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005855 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005856#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005857 if (bc->ssl_conf.early_data)
5858 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005859#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005860
Willy Tarreau82531f62021-10-06 12:15:18 +02005861 _HA_ATOMIC_INC(&global.sslconns);
5862 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005863 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005864 return 0;
5865 }
5866 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005867 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005868err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005869 if (ctx && ctx->wait_event.tasklet)
5870 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005871 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005872 return -1;
5873}
5874
5875
5876/* This is the callback which is used when an SSL handshake is pending. It
5877 * updates the FD status if it wants some polling before being called again.
5878 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5879 * otherwise it returns non-zero and removes itself from the connection's
5880 * flags (the bit is provided in <flag> by the caller).
5881 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005882static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005883{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005884 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Emeric Brun46591952012-05-18 15:47:34 +02005885 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005886 struct ssl_counters *counters = NULL;
5887 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005888 struct listener *li;
5889 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005890 socklen_t lskerr;
5891 int skerr;
5892
Emeric Brun46591952012-05-18 15:47:34 +02005893
Willy Tarreau3c728722014-01-23 13:50:42 +01005894 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005895 return 0;
5896
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005897 /* get counters */
5898 switch (obj_type(conn->target)) {
5899 case OBJ_TYPE_LISTENER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005900 li = __objt_listener(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005901 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5902 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5903 &ssl_stats_module);
5904 break;
5905
5906 case OBJ_TYPE_SERVER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005907 srv = __objt_server(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005908 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5909 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5910 &ssl_stats_module);
5911 break;
5912
5913 default:
5914 break;
5915 }
5916
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005917 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005918 goto out_error;
5919
Willy Tarreau06300382021-02-02 15:42:25 +01005920 /* don't start calculating a handshake on a dead connection */
5921 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5922 goto out_error;
5923
5924 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5925 * status from the lower layers, so let's check the FD directly. Ideally
5926 * the xprt layers should provide some status indicating their knowledge
5927 * of shutdowns or error.
5928 */
Willy Tarreau07ecfc52022-04-11 18:07:03 +02005929 BUG_ON(conn->flags & CO_FL_FDLESS);
5930
Willy Tarreau06300382021-02-02 15:42:25 +01005931 skerr = 0;
5932 lskerr = sizeof(skerr);
5933 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5934 skerr != 0)
5935 goto out_error;
5936
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005937#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005938 /*
5939 * Check if we have early data. If we do, we have to read them
5940 * before SSL_do_handshake() is called, And there's no way to
5941 * detect early data, except to try to read them
5942 */
5943 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005944 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005945
Olivier Houchard54907bb2019-12-19 15:02:39 +01005946 while (1) {
5947 ret = SSL_read_early_data(ctx->ssl,
5948 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5949 &read_data);
5950 if (ret == SSL_READ_EARLY_DATA_ERROR)
5951 goto check_error;
5952 if (read_data > 0) {
5953 conn->flags |= CO_FL_EARLY_DATA;
5954 b_add(&ctx->early_buf, read_data);
5955 }
5956 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5957 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5958 if (!b_data(&ctx->early_buf))
5959 b_free(&ctx->early_buf);
5960 break;
5961 }
5962 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005963 }
5964#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005965 /* If we use SSL_do_handshake to process a reneg initiated by
5966 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5967 * Usually SSL_write and SSL_read are used and process implicitly
5968 * the reneg handshake.
5969 * Here we use SSL_peek as a workaround for reneg.
5970 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005971 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005972 char c;
5973
Olivier Houchard66ab4982019-02-26 18:37:15 +01005974 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005975 if (ret <= 0) {
5976 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005977 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005978
Emeric Brun674b7432012-11-08 19:21:55 +01005979 if (ret == SSL_ERROR_WANT_WRITE) {
5980 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005981 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005982 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005983 return 0;
5984 }
5985 else if (ret == SSL_ERROR_WANT_READ) {
5986 /* handshake may have been completed but we have
5987 * no more data to read.
5988 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005989 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005990 ret = 1;
5991 goto reneg_ok;
5992 }
5993 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005994 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005995 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005996 return 0;
5997 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005998#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005999 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006000 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006001 return 0;
6002 }
6003#endif
Emeric Brun674b7432012-11-08 19:21:55 +01006004 else if (ret == SSL_ERROR_SYSCALL) {
6005 /* if errno is null, then connection was successfully established */
6006 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
6007 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01006008 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02006009#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
6010 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006011 conn->err_code = CO_ER_SSL_HANDSHAKE;
6012#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006013 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02006014#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02006015 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006016 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006017 empty_handshake = state == TLS_ST_BEFORE;
6018#else
Lukas Tribus49799162019-07-08 14:29:15 +02006019 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
6020 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006021#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006022 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02006023 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006024 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006025 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6026 else
6027 conn->err_code = CO_ER_SSL_EMPTY;
6028 }
6029 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006030 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006031 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6032 else
6033 conn->err_code = CO_ER_SSL_ABORT;
6034 }
6035 }
6036 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006037 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006038 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01006039 else
Emeric Brun29f037d2014-04-25 19:05:36 +02006040 conn->err_code = CO_ER_SSL_HANDSHAKE;
6041 }
Lukas Tribus49799162019-07-08 14:29:15 +02006042#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01006043 }
Emeric Brun674b7432012-11-08 19:21:55 +01006044 goto out_error;
6045 }
6046 else {
6047 /* Fail on all other handshake errors */
6048 /* Note: OpenSSL may leave unread bytes in the socket's
6049 * buffer, causing an RST to be emitted upon close() on
6050 * TCP sockets. We first try to drain possibly pending
6051 * data to avoid this as much as possible.
6052 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01006053 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01006054 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006055 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02006056 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01006057 goto out_error;
6058 }
6059 }
6060 /* read some data: consider handshake completed */
6061 goto reneg_ok;
6062 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006063 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006064check_error:
Emeric Brun46591952012-05-18 15:47:34 +02006065 if (ret != 1) {
6066 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006067 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006068
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02006069 if (!ctx->error_code)
6070 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton7c6898e2021-07-29 09:45:51 +02006071
Emeric Brun46591952012-05-18 15:47:34 +02006072 if (ret == SSL_ERROR_WANT_WRITE) {
6073 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02006074 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02006075 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02006076 return 0;
6077 }
6078 else if (ret == SSL_ERROR_WANT_READ) {
6079 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02006080 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02006081 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6082 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02006083 return 0;
6084 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006085#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006086 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006087 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006088 return 0;
6089 }
6090#endif
Willy Tarreau89230192012-09-28 20:22:13 +02006091 else if (ret == SSL_ERROR_SYSCALL) {
6092 /* if errno is null, then connection was successfully established */
6093 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
6094 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006095 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02006096#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
6097 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006098 conn->err_code = CO_ER_SSL_HANDSHAKE;
6099#else
6100 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02006101#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02006102 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006103 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006104 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006105#else
Lukas Tribus49799162019-07-08 14:29:15 +02006106 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
6107 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006108#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006109 if (empty_handshake) {
6110 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006111 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006112 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6113 else
6114 conn->err_code = CO_ER_SSL_EMPTY;
6115 }
6116 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006117 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006118 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6119 else
6120 conn->err_code = CO_ER_SSL_ABORT;
6121 }
Emeric Brun29f037d2014-04-25 19:05:36 +02006122 }
6123 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006124 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006125 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6126 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006127 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02006128 }
Lukas Tribus49799162019-07-08 14:29:15 +02006129#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02006130 }
Willy Tarreau89230192012-09-28 20:22:13 +02006131 goto out_error;
6132 }
Emeric Brun46591952012-05-18 15:47:34 +02006133 else {
6134 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02006135 /* Note: OpenSSL may leave unread bytes in the socket's
6136 * buffer, causing an RST to be emitted upon close() on
6137 * TCP sockets. We first try to drain possibly pending
6138 * data to avoid this as much as possible.
6139 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01006140 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01006141 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006142 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02006143 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006144 goto out_error;
6145 }
6146 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006147#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01006148 else {
6149 /*
6150 * If the server refused the early data, we have to send a
6151 * 425 to the client, as we no longer have the data to sent
6152 * them again.
6153 */
6154 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006155 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006156 conn->err_code = CO_ER_SSL_EARLY_FAILED;
6157 goto out_error;
6158 }
6159 }
6160 }
6161#endif
6162
Emeric Brun46591952012-05-18 15:47:34 +02006163
Emeric Brun674b7432012-11-08 19:21:55 +01006164reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00006165
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006166#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006167 /* ASYNC engine API doesn't support moving read/write
6168 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006169 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00006170 */
6171 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006172 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006173#endif
Emeric Brun46591952012-05-18 15:47:34 +02006174 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006175 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02006176 if (objt_server(conn->target)) {
6177 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
6178 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
6179 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02006180 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02006181 else {
6182 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
6183 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
6184 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
6185 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006186
Willy Tarreau42995282020-11-06 13:19:18 +01006187 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006188 HA_ATOMIC_INC(&counters->sess);
6189 HA_ATOMIC_INC(&counters_px->sess);
Willy Tarreau42995282020-11-06 13:19:18 +01006190 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006191 }
Willy Tarreau42995282020-11-06 13:19:18 +01006192 else if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006193 HA_ATOMIC_INC(&counters->reused_sess);
6194 HA_ATOMIC_INC(&counters_px->reused_sess);
Emeric Brun46591952012-05-18 15:47:34 +02006195 }
6196
6197 /* The connection is now established at both layers, it's time to leave */
6198 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
6199 return 1;
6200
6201 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006202 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006203 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006204 ERR_clear_error();
6205
Emeric Brun9fa89732012-10-04 17:09:56 +02006206 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01006207 if (objt_server(conn->target)) {
6208 struct server *s = __objt_server(conn->target);
6209 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
6210 * one cache per thread, it only prevents to flush it from the CLI in
6211 * another thread */
6212
6213 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01006214 if (s->ssl_ctx.reused_sess[tid].ptr)
6215 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01006216 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02006217 }
6218
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006219 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006220 HA_ATOMIC_INC(&counters->failed_handshake);
6221 HA_ATOMIC_INC(&counters_px->failed_handshake);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006222 }
6223
Emeric Brun46591952012-05-18 15:47:34 +02006224 /* Fail on all other handshake errors */
6225 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01006226 if (!conn->err_code)
6227 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006228 return 0;
6229}
6230
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006231/* Called from the upper layer, to subscribe <es> to events <event_type>. The
6232 * event subscriber <es> is not allowed to change from a previous call as long
6233 * as at least one event is still subscribed. The <event_type> must only be a
6234 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
6235 * unless the transport layer was already released.
6236 */
6237static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006238{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006239 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006240
Olivier Houchard0ff28652019-06-24 18:57:39 +02006241 if (!ctx)
6242 return -1;
6243
Willy Tarreau113d52b2020-01-10 09:20:26 +01006244 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006245 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006246
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006247 ctx->subs = es;
6248 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006249
6250 /* we may have to subscribe to lower layers for new events */
6251 event_type &= ~ctx->wait_event.events;
6252 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
6253 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006254 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006255}
6256
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006257/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
6258 * The <es> pointer is not allowed to differ from the one passed to the
6259 * subscribe() call. It always returns zero.
6260 */
6261static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006262{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006263 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006264
Willy Tarreau113d52b2020-01-10 09:20:26 +01006265 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006266 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006267
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006268 es->events &= ~event_type;
6269 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01006270 ctx->subs = NULL;
6271
6272 /* If we subscribed, and we're not doing the handshake,
6273 * then we subscribed because the upper layer asked for it,
6274 * as the upper layer is no longer interested, we can
6275 * unsubscribe too.
6276 */
6277 event_type &= ctx->wait_event.events;
6278 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
6279 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006280
6281 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006282}
6283
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006284/* The connection has been taken over, so destroy the old tasklet and create
6285 * a new one. The original thread ID must be passed into orig_tid
6286 * It should be called with the takeover lock for the old thread held.
6287 * Returns 0 on success, and -1 on failure
6288 */
6289static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
6290{
6291 struct ssl_sock_ctx *ctx = xprt_ctx;
6292 struct tasklet *tl = tasklet_new();
6293
6294 if (!tl)
6295 return -1;
6296
6297 ctx->wait_event.tasklet->context = NULL;
6298 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
6299 ctx->wait_event.tasklet = tl;
6300 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
6301 ctx->wait_event.tasklet->context = ctx;
6302 return 0;
6303}
6304
Willy Tarreau41491682021-03-02 17:29:56 +01006305/* notify the next xprt that the connection is about to become idle and that it
6306 * may be stolen at any time after the function returns and that any tasklet in
6307 * the chain must be careful before dereferencing its context.
6308 */
6309static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
6310{
6311 struct ssl_sock_ctx *ctx = xprt_ctx;
6312
6313 if (!ctx || !ctx->wait_event.tasklet)
6314 return;
6315
6316 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6317 if (ctx->xprt)
6318 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
6319}
6320
6321/* notify the next xprt that the connection is not idle anymore and that it may
6322 * not be stolen before the next xprt_set_idle().
6323 */
6324static void ssl_set_used(struct connection *conn, void *xprt_ctx)
6325{
6326 struct ssl_sock_ctx *ctx = xprt_ctx;
6327
6328 if (!ctx || !ctx->wait_event.tasklet)
6329 return;
6330
6331 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6332 if (ctx->xprt)
6333 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
6334}
6335
Olivier Houchard2e055482019-05-27 19:50:12 +02006336/* Use the provided XPRT as an underlying XPRT, and provide the old one.
6337 * Returns 0 on success, and non-zero on failure.
6338 */
6339static 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)
6340{
6341 struct ssl_sock_ctx *ctx = xprt_ctx;
6342
6343 if (oldxprt_ops != NULL)
6344 *oldxprt_ops = ctx->xprt;
6345 if (oldxprt_ctx != NULL)
6346 *oldxprt_ctx = ctx->xprt_ctx;
6347 ctx->xprt = toadd_ops;
6348 ctx->xprt_ctx = toadd_ctx;
6349 return 0;
6350}
6351
Olivier Houchard5149b592019-05-23 17:47:36 +02006352/* Remove the specified xprt. If if it our underlying XPRT, remove it and
6353 * return 0, otherwise just call the remove_xprt method from the underlying
6354 * XPRT.
6355 */
6356static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
6357{
6358 struct ssl_sock_ctx *ctx = xprt_ctx;
6359
6360 if (ctx->xprt_ctx == toremove_ctx) {
6361 ctx->xprt_ctx = newctx;
6362 ctx->xprt = newops;
6363 return 0;
6364 }
6365 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
6366}
6367
Willy Tarreau144f84a2021-03-02 16:09:26 +01006368struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02006369{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006370 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006371 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006372 struct connection *conn;
6373 int conn_in_list;
6374 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006375
Willy Tarreau41491682021-03-02 17:29:56 +01006376 if (state & TASK_F_USR1) {
6377 /* the tasklet was idling on an idle connection, it might have
6378 * been stolen, let's be careful!
6379 */
6380 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6381 if (tl->context == NULL) {
6382 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6383 tasklet_free(tl);
6384 return NULL;
6385 }
6386 conn = ctx->conn;
6387 conn_in_list = conn->flags & CO_FL_LIST_MASK;
6388 if (conn_in_list)
6389 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006390 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01006391 } else {
6392 conn = ctx->conn;
6393 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006394 }
Willy Tarreau41491682021-03-02 17:29:56 +01006395
Olivier Houchardea8dd942019-05-20 14:02:16 +02006396 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01006397 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006398 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006399 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
6400 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01006401 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006402 }
6403 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006404 /* If we had an error, or the handshake is done and I/O is available,
6405 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01006406 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02006407 * we can't be sure conn_fd_handler() will be called again.
6408 */
6409 if ((ctx->conn->flags & CO_FL_ERROR) ||
6410 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006411 int woke = 0;
6412
6413 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006414 if (ctx->subs) {
6415 tasklet_wakeup(ctx->subs->tasklet);
6416 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006417 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006418 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006419 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006420
Olivier Houchardea8dd942019-05-20 14:02:16 +02006421 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01006422 * upper layers know. If we have no mux, create it,
6423 * and once we have a mux, call its wake method if we didn't
6424 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02006425 */
6426 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01006427 if (!ctx->conn->mux)
6428 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006429 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006430 ret = ctx->conn->mux->wake(ctx->conn);
6431 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006432 }
6433 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006434#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006435 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006436 else if (b_data(&ctx->early_buf) && ctx->subs &&
6437 ctx->subs->events & SUB_RETRY_RECV) {
6438 tasklet_wakeup(ctx->subs->tasklet);
6439 ctx->subs->events &= ~SUB_RETRY_RECV;
6440 if (!ctx->subs->events)
6441 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01006442 }
6443#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006444leave:
6445 if (!ret && conn_in_list) {
6446 struct server *srv = objt_server(conn->target);
6447
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006448 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006449 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau430bf4a2021-03-04 09:45:32 +01006450 ebmb_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006451 else
Willy Tarreau430bf4a2021-03-04 09:45:32 +01006452 ebmb_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006453 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006454 }
Willy Tarreau74163142021-03-13 11:30:19 +01006455 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006456}
6457
Emeric Brun46591952012-05-18 15:47:34 +02006458/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01006459 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02006460 * buffer wraps, in which case a second call may be performed. The connection's
6461 * flags are updated with whatever special event is detected (error, read0,
6462 * empty). The caller is responsible for taking care of those events and
6463 * avoiding the call if inappropriate. The function does not call the
6464 * connection's polling update function, so the caller is responsible for this.
6465 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006466static 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 +02006467{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006468 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02006469 ssize_t ret;
6470 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02006471
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006472 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006473 goto out_error;
6474
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006475#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006476 if (b_data(&ctx->early_buf)) {
6477 try = b_contig_space(buf);
6478 if (try > b_data(&ctx->early_buf))
6479 try = b_data(&ctx->early_buf);
6480 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
6481 b_add(buf, try);
6482 b_del(&ctx->early_buf, try);
6483 if (b_data(&ctx->early_buf) == 0)
6484 b_free(&ctx->early_buf);
6485 return try;
6486 }
6487#endif
6488
Willy Tarreau911db9b2020-01-23 16:27:54 +01006489 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006490 /* a handshake was requested */
6491 return 0;
6492
Emeric Brun46591952012-05-18 15:47:34 +02006493 /* read the largest possible block. For this, we perform only one call
6494 * to recv() unless the buffer wraps and we exactly fill the first hunk,
6495 * in which case we accept to do it once again. A new attempt is made on
6496 * EINTR too.
6497 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01006498 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006499
Willy Tarreau591d4452018-06-15 17:21:00 +02006500 try = b_contig_space(buf);
6501 if (!try)
6502 break;
6503
Willy Tarreauabf08d92014-01-14 11:31:27 +01006504 if (try > count)
6505 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02006506
Olivier Houchard66ab4982019-02-26 18:37:15 +01006507 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02006508
Emeric Brune1f38db2012-09-03 20:36:47 +02006509 if (conn->flags & CO_FL_ERROR) {
6510 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006511 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006512 }
Emeric Brun46591952012-05-18 15:47:34 +02006513 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006514 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006515 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006516 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006517 }
Emeric Brun46591952012-05-18 15:47:34 +02006518 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006519 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006520 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006521 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006522 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006523 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006524#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006525 /* Async mode can be re-enabled, because we're leaving data state.*/
6526 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006527 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006528#endif
Emeric Brun46591952012-05-18 15:47:34 +02006529 break;
6530 }
6531 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006532 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006533 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6534 SUB_RETRY_RECV,
6535 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006536 /* handshake is running, and it may need to re-enable read */
6537 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006538#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006539 /* Async mode can be re-enabled, because we're leaving data state.*/
6540 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006541 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006542#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006543 break;
6544 }
Emeric Brun46591952012-05-18 15:47:34 +02006545 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006546 } else if (ret == SSL_ERROR_ZERO_RETURN)
6547 goto read0;
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006548 else if (ret == SSL_ERROR_SSL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006549 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6550 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006551 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006552 conn->err_code = CO_ERR_SSL_FATAL;
6553 }
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006554 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6555 * stack before shutting down the connection for
6556 * reading. */
Willy Tarreauacef5e22022-04-25 20:32:15 +02006557 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN || errno == EWOULDBLOCK))
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006558 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006559 /* otherwise it's a real error */
6560 goto out_error;
6561 }
6562 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006563 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006564 return done;
6565
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006566 clear_ssl_error:
6567 /* Clear openssl global errors stack */
6568 ssl_sock_dump_errors(conn);
6569 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006570 read0:
6571 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006572 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006573
Emeric Brun46591952012-05-18 15:47:34 +02006574 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006575 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006576 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006577 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006578 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006579 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006580}
6581
6582
Willy Tarreau787db9a2018-06-14 18:31:46 +02006583/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6584 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6585 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006586 * Only one call to send() is performed, unless the buffer wraps, in which case
6587 * a second call may be performed. The connection's flags are updated with
6588 * whatever special event is detected (error, empty). The caller is responsible
6589 * for taking care of those events and avoiding the call if inappropriate. The
6590 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006591 * is responsible for this. The buffer's output is not adjusted, it's up to the
6592 * caller to take care of this. It's up to the caller to update the buffer's
6593 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006594 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006595static 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 +02006596{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006597 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006598 ssize_t ret;
6599 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006600
6601 done = 0;
6602
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006603 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006604 goto out_error;
6605
Willy Tarreau911db9b2020-01-23 16:27:54 +01006606 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006607 /* a handshake was requested */
6608 return 0;
6609
6610 /* send the largest possible block. For this we perform only one call
6611 * to send() unless the buffer wraps and we exactly fill the first hunk,
6612 * in which case we accept to do it once again.
6613 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006614 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006615#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006616 size_t written_data;
6617#endif
6618
Willy Tarreau787db9a2018-06-14 18:31:46 +02006619 try = b_contig_data(buf, done);
6620 if (try > count)
6621 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006622
Thomas Prückl10243932022-04-27 13:04:54 +02006623 if (global_ssl.hard_max_record && try > global_ssl.hard_max_record)
6624 try = global_ssl.hard_max_record;
6625
Willy Tarreau7bed9452014-02-02 02:00:24 +01006626 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006627 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006628 global_ssl.max_record && try > global_ssl.max_record) {
6629 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006630 }
6631 else {
6632 /* we need to keep the information about the fact that
6633 * we're not limiting the upcoming send(), because if it
6634 * fails, we'll have to retry with at least as many data.
6635 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006636 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006637 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006638
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006639#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006640 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006641 unsigned int max_early;
6642
Olivier Houchard522eea72017-11-03 16:27:47 +01006643 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006644 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006645 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006646 if (SSL_get0_session(ctx->ssl))
6647 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006648 else
6649 max_early = 0;
6650 }
6651
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006652 if (try + ctx->sent_early_data > max_early) {
6653 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006654 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006655 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006656 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006657 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006658 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006659 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006660 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006661 if (ret == 1) {
6662 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006663 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006664 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006665 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006666 /* Initiate the handshake, now */
6667 tasklet_wakeup(ctx->wait_event.tasklet);
6668 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006669
Olivier Houchardc2aae742017-09-22 18:26:28 +02006670 }
6671
6672 } else
6673#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006674 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006675
Emeric Brune1f38db2012-09-03 20:36:47 +02006676 if (conn->flags & CO_FL_ERROR) {
6677 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006678 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006679 }
Emeric Brun46591952012-05-18 15:47:34 +02006680 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006681 /* A send succeeded, so we can consider ourself connected */
6682 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006683 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006684 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006685 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006686 }
6687 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006688 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006689
Emeric Brun46591952012-05-18 15:47:34 +02006690 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006691 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006692 /* handshake is running, and it may need to re-enable write */
6693 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006694 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006695#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006696 /* Async mode can be re-enabled, because we're leaving data state.*/
6697 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006698 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006699#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006700 break;
6701 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006702
Emeric Brun46591952012-05-18 15:47:34 +02006703 break;
6704 }
6705 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006706 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006707 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006708 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6709 SUB_RETRY_RECV,
6710 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006711#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006712 /* Async mode can be re-enabled, because we're leaving data state.*/
6713 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006714 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006715#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006716 break;
6717 }
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006718 else if (ret == SSL_ERROR_SSL || ret == SSL_ERROR_SYSCALL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006719 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6720
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02006721 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006722 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006723 conn->err_code = CO_ERR_SSL_FATAL;
6724 }
Emeric Brun46591952012-05-18 15:47:34 +02006725 goto out_error;
6726 }
6727 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006728 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006729 return done;
6730
6731 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006732 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006733 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006734 ERR_clear_error();
6735
Emeric Brun46591952012-05-18 15:47:34 +02006736 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006737 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006738}
6739
Willy Tarreau832e2422021-05-13 10:11:03 +02006740void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006741
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006742 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006743
Olivier Houchardea8dd942019-05-20 14:02:16 +02006744
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006745 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006746 if (ctx->wait_event.events != 0)
6747 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6748 ctx->wait_event.events,
6749 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006750 if (ctx->subs) {
6751 ctx->subs->events = 0;
6752 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006753 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006754
Olivier Houchard692c1d02019-05-23 18:41:47 +02006755 if (ctx->xprt->close)
6756 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006757#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006758 if (global_ssl.async) {
6759 OSSL_ASYNC_FD all_fd[32], afd;
6760 size_t num_all_fds = 0;
6761 int i;
6762
Olivier Houchard66ab4982019-02-26 18:37:15 +01006763 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006764 if (num_all_fds > 32) {
6765 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6766 return;
6767 }
6768
Olivier Houchard66ab4982019-02-26 18:37:15 +01006769 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006770
6771 /* If an async job is pending, we must try to
6772 to catch the end using polling before calling
6773 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006774 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006775 for (i=0 ; i < num_all_fds ; i++) {
6776 /* switch on an handler designed to
6777 * handle the SSL_free
6778 */
6779 afd = all_fd[i];
6780 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006781 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006782 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006783 /* To ensure that the fd cache won't be used
6784 * and we'll catch a real RD event.
6785 */
6786 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006787 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006788 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006789 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006790 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006791 return;
6792 }
Emeric Brun3854e012017-05-17 20:42:48 +02006793 /* Else we can remove the fds from the fdtab
6794 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006795 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006796 * because the fd is owned by the engine.
6797 * the engine is responsible to close
6798 */
6799 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +02006800 fd_stop_both(all_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006801 }
6802#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006803 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006804 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006805 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006806 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau82531f62021-10-06 12:15:18 +02006807 _HA_ATOMIC_DEC(&global.sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006808 }
Emeric Brun46591952012-05-18 15:47:34 +02006809}
6810
6811/* This function tries to perform a clean shutdown on an SSL connection, and in
6812 * any case, flags the connection as reusable if no handshake was in progress.
6813 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006814static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006815{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006816 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006817
Willy Tarreau911db9b2020-01-23 16:27:54 +01006818 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006819 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006820 if (!clean)
6821 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006822 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006823 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006824 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006825 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006826 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006827 ERR_clear_error();
6828 }
Emeric Brun46591952012-05-18 15:47:34 +02006829}
6830
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006831
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006832/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006833int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6834{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006835 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemandd4f946c2019-12-05 10:26:40 +01006836 X509 *crt;
6837
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006838 if (!ctx)
William Lallemandd4f946c2019-12-05 10:26:40 +01006839 return 0;
William Lallemandd4f946c2019-12-05 10:26:40 +01006840 crt = SSL_get_certificate(ctx->ssl);
6841 if (!crt)
6842 return 0;
6843
6844 return cert_get_pkey_algo(crt, out);
6845}
6846
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006847/* used for ppv2 cert signature (can be used for logging) */
6848const char *ssl_sock_get_cert_sig(struct connection *conn)
6849{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006850 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006851
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006852 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6853 X509 *crt;
6854
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006855 if (!ctx)
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006856 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006857 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006858 if (!crt)
6859 return NULL;
6860 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6861 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6862}
6863
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006864/* used for ppv2 authority */
6865const char *ssl_sock_get_sni(struct connection *conn)
6866{
6867#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006868 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006869
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006870 if (!ctx)
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006871 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006872 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006873#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006874 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006875#endif
6876}
6877
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006878/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006879const char *ssl_sock_get_cipher_name(struct connection *conn)
6880{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006881 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006882
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006883 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006884 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006885 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006886}
6887
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006888/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006889const char *ssl_sock_get_proto_version(struct connection *conn)
6890{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006891 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006892
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006893 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006894 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006895 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006896}
6897
Olivier Houchardab28a322018-12-21 19:45:40 +01006898void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6899{
6900#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006901 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006902
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006903 if (!ctx)
Olivier Houcharde488ea82019-06-28 14:10:33 +02006904 return;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006905 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006906#endif
6907}
6908
Willy Tarreau119a4082016-12-22 21:58:38 +01006909/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6910 * to disable SNI.
6911 */
Willy Tarreau63076412015-07-10 11:33:32 +02006912void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6913{
6914#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006915 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemande18d4e82021-11-17 02:59:21 +01006916 struct server *s;
Willy Tarreau119a4082016-12-22 21:58:38 +01006917 char *prev_name;
6918
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006919 if (!ctx)
Willy Tarreau63076412015-07-10 11:33:32 +02006920 return;
Willy Tarreau77bfa662021-12-23 11:12:13 +01006921
6922 BUG_ON(!(conn->flags & CO_FL_WAIT_L6_CONN));
6923 BUG_ON(!(conn->flags & CO_FL_SSL_WAIT_HS));
6924
William Lallemande18d4e82021-11-17 02:59:21 +01006925 s = __objt_server(conn->target);
Willy Tarreau63076412015-07-10 11:33:32 +02006926
Willy Tarreau119a4082016-12-22 21:58:38 +01006927 /* if the SNI changes, we must destroy the reusable context so that a
William Lallemande18d4e82021-11-17 02:59:21 +01006928 * new connection will present a new SNI. compare with the SNI
6929 * previously stored in the reused_sess */
6930 /* the RWLOCK is used to ensure that we are not trying to flush the
6931 * cache from the CLI */
6932
6933 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
6934 prev_name = s->ssl_ctx.reused_sess[tid].sni;
Willy Tarreau119a4082016-12-22 21:58:38 +01006935 if ((!prev_name && hostname) ||
6936 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006937 SSL_set_session(ctx->ssl, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01006938 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau119a4082016-12-22 21:58:38 +01006939
Olivier Houchard66ab4982019-02-26 18:37:15 +01006940 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006941#endif
6942}
6943
Emeric Brun0abf8362014-06-24 18:26:41 +02006944/* Extract peer certificate's common name into the chunk dest
6945 * Returns
6946 * the len of the extracted common name
6947 * or 0 if no CN found in DN
6948 * or -1 on error case (i.e. no peer certificate)
6949 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006950int ssl_sock_get_remote_common_name(struct connection *conn,
6951 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006952{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006953 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
David Safb76832014-05-08 23:42:08 -04006954 X509 *crt = NULL;
6955 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006956 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006957 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006958 .area = (char *)&find_cn,
6959 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006960 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006961 int result = -1;
David Safb76832014-05-08 23:42:08 -04006962
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006963 if (!ctx)
Emeric Brun0abf8362014-06-24 18:26:41 +02006964 goto out;
David Safb76832014-05-08 23:42:08 -04006965
6966 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006967 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006968 if (!crt)
6969 goto out;
6970
6971 name = X509_get_subject_name(crt);
6972 if (!name)
6973 goto out;
David Safb76832014-05-08 23:42:08 -04006974
Emeric Brun0abf8362014-06-24 18:26:41 +02006975 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6976out:
David Safb76832014-05-08 23:42:08 -04006977 if (crt)
6978 X509_free(crt);
6979
6980 return result;
6981}
6982
Dave McCowan328fb582014-07-30 10:39:13 -04006983/* returns 1 if client passed a certificate for this session, 0 if not */
6984int ssl_sock_get_cert_used_sess(struct connection *conn)
6985{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006986 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dave McCowan328fb582014-07-30 10:39:13 -04006987 X509 *crt = NULL;
6988
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006989 if (!ctx)
Dave McCowan328fb582014-07-30 10:39:13 -04006990 return 0;
6991
6992 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006993 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006994 if (!crt)
6995 return 0;
6996
6997 X509_free(crt);
6998 return 1;
6999}
7000
7001/* returns 1 if client passed a certificate for this connection, 0 if not */
7002int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04007003{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007004 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01007005
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007006 if (!ctx)
David Safb76832014-05-08 23:42:08 -04007007 return 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01007008 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04007009}
7010
7011/* returns result from SSL verify */
7012unsigned int ssl_sock_get_verify_result(struct connection *conn)
7013{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007014 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01007015
Willy Tarreau939b0bf2022-04-11 11:29:11 +02007016 if (!ctx)
David Safb76832014-05-08 23:42:08 -04007017 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Olivier Houchard66ab4982019-02-26 18:37:15 +01007018 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04007019}
7020
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007021/* Returns the application layer protocol name in <str> and <len> when known.
7022 * Zero is returned if the protocol name was not found, otherwise non-zero is
7023 * returned. The string is allocated in the SSL context and doesn't have to be
7024 * freed by the caller. NPN is also checked if available since older versions
7025 * of openssl (1.0.1) which are more common in field only support this one.
7026 */
Amaury Denoyelle71e588c2021-11-12 11:23:29 +01007027int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007028{
Olivier Houchard66ab4982019-02-26 18:37:15 +01007029#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
7030 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01007031 struct ssl_sock_ctx *ctx = xprt_ctx;
7032 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007033 return 0;
7034
7035 *str = NULL;
7036
7037#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01007038 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007039 if (*str)
7040 return 1;
7041#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01007042#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01007043 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007044 if (*str)
7045 return 1;
7046#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01007047#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007048 return 0;
7049}
7050
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007051/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02007052int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007053{
7054 X509 *ca;
7055 X509_NAME *name = NULL;
7056 ASN1_OCTET_STRING *skid = NULL;
7057 STACK_OF(X509) *chain = NULL;
7058 struct issuer_chain *issuer;
7059 struct eb64_node *node;
7060 char *path;
7061 u64 key;
7062 int ret = 0;
7063
7064 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
7065 if (chain == NULL) {
7066 chain = sk_X509_new_null();
7067 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
7068 name = X509_get_subject_name(ca);
7069 }
7070 if (!sk_X509_push(chain, ca)) {
7071 X509_free(ca);
7072 goto end;
7073 }
7074 }
7075 if (!chain) {
7076 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
7077 goto end;
7078 }
7079 if (!skid) {
7080 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
7081 goto end;
7082 }
7083 if (!name) {
7084 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
7085 goto end;
7086 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01007087 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01007088 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007089 issuer = container_of(node, typeof(*issuer), node);
7090 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
7091 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
7092 goto end;
7093 }
7094 }
7095 issuer = calloc(1, sizeof *issuer);
7096 path = strdup(fp);
7097 if (!issuer || !path) {
7098 free(issuer);
7099 free(path);
7100 goto end;
7101 }
7102 issuer->node.key = key;
7103 issuer->path = path;
7104 issuer->chain = chain;
7105 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01007106 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007107 ret = 1;
7108 end:
7109 if (skid)
7110 ASN1_OCTET_STRING_free(skid);
7111 if (chain)
7112 sk_X509_pop_free(chain, X509_free);
7113 return ret;
7114}
7115
William Lallemandda8584c2020-05-14 10:14:37 +02007116 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007117{
7118 AUTHORITY_KEYID *akid;
7119 struct issuer_chain *issuer = NULL;
7120
7121 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01007122 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007123 struct eb64_node *node;
7124 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01007125 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007126 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
7127 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
7128 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
7129 issuer = ti;
7130 break;
7131 }
7132 }
7133 AUTHORITY_KEYID_free(akid);
7134 }
7135 return issuer;
7136}
7137
William Lallemanddad31052020-05-14 17:47:32 +02007138void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007139{
7140 struct eb64_node *node, *back;
7141 struct issuer_chain *issuer;
7142
William Lallemande0f3fd52020-02-25 14:53:06 +01007143 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007144 while (node) {
7145 issuer = container_of(node, typeof(*issuer), node);
7146 back = eb64_next(node);
7147 eb64_delete(node);
7148 free(issuer->path);
7149 sk_X509_pop_free(issuer->chain, X509_free);
7150 free(issuer);
7151 node = back;
7152 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007153}
7154
William Lallemandd7bfbe22022-04-11 18:41:24 +02007155#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007156static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01007157 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007158
Emeric Brun3854e012017-05-17 20:42:48 +02007159 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01007160 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007161 err_code = ERR_ABORT;
7162 }
7163 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01007164}
Willy Tarreau9ceda382016-12-21 23:13:03 +01007165#endif
7166
Willy Tarreaude5675a2021-01-20 14:41:29 +01007167/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007168 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01007169 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01007170static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01007171{
7172 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007173 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007174
7175 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007176 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007177
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007178 if (sctx->conn != conn) {
7179 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
7180 ret = 1;
7181 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01007182 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
7183
7184 if (sctx->xprt) {
7185 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
7186 if (sctx->xprt_ctx)
7187 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
7188 }
7189
7190 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007191
7192 /* as soon as a shutdown is reported the lower layer unregisters its
7193 * subscriber, so the situations below are transient and rare enough to
7194 * be reported as suspicious. In any case they shouldn't last.
7195 */
7196 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
7197 ret = 1;
7198 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
7199 ret = 1;
7200
Willy Tarreaude5675a2021-01-20 14:41:29 +01007201 chunk_appendf(&trash, " .subs=%p", sctx->subs);
7202 if (sctx->subs) {
7203 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007204 if (sctx->subs->tasklet->calls >= 1000000)
7205 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007206 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
7207 sctx->subs->tasklet->calls,
7208 sctx->subs->tasklet->context);
7209 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
7210 chunk_appendf(&trash, ")");
7211 }
7212 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
7213 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007214 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007215}
7216
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007217#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02007218/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007219 * each reference. The variable <ref> must point to the current node's list
7220 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02007221 */
William Lallemand32af2032016-10-29 18:09:35 +02007222static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007223struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02007224{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007225 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007226 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02007227
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007228 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007229 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007230 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02007231
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007232 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02007233}
7234
7235static inline
7236struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
7237{
7238 int id;
7239 char *error;
7240
7241 /* If the reference starts by a '#', this is numeric id. */
7242 if (reference[0] == '#') {
7243 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
7244 id = strtol(reference + 1, &error, 10);
7245 if (*error != '\0')
7246 return NULL;
7247
7248 /* Perform the unique id lookup. */
7249 return tlskeys_ref_lookupid(id);
7250 }
7251
7252 /* Perform the string lookup. */
7253 return tlskeys_ref_lookup(reference);
7254}
7255#endif
7256
7257
7258#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7259
Willy Tarreaua9380522022-05-05 08:50:17 +02007260/* dumps all tls keys. Relies on the show_keys_ctx context from the appctx. */
Willy Tarreaubd338642022-05-05 08:59:17 +02007261static int cli_io_handler_tlskeys_files(struct appctx *appctx)
7262{
Willy Tarreaua9380522022-05-05 08:50:17 +02007263 struct show_keys_ctx *ctx = appctx->svcctx;
William Lallemand32af2032016-10-29 18:09:35 +02007264
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007265 switch (ctx->state) {
7266 case SHOW_KEYS_INIT:
William Lallemand32af2032016-10-29 18:09:35 +02007267 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08007268 * quit the function with returning 0. The function is called
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007269 * later and restart at the state "SHOW_KEYS_INIT".
William Lallemand32af2032016-10-29 18:09:35 +02007270 */
7271 chunk_reset(&trash);
7272
Willy Tarreaubd338642022-05-05 08:59:17 +02007273 if (ctx->dump_entries)
William Lallemand32af2032016-10-29 18:09:35 +02007274 chunk_appendf(&trash, "# id secret\n");
7275 else
7276 chunk_appendf(&trash, "# id (file)\n");
7277
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007278 if (applet_putchk(appctx, &trash) == -1)
William Lallemand32af2032016-10-29 18:09:35 +02007279 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007280
William Lallemand32af2032016-10-29 18:09:35 +02007281 /* Now, we start the browsing of the references lists.
7282 * Note that the following call to LIST_ELEM return bad pointer. The only
7283 * available field of this pointer is <list>. It is used with the function
7284 * tlskeys_list_get_next() for retruning the first available entry
7285 */
Willy Tarreaua9380522022-05-05 08:50:17 +02007286 if (ctx->next_ref == NULL)
7287 ctx->next_ref = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007288
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007289 ctx->state = SHOW_KEYS_LIST;
William Lallemand32af2032016-10-29 18:09:35 +02007290 /* fall through */
7291
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007292 case SHOW_KEYS_LIST:
Willy Tarreaua9380522022-05-05 08:50:17 +02007293 while (ctx->next_ref) {
7294 struct tls_keys_ref *ref = ctx->next_ref;
William Lallemand32af2032016-10-29 18:09:35 +02007295
7296 chunk_reset(&trash);
Willy Tarreaubd338642022-05-05 08:59:17 +02007297 if (ctx->dump_entries && ctx->next_index == 0)
William Lallemand32af2032016-10-29 18:09:35 +02007298 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007299
Willy Tarreaua9380522022-05-05 08:50:17 +02007300 if (ctx->next_index == 0)
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007301 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
7302
Willy Tarreaubd338642022-05-05 08:59:17 +02007303 if (ctx->dump_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01007304 int head;
7305
7306 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
7307 head = ref->tls_ticket_enc_index;
Willy Tarreaua9380522022-05-05 08:50:17 +02007308 while (ctx->next_index < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02007309 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02007310
7311 chunk_reset(t2);
7312 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01007313 if (ref->key_size_bits == 128) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007314 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007315 sizeof(struct tls_sess_key_128),
7316 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007317 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007318 t2->area);
7319 }
7320 else if (ref->key_size_bits == 256) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007321 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007322 sizeof(struct tls_sess_key_256),
7323 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007324 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007325 t2->area);
7326 }
7327 else {
7328 /* This case should never happen */
Willy Tarreaua9380522022-05-05 08:50:17 +02007329 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, ctx->next_index);
Emeric Brun9e754772019-01-10 17:51:55 +01007330 }
William Lallemand32af2032016-10-29 18:09:35 +02007331
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007332 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007333 /* let's try again later from this stream. We add ourselves into
7334 * this stream's users so that it can remove us upon termination.
7335 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01007336 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
William Lallemand32af2032016-10-29 18:09:35 +02007337 return 0;
7338 }
Willy Tarreaua9380522022-05-05 08:50:17 +02007339 ctx->next_index++;
William Lallemand32af2032016-10-29 18:09:35 +02007340 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01007341 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaua9380522022-05-05 08:50:17 +02007342 ctx->next_index = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007343 }
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007344 if (applet_putchk(appctx, &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007345 /* let's try again later from this stream. We add ourselves into
7346 * this stream's users so that it can remove us upon termination.
7347 */
William Lallemand32af2032016-10-29 18:09:35 +02007348 return 0;
7349 }
7350
Willy Tarreaua9380522022-05-05 08:50:17 +02007351 if (ctx->names_only == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02007352 break;
7353
7354 /* get next list entry and check the end of the list */
Willy Tarreaua9380522022-05-05 08:50:17 +02007355 ctx->next_ref = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007356 }
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007357 ctx->state = SHOW_KEYS_DONE;
William Lallemand32af2032016-10-29 18:09:35 +02007358 /* fall through */
7359
7360 default:
William Lallemand32af2032016-10-29 18:09:35 +02007361 return 1;
7362 }
7363 return 0;
7364}
7365
Willy Tarreaua9380522022-05-05 08:50:17 +02007366/* Prepares a "show_keys_ctx" and sets the appropriate io_handler if needed */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007367static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007368{
Willy Tarreaua9380522022-05-05 08:50:17 +02007369 struct show_keys_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
7370
William Lallemand32af2032016-10-29 18:09:35 +02007371 /* no parameter, shows only file list */
7372 if (!*args[2]) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007373 ctx->names_only = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007374 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007375 }
7376
7377 if (args[2][0] == '*') {
7378 /* list every TLS ticket keys */
Willy Tarreaua9380522022-05-05 08:50:17 +02007379 ctx->names_only = 1;
William Lallemand32af2032016-10-29 18:09:35 +02007380 } else {
Willy Tarreaua9380522022-05-05 08:50:17 +02007381 ctx->next_ref = tlskeys_ref_lookup_ref(args[2]);
7382 if (!ctx->next_ref)
Willy Tarreau9d008692019-08-09 11:21:01 +02007383 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02007384 }
Willy Tarreaubd338642022-05-05 08:59:17 +02007385
7386 ctx->dump_entries = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007387 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007388}
7389
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007390static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007391{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007392 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02007393 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007394
William Lallemand32af2032016-10-29 18:09:35 +02007395 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02007396 if (!*args[3] || !*args[4])
7397 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 +02007398
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007399 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02007400 if (!ref)
7401 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02007402
Willy Tarreau1c913e42018-08-22 05:26:57 +02007403 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02007404 if (ret < 0)
7405 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01007406
Willy Tarreau1c913e42018-08-22 05:26:57 +02007407 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02007408 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
7409 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007410
Willy Tarreau9d008692019-08-09 11:21:01 +02007411 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02007412}
William Lallemandd4f946c2019-12-05 10:26:40 +01007413#endif
William Lallemand419e6342020-04-08 12:05:39 +02007414
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007415static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007416{
7417#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
7418 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02007419 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02007420
7421 if (!payload)
7422 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02007423
7424 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02007425 if (!*payload)
7426 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02007427
7428 /* remove \r and \n from the payload */
7429 for (i = 0, j = 0; payload[i]; i++) {
7430 if (payload[i] == '\r' || payload[i] == '\n')
7431 continue;
7432 payload[j++] = payload[i];
7433 }
7434 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007435
Willy Tarreau1c913e42018-08-22 05:26:57 +02007436 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02007437 if (ret < 0)
7438 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007439
Willy Tarreau1c913e42018-08-22 05:26:57 +02007440 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02007441 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02007442 if (err)
7443 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
7444 else
7445 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007446 }
Willy Tarreau9d008692019-08-09 11:21:01 +02007447
7448 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02007449#else
Willy Tarreau9d008692019-08-09 11:21:01 +02007450 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 +02007451#endif
7452
Elliot Otchet71f82972020-01-15 08:12:14 -05007453}
7454
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007455
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007456#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 +02007457static int cli_io_handler_show_ocspresponse_detail(struct appctx *appctx);
7458#endif
7459
Willy Tarreau170b35b2022-05-05 09:09:15 +02007460/* parsing function for 'show ssl ocsp-response [id]'. If an entry is forced,
7461 * it's set into appctx->svcctx.
7462 */
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007463static int cli_parse_show_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
7464{
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007465#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 +02007466 if (*args[3]) {
7467 struct certificate_ocsp *ocsp = NULL;
7468 char *key = NULL;
7469 int key_length = 0;
7470
7471 if (strlen(args[3]) > OCSP_MAX_CERTID_ASN1_LENGTH*2) {
7472 return cli_err(appctx, "'show ssl ocsp-response' received a too big key.\n");
7473 }
7474
7475 if (parse_binary(args[3], &key, &key_length, NULL)) {
7476
7477 char full_key[OCSP_MAX_CERTID_ASN1_LENGTH] = {};
7478 memcpy(full_key, key, key_length);
7479
7480 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, full_key, OCSP_MAX_CERTID_ASN1_LENGTH);
7481 }
7482 if (key)
7483 ha_free(&key);
7484
7485 if (!ocsp) {
7486 return cli_err(appctx, "Certificate ID does not match any certificate.\n");
7487 }
7488
Willy Tarreau170b35b2022-05-05 09:09:15 +02007489 appctx->svcctx = ocsp;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007490 appctx->io_handler = cli_io_handler_show_ocspresponse_detail;
7491 }
7492
7493 return 0;
7494
7495#else
7496 return cli_err(appctx, "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n");
7497#endif
7498}
7499
7500
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007501#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 +02007502/*
7503 * This function dumps the details of an OCSP_CERTID. It is based on
7504 * ocsp_certid_print in OpenSSL.
7505 */
7506static inline int ocsp_certid_print(BIO *bp, OCSP_CERTID *certid, int indent)
7507{
7508 ASN1_OCTET_STRING *piNameHash = NULL;
7509 ASN1_OCTET_STRING *piKeyHash = NULL;
7510 ASN1_INTEGER *pSerial = NULL;
7511
7512 if (OCSP_id_get0_info(&piNameHash, NULL, &piKeyHash, &pSerial, certid)) {
7513
7514 BIO_printf(bp, "%*sCertificate ID:\n", indent, "");
7515 indent += 2;
Remi Tricot-Le Bretoncc750ef2021-12-17 18:53:23 +01007516 BIO_printf(bp, "%*sIssuer Name Hash: ", indent, "");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007517 i2a_ASN1_STRING(bp, piNameHash, 0);
7518 BIO_printf(bp, "\n%*sIssuer Key Hash: ", indent, "");
7519 i2a_ASN1_STRING(bp, piKeyHash, 0);
7520 BIO_printf(bp, "\n%*sSerial Number: ", indent, "");
7521 i2a_ASN1_INTEGER(bp, pSerial);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007522 }
7523 return 1;
7524}
7525#endif
7526
7527/*
7528 * IO handler of "show ssl ocsp-response". The command taking a specific ID
7529 * is managed in cli_io_handler_show_ocspresponse_detail.
Willy Tarreau170b35b2022-05-05 09:09:15 +02007530 * The current entry is taken from appctx->svcctx.
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007531 */
7532static int cli_io_handler_show_ocspresponse(struct appctx *appctx)
7533{
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007534#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 +02007535 struct buffer *trash = alloc_trash_chunk();
7536 struct buffer *tmp = NULL;
7537 struct ebmb_node *node;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007538 struct certificate_ocsp *ocsp = NULL;
7539 BIO *bio = NULL;
7540 int write = -1;
7541
7542 if (trash == NULL)
7543 return 1;
7544
7545 tmp = alloc_trash_chunk();
7546 if (!tmp)
7547 goto end;
7548
7549 if ((bio = BIO_new(BIO_s_mem())) == NULL)
7550 goto end;
7551
Willy Tarreau170b35b2022-05-05 09:09:15 +02007552 if (!appctx->svcctx) {
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007553 chunk_appendf(trash, "# Certificate IDs\n");
7554 node = ebmb_first(&cert_ocsp_tree);
7555 } else {
Willy Tarreau170b35b2022-05-05 09:09:15 +02007556 node = &((struct certificate_ocsp *)appctx->svcctx)->key;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007557 }
7558
7559 while (node) {
7560 OCSP_CERTID *certid = NULL;
7561 const unsigned char *p = NULL;
7562 int i;
7563
7564 ocsp = ebmb_entry(node, struct certificate_ocsp, key);
7565
7566 /* Dump the key in hexadecimal */
7567 chunk_appendf(trash, "Certificate ID key : ");
7568 for (i = 0; i < ocsp->key_length; ++i) {
7569 chunk_appendf(trash, "%02x", ocsp->key_data[i]);
7570 }
7571 chunk_appendf(trash, "\n");
7572
7573 p = ocsp->key_data;
7574
7575 /* Decode the certificate ID (serialized into the key). */
7576 d2i_OCSP_CERTID(&certid, &p, ocsp->key_length);
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007577 if (!certid)
7578 goto end;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007579
7580 /* Dump the CERTID info */
7581 ocsp_certid_print(bio, certid, 1);
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007582 OCSP_CERTID_free(certid);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007583 write = BIO_read(bio, tmp->area, tmp->size-1);
Remi Tricot-Le Bretoncc750ef2021-12-17 18:53:23 +01007584 /* strip trailing LFs */
7585 while (write > 0 && tmp->area[write-1] == '\n')
7586 write--;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007587 tmp->area[write] = '\0';
7588
7589 chunk_appendf(trash, "%s\n", tmp->area);
7590
7591 node = ebmb_next(node);
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007592 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007593 goto yield;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007594 }
7595
7596end:
Willy Tarreau170b35b2022-05-05 09:09:15 +02007597 appctx->svcctx = NULL;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007598 if (trash)
7599 free_trash_chunk(trash);
7600 if (tmp)
7601 free_trash_chunk(tmp);
7602 if (bio)
7603 BIO_free(bio);
7604 return 1;
7605
7606yield:
7607
7608 if (trash)
7609 free_trash_chunk(trash);
7610 if (tmp)
7611 free_trash_chunk(tmp);
7612 if (bio)
7613 BIO_free(bio);
Willy Tarreau170b35b2022-05-05 09:09:15 +02007614 appctx->svcctx = ocsp;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007615 return 0;
7616#else
7617 return cli_err(appctx, "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n");
7618#endif
7619}
7620
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007621#ifdef HAVE_SSL_PROVIDERS
7622struct provider_name {
7623 const char *name;
7624 struct list list;
7625};
7626
7627
7628static int ssl_provider_get_name_cb(OSSL_PROVIDER *provider, void *cbdata)
7629{
7630 struct list *provider_names = cbdata;
7631 struct provider_name *item = NULL;
7632 const char *name = OSSL_PROVIDER_get0_name(provider);
7633
7634 if (!provider_names)
7635 return 0;
7636
7637 item = calloc(1, sizeof(*item));
7638
7639 if (!item)
7640 return 0;
7641
7642 item->name = name;
7643 LIST_APPEND(provider_names, &item->list);
7644
7645 return 1;
7646}
7647
7648static void ssl_provider_get_name_list(struct list *provider_names)
7649{
7650 if (!provider_names)
7651 return;
7652
7653 OSSL_PROVIDER_do_all(NULL, ssl_provider_get_name_cb, provider_names);
7654}
7655
7656static void ssl_provider_clear_name_list(struct list *provider_names)
7657{
7658 struct provider_name *item = NULL, *item_s = NULL;
7659
7660 if (provider_names) {
7661 list_for_each_entry_safe(item, item_s, provider_names, list) {
7662 LIST_DELETE(&item->list);
7663 free(item);
7664 }
7665 }
7666}
7667
7668static int cli_io_handler_show_providers(struct appctx *appctx)
7669{
7670 struct buffer *trash = get_trash_chunk();
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007671 struct list provider_names;
7672 struct provider_name *name;
7673
7674 LIST_INIT(&provider_names);
7675
7676 chunk_appendf(trash, "Loaded providers : \n");
7677
7678 ssl_provider_get_name_list(&provider_names);
7679
7680 list_for_each_entry(name, &provider_names, list) {
7681 chunk_appendf(trash, "\t- %s\n", name->name);
7682 }
7683
7684 ssl_provider_clear_name_list(&provider_names);
7685
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007686 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007687 goto yield;
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007688
7689 return 1;
7690
7691yield:
7692 return 0;
7693}
7694#endif
7695
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007696
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007697#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 +02007698/*
7699 * Dump the details about an OCSP response in DER format stored in
7700 * <ocsp_response> into buffer <out>.
7701 * Returns 0 in case of success.
7702 */
7703int ssl_ocsp_response_print(struct buffer *ocsp_response, struct buffer *out)
7704{
7705 BIO *bio = NULL;
7706 int write = -1;
7707 OCSP_RESPONSE *resp;
7708 const unsigned char *p;
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01007709 int retval = -1;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007710
7711 if (!ocsp_response)
7712 return -1;
7713
7714 if ((bio = BIO_new(BIO_s_mem())) == NULL)
7715 return -1;
7716
7717 p = (const unsigned char*)ocsp_response->area;
7718
7719 resp = d2i_OCSP_RESPONSE(NULL, &p, ocsp_response->data);
7720 if (!resp) {
7721 chunk_appendf(out, "Unable to parse OCSP response");
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007722 goto end;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007723 }
7724
7725 if (OCSP_RESPONSE_print(bio, resp, 0) != 0) {
Remi Tricot-Le Breton2e7d1eb2022-01-11 10:11:10 +01007726 struct buffer *trash = get_trash_chunk();
7727 struct ist ist_block = IST_NULL;
7728 struct ist ist_double_lf = IST_NULL;
7729 static struct ist double_lf = IST("\n\n");
7730
7731 write = BIO_read(bio, trash->area, trash->size - 1);
Remi Tricot-Le Breton1b01b7f2022-02-16 15:17:09 +01007732 if (write <= 0)
7733 goto end;
Remi Tricot-Le Breton2e7d1eb2022-01-11 10:11:10 +01007734 trash->data = write;
7735
7736 /* Look for empty lines in the 'trash' buffer and add a space to
7737 * the beginning to avoid having empty lines in the output
7738 * (without changing the appearance of the information
7739 * displayed).
7740 */
7741 ist_block = ist2(b_orig(trash), b_data(trash));
7742
7743 ist_double_lf = istist(ist_block, double_lf);
7744
7745 while (istlen(ist_double_lf)) {
7746 /* istptr(ist_double_lf) points to the first \n of a
7747 * \n\n pattern.
7748 */
7749 uint empty_line_offset = istptr(ist_double_lf) + 1 - istptr(ist_block);
7750
7751 /* Write up to the first '\n' of the "\n\n" pattern into
7752 * the output buffer.
7753 */
7754 b_putblk(out, istptr(ist_block), empty_line_offset);
7755 /* Add an extra space. */
7756 b_putchr(out, ' ');
7757
7758 /* Keep looking for empty lines in the rest of the data. */
7759 ist_block = istadv(ist_block, empty_line_offset);
7760
7761 ist_double_lf = istist(ist_block, double_lf);
7762 }
7763
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01007764 retval = (b_istput(out, ist_block) <= 0);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007765 }
7766
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007767end:
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007768 if (bio)
7769 BIO_free(bio);
7770
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007771 OCSP_RESPONSE_free(resp);
7772
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01007773 return retval;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007774}
7775
7776/*
7777 * Dump the details of the OCSP response of ID <ocsp_certid> into buffer <out>.
7778 * Returns 0 in case of success.
7779 */
7780int ssl_get_ocspresponse_detail(unsigned char *ocsp_certid, struct buffer *out)
7781{
7782 struct certificate_ocsp *ocsp;
7783
7784 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, ocsp_certid, OCSP_MAX_CERTID_ASN1_LENGTH);
7785 if (!ocsp)
7786 return -1;
7787
7788 return ssl_ocsp_response_print(&ocsp->response, out);
7789}
7790
7791
Willy Tarreau170b35b2022-05-05 09:09:15 +02007792/* IO handler of details "show ssl ocsp-response <id>".
7793 * The current entry is taken from appctx->svcctx.
7794 */
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007795static int cli_io_handler_show_ocspresponse_detail(struct appctx *appctx)
7796{
7797 struct buffer *trash = alloc_trash_chunk();
Willy Tarreau170b35b2022-05-05 09:09:15 +02007798 struct certificate_ocsp *ocsp = appctx->svcctx;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007799
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007800 if (trash == NULL)
7801 return 1;
7802
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01007803 if (ssl_ocsp_response_print(&ocsp->response, trash)) {
7804 free_trash_chunk(trash);
7805 return 1;
7806 }
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007807
Willy Tarreaud0a06d52022-05-18 15:07:19 +02007808 if (applet_putchk(appctx, trash) == -1)
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007809 goto yield;
Willy Tarreau170b35b2022-05-05 09:09:15 +02007810
7811 appctx->svcctx = NULL;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007812 if (trash)
7813 free_trash_chunk(trash);
7814 return 1;
7815
7816yield:
7817 if (trash)
7818 free_trash_chunk(trash);
7819
7820 return 0;
7821}
7822#endif
7823
William Lallemand32af2032016-10-29 18:09:35 +02007824/* register cli keywords */
7825static struct cli_kw_list cli_kws = {{ },{
7826#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Willy Tarreaubd338642022-05-05 08:59:17 +02007827 { { "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 +02007828 { { "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 +02007829#endif
Willy Tarreaub205bfd2021-05-07 11:38:37 +02007830 { { "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 +02007831
7832 { { "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 +02007833#ifdef HAVE_SSL_PROVIDERS
7834 { { "show", "ssl", "providers", NULL }, "show ssl providers : show loaded SSL providers", NULL, cli_io_handler_show_providers },
7835#endif
William Lallemand32af2032016-10-29 18:09:35 +02007836 { { NULL }, NULL, NULL, NULL }
7837}};
7838
Willy Tarreau0108d902018-11-25 19:14:37 +01007839INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02007840
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02007841/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02007842struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02007843 .snd_buf = ssl_sock_from_buf,
7844 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01007845 .subscribe = ssl_subscribe,
7846 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02007847 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02007848 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02007849 .rcv_pipe = NULL,
7850 .snd_pipe = NULL,
7851 .shutr = NULL,
7852 .shutw = ssl_sock_shutw,
7853 .close = ssl_sock_close,
7854 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01007855 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01007856 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01007857 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01007858 .prepare_srv = ssl_sock_prepare_srv_ctx,
7859 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007860 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02007861 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01007862 .set_idle = ssl_set_idle,
7863 .set_used = ssl_set_used,
Willy Tarreaude827952022-04-11 10:43:28 +02007864 .get_ssl_sock_ctx = ssl_sock_get_ctx,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01007865 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01007866 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02007867};
7868
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007869enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
7870 struct session *sess, struct stream *s, int flags)
7871{
7872 struct connection *conn;
7873
7874 conn = objt_conn(sess->origin);
7875
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007876 if (conn) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007877 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Willy Tarreaub52d4d22022-05-27 10:44:39 +02007878 sc_ep_set(s->scf, SE_FL_WAIT_FOR_HS);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007879 s->req.flags |= CF_READ_NULL;
7880 return ACT_RET_YIELD;
7881 }
7882 }
7883 return (ACT_RET_CONT);
7884}
7885
7886static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
7887{
7888 rule->action_ptr = ssl_action_wait_for_hs;
7889
7890 return ACT_RET_PRS_OK;
7891}
7892
7893static struct action_kw_list http_req_actions = {ILH, {
7894 { "wait-for-handshake", ssl_parse_wait_for_hs },
7895 { /* END */ }
7896}};
7897
Willy Tarreau0108d902018-11-25 19:14:37 +01007898INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
7899
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007900#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007901
7902static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7903{
7904 if (ptr) {
7905 chunk_destroy(ptr);
7906 free(ptr);
7907 }
7908}
7909
7910#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007911
7912#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7913static void ssl_sock_ocsp_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7914{
7915 struct ocsp_cbk_arg *ocsp_arg;
7916
7917 if (ptr) {
7918 ocsp_arg = ptr;
7919
7920 if (ocsp_arg->is_single) {
7921 ssl_sock_free_ocsp(ocsp_arg->s_ocsp);
7922 ocsp_arg->s_ocsp = NULL;
7923 } else {
7924 int i;
7925
7926 for (i = 0; i < SSL_SOCK_NUM_KEYTYPES; i++) {
7927 ssl_sock_free_ocsp(ocsp_arg->m_ocsp[i]);
7928 ocsp_arg->m_ocsp[i] = NULL;
7929 }
7930 }
7931 free(ocsp_arg);
7932 }
7933}
7934#endif
7935
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007936static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7937{
Willy Tarreaubafbe012017-11-24 17:34:44 +01007938 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007939}
William Lallemand7d42ef52020-07-06 11:41:30 +02007940
William Lallemand722180a2021-06-09 16:46:12 +02007941#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007942static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7943{
7944 struct ssl_keylog *keylog;
7945
7946 if (!ptr)
7947 return;
7948
7949 keylog = ptr;
7950
7951 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7952 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7953 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7954 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7955 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7956 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7957 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7958 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7959
7960 pool_free(pool_head_ssl_keylog, ptr);
7961}
7962#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007963
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007964static void ssl_sock_clt_crt_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7965{
7966 if (!ptr)
7967 return;
7968
7969 X509_free((X509*)ptr);
7970}
7971
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01007972static void ssl_sock_clt_sni_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7973{
7974 pool_free(ssl_sock_client_sni_pool, ptr);
7975}
7976
Willy Tarreau92faadf2012-10-10 23:04:25 +02007977static void __ssl_sock_init(void)
7978{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007979#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007980 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007981 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007982#endif
Emeric Brun46591952012-05-18 15:47:34 +02007983
Willy Tarreauef934602016-12-22 23:12:01 +01007984 if (global_ssl.listen_default_ciphers)
7985 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7986 if (global_ssl.connect_default_ciphers)
7987 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007988#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007989 if (global_ssl.listen_default_ciphersuites)
7990 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7991 if (global_ssl.connect_default_ciphersuites)
7992 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7993#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007994
Willy Tarreau13e14102016-12-22 20:25:26 +01007995 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007996#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007997 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007998#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007999#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02008000 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05008001 n = sk_SSL_COMP_num(cm);
8002 while (n--) {
8003 (void) sk_SSL_COMP_pop(cm);
8004 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05008005#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05008006
Willy Tarreau5db847a2019-05-09 14:13:35 +02008007#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02008008 ssl_locking_init();
8009#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05008010#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01008011 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
8012#endif
William Lallemand76b4a122020-08-04 17:41:39 +02008013
8014#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
8015 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
8016#endif
8017
Thierry FOURNIER28962c92018-06-17 21:37:05 +02008018 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02008019 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 +01008020#ifdef USE_QUIC
8021 ssl_qc_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
8022#endif /* USE_QUIC */
William Lallemand722180a2021-06-09 16:46:12 +02008023#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02008024 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
8025#endif
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02008026 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 +01008027 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 +02008028#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00008029 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00008030 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02008031#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01008032#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
8033 hap_register_post_check(tlskeys_finalize_config);
8034#endif
Willy Tarreau80713382018-11-26 10:19:54 +01008035
8036 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
8037 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
8038
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01008039 hap_register_post_deinit(ssl_free_global_issuers);
8040
Willy Tarreau80713382018-11-26 10:19:54 +01008041#ifndef OPENSSL_NO_DH
8042 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
8043 hap_register_post_deinit(ssl_free_dh);
8044#endif
William Lallemandd7bfbe22022-04-11 18:41:24 +02008045#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Willy Tarreau80713382018-11-26 10:19:54 +01008046 hap_register_post_deinit(ssl_free_engines);
8047#endif
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02008048#ifdef HAVE_SSL_PROVIDERS
8049 hap_register_post_deinit(ssl_unload_providers);
8050#endif
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01008051#if HA_OPENSSL_VERSION_NUMBER < 0x3000000fL
Willy Tarreau80713382018-11-26 10:19:54 +01008052 /* Load SSL string for the verbose & debug mode. */
8053 ERR_load_SSL_strings();
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01008054#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02008055 ha_meth = BIO_meth_new(0x666, "ha methods");
8056 BIO_meth_set_write(ha_meth, ha_ssl_write);
8057 BIO_meth_set_read(ha_meth, ha_ssl_read);
8058 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
8059 BIO_meth_set_create(ha_meth, ha_ssl_new);
8060 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
8061 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
8062 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02008063
8064 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02008065
Dragan Dosen9ac98092020-05-11 15:51:45 +02008066 /* Try to register dedicated SSL/TLS protocol message callbacks for
8067 * heartbleed attack (CVE-2014-0160) and clienthello.
8068 */
8069 hap_register_post_check(ssl_sock_register_msg_callbacks);
8070
Dragan Dosen1e7ed042020-05-08 18:30:00 +02008071 /* Try to free all callbacks that were registered by using
8072 * ssl_sock_register_msg_callback().
8073 */
8074 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01008075}
Willy Tarreau79367f92022-04-25 19:18:24 +02008076INITCALL0(STG_REGISTER, __ssl_sock_init);
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01008077
Willy Tarreau80713382018-11-26 10:19:54 +01008078/* Compute and register the version string */
8079static void ssl_register_build_options()
8080{
8081 char *ptr = NULL;
8082 int i;
8083
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008084 memprintf(&ptr, "Built with OpenSSL version : "
8085#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01008086 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008087#else /* OPENSSL_IS_BORINGSSL */
8088 OPENSSL_VERSION_TEXT
8089 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08008090 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02008091 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008092#endif
8093 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02008094#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008095 "no (library version too old)"
8096#elif defined(OPENSSL_NO_TLSEXT)
8097 "no (disabled via OPENSSL_NO_TLSEXT)"
8098#else
8099 "yes"
8100#endif
8101 "", ptr);
8102
8103 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
8104#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
8105 "yes"
8106#else
8107#ifdef OPENSSL_NO_TLSEXT
8108 "no (because of OPENSSL_NO_TLSEXT)"
8109#else
8110 "no (version might be too old, 0.9.8f min needed)"
8111#endif
8112#endif
8113 "", ptr);
8114
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02008115 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
8116 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
8117 if (methodVersions[i].option)
8118 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01008119
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02008120#ifdef HAVE_SSL_PROVIDERS
8121 {
8122 struct list provider_names;
8123 struct provider_name *name;
8124 LIST_INIT(&provider_names);
8125 ssl_provider_get_name_list(&provider_names);
8126
8127 memprintf(&ptr, "%s\nOpenSSL providers loaded :", ptr);
8128
8129 list_for_each_entry(name, &provider_names, list) {
8130 memprintf(&ptr, "%s %s", ptr, name->name);
8131 }
8132
8133 ssl_provider_clear_name_list(&provider_names);
8134 }
8135#endif
8136
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008137 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01008138}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008139
Willy Tarreau80713382018-11-26 10:19:54 +01008140INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02008141
William Lallemandd7bfbe22022-04-11 18:41:24 +02008142#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00008143void ssl_free_engines(void) {
8144 struct ssl_engine_list *wl, *wlb;
8145 /* free up engine list */
8146 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
8147 ENGINE_finish(wl->e);
8148 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02008149 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00008150 free(wl);
8151 }
8152}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02008153#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02008154
Remi Tricot-Le Breton1746a382022-05-16 16:24:33 +02008155#ifdef HAVE_SSL_PROVIDERS
8156void ssl_unload_providers(void) {
8157 struct ssl_provider_list *prov, *provb;
8158 list_for_each_entry_safe(prov, provb, &openssl_providers, list) {
8159 OSSL_PROVIDER_unload(prov->provider);
8160 LIST_DELETE(&prov->list);
8161 free(prov);
8162 }
8163}
8164#endif
8165
Remi Gacogned3a23c32015-05-28 16:39:47 +02008166#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00008167void ssl_free_dh(void) {
8168 if (local_dh_1024) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008169 HASSL_DH_free(local_dh_1024);
Grant Zhang872f9c22017-01-21 01:10:18 +00008170 local_dh_1024 = NULL;
8171 }
8172 if (local_dh_2048) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008173 HASSL_DH_free(local_dh_2048);
Grant Zhang872f9c22017-01-21 01:10:18 +00008174 local_dh_2048 = NULL;
8175 }
8176 if (local_dh_4096) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008177 HASSL_DH_free(local_dh_4096);
Grant Zhang872f9c22017-01-21 01:10:18 +00008178 local_dh_4096 = NULL;
8179 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02008180 if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008181 HASSL_DH_free(global_dh);
Remi Gacogne47783ef2015-05-29 15:53:22 +02008182 global_dh = NULL;
8183 }
Grant Zhang872f9c22017-01-21 01:10:18 +00008184}
8185#endif
8186
Grant Zhang872f9c22017-01-21 01:10:18 +00008187static void __ssl_sock_deinit(void)
8188{
8189#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02008190 if (ssl_ctx_lru_tree) {
8191 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01008192 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02008193 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02008194#endif
8195
Willy Tarreau5db847a2019-05-09 14:13:35 +02008196#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02008197 ERR_remove_state(0);
8198 ERR_free_strings();
8199
8200 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08008201#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02008202
Willy Tarreau5db847a2019-05-09 14:13:35 +02008203#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02008204 CRYPTO_cleanup_all_ex_data();
8205#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02008206 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02008207}
Willy Tarreau79367f92022-04-25 19:18:24 +02008208REGISTER_POST_DEINIT(__ssl_sock_deinit);
Remi Gacogned3a23c32015-05-28 16:39:47 +02008209
William Dauchyf6370442020-11-14 19:25:33 +01008210
Emeric Brun46591952012-05-18 15:47:34 +02008211/*
8212 * Local variables:
8213 * c-indent-level: 8
8214 * c-basic-offset: 8
8215 * End:
8216 */