blob: 6ffdf4d94637efef84ee00de29be5d7110f5c7a8 [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>
Christopher Faulet908628c2022-03-25 16:43:49 +010054#include <haproxy/conn_stream.h>
55#include <haproxy/cs_utils.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020056#include <haproxy/dynbuf.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020057#include <haproxy/errors.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020058#include <haproxy/fd.h>
59#include <haproxy/freq_ctr.h>
Willy Tarreau762d7a52020-06-04 11:23:07 +020060#include <haproxy/frontend.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020061#include <haproxy/global.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020062#include <haproxy/http_rules.h>
Willy Tarreauaeed4a82020-06-04 22:01:04 +020063#include <haproxy/log.h>
Willy Tarreau6019fab2020-05-27 16:26:00 +020064#include <haproxy/openssl-compat.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020065#include <haproxy/pattern-t.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020066#include <haproxy/proto_tcp.h>
Willy Tarreaua264d962020-06-04 22:29:18 +020067#include <haproxy/proxy.h>
Willy Tarreau1e56f922020-06-04 23:20:13 +020068#include <haproxy/server.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020069#include <haproxy/shctx.h>
Willy Tarreau47d7f902020-06-04 14:25:47 +020070#include <haproxy/ssl_ckch.h>
Willy Tarreau52d88722020-06-04 14:29:23 +020071#include <haproxy/ssl_crtlist.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020072#include <haproxy/ssl_sock.h>
Willy Tarreaub2bd8652020-06-04 14:21:22 +020073#include <haproxy/ssl_utils.h>
William Lallemand43c2ce42022-03-16 17:48:19 +010074#include <haproxy/sample.h>
Amaury Denoyelle9963fa72020-11-03 17:10:00 +010075#include <haproxy/stats.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020076#include <haproxy/stream-t.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020077#include <haproxy/task.h>
Willy Tarreauc2f7c582020-06-02 18:15:32 +020078#include <haproxy/ticks.h>
Willy Tarreau92b4f132020-06-01 11:05:15 +020079#include <haproxy/time.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020080#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020081#include <haproxy/vars.h>
Frédéric Lécailleec216522020-11-23 14:33:30 +010082#include <haproxy/xprt_quic.h>
Tim Duesterhusd5fc8fc2021-09-11 17:51:13 +020083#include <haproxy/xxhash.h>
Remi Tricot-Le Breton2e7d1eb2022-01-11 10:11:10 +010084#include <haproxy/istbuf.h>
Emeric Brun46591952012-05-18 15:47:34 +020085
Emeric Brun46591952012-05-18 15:47:34 +020086
Willy Tarreau9356dac2019-05-10 09:22:53 +020087/* ***** READ THIS before adding code here! *****
88 *
89 * Due to API incompatibilities between multiple OpenSSL versions and their
90 * derivatives, it's often tempting to add macros to (re-)define certain
91 * symbols. Please do not do this here, and do it in common/openssl-compat.h
92 * exclusively so that the whole code consistently uses the same macros.
93 *
94 * Whenever possible if a macro is missing in certain versions, it's better
95 * to conditionally define it in openssl-compat.h than using lots of ifdefs.
96 */
97
Emeric Brunece0c332017-12-06 13:51:49 +010098int nb_engines = 0;
Emeric Brune1f38db2012-09-03 20:36:47 +020099
William Lallemande0f3fd52020-02-25 14:53:06 +0100100static struct eb_root cert_issuer_tree = EB_ROOT; /* issuers tree from "issuers-chain-path" */
101
William Lallemand7fd8b452020-05-07 15:20:43 +0200102struct global_ssl global_ssl = {
Willy Tarreauef934602016-12-22 23:12:01 +0100103#ifdef LISTEN_DEFAULT_CIPHERS
104 .listen_default_ciphers = LISTEN_DEFAULT_CIPHERS,
105#endif
106#ifdef CONNECT_DEFAULT_CIPHERS
107 .connect_default_ciphers = CONNECT_DEFAULT_CIPHERS,
108#endif
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +0500109#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200110 .listen_default_ciphersuites = LISTEN_DEFAULT_CIPHERSUITES,
Dirkjan Bussink415150f2018-09-14 11:14:21 +0200111 .connect_default_ciphersuites = CONNECT_DEFAULT_CIPHERSUITES,
112#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100113 .listen_default_ssloptions = BC_SSL_O_NONE,
114 .connect_default_ssloptions = SRV_SSL_O_NONE,
115
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +0200116 .listen_default_sslmethods.flags = MC_SSL_O_ALL,
117 .listen_default_sslmethods.min = CONF_TLSV_NONE,
118 .listen_default_sslmethods.max = CONF_TLSV_NONE,
119 .connect_default_sslmethods.flags = MC_SSL_O_ALL,
120 .connect_default_sslmethods.min = CONF_TLSV_NONE,
121 .connect_default_sslmethods.max = CONF_TLSV_NONE,
122
Willy Tarreauef934602016-12-22 23:12:01 +0100123#ifdef DEFAULT_SSL_MAX_RECORD
124 .max_record = DEFAULT_SSL_MAX_RECORD,
125#endif
Thomas Prückl10243932022-04-27 13:04:54 +0200126 .hard_max_record = 0,
Willy Tarreauef934602016-12-22 23:12:01 +0100127 .default_dh_param = SSL_DEFAULT_DH_PARAM,
128 .ctx_cache = DEFAULT_SSL_CTX_CACHE,
Marcin Deranek310a2602021-07-13 19:04:24 +0200129 .capture_buffer_size = 0,
William Lallemand3af48e72020-02-03 17:15:52 +0100130 .extra_files = SSL_GF_ALL,
William Lallemand8e8581e2020-10-20 17:36:46 +0200131 .extra_files_noext = 0,
William Lallemand722180a2021-06-09 16:46:12 +0200132#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200133 .keylog = 0
134#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100135};
136
Olivier Houcharda8955d52019-04-07 22:00:38 +0200137static BIO_METHOD *ha_meth;
138
Olivier Houchard66ab4982019-02-26 18:37:15 +0100139DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx_pool", sizeof(struct ssl_sock_ctx));
140
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100141DECLARE_STATIC_POOL(ssl_sock_client_sni_pool, "ssl_sock_client_sni_pool", TLSEXT_MAXLEN_host_name + 1);
142
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100143/* ssl stats module */
144enum {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100145 SSL_ST_SESS,
146 SSL_ST_REUSED_SESS,
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100147 SSL_ST_FAILED_HANDSHAKE,
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100148
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100149 SSL_ST_STATS_COUNT /* must be the last member of the enum */
150};
151
152static struct name_desc ssl_stats[] = {
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100153 [SSL_ST_SESS] = { .name = "ssl_sess",
154 .desc = "Total number of ssl sessions established" },
155 [SSL_ST_REUSED_SESS] = { .name = "ssl_reused_sess",
156 .desc = "Total number of ssl sessions reused" },
157 [SSL_ST_FAILED_HANDSHAKE] = { .name = "ssl_failed_handshake",
158 .desc = "Total number of failed handshake" },
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100159};
160
161static struct ssl_counters {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100162 long long sess;
163 long long reused_sess;
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100164 long long failed_handshake;
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100165} ssl_counters;
166
167static void ssl_fill_stats(void *data, struct field *stats)
168{
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100169 struct ssl_counters *counters = data;
170
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100171 stats[SSL_ST_SESS] = mkf_u64(FN_COUNTER, counters->sess);
172 stats[SSL_ST_REUSED_SESS] = mkf_u64(FN_COUNTER, counters->reused_sess);
173 stats[SSL_ST_FAILED_HANDSHAKE] = mkf_u64(FN_COUNTER, counters->failed_handshake);
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100174}
175
176static struct stats_module ssl_stats_module = {
177 .name = "ssl",
178 .fill_stats = ssl_fill_stats,
179 .stats = ssl_stats,
180 .stats_count = SSL_ST_STATS_COUNT,
181 .counters = &ssl_counters,
182 .counters_size = sizeof(ssl_counters),
183 .domain_flags = MK_STATS_PROXY_DOMAIN(STATS_PX_CAP_FE|STATS_PX_CAP_LI|STATS_PX_CAP_BE|STATS_PX_CAP_SRV),
184 .clearable = 1,
185};
186
187INITCALL1(STG_REGISTER, stats_register_module, &ssl_stats_module);
188
Willy Tarreaua9380522022-05-05 08:50:17 +0200189/* CLI context for "show tls-keys" */
190struct show_keys_ctx {
191 struct tls_keys_ref *next_ref; /* next reference to be dumped */
192 int names_only; /* non-zero = only show file names */
193 int next_index; /* next index to be dumped */
Willy Tarreaubd338642022-05-05 08:59:17 +0200194 int dump_entries; /* dump entries also */
Willy Tarreau9c5a38c2022-05-05 09:03:44 +0200195 enum {
196 SHOW_KEYS_INIT = 0,
197 SHOW_KEYS_LIST,
198 SHOW_KEYS_DONE,
199 } state; /* phase of the current dump */
Willy Tarreaua9380522022-05-05 08:50:17 +0200200};
201
Willy Tarreau691d5032021-01-20 14:55:01 +0100202/* ssl_sock_io_cb is exported to see it resolved in "show fd" */
Willy Tarreau144f84a2021-03-02 16:09:26 +0100203struct task *ssl_sock_io_cb(struct task *, void *, unsigned int);
Olivier Houchard000694c2019-05-23 14:45:12 +0200204static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
Olivier Houchardea8dd942019-05-20 14:02:16 +0200205
Olivier Houcharda8955d52019-04-07 22:00:38 +0200206/* Methods to implement OpenSSL BIO */
207static int ha_ssl_write(BIO *h, const char *buf, int num)
208{
209 struct buffer tmpbuf;
210 struct ssl_sock_ctx *ctx;
211 int ret;
212
213 ctx = BIO_get_data(h);
214 tmpbuf.size = num;
215 tmpbuf.area = (void *)(uintptr_t)buf;
216 tmpbuf.data = num;
217 tmpbuf.head = 0;
218 ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200219 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200220 BIO_set_retry_write(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200221 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200222 } else if (ret == 0)
223 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200224 return ret;
225}
226
227static int ha_ssl_gets(BIO *h, char *buf, int size)
228{
229
230 return 0;
231}
232
233static int ha_ssl_puts(BIO *h, const char *str)
234{
235
236 return ha_ssl_write(h, str, strlen(str));
237}
238
239static int ha_ssl_read(BIO *h, char *buf, int size)
240{
241 struct buffer tmpbuf;
242 struct ssl_sock_ctx *ctx;
243 int ret;
244
245 ctx = BIO_get_data(h);
246 tmpbuf.size = size;
247 tmpbuf.area = buf;
248 tmpbuf.data = 0;
249 tmpbuf.head = 0;
250 ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200251 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200252 BIO_set_retry_read(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200253 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200254 } else if (ret == 0)
255 BIO_clear_retry_flags(h);
Olivier Houcharda8955d52019-04-07 22:00:38 +0200256
257 return ret;
258}
259
260static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
261{
262 int ret = 0;
263 switch (cmd) {
264 case BIO_CTRL_DUP:
265 case BIO_CTRL_FLUSH:
266 ret = 1;
267 break;
268 }
269 return ret;
270}
271
272static int ha_ssl_new(BIO *h)
273{
274 BIO_set_init(h, 1);
275 BIO_set_data(h, NULL);
276 BIO_clear_flags(h, ~0);
277 return 1;
278}
279
280static int ha_ssl_free(BIO *data)
281{
282
283 return 1;
284}
285
286
Willy Tarreau5db847a2019-05-09 14:13:35 +0200287#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100288
Emeric Brun821bb9b2017-06-15 16:37:39 +0200289static HA_RWLOCK_T *ssl_rwlocks;
290
291
292unsigned long ssl_id_function(void)
293{
294 return (unsigned long)tid;
295}
296
297void ssl_locking_function(int mode, int n, const char * file, int line)
298{
299 if (mode & CRYPTO_LOCK) {
300 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100301 HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200302 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100303 HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200304 }
305 else {
306 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100307 HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200308 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100309 HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200310 }
311}
312
313static int ssl_locking_init(void)
314{
315 int i;
316
317 ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
318 if (!ssl_rwlocks)
319 return -1;
320
321 for (i = 0 ; i < CRYPTO_num_locks() ; i++)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100322 HA_RWLOCK_INIT(&ssl_rwlocks[i]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200323
324 CRYPTO_set_id_callback(ssl_id_function);
325 CRYPTO_set_locking_callback(ssl_locking_function);
326
327 return 0;
328}
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100329
Emeric Brun821bb9b2017-06-15 16:37:39 +0200330#endif
331
Willy Tarreauaf613e82020-06-05 08:40:51 +0200332__decl_thread(HA_SPINLOCK_T ckch_lock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200333
William Lallemandbc6ca7c2019-10-29 23:48:19 +0100334
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200335
336/* mimic what X509_STORE_load_locations do with store_ctx */
337static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
338{
Remi Tricot-Le Bretond75b99e2021-05-17 11:45:55 +0200339 X509_STORE *store = NULL;
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +0100340 struct cafile_entry *ca_e = ssl_store_get_cafile_entry(path, 0);
341 if (ca_e)
342 store = ca_e->ca_store;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200343 if (store_ctx && store) {
344 int i;
345 X509_OBJECT *obj;
346 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
347 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
348 obj = sk_X509_OBJECT_value(objs, i);
349 switch (X509_OBJECT_get_type(obj)) {
350 case X509_LU_X509:
351 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
352 break;
353 case X509_LU_CRL:
354 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
355 break;
356 default:
357 break;
358 }
359 }
360 return 1;
361 }
362 return 0;
363}
364
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500365/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200366static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
367{
368 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
369 return ssl_set_cert_crl_file(store_ctx, path);
370}
371
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200372/*
373 Extract CA_list from CA_file already in tree.
374 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
375 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
376*/
377static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
378{
379 struct ebmb_node *eb;
380 struct cafile_entry *ca_e;
381
382 eb = ebst_lookup(&cafile_tree, path);
383 if (!eb)
384 return NULL;
385 ca_e = ebmb_entry(eb, struct cafile_entry, node);
386
387 if (ca_e->ca_list == NULL) {
388 int i;
389 unsigned long key;
390 struct eb_root ca_name_tree = EB_ROOT;
391 struct eb64_node *node, *back;
392 struct {
393 struct eb64_node node;
394 X509_NAME *xname;
395 } *ca_name;
396 STACK_OF(X509_OBJECT) *objs;
397 STACK_OF(X509_NAME) *skn;
398 X509 *x;
399 X509_NAME *xn;
400
401 skn = sk_X509_NAME_new_null();
402 /* take x509 from cafile_tree */
403 objs = X509_STORE_get0_objects(ca_e->ca_store);
404 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
405 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
406 if (!x)
407 continue;
408 xn = X509_get_subject_name(x);
409 if (!xn)
410 continue;
411 /* Check for duplicates. */
412 key = X509_NAME_hash(xn);
413 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
414 node && ca_name == NULL;
415 node = eb64_next(node)) {
416 ca_name = container_of(node, typeof(*ca_name), node);
417 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
418 ca_name = NULL;
419 }
420 /* find a duplicate */
421 if (ca_name)
422 continue;
423 ca_name = calloc(1, sizeof *ca_name);
424 xn = X509_NAME_dup(xn);
425 if (!ca_name ||
426 !xn ||
427 !sk_X509_NAME_push(skn, xn)) {
428 free(ca_name);
429 X509_NAME_free(xn);
430 sk_X509_NAME_pop_free(skn, X509_NAME_free);
431 sk_X509_NAME_free(skn);
432 skn = NULL;
433 break;
434 }
435 ca_name->node.key = key;
436 ca_name->xname = xn;
437 eb64_insert(&ca_name_tree, &ca_name->node);
438 }
439 ca_e->ca_list = skn;
440 /* remove temporary ca_name tree */
441 node = eb64_first(&ca_name_tree);
442 while (node) {
443 ca_name = container_of(node, typeof(*ca_name), node);
444 back = eb64_next(node);
445 eb64_delete(node);
446 free(ca_name);
447 node = back;
448 }
449 }
450 return ca_e->ca_list;
451}
452
Willy Tarreauff882702021-04-10 17:23:00 +0200453struct pool_head *pool_head_ssl_capture __read_mostly = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200454int ssl_capture_ptr_index = -1;
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +0100455int ssl_app_data_index = -1;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +0100456#ifdef USE_QUIC
457int ssl_qc_app_data_index = -1;
458#endif /* USE_QUIC */
Willy Tarreauef934602016-12-22 23:12:01 +0100459
William Lallemand722180a2021-06-09 16:46:12 +0200460#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200461int ssl_keylog_index = -1;
Willy Tarreauff882702021-04-10 17:23:00 +0200462struct pool_head *pool_head_ssl_keylog __read_mostly = NULL;
463struct pool_head *pool_head_ssl_keylog_str __read_mostly = NULL;
William Lallemand7d42ef52020-07-06 11:41:30 +0200464#endif
465
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +0200466int ssl_client_crt_ref_index = -1;
467
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +0100468/* Used to store the client's SNI in case of ClientHello callback error */
469int ssl_client_sni_index = -1;
470
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200471#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
472struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
473#endif
474
William Lallemandd7bfbe22022-04-11 18:41:24 +0200475#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200476unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000477struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
478struct ssl_engine_list {
479 struct list list;
480 ENGINE *e;
481};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200482#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000483
Remi Gacogne8de54152014-07-15 11:36:40 +0200484#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200485static int ssl_dh_ptr_index = -1;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +0100486static HASSL_DH *global_dh = NULL;
487static HASSL_DH *local_dh_1024 = NULL;
488static HASSL_DH *local_dh_2048 = NULL;
489static HASSL_DH *local_dh_4096 = NULL;
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100490#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +0100491static DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +0100492#else
493static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey);
494#endif
Remi Gacogne8de54152014-07-15 11:36:40 +0200495#endif /* OPENSSL_NO_DH */
496
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100497#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200498/* X509V3 Extensions that will be added on generated certificates */
499#define X509V3_EXT_SIZE 5
500static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
501 "basicConstraints",
502 "nsComment",
503 "subjectKeyIdentifier",
504 "authorityKeyIdentifier",
505 "keyUsage",
506};
507static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
508 "CA:FALSE",
509 "\"OpenSSL Generated Certificate\"",
510 "hash",
511 "keyid,issuer:always",
512 "nonRepudiation,digitalSignature,keyEncipherment"
513};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200514/* LRU cache to store generated certificate */
515static struct lru64_head *ssl_ctx_lru_tree = NULL;
516static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200517static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100518__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200519
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200520#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
521
yanbzhube2774d2015-12-10 15:07:30 -0500522/* The order here matters for picking a default context,
523 * keep the most common keytype at the bottom of the list
524 */
525const char *SSL_SOCK_KEYTYPE_NAMES[] = {
526 "dsa",
527 "ecdsa",
528 "rsa"
529};
yanbzhube2774d2015-12-10 15:07:30 -0500530
William Lallemandc3cd35f2017-11-28 11:04:43 +0100531static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100532static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
533
Dragan Dosen9ac98092020-05-11 15:51:45 +0200534/* Dedicated callback functions for heartbeat and clienthello.
535 */
536#ifdef TLS1_RT_HEARTBEAT
537static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
538 int content_type, const void *buf, size_t len,
539 SSL *ssl);
540#endif
541static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
542 int content_type, const void *buf, size_t len,
543 SSL *ssl);
544
William Lallemand722180a2021-06-09 16:46:12 +0200545#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200546static void ssl_init_keylog(struct connection *conn, int write_p, int version,
547 int content_type, const void *buf, size_t len,
548 SSL *ssl);
549#endif
550
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200551/* List head of all registered SSL/TLS protocol message callbacks. */
552struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
553
554/* Registers the function <func> in order to be called on SSL/TLS protocol
555 * message processing. It will return 0 if the function <func> is not set
556 * or if it fails to allocate memory.
557 */
558int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
559{
560 struct ssl_sock_msg_callback *cbk;
561
562 if (!func)
563 return 0;
564
565 cbk = calloc(1, sizeof(*cbk));
566 if (!cbk) {
567 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
568 return 0;
569 }
570
571 cbk->func = func;
572
Willy Tarreau2b718102021-04-21 07:32:39 +0200573 LIST_APPEND(&ssl_sock_msg_callbacks, &cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200574
575 return 1;
576}
577
Dragan Dosen9ac98092020-05-11 15:51:45 +0200578/* Used to register dedicated SSL/TLS protocol message callbacks.
579 */
580static int ssl_sock_register_msg_callbacks(void)
581{
582#ifdef TLS1_RT_HEARTBEAT
583 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
584 return ERR_ABORT;
585#endif
Marcin Deranek310a2602021-07-13 19:04:24 +0200586 if (global_ssl.capture_buffer_size > 0) {
Dragan Dosen9ac98092020-05-11 15:51:45 +0200587 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
588 return ERR_ABORT;
589 }
William Lallemand722180a2021-06-09 16:46:12 +0200590#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200591 if (global_ssl.keylog > 0) {
592 if (!ssl_sock_register_msg_callback(ssl_init_keylog))
593 return ERR_ABORT;
594 }
595#endif
596
Christopher Fauletfc633b62020-11-06 15:24:23 +0100597 return ERR_NONE;
Dragan Dosen9ac98092020-05-11 15:51:45 +0200598}
599
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200600/* Used to free all SSL/TLS protocol message callbacks that were
601 * registered by using ssl_sock_register_msg_callback().
602 */
603static void ssl_sock_unregister_msg_callbacks(void)
604{
605 struct ssl_sock_msg_callback *cbk, *cbkback;
606
607 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +0200608 LIST_DELETE(&cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200609 free(cbk);
610 }
611}
612
Willy Tarreaude827952022-04-11 10:43:28 +0200613static struct ssl_sock_ctx *ssl_sock_get_ctx(struct connection *conn)
614{
615 if (!conn || conn->xprt != xprt_get(XPRT_SSL) || !conn->xprt_ctx)
616 return NULL;
617
618 return (struct ssl_sock_ctx *)conn->xprt_ctx;
619}
620
Dragan Doseneb607fe2020-05-11 17:17:06 +0200621SSL *ssl_sock_get_ssl_object(struct connection *conn)
622{
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200623 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dragan Doseneb607fe2020-05-11 17:17:06 +0200624
Willy Tarreau939b0bf2022-04-11 11:29:11 +0200625 return ctx ? ctx->ssl : NULL;
Dragan Doseneb607fe2020-05-11 17:17:06 +0200626}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100627/*
628 * This function gives the detail of the SSL error. It is used only
629 * if the debug mode and the verbose mode are activated. It dump all
630 * the SSL error until the stack was empty.
631 */
632static forceinline void ssl_sock_dump_errors(struct connection *conn)
633{
634 unsigned long ret;
635
636 if (unlikely(global.mode & MODE_DEBUG)) {
637 while(1) {
Remi Tricot-Le Breton1effd9a2022-02-11 12:04:44 +0100638 const char *func = NULL;
639 ERR_peek_error_func(&func);
640
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100641 ret = ERR_get_error();
642 if (ret == 0)
643 return;
Willy Tarreau566cebc2021-03-02 19:32:39 +0100644 fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
Willy Tarreau0e9c2642022-04-11 18:01:28 +0200645 conn_fd(conn), ret,
Remi Tricot-Le Breton1effd9a2022-02-11 12:04:44 +0100646 func, ERR_reason_error_string(ret));
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100647 }
648 }
649}
650
yanbzhube2774d2015-12-10 15:07:30 -0500651
William Lallemandd7bfbe22022-04-11 18:41:24 +0200652#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
William Lallemanddad31052020-05-14 17:47:32 +0200653int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000654{
655 int err_code = ERR_ABORT;
656 ENGINE *engine;
657 struct ssl_engine_list *el;
658
659 /* grab the structural reference to the engine */
660 engine = ENGINE_by_id(engine_id);
661 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100662 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000663 goto fail_get;
664 }
665
666 if (!ENGINE_init(engine)) {
667 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100668 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000669 goto fail_init;
670 }
671
672 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100673 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000674 goto fail_set_method;
675 }
676
677 el = calloc(1, sizeof(*el));
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200678 if (!el)
679 goto fail_alloc;
Grant Zhang872f9c22017-01-21 01:10:18 +0000680 el->e = engine;
Willy Tarreau2b718102021-04-21 07:32:39 +0200681 LIST_INSERT(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100682 nb_engines++;
683 if (global_ssl.async)
684 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000685 return 0;
686
Remi Tricot-Le Breton612b2c32021-05-12 17:45:21 +0200687fail_alloc:
Grant Zhang872f9c22017-01-21 01:10:18 +0000688fail_set_method:
689 /* release the functional reference from ENGINE_init() */
690 ENGINE_finish(engine);
691
692fail_init:
693 /* release the structural reference from ENGINE_by_id() */
694 ENGINE_free(engine);
695
696fail_get:
697 return err_code;
698}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200699#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000700
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +0500701#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +0200702/*
703 * openssl async fd handler
704 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200705void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000706{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200707 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000708
Emeric Brun3854e012017-05-17 20:42:48 +0200709 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000710 * to poll this fd until it is requested
711 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000712 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000713 fd_cant_recv(fd);
714
715 /* crypto engine is available, let's notify the associated
716 * connection that it can pursue its processing.
717 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200718 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000719}
720
Emeric Brun3854e012017-05-17 20:42:48 +0200721/*
722 * openssl async delayed SSL_free handler
723 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200724void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000725{
726 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200727 OSSL_ASYNC_FD all_fd[32];
728 size_t num_all_fds = 0;
729 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000730
Emeric Brun3854e012017-05-17 20:42:48 +0200731 /* We suppose that the async job for a same SSL *
732 * are serialized. So if we are awake it is
733 * because the running job has just finished
734 * and we can remove all async fds safely
735 */
736 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
737 if (num_all_fds > 32) {
738 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
739 return;
740 }
741
742 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
743 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200744 fd_stop_both(all_fd[i]);
Emeric Brun3854e012017-05-17 20:42:48 +0200745
746 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000747 SSL_free(ssl);
Willy Tarreau82531f62021-10-06 12:15:18 +0200748 _HA_ATOMIC_DEC(&global.sslconns);
Willy Tarreau4781b152021-04-06 13:53:36 +0200749 _HA_ATOMIC_DEC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000750}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000751/*
Emeric Brun3854e012017-05-17 20:42:48 +0200752 * function used to manage a returned SSL_ERROR_WANT_ASYNC
753 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000754 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200755static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000756{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100757 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200758 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200759 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000760 size_t num_add_fds = 0;
761 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200762 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000763
764 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
765 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200766 if (num_add_fds > 32 || num_del_fds > 32) {
767 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 +0000768 return;
769 }
770
Emeric Brun3854e012017-05-17 20:42:48 +0200771 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000772
Emeric Brun3854e012017-05-17 20:42:48 +0200773 /* We remove unused fds from the fdtab */
774 for (i=0 ; i < num_del_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +0200775 fd_stop_both(del_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000776
Emeric Brun3854e012017-05-17 20:42:48 +0200777 /* We add new fds to the fdtab */
778 for (i=0 ; i < num_add_fds ; i++) {
Olivier Houchardea8dd942019-05-20 14:02:16 +0200779 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000780 }
781
Emeric Brun3854e012017-05-17 20:42:48 +0200782 num_add_fds = 0;
783 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
784 if (num_add_fds > 32) {
785 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
786 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000787 }
Emeric Brun3854e012017-05-17 20:42:48 +0200788
789 /* We activate the polling for all known async fds */
790 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000791 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200792 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000793 /* To ensure that the fd cache won't be used
794 * We'll prefer to catch a real RD event
795 * because handling an EAGAIN on this fd will
796 * result in a context switch and also
797 * some engines uses a fd in blocking mode.
798 */
799 fd_cant_recv(add_fd[i]);
800 }
Emeric Brun3854e012017-05-17 20:42:48 +0200801
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000802}
803#endif
804
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200805#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 +0200806/*
807 * This function returns the number of seconds elapsed
808 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
809 * date presented un ASN1_GENERALIZEDTIME.
810 *
811 * In parsing error case, it returns -1.
812 */
813static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
814{
815 long epoch;
816 char *p, *end;
817 const unsigned short month_offset[12] = {
818 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
819 };
Remi Tricot-Le Bretona3a0cce2021-06-09 17:16:18 +0200820 unsigned long year, month;
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200821
822 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
823
824 p = (char *)d->data;
825 end = p + d->length;
826
827 if (end - p < 4) return -1;
828 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
829 p += 4;
830 if (end - p < 2) return -1;
831 month = 10 * (p[0] - '0') + p[1] - '0';
832 if (month < 1 || month > 12) return -1;
833 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
834 We consider leap years and the current month (<marsh or not) */
835 epoch = ( ((year - 1970) * 365)
836 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
837 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
838 + month_offset[month-1]
839 ) * 24 * 60 * 60;
840 p += 2;
841 if (end - p < 2) return -1;
842 /* Add the number of seconds of completed days of current month */
843 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
844 p += 2;
845 if (end - p < 2) return -1;
846 /* Add the completed hours of the current day */
847 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
848 p += 2;
849 if (end - p < 2) return -1;
850 /* Add the completed minutes of the current hour */
851 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
852 p += 2;
853 if (p == end) return -1;
854 /* Test if there is available seconds */
855 if (p[0] < '0' || p[0] > '9')
856 goto nosec;
857 if (end - p < 2) return -1;
858 /* Add the seconds of the current minute */
859 epoch += 10 * (p[0] - '0') + p[1] - '0';
860 p += 2;
861 if (p == end) return -1;
862 /* Ignore seconds float part if present */
863 if (p[0] == '.') {
864 do {
865 if (++p == end) return -1;
866 } while (p[0] >= '0' && p[0] <= '9');
867 }
868
869nosec:
870 if (p[0] == 'Z') {
871 if (end - p != 1) return -1;
872 return epoch;
873 }
874 else if (p[0] == '+') {
875 if (end - p != 5) return -1;
876 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700877 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 +0200878 }
879 else if (p[0] == '-') {
880 if (end - p != 5) return -1;
881 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700882 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 +0200883 }
884
885 return -1;
886}
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200887#endif
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200888
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200889#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
William Lallemand104a7a62019-10-14 14:14:59 +0200890/*
891 * struct alignment works here such that the key.key is the same as key_data
892 * Do not change the placement of key_data
893 */
894struct certificate_ocsp {
895 struct ebmb_node key;
896 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
Remi Tricot-Le Breton5aa1dce2021-06-10 13:51:12 +0200897 unsigned int key_length;
William Lallemand104a7a62019-10-14 14:14:59 +0200898 struct buffer response;
William Lallemand76b4a122020-08-04 17:41:39 +0200899 int refcount;
William Lallemand104a7a62019-10-14 14:14:59 +0200900 long expire;
901};
902
903struct ocsp_cbk_arg {
904 int is_single;
905 int single_kt;
906 union {
907 struct certificate_ocsp *s_ocsp;
908 /*
909 * m_ocsp will have multiple entries dependent on key type
910 * Entry 0 - DSA
911 * Entry 1 - ECDSA
912 * Entry 2 - RSA
913 */
914 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
915 };
916};
917
Emeric Brun1d3865b2014-06-20 15:37:32 +0200918static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200919
920/* This function starts to check if the OCSP response (in DER format) contained
921 * in chunk 'ocsp_response' is valid (else exits on error).
922 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
923 * contained in the OCSP Response and exits on error if no match.
924 * If it's a valid OCSP Response:
925 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
926 * pointed by 'ocsp'.
927 * If 'ocsp' is NULL, the function looks up into the OCSP response's
928 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
929 * from the response) and exits on error if not found. Finally, If an OCSP response is
930 * already present in the container, it will be overwritten.
931 *
932 * Note: OCSP response containing more than one OCSP Single response is not
933 * considered valid.
934 *
935 * Returns 0 on success, 1 in error case.
936 */
Willy Tarreau83061a82018-07-13 11:56:34 +0200937static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
938 struct certificate_ocsp *ocsp,
939 OCSP_CERTID *cid, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +0200940{
941 OCSP_RESPONSE *resp;
942 OCSP_BASICRESP *bs = NULL;
943 OCSP_SINGLERESP *sr;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200944 OCSP_CERTID *id;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200945 unsigned char *p = (unsigned char *) ocsp_response->area;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200946 int rc , count_sr;
Emeric Brun13a6b482014-06-20 15:44:34 +0200947 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200948 int reason;
949 int ret = 1;
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +0200950#ifdef HAVE_ASN1_TIME_TO_TM
951 struct tm nextupd_tm = {0};
952#endif
Emeric Brun4147b2e2014-06-16 18:36:30 +0200953
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200954 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
955 ocsp_response->data);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200956 if (!resp) {
957 memprintf(err, "Unable to parse OCSP response");
958 goto out;
959 }
960
961 rc = OCSP_response_status(resp);
962 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
963 memprintf(err, "OCSP response status not successful");
964 goto out;
965 }
966
967 bs = OCSP_response_get1_basic(resp);
968 if (!bs) {
969 memprintf(err, "Failed to get basic response from OCSP Response");
970 goto out;
971 }
972
973 count_sr = OCSP_resp_count(bs);
974 if (count_sr > 1) {
975 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
976 goto out;
977 }
978
979 sr = OCSP_resp_get0(bs, 0);
980 if (!sr) {
981 memprintf(err, "Failed to get OCSP single response");
982 goto out;
983 }
984
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200985 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
986
Emeric Brun4147b2e2014-06-16 18:36:30 +0200987 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
Emmanuel Hocdetef607052017-10-24 14:57:16 +0200988 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
Emmanuel Hocdet872085c2017-10-10 15:18:52 +0200989 memprintf(err, "OCSP single response: certificate status is unknown");
Emeric Brun4147b2e2014-06-16 18:36:30 +0200990 goto out;
991 }
992
Emeric Brun13a6b482014-06-20 15:44:34 +0200993 if (!nextupd) {
994 memprintf(err, "OCSP single response: missing nextupdate");
995 goto out;
996 }
997
Emeric Brunc8b27b62014-06-19 14:16:17 +0200998 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200999 if (!rc) {
1000 memprintf(err, "OCSP single response: no longer valid.");
1001 goto out;
1002 }
1003
1004 if (cid) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001005 if (OCSP_id_cmp(id, cid)) {
Emeric Brun4147b2e2014-06-16 18:36:30 +02001006 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
1007 goto out;
1008 }
1009 }
1010
1011 if (!ocsp) {
1012 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
1013 unsigned char *p;
1014
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001015 rc = i2d_OCSP_CERTID(id, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001016 if (!rc) {
1017 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
1018 goto out;
1019 }
1020
1021 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
1022 memprintf(err, "OCSP single response: Certificate ID too long");
1023 goto out;
1024 }
1025
1026 p = key;
1027 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001028 i2d_OCSP_CERTID(id, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001029 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
1030 if (!ocsp) {
1031 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
1032 goto out;
1033 }
1034 }
1035
1036 /* According to comments on "chunk_dup", the
1037 previous chunk buffer will be freed */
1038 if (!chunk_dup(&ocsp->response, ocsp_response)) {
1039 memprintf(err, "OCSP response: Memory allocation error");
1040 goto out;
1041 }
1042
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +02001043#ifdef HAVE_ASN1_TIME_TO_TM
1044 if (ASN1_TIME_to_tm(nextupd, &nextupd_tm) == 0) {
1045 memprintf(err, "OCSP single response: Invalid \"Next Update\" time");
1046 goto out;
1047 }
1048 ocsp->expire = my_timegm(&nextupd_tm) - OCSP_MAX_RESPONSE_TIME_SKEW;
1049#else
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001050 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
Remi Tricot-Le Bretona3a0cce2021-06-09 17:16:18 +02001051 if (ocsp->expire < 0) {
1052 memprintf(err, "OCSP single response: Invalid \"Next Update\" time");
1053 goto out;
1054 }
Remi Tricot-Le Breton69164932021-06-11 10:28:09 +02001055#endif
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001056
Emeric Brun4147b2e2014-06-16 18:36:30 +02001057 ret = 0;
1058out:
Janusz Dziemidowicz8d710492017-03-08 16:59:41 +01001059 ERR_clear_error();
1060
Emeric Brun4147b2e2014-06-16 18:36:30 +02001061 if (bs)
1062 OCSP_BASICRESP_free(bs);
1063
1064 if (resp)
1065 OCSP_RESPONSE_free(resp);
1066
1067 return ret;
1068}
1069/*
1070 * External function use to update the OCSP response in the OCSP response's
1071 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
1072 * to update in DER format.
1073 *
1074 * Returns 0 on success, 1 in error case.
1075 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001076int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001077{
1078 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
1079}
1080
William Lallemand4a660132019-10-14 14:51:41 +02001081#endif
1082
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001083
1084/*
1085 * Initialize an HMAC context <hctx> using the <key> and <md> parameters.
1086 * Returns -1 in case of error, 1 otherwise.
1087 */
1088static int ssl_hmac_init(MAC_CTX *hctx, unsigned char *key, int key_len, const EVP_MD *md)
1089{
1090#ifdef HAVE_OSSL_PARAM
1091 OSSL_PARAM params[3];
1092
1093 params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, key, key_len);
1094 params[1] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, (char*)EVP_MD_name(md), 0);
1095 params[2] = OSSL_PARAM_construct_end();
1096 if (EVP_MAC_CTX_set_params(hctx, params) == 0)
1097 return -1; /* error in mac initialisation */
1098
1099#else
1100 HMAC_Init_ex(hctx, key, key_len, md, NULL);
1101#endif
1102 return 1;
1103}
1104
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001105#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +01001106
1107static 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 +01001108{
Christopher Faulet16f45c82018-02-16 11:23:49 +01001109 struct tls_keys_ref *ref;
Emeric Brun9e754772019-01-10 17:51:55 +01001110 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001111 struct connection *conn;
1112 int head;
1113 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001114 int ret = -1; /* error by default */
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001115
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001116 conn = SSL_get_ex_data(s, ssl_app_data_index);
Willy Tarreau07d94e42018-09-20 10:57:52 +02001117 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001118 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1119
1120 keys = ref->tlskeys;
1121 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001122
1123 if (enc) {
1124 memcpy(key_name, keys[head].name, 16);
1125
1126 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +01001127 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001128
Emeric Brun9e754772019-01-10 17:51:55 +01001129 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001130
Emeric Brun9e754772019-01-10 17:51:55 +01001131 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
1132 goto end;
1133
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001134 if (ssl_hmac_init(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
1135 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +01001136 ret = 1;
1137 }
1138 else if (ref->key_size_bits == 256 ) {
1139
1140 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
1141 goto end;
1142
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001143 if (ssl_hmac_init(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
1144 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +01001145 ret = 1;
1146 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001147 } else {
1148 for (i = 0; i < TLS_TICKETS_NO; i++) {
1149 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
1150 goto found;
1151 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01001152 ret = 0;
1153 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001154
Christopher Faulet16f45c82018-02-16 11:23:49 +01001155 found:
Emeric Brun9e754772019-01-10 17:51:55 +01001156 if (ref->key_size_bits == 128) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001157 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT()) < 0)
1158 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +01001159 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
1160 goto end;
1161 /* 2 for key renewal, 1 if current key is still valid */
1162 ret = i ? 2 : 1;
1163 }
1164 else if (ref->key_size_bits == 256) {
Remi Tricot-Le Bretonc9414e22022-02-08 17:45:59 +01001165 if (ssl_hmac_init(hctx, keys[(head + i) % TLS_TICKETS_NO].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT()) < 0)
1166 goto end;
Emeric Brun9e754772019-01-10 17:51:55 +01001167 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
1168 goto end;
1169 /* 2 for key renewal, 1 if current key is still valid */
1170 ret = i ? 2 : 1;
1171 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001172 }
Emeric Brun9e754772019-01-10 17:51:55 +01001173
Christopher Faulet16f45c82018-02-16 11:23:49 +01001174 end:
1175 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1176 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001177}
1178
1179struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
1180{
1181 struct tls_keys_ref *ref;
1182
1183 list_for_each_entry(ref, &tlskeys_reference, list)
1184 if (ref->filename && strcmp(filename, ref->filename) == 0)
1185 return ref;
1186 return NULL;
1187}
1188
1189struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1190{
1191 struct tls_keys_ref *ref;
1192
1193 list_for_each_entry(ref, &tlskeys_reference, list)
1194 if (ref->unique_id == unique_id)
1195 return ref;
1196 return NULL;
1197}
1198
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001199/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001200 * match existing ones, this function returns -1
1201 * else it returns 0 on success.
1202 */
1203int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001204 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001205{
Emeric Brun9e754772019-01-10 17:51:55 +01001206 if (ref->key_size_bits == 128) {
1207 if (tlskey->data != sizeof(struct tls_sess_key_128))
1208 return -1;
1209 }
1210 else if (ref->key_size_bits == 256) {
1211 if (tlskey->data != sizeof(struct tls_sess_key_256))
1212 return -1;
1213 }
1214 else
1215 return -1;
1216
Christopher Faulet16f45c82018-02-16 11:23:49 +01001217 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001218 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1219 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001220 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1221 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001222
1223 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001224}
1225
Willy Tarreau83061a82018-07-13 11:56:34 +02001226int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001227{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001228 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1229
1230 if(!ref) {
1231 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1232 return 1;
1233 }
Emeric Brun9e754772019-01-10 17:51:55 +01001234 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1235 memprintf(err, "Invalid key size");
1236 return 1;
1237 }
1238
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001239 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001240}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001241
1242/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001243 * automatic ids. It's called just after the basic checks. It returns
1244 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001245 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001246static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001247{
1248 int i = 0;
1249 struct tls_keys_ref *ref, *ref2, *ref3;
1250 struct list tkr = LIST_HEAD_INIT(tkr);
1251
1252 list_for_each_entry(ref, &tlskeys_reference, list) {
1253 if (ref->unique_id == -1) {
1254 /* Look for the first free id. */
1255 while (1) {
1256 list_for_each_entry(ref2, &tlskeys_reference, list) {
1257 if (ref2->unique_id == i) {
1258 i++;
1259 break;
1260 }
1261 }
1262 if (&ref2->list == &tlskeys_reference)
1263 break;
1264 }
1265
1266 /* Uses the unique id and increment it for the next entry. */
1267 ref->unique_id = i;
1268 i++;
1269 }
1270 }
1271
1272 /* This sort the reference list by id. */
1273 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001274 LIST_DELETE(&ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001275 list_for_each_entry(ref3, &tkr, list) {
1276 if (ref->unique_id < ref3->unique_id) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001277 LIST_APPEND(&ref3->list, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001278 break;
1279 }
1280 }
1281 if (&ref3->list == &tkr)
Willy Tarreau2b718102021-04-21 07:32:39 +02001282 LIST_APPEND(&tkr, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001283 }
1284
1285 /* swap root */
Willy Tarreau2b718102021-04-21 07:32:39 +02001286 LIST_INSERT(&tkr, &tlskeys_reference);
1287 LIST_DELETE(&tkr);
Christopher Fauletfc633b62020-11-06 15:24:23 +01001288 return ERR_NONE;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001289}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001290#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1291
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001292#ifndef OPENSSL_NO_OCSP
William Lallemand76b4a122020-08-04 17:41:39 +02001293int ocsp_ex_index = -1;
1294
yanbzhube2774d2015-12-10 15:07:30 -05001295int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1296{
1297 switch (evp_keytype) {
1298 case EVP_PKEY_RSA:
1299 return 2;
1300 case EVP_PKEY_DSA:
1301 return 0;
1302 case EVP_PKEY_EC:
1303 return 1;
1304 }
1305
1306 return -1;
1307}
1308
Emeric Brun4147b2e2014-06-16 18:36:30 +02001309/*
1310 * Callback used to set OCSP status extension content in server hello.
1311 */
1312int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1313{
yanbzhube2774d2015-12-10 15:07:30 -05001314 struct certificate_ocsp *ocsp;
1315 struct ocsp_cbk_arg *ocsp_arg;
1316 char *ssl_buf;
William Lallemand76b4a122020-08-04 17:41:39 +02001317 SSL_CTX *ctx;
yanbzhube2774d2015-12-10 15:07:30 -05001318 EVP_PKEY *ssl_pkey;
1319 int key_type;
1320 int index;
1321
William Lallemand76b4a122020-08-04 17:41:39 +02001322 ctx = SSL_get_SSL_CTX(ssl);
1323 if (!ctx)
1324 return SSL_TLSEXT_ERR_NOACK;
1325
1326 ocsp_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
1327 if (!ocsp_arg)
1328 return SSL_TLSEXT_ERR_NOACK;
yanbzhube2774d2015-12-10 15:07:30 -05001329
1330 ssl_pkey = SSL_get_privatekey(ssl);
1331 if (!ssl_pkey)
1332 return SSL_TLSEXT_ERR_NOACK;
1333
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001334 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001335
1336 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1337 ocsp = ocsp_arg->s_ocsp;
1338 else {
1339 /* For multiple certs per context, we have to find the correct OCSP response based on
1340 * the certificate type
1341 */
1342 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1343
1344 if (index < 0)
1345 return SSL_TLSEXT_ERR_NOACK;
1346
1347 ocsp = ocsp_arg->m_ocsp[index];
1348
1349 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001350
1351 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001352 !ocsp->response.area ||
1353 !ocsp->response.data ||
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001354 (ocsp->expire < now.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001355 return SSL_TLSEXT_ERR_NOACK;
1356
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001357 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001358 if (!ssl_buf)
1359 return SSL_TLSEXT_ERR_NOACK;
1360
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001361 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
1362 SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001363
1364 return SSL_TLSEXT_ERR_OK;
1365}
1366
William Lallemand4a660132019-10-14 14:51:41 +02001367#endif
1368
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001369#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
William Lallemand76b4a122020-08-04 17:41:39 +02001370
1371
1372/*
1373 * Decrease the refcount of the struct ocsp_response and frees it if it's not
1374 * used anymore. Also removes it from the tree if free'd.
1375 */
1376static void ssl_sock_free_ocsp(struct certificate_ocsp *ocsp)
1377{
1378 if (!ocsp)
1379 return;
1380
1381 ocsp->refcount--;
1382 if (ocsp->refcount <= 0) {
1383 ebmb_delete(&ocsp->key);
1384 chunk_destroy(&ocsp->response);
1385 free(ocsp);
1386 }
1387}
1388
1389
Emeric Brun4147b2e2014-06-16 18:36:30 +02001390/*
1391 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001392 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1393 * status extension, the issuer's certificate is mandatory. It should be
1394 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001395 *
William Lallemand246c0242019-10-11 08:59:13 +02001396 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1397 * OCSP response. If file is empty or content is not a valid OCSP response,
1398 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1399 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001400 *
1401 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001402 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001403 */
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001404static 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 +02001405{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001406 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001407 OCSP_CERTID *cid = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001408 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001409 struct certificate_ocsp *ocsp = NULL, *iocsp;
1410 char *warn = NULL;
1411 unsigned char *p;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001412 void (*callback) (void);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001413
Emeric Brun4147b2e2014-06-16 18:36:30 +02001414
William Lallemand246c0242019-10-11 08:59:13 +02001415 x = ckch->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001416 if (!x)
1417 goto out;
1418
William Lallemand246c0242019-10-11 08:59:13 +02001419 issuer = ckch->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001420 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1421 if (chain) {
1422 /* check if one of the certificate of the chain is the issuer */
1423 for (i = 0; i < sk_X509_num(chain); i++) {
1424 X509 *ti = sk_X509_value(chain, i);
1425 if (X509_check_issued(ti, x) == X509_V_OK) {
1426 issuer = ti;
1427 break;
1428 }
1429 }
1430 }
William Lallemand246c0242019-10-11 08:59:13 +02001431 if (!issuer)
1432 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001433
1434 cid = OCSP_cert_to_id(0, x, issuer);
1435 if (!cid)
1436 goto out;
1437
1438 i = i2d_OCSP_CERTID(cid, NULL);
1439 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1440 goto out;
1441
Vincent Bernat02779b62016-04-03 13:48:43 +02001442 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001443 if (!ocsp)
1444 goto out;
1445
1446 p = ocsp->key_data;
Remi Tricot-Le Breton5aa1dce2021-06-10 13:51:12 +02001447 ocsp->key_length = i2d_OCSP_CERTID(cid, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001448
1449 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1450 if (iocsp == ocsp)
1451 ocsp = NULL;
1452
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001453#ifndef SSL_CTX_get_tlsext_status_cb
1454# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1455 *cb = (void (*) (void))ctx->tlsext_status_cb;
1456#endif
1457 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1458
1459 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001460 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001461 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001462
William Lallemanda560c062020-07-31 11:43:20 +02001463 cb_arg = calloc(1, sizeof(*cb_arg));
1464 if (!cb_arg)
1465 goto out;
1466
yanbzhube2774d2015-12-10 15:07:30 -05001467 cb_arg->is_single = 1;
1468 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001469 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001470
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001471 pkey = X509_get_pubkey(x);
1472 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1473 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001474
1475 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001476 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 */
1477
yanbzhube2774d2015-12-10 15:07:30 -05001478 } else {
1479 /*
1480 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1481 * Update that cb_arg with the new cert's staple
1482 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001483 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001484 struct certificate_ocsp *tmp_ocsp;
1485 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001486 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001487 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001488
William Lallemand76b4a122020-08-04 17:41:39 +02001489 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001490
1491 /*
1492 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1493 * the order of operations below matter, take care when changing it
1494 */
1495 tmp_ocsp = cb_arg->s_ocsp;
1496 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1497 cb_arg->s_ocsp = NULL;
1498 cb_arg->m_ocsp[index] = tmp_ocsp;
1499 cb_arg->is_single = 0;
1500 cb_arg->single_kt = 0;
1501
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001502 pkey = X509_get_pubkey(x);
1503 key_type = EVP_PKEY_base_id(pkey);
1504 EVP_PKEY_free(pkey);
1505
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001506 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001507 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001508 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001509 iocsp->refcount++;
1510 }
yanbzhube2774d2015-12-10 15:07:30 -05001511 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001512
1513 ret = 0;
1514
1515 warn = NULL;
William Lallemand86e4d632020-08-07 00:44:32 +02001516 if (ssl_sock_load_ocsp_response(ckch->ocsp_response, iocsp, cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001517 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001518 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001519 }
1520
1521out:
Emeric Brun4147b2e2014-06-16 18:36:30 +02001522 if (cid)
1523 OCSP_CERTID_free(cid);
1524
1525 if (ocsp)
1526 free(ocsp);
1527
1528 if (warn)
1529 free(warn);
1530
Emeric Brun4147b2e2014-06-16 18:36:30 +02001531 return ret;
1532}
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001533#endif
1534
1535#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001536static 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 +02001537{
William Lallemand4a660132019-10-14 14:51:41 +02001538 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 +02001539}
1540#endif
1541
William Lallemand4a660132019-10-14 14:51:41 +02001542
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001543#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001544
1545#define CT_EXTENSION_TYPE 18
1546
William Lallemand03c331c2020-05-13 10:10:01 +02001547int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001548
1549int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1550{
Willy Tarreau83061a82018-07-13 11:56:34 +02001551 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001552
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001553 *out = (unsigned char *) sctl->area;
1554 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001555
1556 return 1;
1557}
1558
1559int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1560{
1561 return 1;
1562}
1563
William Lallemanda17f4112019-10-10 15:16:44 +02001564static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001565{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001566 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001567
William Lallemanda17f4112019-10-10 15:16:44 +02001568 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 +01001569 goto out;
1570
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001571 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1572
1573 ret = 0;
1574
1575out:
1576 return ret;
1577}
1578
1579#endif
1580
Emeric Brune1f38db2012-09-03 20:36:47 +02001581void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1582{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001583 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001584#ifdef USE_QUIC
1585 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1586#endif /* USE_QUIC */
1587 struct ssl_sock_ctx *ctx = NULL;
1588
Emeric Brund8b2bb52014-01-28 15:43:53 +01001589 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001590 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001591
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001592 if (conn)
Willy Tarreau939b0bf2022-04-11 11:29:11 +02001593 ctx = conn_get_ssl_sock_ctx(conn);
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001594#ifdef USE_QUIC
1595 else if (qc)
1596 ctx = qc->xprt_ctx;
1597#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01001598
1599 if (!ctx) {
1600 /* must never happen */
1601 ABORT_NOW();
1602 return;
1603 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001604
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001605#ifndef SSL_OP_NO_RENEGOTIATION
1606 /* Please note that BoringSSL defines this macro to zero so don't
1607 * change this to #if and do not assign a default value to this macro!
1608 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001609 if (where & SSL_CB_HANDSHAKE_START) {
1610 /* Disable renegotiation (CVE-2009-3555) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01001611 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 +02001612 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001613 conn->err_code = CO_ER_SSL_RENEG;
1614 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001615 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001616#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001617
1618 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001619 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001620 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001621 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001622 consider that the buffering was activated,
1623 so we rise the output buffer size from 4k
1624 to 16k */
1625 write_bio = SSL_get_wbio(ssl);
1626 if (write_bio != SSL_get_rbio(ssl)) {
1627 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001628 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001629 }
1630 }
1631 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001632}
1633
Emeric Brune64aef12012-09-21 13:15:06 +02001634/* Callback is called for each certificate of the chain during a verify
1635 ok is set to 1 if preverify detect no error on current certificate.
1636 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001637int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001638{
1639 SSL *ssl;
1640 struct connection *conn;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001641 struct ssl_sock_ctx *ctx;
Emeric Brun81c00f02012-09-21 14:31:21 +02001642 int err, depth;
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001643 X509 *client_crt;
1644 STACK_OF(X509) *certs;
Emeric Brune64aef12012-09-21 13:15:06 +02001645
1646 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001647 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001648 client_crt = SSL_get_ex_data(ssl, ssl_client_crt_ref_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001649
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02001650 ctx = __conn_get_ssl_sock_ctx(conn);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001651 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001652
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001653 depth = X509_STORE_CTX_get_error_depth(x_store);
1654 err = X509_STORE_CTX_get_error(x_store);
1655
Emeric Brun81c00f02012-09-21 14:31:21 +02001656 if (ok) /* no errors */
1657 return ok;
1658
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001659 /* Keep a reference to the client's certificate in order to be able to
1660 * dump some fetches values in a log even when the verification process
1661 * fails. */
1662 if (depth == 0) {
1663 X509_free(client_crt);
1664 client_crt = X509_STORE_CTX_get0_cert(x_store);
1665 if (client_crt) {
1666 X509_up_ref(client_crt);
1667 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
1668 }
1669 }
1670 else {
1671 /* An error occurred on a CA certificate of the certificate
1672 * chain, we might never call this verify callback on the client
1673 * certificate's depth (which is 0) so we try to store the
1674 * reference right now. */
Remi Tricot-Le Bretonf95c2952021-08-20 09:51:23 +02001675 certs = X509_STORE_CTX_get1_chain(x_store);
1676 if (certs) {
1677 client_crt = sk_X509_value(certs, 0);
1678 if (client_crt) {
1679 X509_up_ref(client_crt);
1680 SSL_set_ex_data(ssl, ssl_client_crt_ref_index, client_crt);
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02001681 }
1682 sk_X509_pop_free(certs, X509_free);
1683 }
1684 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001685
1686 /* check if CA error needs to be ignored */
1687 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001688 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1689 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1690 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001691 }
1692
Willy Tarreau731248f2020-02-04 14:02:02 +01001693 if (err < 64 && __objt_listener(conn->target)->bind_conf->ca_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001694 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001695 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001696 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001697 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001698
Willy Tarreau20879a02012-12-03 16:32:10 +01001699 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001700 return 0;
1701 }
1702
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001703 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1704 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001705
Emeric Brun81c00f02012-09-21 14:31:21 +02001706 /* check if certificate error needs to be ignored */
Willy Tarreau731248f2020-02-04 14:02:02 +01001707 if (err < 64 && __objt_listener(conn->target)->bind_conf->crt_ignerr & (1ULL << err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001708 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001709 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001710 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001711 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001712
Willy Tarreau20879a02012-12-03 16:32:10 +01001713 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001714 return 0;
Emeric Brune64aef12012-09-21 13:15:06 +02001715}
1716
Dragan Dosen9ac98092020-05-11 15:51:45 +02001717#ifdef TLS1_RT_HEARTBEAT
1718static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1719 int content_type, const void *buf, size_t len,
1720 SSL *ssl)
1721{
1722 /* test heartbeat received (write_p is set to 0
1723 for a received record) */
1724 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02001725 struct ssl_sock_ctx *ctx = __conn_get_ssl_sock_ctx(conn);
Dragan Dosen9ac98092020-05-11 15:51:45 +02001726 const unsigned char *p = buf;
1727 unsigned int payload;
1728
1729 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1730
1731 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1732 if (*p != TLS1_HB_REQUEST)
1733 return;
1734
1735 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1736 goto kill_it;
1737
1738 payload = (p[1] * 256) + p[2];
1739 if (3 + payload + 16 <= len)
1740 return; /* OK no problem */
1741 kill_it:
1742 /* We have a clear heartbleed attack (CVE-2014-0160), the
1743 * advertised payload is larger than the advertised packet
1744 * length, so we have garbage in the buffer between the
1745 * payload and the end of the buffer (p+len). We can't know
1746 * if the SSL stack is patched, and we don't know if we can
1747 * safely wipe out the area between p+3+len and payload.
1748 * So instead, we prevent the response from being sent by
1749 * setting the max_send_fragment to 0 and we report an SSL
1750 * error, which will kill this connection. It will be reported
1751 * above as SSL_ERROR_SSL while an other handshake failure with
1752 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1753 */
1754 ssl->max_send_fragment = 0;
1755 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1756 }
1757}
1758#endif
1759
1760static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1761 int content_type, const void *buf, size_t len,
1762 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001763{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001764 struct ssl_capture *capture;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001765 uchar *msg;
1766 uchar *end;
1767 uchar *extensions_end;
1768 uchar *ec_start = NULL;
1769 uchar *ec_formats_start = NULL;
1770 uchar *list_end;
1771 ushort protocol_version;
1772 ushort extension_id;
1773 ushort ec_len = 0;
1774 uchar ec_formats_len = 0;
1775 int offset = 0;
1776 int rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001777
1778 /* This function is called for "from client" and "to server"
1779 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001780 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001781 */
1782
1783 /* "write_p" is set to 0 is the bytes are received messages,
1784 * otherwise it is set to 1.
1785 */
1786 if (write_p != 0)
1787 return;
1788
1789 /* content_type contains the type of message received or sent
1790 * according with the SSL/TLS protocol spec. This message is
1791 * encoded with one byte. The value 256 (two bytes) is used
1792 * for designing the SSL/TLS record layer. According with the
1793 * rfc6101, the expected message (other than 256) are:
1794 * - change_cipher_spec(20)
1795 * - alert(21)
1796 * - handshake(22)
1797 * - application_data(23)
1798 * - (255)
1799 * We are interessed by the handshake and specially the client
1800 * hello.
1801 */
1802 if (content_type != 22)
1803 return;
1804
1805 /* The message length is at least 4 bytes, containing the
1806 * message type and the message length.
1807 */
1808 if (len < 4)
1809 return;
1810
1811 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001812 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001813 * - hello_request(0)
1814 * - client_hello(1)
1815 * - server_hello(2)
1816 * - certificate(11)
1817 * - server_key_exchange (12)
1818 * - certificate_request(13)
1819 * - server_hello_done(14)
1820 * We are interested by the client hello.
1821 */
1822 msg = (unsigned char *)buf;
1823 if (msg[0] != 1)
1824 return;
1825
1826 /* Next three bytes are the length of the message. The total length
1827 * must be this decoded length + 4. If the length given as argument
1828 * is not the same, we abort the protocol dissector.
1829 */
1830 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1831 if (len < rec_len + 4)
1832 return;
1833 msg += 4;
1834 end = msg + rec_len;
1835 if (end < msg)
1836 return;
1837
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001838 /* Expect 2 bytes for protocol version
1839 * (1 byte for major and 1 byte for minor)
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001840 */
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001841 if (msg + 2 > end)
1842 return;
1843 protocol_version = (msg[0] << 8) + msg[1];
1844 msg += 2;
1845
1846 /* Expect the random, composed by 4 bytes for the unix time and
1847 * 28 bytes for unix payload. So we jump 4 + 28.
1848 */
1849 msg += 4 + 28;
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001850 if (msg > end)
1851 return;
1852
1853 /* Next, is session id:
1854 * if present, we have to jump by length + 1 for the size information
1855 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001856 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001857 if (msg[0] > 0)
1858 msg += msg[0];
1859 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001860 if (msg > end)
1861 return;
1862
1863 /* Next two bytes are the ciphersuite length. */
1864 if (msg + 2 > end)
1865 return;
1866 rec_len = (msg[0] << 8) + msg[1];
1867 msg += 2;
1868 if (msg + rec_len > end || msg + rec_len < msg)
1869 return;
1870
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001871 capture = pool_zalloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001872 if (!capture)
1873 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001874 /* Compute the xxh64 of the ciphersuite. */
1875 capture->xxh64 = XXH64(msg, rec_len, 0);
1876
1877 /* Capture the ciphersuite. */
Marcin Deranek310a2602021-07-13 19:04:24 +02001878 capture->ciphersuite_len = MIN(global_ssl.capture_buffer_size, rec_len);
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001879 capture->ciphersuite_offset = 0;
1880 memcpy(capture->data, msg, capture->ciphersuite_len);
1881 msg += rec_len;
1882 offset += capture->ciphersuite_len;
1883
1884 /* Initialize other data */
1885 capture->protocol_version = protocol_version;
1886
1887 /* Next, compression methods:
1888 * if present, we have to jump by length + 1 for the size information
1889 * if not present, we have to jump by 1 only
1890 */
1891 if (msg[0] > 0)
1892 msg += msg[0];
1893 msg += 1;
1894 if (msg > end)
1895 goto store_capture;
1896
1897 /* We reached extensions */
1898 if (msg + 2 > end)
1899 goto store_capture;
1900 rec_len = (msg[0] << 8) + msg[1];
1901 msg += 2;
1902 if (msg + rec_len > end || msg + rec_len < msg)
1903 goto store_capture;
1904 extensions_end = msg + rec_len;
1905 capture->extensions_offset = offset;
1906
1907 /* Parse each extension */
1908 while (msg + 4 < extensions_end) {
1909 /* Add 2 bytes of extension_id */
Marcin Deranek310a2602021-07-13 19:04:24 +02001910 if (global_ssl.capture_buffer_size >= offset + 2) {
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001911 capture->data[offset++] = msg[0];
1912 capture->data[offset++] = msg[1];
1913 capture->extensions_len += 2;
1914 }
1915 else
1916 break;
1917 extension_id = (msg[0] << 8) + msg[1];
1918 /* Length of the extension */
1919 rec_len = (msg[2] << 8) + msg[3];
1920
1921 /* Expect 2 bytes extension id + 2 bytes extension size */
1922 msg += 2 + 2;
1923 if (msg + rec_len > extensions_end || msg + rec_len < msg)
1924 goto store_capture;
1925 /* TLS Extensions
1926 * https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml */
1927 if (extension_id == 0x000a) {
1928 /* Elliptic Curves:
1929 * https://www.rfc-editor.org/rfc/rfc8422.html
1930 * https://www.rfc-editor.org/rfc/rfc7919.html */
1931 list_end = msg + rec_len;
1932 if (msg + 2 > list_end)
1933 goto store_capture;
1934 rec_len = (msg[0] << 8) + msg[1];
1935 msg += 2;
1936
1937 if (msg + rec_len > list_end || msg + rec_len < msg)
1938 goto store_capture;
1939 /* Store location/size of the list */
1940 ec_start = msg;
1941 ec_len = rec_len;
1942 }
1943 else if (extension_id == 0x000b) {
1944 /* Elliptic Curves Point Formats:
1945 * https://www.rfc-editor.org/rfc/rfc8422.html */
1946 list_end = msg + rec_len;
1947 if (msg + 1 > list_end)
1948 goto store_capture;
1949 rec_len = msg[0];
1950 msg += 1;
1951
1952 if (msg + rec_len > list_end || msg + rec_len < msg)
1953 goto store_capture;
1954 /* Store location/size of the list */
1955 ec_formats_start = msg;
1956 ec_formats_len = rec_len;
1957 }
1958 msg += rec_len;
1959 }
1960
1961 if (ec_start) {
1962 rec_len = ec_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001963 if (offset + rec_len > global_ssl.capture_buffer_size)
1964 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001965 memcpy(capture->data + offset, ec_start, rec_len);
1966 capture->ec_offset = offset;
1967 capture->ec_len = rec_len;
1968 offset += rec_len;
1969 }
1970 if (ec_formats_start) {
1971 rec_len = ec_formats_len;
Marcin Deranek310a2602021-07-13 19:04:24 +02001972 if (offset + rec_len > global_ssl.capture_buffer_size)
1973 rec_len = global_ssl.capture_buffer_size - offset;
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001974 memcpy(capture->data + offset, ec_formats_start, rec_len);
1975 capture->ec_formats_offset = offset;
1976 capture->ec_formats_len = rec_len;
1977 offset += rec_len;
1978 }
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001979
Marcin Deranek769fd2e2021-07-12 14:16:55 +02001980 store_capture:
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001981 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001982}
William Lallemand7d42ef52020-07-06 11:41:30 +02001983
1984
William Lallemand722180a2021-06-09 16:46:12 +02001985#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001986static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1987 int content_type, const void *buf, size_t len,
1988 SSL *ssl)
1989{
1990 struct ssl_keylog *keylog;
1991
1992 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1993 return;
1994
Willy Tarreauf208ac02021-03-22 21:10:12 +01001995 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02001996 if (!keylog)
1997 return;
1998
William Lallemand7d42ef52020-07-06 11:41:30 +02001999 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
2000 pool_free(pool_head_ssl_keylog, keylog);
2001 return;
2002 }
2003}
2004#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01002005
Emeric Brun29f037d2014-04-25 19:05:36 +02002006/* Callback is called for ssl protocol analyse */
2007void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
2008{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02002009 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2010 struct ssl_sock_msg_callback *cbk;
2011
Dragan Dosen1e7ed042020-05-08 18:30:00 +02002012 /* Try to call all callback functions that were registered by using
2013 * ssl_sock_register_msg_callback().
2014 */
2015 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
2016 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
2017 }
Emeric Brun29f037d2014-04-25 19:05:36 +02002018}
2019
Bernard Spil13c53f82018-02-15 13:34:58 +01002020#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01002021static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
2022 const unsigned char *in, unsigned int inlen,
2023 void *arg)
2024{
2025 struct server *srv = arg;
2026
2027 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
2028 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
2029 return SSL_TLSEXT_ERR_OK;
2030 return SSL_TLSEXT_ERR_NOACK;
2031}
2032#endif
2033
2034#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02002035/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002036 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02002037 */
2038static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
2039 unsigned int *len, void *arg)
2040{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002041 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02002042
2043 *data = (const unsigned char *)conf->npn_str;
2044 *len = conf->npn_len;
2045 return SSL_TLSEXT_ERR_OK;
2046}
2047#endif
2048
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002049#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02002050/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002051 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02002052 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002053static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
2054 unsigned char *outlen,
2055 const unsigned char *server,
2056 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02002057{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002058 struct ssl_bind_conf *conf = arg;
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002059#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002060 struct quic_conn *qc = SSL_get_ex_data(s, ssl_qc_app_data_index);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002061#endif
Willy Tarreauab861d32013-04-02 02:30:41 +02002062
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002063 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
2064 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01002065#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002066 if (qc)
2067 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille067a82b2021-11-19 17:02:20 +01002068#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01002069 return SSL_TLSEXT_ERR_NOACK;
2070 }
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002071
2072#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002073 if (qc && !quic_set_app_ops(qc, *out, *outlen)) {
2074 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
Frédéric Lécaille1761fdf2021-12-14 19:40:04 +01002075 return SSL_TLSEXT_ERR_NOACK;
2076 }
2077#endif
2078
Willy Tarreauab861d32013-04-02 02:30:41 +02002079 return SSL_TLSEXT_ERR_OK;
2080}
2081#endif
2082
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02002083#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002084#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002085
Shimi Gersneradabbfe2020-08-23 13:58:13 +03002086/* Configure a DNS SAN extenion on a certificate. */
2087int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
2088 int failure = 0;
2089 X509_EXTENSION *san_ext = NULL;
2090 CONF *conf = NULL;
2091 struct buffer *san_name = get_trash_chunk();
2092
2093 conf = NCONF_new(NULL);
2094 if (!conf) {
2095 failure = 1;
2096 goto cleanup;
2097 }
2098
2099 /* Build an extension based on the DNS entry above */
2100 chunk_appendf(san_name, "DNS:%s", servername);
2101 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
2102 if (!san_ext) {
2103 failure = 1;
2104 goto cleanup;
2105 }
2106
2107 /* Add the extension */
2108 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
2109 failure = 1;
2110 goto cleanup;
2111 }
2112
2113 /* Success */
2114 failure = 0;
2115
2116cleanup:
2117 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
2118 if (NULL != conf) NCONF_free(conf);
2119
2120 return failure;
2121}
2122
Christopher Faulet30548802015-06-11 13:39:32 +02002123/* Create a X509 certificate with the specified servername and serial. This
2124 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02002125static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002126ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002127{
Shimi Gersner5846c492020-08-23 13:58:12 +03002128 X509 *cacert = bind_conf->ca_sign_ckch->cert;
2129 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002130 SSL_CTX *ssl_ctx = NULL;
2131 X509 *newcrt = NULL;
2132 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002133 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002134 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002135 X509_NAME *name;
2136 const EVP_MD *digest;
2137 X509V3_CTX ctx;
2138 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002139 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002140
Christopher Faulet48a83322017-07-28 16:56:09 +02002141 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05002142#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002143 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
2144#else
2145 tmp_ssl = SSL_new(bind_conf->default_ctx);
2146 if (tmp_ssl)
2147 pkey = SSL_get_privatekey(tmp_ssl);
2148#endif
2149 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002150 goto mkcert_error;
2151
2152 /* Create the certificate */
2153 if (!(newcrt = X509_new()))
2154 goto mkcert_error;
2155
2156 /* Set version number for the certificate (X509v3) and the serial
2157 * number */
2158 if (X509_set_version(newcrt, 2L) != 1)
2159 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02002160 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002161
2162 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08002163 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
2164 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02002165 goto mkcert_error;
2166
2167 /* set public key in the certificate */
2168 if (X509_set_pubkey(newcrt, pkey) != 1)
2169 goto mkcert_error;
2170
2171 /* Set issuer name from the CA */
2172 if (!(name = X509_get_subject_name(cacert)))
2173 goto mkcert_error;
2174 if (X509_set_issuer_name(newcrt, name) != 1)
2175 goto mkcert_error;
2176
2177 /* Set the subject name using the same, but the CN */
2178 name = X509_NAME_dup(name);
2179 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
2180 (const unsigned char *)servername,
2181 -1, -1, 0) != 1) {
2182 X509_NAME_free(name);
2183 goto mkcert_error;
2184 }
2185 if (X509_set_subject_name(newcrt, name) != 1) {
2186 X509_NAME_free(name);
2187 goto mkcert_error;
2188 }
2189 X509_NAME_free(name);
2190
2191 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002192 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002193 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
2194 for (i = 0; i < X509V3_EXT_SIZE; i++) {
2195 X509_EXTENSION *ext;
2196
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002197 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02002198 goto mkcert_error;
2199 if (!X509_add_ext(newcrt, ext, -1)) {
2200 X509_EXTENSION_free(ext);
2201 goto mkcert_error;
2202 }
2203 X509_EXTENSION_free(ext);
2204 }
2205
Shimi Gersneradabbfe2020-08-23 13:58:13 +03002206 /* Add SAN extension */
2207 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
2208 goto mkcert_error;
2209 }
2210
Christopher Faulet31af49d2015-06-09 17:29:50 +02002211 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002212
2213 key_type = EVP_PKEY_base_id(capkey);
2214
2215 if (key_type == EVP_PKEY_DSA)
2216 digest = EVP_sha1();
2217 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002218 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002219 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02002220 digest = EVP_sha256();
2221 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05002222#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02002223 int nid;
2224
2225 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
2226 goto mkcert_error;
2227 if (!(digest = EVP_get_digestbynid(nid)))
2228 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02002229#else
2230 goto mkcert_error;
2231#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02002232 }
2233
Christopher Faulet31af49d2015-06-09 17:29:50 +02002234 if (!(X509_sign(newcrt, capkey, digest)))
2235 goto mkcert_error;
2236
2237 /* Create and set the new SSL_CTX */
2238 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
2239 goto mkcert_error;
2240 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
2241 goto mkcert_error;
2242 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
2243 goto mkcert_error;
2244 if (!SSL_CTX_check_private_key(ssl_ctx))
2245 goto mkcert_error;
2246
Shimi Gersner5846c492020-08-23 13:58:12 +03002247 /* Build chaining the CA cert and the rest of the chain, keep these order */
2248#if defined(SSL_CTX_add1_chain_cert)
2249 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
2250 goto mkcert_error;
2251 }
2252
2253 if (bind_conf->ca_sign_ckch->chain) {
2254 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2255 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2256 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2257 goto mkcert_error;
2258 }
2259 }
2260 }
2261#endif
2262
Christopher Faulet31af49d2015-06-09 17:29:50 +02002263 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002264
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002265#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002266#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01002267 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01002268#else
2269 ssl_sock_set_tmp_dh_from_pkey(ssl_ctx, pkey);
2270#endif
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002271#endif
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002272
2273#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
2274#if defined(SSL_CTX_set1_curves_list)
2275 {
2276 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
2277 if (!SSL_CTX_set1_curves_list(ssl_ctx, ecdhe))
2278 goto end;
2279 }
2280#endif
2281#else
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002282#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2283 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002284 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002285 EC_KEY *ecc;
2286 int nid;
2287
2288 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2289 goto end;
2290 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2291 goto end;
2292 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2293 EC_KEY_free(ecc);
2294 }
Remi Tricot-Le Bretonc11e7e12022-02-08 17:45:56 +01002295#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
2296#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002297 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002298 return ssl_ctx;
2299
2300 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002301 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002302 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002303 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2304 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002305 return NULL;
2306}
2307
Christopher Faulet7969a332015-10-09 11:15:03 +02002308
Christopher Faulet30548802015-06-11 13:39:32 +02002309/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002310 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002311SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002312ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002313{
2314 struct lru64 *lru = NULL;
2315
2316 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002317 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002318 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002319 if (lru && lru->domain) {
2320 if (ssl)
2321 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002322 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002323 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002324 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002325 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002326 }
2327 return NULL;
2328}
2329
Emeric Brun821bb9b2017-06-15 16:37:39 +02002330/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2331 * function is not thread-safe, it should only be used to check if a certificate
2332 * exists in the lru cache (with no warranty it will not be removed by another
2333 * thread). It is kept for backward compatibility. */
2334SSL_CTX *
2335ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2336{
2337 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2338}
2339
Christopher Fauletd2cab922015-07-28 16:03:47 +02002340/* Set a certificate int the LRU cache used to store generated
2341 * certificate. Return 0 on success, otherwise -1 */
2342int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002343ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002344{
2345 struct lru64 *lru = NULL;
2346
2347 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002348 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002349 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002350 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002351 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002352 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002353 }
Christopher Faulet30548802015-06-11 13:39:32 +02002354 if (lru->domain && lru->data)
2355 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002356 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002357 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002358 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002359 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002360 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002361}
2362
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002363/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002364unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002365ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002366{
2367 return XXH32(data, len, ssl_ctx_lru_seed);
2368}
2369
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002370/* Generate a cert and immediately assign it to the SSL session so that the cert's
2371 * refcount is maintained regardless of the cert's presence in the LRU cache.
2372 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002373static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002374ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002375{
Shimi Gersner5846c492020-08-23 13:58:12 +03002376 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002377 SSL_CTX *ssl_ctx = NULL;
2378 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002379 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002380
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002381 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002382 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002383 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002384 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002385 if (lru && lru->domain)
2386 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002387 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002388 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002389 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002390 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002391 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002392 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002393 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002394 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002395 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002396 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002397 SSL_set_SSL_CTX(ssl, ssl_ctx);
2398 /* No LRU cache, this CTX will be released as soon as the session dies */
2399 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002400 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002401 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002402 return 0;
2403}
2404static int
2405ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2406{
2407 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002408 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002409
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002410 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002411 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002412 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002413 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002414 }
2415 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002416}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002417#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002418
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002419#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002420
2421static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002422{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002423#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002424 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002425 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2426#endif
2427}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002428static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2429 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002430 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2431}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002432static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002433#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002434 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002435 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2436#endif
2437}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002438static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002439#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002440 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002441 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2442#endif
2443}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002444/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002445static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2446/* Unusable in this context. */
2447static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2448static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2449static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2450static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2451static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002452#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002453
2454static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2455 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002456 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2457}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002458static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2459 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2460 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2461}
2462static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2463 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002464 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2465}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002466static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2467 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2468 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2469}
2470static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2471 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002472 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2473}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002474static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2475 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2476 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2477}
2478static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2479 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002480 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2481}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002482static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2483 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2484 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2485}
2486static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002487#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002488 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002489 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2490#endif
2491}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002492static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
William Lallemandf22b0322021-06-02 16:09:11 +02002493#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002494 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2495 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002496#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002497}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002498#endif
2499static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2500static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002501
William Lallemand7fd8b452020-05-07 15:20:43 +02002502struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002503 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2504 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2505 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2506 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2507 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2508 {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 +02002509};
2510
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002511static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2512{
2513 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2514 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2515 SSL_set_SSL_CTX(ssl, ctx);
2516}
2517
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002518#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002519
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002520int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002521{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002522 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002523 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002524
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002525 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || s->generate_certs)
2526 return SSL_TLSEXT_ERR_OK;
2527 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002528}
2529
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002530#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002531int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002532{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002533 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002534#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002535int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002536{
2537#endif
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002538 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
2539#ifdef USE_QUIC
2540 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
2541#endif /* USE_QUIC */
2542 struct bind_conf *s = NULL;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002543 const uint8_t *extension_data;
2544 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002545 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002546
2547 char *wildp = NULL;
2548 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002549 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002550 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002551 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002552 int i;
2553
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002554 if (conn)
2555 s = __objt_listener(conn->target)->bind_conf;
2556#ifdef USE_QUIC
2557 else if (qc)
2558 s = qc->li->bind_conf;
2559#endif /* USE_QUIC */
Amaury Denoyelle7c564bf2022-01-24 11:04:05 +01002560
2561 if (!s) {
2562 /* must never happen */
2563 ABORT_NOW();
2564 return 0;
2565 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002566
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002567#ifdef USE_QUIC
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002568 if (qc) {
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002569 /* Look for the QUIC transport parameters. */
2570#ifdef OPENSSL_IS_BORINGSSL
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002571 if (!SSL_early_callback_ctx_extension_get(ctx, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002572 &extension_data, &extension_len))
2573#else
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002574 if (!SSL_client_hello_get0_ext(ssl, qc->tps_tls_ext,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002575 &extension_data, &extension_len))
2576#endif
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002577 {
2578 /* This is not redundant. It we only return 0 without setting
2579 * <*al>, this has as side effect to generate another TLS alert
2580 * which would be set after calling quic_set_tls_alert().
2581 */
2582 *al = SSL_AD_MISSING_EXTENSION;
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002583 quic_set_tls_alert(qc, SSL_AD_MISSING_EXTENSION);
Frédéric Lécailleb5b52472021-11-22 15:55:16 +01002584 return 0;
2585 }
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002586
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002587 if (!quic_transport_params_store(qc, 0, extension_data,
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002588 extension_data + extension_len))
2589 goto abort;
2590 }
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002591#endif /* USE_QUIC */
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002592
Olivier Houchard9679ac92017-10-27 14:58:08 +02002593 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002594 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002595#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002596 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2597 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002598#else
2599 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2600#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002601 /*
2602 * The server_name extension was given too much extensibility when it
2603 * was written, so parsing the normal case is a bit complex.
2604 */
2605 size_t len;
2606 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002607 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002608 /* Extract the length of the supplied list of names. */
2609 len = (*extension_data++) << 8;
2610 len |= *extension_data++;
2611 if (len + 2 != extension_len)
2612 goto abort;
2613 /*
2614 * The list in practice only has a single element, so we only consider
2615 * the first one.
2616 */
2617 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2618 goto abort;
2619 extension_len = len - 1;
2620 /* Now we can finally pull out the byte array with the actual hostname. */
2621 if (extension_len <= 2)
2622 goto abort;
2623 len = (*extension_data++) << 8;
2624 len |= *extension_data++;
2625 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2626 || memchr(extension_data, 0, len) != NULL)
2627 goto abort;
2628 servername = extension_data;
2629 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002630 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002631#if (!defined SSL_NO_GENERATE_CERTIFICATES)
2632 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002633 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002634 }
2635#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002636 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002637 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002638 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002639 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002640 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002641 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002642 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002643 goto abort;
2644 }
2645
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002646 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002647#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002648 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002649#else
2650 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2651#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002652 uint8_t sign;
2653 size_t len;
2654 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002655 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002656 len = (*extension_data++) << 8;
2657 len |= *extension_data++;
2658 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002659 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002660 if (len % 2 != 0)
2661 goto abort;
2662 for (; len > 0; len -= 2) {
2663 extension_data++; /* hash */
2664 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002665 switch (sign) {
2666 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002667 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002668 break;
2669 case TLSEXT_signature_ecdsa:
2670 has_ecdsa_sig = 1;
2671 break;
2672 default:
2673 continue;
2674 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002675 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002676 break;
2677 }
2678 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002679 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002680 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002681 }
2682 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002683 const SSL_CIPHER *cipher;
2684 size_t len;
2685 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002686 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002687#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002688 len = ctx->cipher_suites_len;
2689 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002690#else
2691 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2692#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002693 if (len % 2 != 0)
2694 goto abort;
2695 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002696#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002697 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002698 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002699#else
2700 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2701#endif
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002702 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002703 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002704 break;
2705 }
2706 }
2707 }
2708
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002709 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002710 trash.area[i] = tolower(servername[i]);
2711 if (!wildp && (trash.area[i] == '.'))
2712 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002713 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002714 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002715
William Lallemand150bfa82019-09-19 17:12:49 +02002716 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002717
William Lallemand94bd3192020-08-14 14:43:35 +02002718 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2719 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002720 for (i = 0; i < 2; i++) {
2721 if (i == 0) /* lookup in full qualified names */
2722 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002723 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002724 node = ebst_lookup(&s->sni_w_ctx, wildp);
2725 else
2726 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002727
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002728 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002729
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002730 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002731 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002732 struct sni_ctx *sni, *sni_tmp;
2733 int skip = 0;
2734
2735 if (i == 1 && wildp) { /* wildcard */
2736 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2737 sni = container_of(n, struct sni_ctx, name);
2738 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002739 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002740 skip = 1;
2741 break;
2742 }
2743 }
2744 if (skip)
2745 continue;
2746 }
2747
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002748 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002749 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002750 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002751 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002752 break;
2753 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002754 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002755 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002756 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002757 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002758 if (!node_anonymous)
2759 node_anonymous = n;
2760 break;
2761 }
2762 }
2763 }
William Lallemand94bd3192020-08-14 14:43:35 +02002764 }
2765 /* Once the certificates are found, select them depending on what is
2766 * supported in the client and by key_signature priority order: EDSA >
2767 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002768 if (has_ecdsa_sig && node_ecdsa)
2769 node = node_ecdsa;
2770 else if (has_rsa_sig && node_rsa)
2771 node = node_rsa;
2772 else if (node_anonymous)
2773 node = node_anonymous;
2774 else if (node_ecdsa)
2775 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2776 else
2777 node = node_rsa; /* no rsa signature case (far far away) */
2778
William Lallemand94bd3192020-08-14 14:43:35 +02002779 if (node) {
2780 /* switch ctx */
2781 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2782 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2783 if (conf) {
2784 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2785 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2786 if (conf->early_data)
2787 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002788 }
William Lallemand94bd3192020-08-14 14:43:35 +02002789 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2790 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002791 }
William Lallemand150bfa82019-09-19 17:12:49 +02002792
William Lallemand02010472019-10-18 11:02:19 +02002793 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002794#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002795 if (s->generate_certs && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002796 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002797 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002798 }
2799#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002800 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002801 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002802 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002803 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002804 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
William Lallemand7980dff2021-11-18 17:46:26 +01002805 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002806 }
William Lallemand7980dff2021-11-18 17:46:26 +01002807
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01002808 /* We are about to raise an handshake error so the servername extension
2809 * callback will never be called and the SNI will never be stored in the
2810 * SSL context. In order for the ssl_fc_sni sample fetch to still work
2811 * in such a case, we store the SNI ourselves as an ex_data information
2812 * in the SSL context.
2813 */
2814 {
2815 char *client_sni = pool_alloc(ssl_sock_client_sni_pool);
2816 if (client_sni) {
2817 strncpy(client_sni, trash.area, TLSEXT_MAXLEN_host_name);
2818 client_sni[TLSEXT_MAXLEN_host_name] = '\0';
2819 SSL_set_ex_data(ssl, ssl_client_sni_index, client_sni);
2820 }
2821 }
2822
William Lallemand7980dff2021-11-18 17:46:26 +01002823 /* other cases fallback on abort, if strict-sni is set but no node was found */
2824
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002825 abort:
2826 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
Amaury Denoyelle9320dd52022-01-19 10:03:30 +01002827 if (conn)
2828 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002829#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002830 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002831#else
2832 *al = SSL_AD_UNRECOGNIZED_NAME;
2833 return 0;
2834#endif
William Lallemand7980dff2021-11-18 17:46:26 +01002835
2836allow_early:
2837#ifdef OPENSSL_IS_BORINGSSL
2838 if (allow_early)
2839 SSL_set_early_data_enabled(ssl, 1);
2840#else
2841 if (!allow_early)
2842 SSL_set_max_early_data(ssl, 0);
2843#endif
2844 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002845}
2846
William Lallemand002e2062021-11-18 15:25:16 +01002847#else /* ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002848
Emeric Brunfc0421f2012-09-07 17:30:07 +02002849/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2850 * warning when no match is found, which implies the default (first) cert
2851 * will keep being used.
2852 */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002853static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002854{
2855 const char *servername;
2856 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002857 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002858 struct bind_conf *s = priv;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002859 int i;
2860 (void)al; /* shut gcc stupid warning */
2861
2862 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002863 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002864#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002865 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl))
2866 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002867#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002868 if (s->strict_sni)
2869 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002870 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002871 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002872 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002873 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002874 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002875
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002876 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002877 if (!servername[i])
2878 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002879 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002880 if (!wildp && (trash.area[i] == '.'))
2881 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002882 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002883 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002884
William Lallemand150bfa82019-09-19 17:12:49 +02002885 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002886 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002887 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002888 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2889 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002890 if (!container_of(n, struct sni_ctx, name)->neg) {
2891 node = n;
2892 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002893 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002894 }
2895 if (!node && wildp) {
2896 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002897 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2898 /* lookup a not neg filter */
2899 if (!container_of(n, struct sni_ctx, name)->neg) {
2900 node = n;
2901 break;
2902 }
2903 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002904 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002905 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002906#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002907 if (s->generate_certs && ssl_sock_generate_certificate(servername, s, ssl)) {
2908 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002909 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002910 return SSL_TLSEXT_ERR_OK;
2911 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002912#endif
William Lallemand21724f02019-11-04 17:56:13 +01002913 if (s->strict_sni) {
2914 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002915 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002916 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002917 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002918 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002919 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002920 }
2921
2922 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002923 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002924 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002925 return SSL_TLSEXT_ERR_OK;
2926}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002927#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002928#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2929
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002930#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002931
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002932static inline HASSL_DH *ssl_new_dh_fromdata(BIGNUM *p, BIGNUM *g)
2933{
2934#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2935 OSSL_PARAM_BLD *tmpl = NULL;
2936 OSSL_PARAM *params = NULL;
2937 EVP_PKEY_CTX *ctx = NULL;
2938 EVP_PKEY *pkey = NULL;
2939
2940 if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
2941 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
2942 || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)
2943 || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
2944 goto end;
2945 }
2946 ctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2947 if (ctx == NULL
2948 || !EVP_PKEY_fromdata_init(ctx)
2949 || !EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params)) {
2950 goto end;
2951 }
2952
2953end:
2954 EVP_PKEY_CTX_free(ctx);
2955 OSSL_PARAM_free(params);
2956 OSSL_PARAM_BLD_free(tmpl);
2957 return pkey;
2958#else
2959
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01002960 HASSL_DH *dh = DH_new();
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01002961
2962 if (!dh)
2963 return NULL;
2964
2965 DH_set0_pqg(dh, p, NULL, g);
2966
2967 return dh;
2968#endif
2969}
2970
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02002971#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02002972static inline HASSL_DH *ssl_get_dh_by_nid(int nid)
2973{
2974#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
2975 OSSL_PARAM params[2];
2976 EVP_PKEY *pkey = NULL;
2977 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
2978 const char *named_group = NULL;
2979
2980 if (!pctx)
2981 goto end;
2982
2983 named_group = OBJ_nid2ln(nid);
2984
2985 if (!named_group)
2986 goto end;
2987
2988 params[0] = OSSL_PARAM_construct_utf8_string("group", (char*)named_group, 0);
2989 params[1] = OSSL_PARAM_construct_end();
2990
2991 if (EVP_PKEY_keygen_init(pctx) && EVP_PKEY_CTX_set_params(pctx, params))
2992 EVP_PKEY_generate(pctx, &pkey);
2993
2994end:
2995 EVP_PKEY_CTX_free(pctx);
2996 return pkey;
2997#else
2998
2999 HASSL_DH *dh = NULL;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003000 dh = DH_new_by_nid(nid);
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003001 return dh;
3002#endif
3003}
Remi Tricot-Le Bretonc69be7c2022-04-20 18:30:17 +02003004#endif
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003005
Remi Tricot-Le Breton7f6425a2022-02-11 12:04:52 +01003006
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003007static HASSL_DH * ssl_get_dh_1024(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003008{
Remi Gacogned3a341a2015-05-29 16:26:17 +02003009 static unsigned char dh1024_p[]={
3010 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
3011 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
3012 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
3013 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
3014 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
3015 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
3016 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
3017 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
3018 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
3019 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
3020 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
3021 };
3022 static unsigned char dh1024_g[]={
3023 0x02,
3024 };
3025
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003026 BIGNUM *p;
3027 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02003028
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003029 HASSL_DH *dh = NULL;
3030
3031 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
3032 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
3033
3034 if (p && g)
3035 dh = ssl_new_dh_fromdata(p, g);
3036
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003037 return dh;
3038}
3039
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003040static HASSL_DH *ssl_get_dh_2048(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003041{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003042#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02003043 static unsigned char dh2048_p[]={
3044 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
3045 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
3046 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
3047 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
3048 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
3049 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
3050 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
3051 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
3052 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
3053 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
3054 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
3055 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
3056 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
3057 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
3058 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
3059 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
3060 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
3061 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
3062 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
3063 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
3064 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
3065 0xB7,0x1F,0x77,0xF3,
3066 };
3067 static unsigned char dh2048_g[]={
3068 0x02,
3069 };
3070
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003071 BIGNUM *p;
3072 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02003073
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003074 HASSL_DH *dh = NULL;
3075
3076 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
3077 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
3078
3079 if (p && g)
3080 dh = ssl_new_dh_fromdata(p, g);
3081
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003082 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003083#else
3084 return ssl_get_dh_by_nid(NID_ffdhe2048);
3085#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003086}
3087
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003088static HASSL_DH *ssl_get_dh_4096(void)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003089{
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003090#if (HA_OPENSSL_VERSION_NUMBER < 0x10101000L)
Remi Gacogned3a341a2015-05-29 16:26:17 +02003091 static unsigned char dh4096_p[]={
3092 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
3093 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
3094 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
3095 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
3096 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
3097 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
3098 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
3099 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
3100 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
3101 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
3102 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
3103 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
3104 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
3105 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
3106 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
3107 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
3108 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
3109 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
3110 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
3111 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
3112 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
3113 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
3114 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
3115 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
3116 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
3117 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
3118 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
3119 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
3120 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
3121 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
3122 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
3123 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
3124 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
3125 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
3126 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
3127 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
3128 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
3129 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
3130 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
3131 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
3132 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
3133 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
3134 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003135 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02003136 static unsigned char dh4096_g[]={
3137 0x02,
3138 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003139
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003140 BIGNUM *p;
3141 BIGNUM *g;
Remi Gacogned3a341a2015-05-29 16:26:17 +02003142
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003143 HASSL_DH *dh = NULL;
3144
3145 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
3146 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
3147
3148 if (p && g)
3149 dh = ssl_new_dh_fromdata(p, g);
3150
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003151 return dh;
Remi Tricot-Le Breton528b3fd2022-04-12 11:31:54 +02003152#else
3153 return ssl_get_dh_by_nid(NID_ffdhe4096);
3154#endif
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003155}
3156
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003157static HASSL_DH *ssl_get_tmp_dh(EVP_PKEY *pkey)
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003158{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003159 HASSL_DH *dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003160 int type;
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003161 int keylen = 0;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003162
3163 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003164
3165 /* The keylen supplied by OpenSSL can only be 512 or 1024.
3166 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
3167 */
3168 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
3169 keylen = EVP_PKEY_bits(pkey);
3170 }
3171
Willy Tarreauef934602016-12-22 23:12:01 +01003172 if (keylen > global_ssl.default_dh_param) {
3173 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003174 }
3175
Remi Gacogned3a341a2015-05-29 16:26:17 +02003176 if (keylen >= 4096) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003177 if (!local_dh_4096)
3178 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02003179 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003180 }
3181 else if (keylen >= 2048) {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003182 if (!local_dh_2048)
3183 local_dh_2048 = ssl_get_dh_2048();
Remi Gacogne8de54152014-07-15 11:36:40 +02003184 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003185 }
3186 else {
Remi Tricot-Le Bretonbed72632022-02-11 12:04:53 +01003187 if (!local_dh_1024)
3188 local_dh_1024 = ssl_get_dh_1024();
Remi Gacogne8de54152014-07-15 11:36:40 +02003189 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02003190 }
3191
3192 return dh;
3193}
3194
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003195#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003196/* Returns Diffie-Hellman parameters matching the private key length
3197 but not exceeding global_ssl.default_dh_param */
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003198static HASSL_DH *ssl_get_tmp_dh_cbk(SSL *ssl, int export, int keylen)
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003199{
3200 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
3201
3202 return ssl_get_tmp_dh(pkey);
3203}
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003204#endif
Remi Tricot-Le Breton292a88c2022-02-11 12:04:49 +01003205
Remi Tricot-Le Breton846eda92022-02-11 12:04:50 +01003206static int ssl_sock_set_tmp_dh(SSL_CTX *ctx, HASSL_DH *dh)
3207{
3208#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
3209 return SSL_CTX_set_tmp_dh(ctx, dh);
3210#else
3211 int retval = 0;
3212 HASSL_DH_up_ref(dh);
3213
3214 retval = SSL_CTX_set0_tmp_dh_pkey(ctx, dh);
3215
3216 if (!retval)
3217 HASSL_DH_free(dh);
3218
3219 return retval;
3220#endif
3221}
3222
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003223#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3224static void ssl_sock_set_tmp_dh_from_pkey(SSL_CTX *ctx, EVP_PKEY *pkey)
3225{
3226 HASSL_DH *dh = NULL;
3227 if (pkey && (dh = ssl_get_tmp_dh(pkey))) {
3228 HASSL_DH_up_ref(dh);
3229 if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dh))
3230 HASSL_DH_free(dh);
3231 }
Remi Tricot-Le Breton5f179302022-02-11 12:04:51 +01003232}
3233#endif
3234
Remi Tricot-Le Breton09ebb332022-02-11 12:04:48 +01003235HASSL_DH *ssl_sock_get_dh_from_bio(BIO *bio)
3236{
3237#if (HA_OPENSSL_VERSION_NUMBER >= 0x3000000fL)
3238 HASSL_DH *dh = NULL;
3239 OSSL_DECODER_CTX *dctx = NULL;
3240 const char *format = "PEM";
3241 const char *keytype = "DH";
3242
3243 dctx = OSSL_DECODER_CTX_new_for_pkey(&dh, format, NULL, keytype,
3244 OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
3245 NULL, NULL);
3246
3247 if (dctx == NULL || OSSL_DECODER_CTX_get_num_decoders(dctx) == 0)
3248 goto end;
3249
3250 /* The DH parameters might not be the first section found in the PEM
3251 * file so we need to iterate over all of them until we find the right
3252 * one.
3253 */
3254 while (!BIO_eof(bio) && !dh)
3255 OSSL_DECODER_from_bio(dctx, bio);
3256
3257end:
3258 OSSL_DECODER_CTX_free(dctx);
3259 return dh;
3260#else
3261 HASSL_DH *dh = NULL;
3262
3263 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3264
3265 return dh;
3266#endif
3267}
3268
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003269static HASSL_DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003270{
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003271 HASSL_DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02003272 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003273
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003274 if (in == NULL)
3275 goto end;
3276
Remi Gacogne47783ef2015-05-29 15:53:22 +02003277 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003278 goto end;
3279
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003280 dh = ssl_sock_get_dh_from_bio(in);
Remi Gacogne47783ef2015-05-29 15:53:22 +02003281
3282end:
3283 if (in)
3284 BIO_free(in);
3285
Emeric Brune1b4ed42018-08-16 15:14:12 +02003286 ERR_clear_error();
3287
Remi Gacogne47783ef2015-05-29 15:53:22 +02003288 return dh;
3289}
3290
3291int ssl_sock_load_global_dh_param_from_file(const char *filename)
3292{
3293 global_dh = ssl_sock_get_dh_from_file(filename);
3294
3295 if (global_dh) {
3296 return 0;
3297 }
3298
3299 return -1;
3300}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003301#endif
3302
William Lallemand9117de92019-10-04 00:29:42 +02003303/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02003304static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02003305 struct bind_conf *s, struct ssl_bind_conf *conf,
3306 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003307{
3308 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003309 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003310
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003311 if (*name == '!') {
3312 neg = 1;
3313 name++;
3314 }
3315 if (*name == '*') {
3316 wild = 1;
3317 name++;
3318 }
3319 /* !* filter is a nop */
3320 if (neg && wild)
3321 return order;
3322 if (*name) {
3323 int j, len;
3324 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003325 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02003326 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003327 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02003328 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003329 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02003330
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003331 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02003332 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02003333 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003334 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02003335 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003336 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003337 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003338 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02003339 sc->order = order++;
3340 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02003341 sc->wild = wild;
3342 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01003343 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02003344 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003345 }
3346 return order;
3347}
3348
William Lallemand6af03992019-07-23 15:00:54 +02003349/*
William Lallemand1d29c742019-10-04 00:53:29 +02003350 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
3351 * This function can't return an error.
3352 *
3353 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
3354 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003355void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02003356{
3357
3358 struct sni_ctx *sc0, *sc0b, *sc1;
3359 struct ebmb_node *node;
3360
3361 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
3362
3363 /* ignore if sc0 was already inserted in a tree */
3364 if (sc0->name.node.leaf_p)
3365 continue;
3366
3367 /* Check for duplicates. */
3368 if (sc0->wild)
3369 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
3370 else
3371 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
3372
3373 for (; node; node = ebmb_next_dup(node)) {
3374 sc1 = ebmb_entry(node, struct sni_ctx, name);
3375 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
3376 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
3377 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02003378 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02003379 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003380 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02003381 break;
William Lallemand1d29c742019-10-04 00:53:29 +02003382 }
3383 }
3384
3385 /* if duplicate, ignore the insertion */
3386 if (!sc0)
3387 continue;
3388
3389 if (sc0->wild)
3390 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
3391 else
3392 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003393 }
William Lallemand21724f02019-11-04 17:56:13 +01003394
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003395 /* replace the default_ctx if required with the instance's ctx. */
3396 if (ckch_inst->is_default) {
3397 SSL_CTX_free(bind_conf->default_ctx);
3398 SSL_CTX_up_ref(ckch_inst->ctx);
3399 bind_conf->default_ctx = ckch_inst->ctx;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003400 bind_conf->default_inst = ckch_inst;
William Lallemand1d29c742019-10-04 00:53:29 +02003401 }
3402}
3403
3404/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003405 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02003406 */
William Lallemande3af8fb2019-10-08 11:36:53 +02003407struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02003408
William Lallemand2954c472020-03-06 21:54:13 +01003409/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02003410struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02003411
Emeric Brun7a883362019-10-17 13:27:40 +02003412/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003413 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02003414 * DH parameter is loaded into the SSL_CTX and if there is no
3415 * DH parameter available in ckchs nor in global, the default
3416 * DH parameters are applied on the SSL_CTX.
3417 * Returns a bitfield containing the flags:
3418 * ERR_FATAL in any fatal error case
3419 * ERR_ALERT if a reason of the error is availabine in err
3420 * ERR_WARN if a warning is available into err
3421 * The value 0 means there is no error nor warning and
3422 * the operation succeed.
3423 */
William Lallemandfa892222019-07-23 16:06:08 +02003424#ifndef OPENSSL_NO_DH
Emeric Brun7a883362019-10-17 13:27:40 +02003425static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct cert_key_and_chain *ckch,
3426 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02003427{
Emeric Brun7a883362019-10-17 13:27:40 +02003428 int ret = 0;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003429 HASSL_DH *dh = NULL;
William Lallemandfa892222019-07-23 16:06:08 +02003430
William Lallemanda8c73742019-07-31 18:31:34 +02003431 if (ckch && ckch->dh) {
William Lallemandfa892222019-07-23 16:06:08 +02003432 dh = ckch->dh;
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003433 if (!ssl_sock_set_tmp_dh(ctx, dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003434 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
3435 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003436 memprintf(err, "%s, DH ciphers won't be available.\n",
3437 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003438 ret |= ERR_WARN;
3439 goto end;
3440 }
William Lallemandfa892222019-07-23 16:06:08 +02003441
3442 if (ssl_dh_ptr_index >= 0) {
3443 /* store a pointer to the DH params to avoid complaining about
3444 ssl-default-dh-param not being set for this SSL_CTX */
3445 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
3446 }
3447 }
3448 else if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01003449 if (!ssl_sock_set_tmp_dh(ctx, global_dh)) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003450 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
3451 err && *err ? *err : "", path);
Emeric Bruna9363eb2019-10-17 14:53:03 +02003452 memprintf(err, "%s, DH ciphers won't be available.\n",
3453 err && *err ? *err : "");
Emeric Bruna9363eb2019-10-17 14:53:03 +02003454 ret |= ERR_WARN;
3455 goto end;
3456 }
William Lallemandfa892222019-07-23 16:06:08 +02003457 }
3458 else {
3459 /* Clear openssl global errors stack */
3460 ERR_clear_error();
3461
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003462 /* We do not want DHE ciphers to be added to the cipher list
3463 * unless there is an explicit global dh option in the conf.
3464 */
3465 if (global_ssl.default_dh_param) {
3466 if (global_ssl.default_dh_param <= 1024) {
3467 /* we are limited to DH parameter of 1024 bits anyway */
3468 if (local_dh_1024 == NULL)
3469 local_dh_1024 = ssl_get_dh_1024();
William Lallemandfa892222019-07-23 16:06:08 +02003470
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003471 if (local_dh_1024 == NULL) {
3472 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3473 err && *err ? *err : "", path);
3474 ret |= ERR_ALERT | ERR_FATAL;
3475 goto end;
3476 }
William Lallemandfa892222019-07-23 16:06:08 +02003477
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003478 if (!ssl_sock_set_tmp_dh(ctx, local_dh_1024)) {
3479 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3480 err && *err ? *err : "", path);
3481 memprintf(err, "%s, DH ciphers won't be available.\n",
3482 err && *err ? *err : "");
3483 ret |= ERR_WARN;
3484 goto end;
3485 }
Emeric Bruna9363eb2019-10-17 14:53:03 +02003486 }
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003487 else {
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003488#if (HA_OPENSSL_VERSION_NUMBER < 0x3000000fL)
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003489 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh_cbk);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003490#else
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003491 ssl_sock_set_tmp_dh_from_pkey(ctx, ckch ? ckch->key : NULL);
Remi Tricot-Le Breton88c56952022-02-11 12:04:56 +01003492#endif
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02003493 }
William Lallemandfa892222019-07-23 16:06:08 +02003494 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003495 }
3496
William Lallemandf9568fc2019-10-16 18:27:58 +02003497end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003498 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003499 return ret;
3500}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003501#endif
William Lallemandfa892222019-07-23 16:06:08 +02003502
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003503
3504/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003505 * Returns a bitfield containing the flags:
3506 * ERR_FATAL in any fatal error case
3507 * ERR_ALERT if the reason of the error is available in err
3508 * ERR_WARN if a warning is available into err
3509 * The value 0 means there is no error nor warning and
3510 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003511 */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003512static int ssl_sock_load_cert_chain(const char *path, const struct cert_key_and_chain *ckch,
3513 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003514{
Emeric Bruna96b5822019-10-17 13:25:14 +02003515 int errcode = 0;
3516
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003517 if (find_chain == NULL) {
3518 errcode |= ERR_FATAL;
3519 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003520 }
3521
3522 if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
3523 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
3524 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003525 errcode |= ERR_ALERT | ERR_FATAL;
3526 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003527 }
3528
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003529 if (ckch->chain) {
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003530 *find_chain = ckch->chain;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003531 } else {
3532 /* Find Certificate Chain in global */
3533 struct issuer_chain *issuer;
Emmanuel Hocdetef87e0a2020-03-23 11:29:11 +01003534 issuer = ssl_get0_issuer_chain(ckch->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003535 if (issuer)
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003536 *find_chain = issuer->chain;
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003537 }
William Lallemand85888572020-02-27 14:48:35 +01003538
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003539 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003540 /* always put a null chain stack in the SSL_CTX so it does not
3541 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003542 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003543 }
3544
William Lallemandf187ce62020-06-02 18:27:20 +02003545 /* Load all certs in the ckch into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003546#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003547 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand935d8292020-08-12 20:02:10 +02003548 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'. Make sure you are linking against Openssl >= 1.0.2.\n",
3549 err && *err ? *err : "", path);
3550 errcode |= ERR_ALERT | ERR_FATAL;
3551 goto end;
3552 }
William Lallemandf187ce62020-06-02 18:27:20 +02003553#else
3554 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003555 X509 *ca;
William Lallemandf187ce62020-06-02 18:27:20 +02003556 STACK_OF(X509) *chain;
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003557 chain = X509_chain_up_ref(*find_chain);
William Lallemandf187ce62020-06-02 18:27:20 +02003558 while ((ca = sk_X509_shift(chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003559 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003560 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3561 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003562 X509_free(ca);
3563 sk_X509_pop_free(chain, X509_free);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003564 errcode |= ERR_ALERT | ERR_FATAL;
3565 goto end;
3566 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003567 }
William Lallemandf187ce62020-06-02 18:27:20 +02003568#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003569
William Lallemand9a1d8392020-08-10 17:28:23 +02003570#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003571 /* remove the Root CA from the SSL_CTX if the option is activated */
3572 if (global_ssl.skip_self_issued_ca) {
3573 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3574 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3575 err && *err ? *err : "", path);
3576 errcode |= ERR_ALERT | ERR_FATAL;
3577 goto end;
3578 }
3579 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003580#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003581
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003582end:
3583 return errcode;
3584}
3585
3586
3587/* Loads the info in ckch into ctx
3588 * Returns a bitfield containing the flags:
3589 * ERR_FATAL in any fatal error case
3590 * ERR_ALERT if the reason of the error is available in err
3591 * ERR_WARN if a warning is available into err
3592 * The value 0 means there is no error nor warning and
3593 * the operation succeed.
3594 */
3595static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
3596{
3597 int errcode = 0;
3598 STACK_OF(X509) *find_chain = NULL;
3599
3600 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3601 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3602 err && *err ? *err : "", path);
3603 errcode |= ERR_ALERT | ERR_FATAL;
3604 return errcode;
3605 }
3606
3607 /* Load certificate chain */
3608 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3609 if (errcode & ERR_CODE)
3610 goto end;
3611
William Lallemandfa892222019-07-23 16:06:08 +02003612#ifndef OPENSSL_NO_DH
3613 /* store a NULL pointer to indicate we have not yet loaded
3614 a custom DH param file */
3615 if (ssl_dh_ptr_index >= 0) {
3616 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3617 }
3618
Emeric Brun7a883362019-10-17 13:27:40 +02003619 errcode |= ssl_sock_load_dh_params(ctx, ckch, path, err);
3620 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003621 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3622 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003623 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003624 }
3625#endif
3626
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003627#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemanda17f4112019-10-10 15:16:44 +02003628 if (sctl_ex_index >= 0 && ckch->sctl) {
3629 if (ssl_sock_load_sctl(ctx, ckch->sctl) < 0) {
3630 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003631 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003632 errcode |= ERR_ALERT | ERR_FATAL;
3633 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003634 }
3635 }
3636#endif
3637
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003638#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
William Lallemand246c0242019-10-11 08:59:13 +02003639 /* Load OCSP Info into context */
3640 if (ckch->ocsp_response) {
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01003641 if (ssl_sock_load_ocsp(ctx, ckch, find_chain) < 0) {
Tim Duesterhus93128532019-11-23 23:45:10 +01003642 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",
3643 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003644 errcode |= ERR_ALERT | ERR_FATAL;
3645 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003646 }
3647 }
William Lallemand246c0242019-10-11 08:59:13 +02003648#endif
3649
Emeric Bruna96b5822019-10-17 13:25:14 +02003650 end:
3651 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003652}
3653
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003654
3655/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
3656 * Returns a bitfield containing the flags:
3657 * ERR_FATAL in any fatal error case
3658 * ERR_ALERT if the reason of the error is available in err
3659 * ERR_WARN if a warning is available into err
3660 * The value 0 means there is no error nor warning and
3661 * the operation succeed.
3662 */
3663static int ssl_sock_put_srv_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch,
3664 SSL_CTX *ctx, char **err)
3665{
3666 int errcode = 0;
3667 STACK_OF(X509) *find_chain = NULL;
3668
3669 /* Load the private key */
3670 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3671 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3672 err && *err ? *err : "", path);
3673 errcode |= ERR_ALERT | ERR_FATAL;
3674 }
3675
3676 /* Load certificate chain */
3677 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3678 if (errcode & ERR_CODE)
3679 goto end;
3680
3681 if (SSL_CTX_check_private_key(ctx) <= 0) {
3682 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3683 err && *err ? *err : "", path);
3684 errcode |= ERR_ALERT | ERR_FATAL;
3685 }
3686
3687end:
3688 return errcode;
3689}
3690
3691
William Lallemand614ca0d2019-10-07 13:52:11 +02003692/*
3693 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003694 *
3695 * Returns a bitfield containing the flags:
3696 * ERR_FATAL in any fatal error case
3697 * ERR_ALERT if the reason of the error is available in err
3698 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003699 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003700int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003701 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003702{
William Lallemandc9402072019-05-15 15:33:54 +02003703 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003704 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003705 int order = 0;
3706 X509_NAME *xname;
3707 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003708 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003709 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003710#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3711 STACK_OF(GENERAL_NAME) *names;
3712#endif
William Lallemand36b84632019-07-18 19:28:17 +02003713 struct cert_key_and_chain *ckch;
William Lallemand614ca0d2019-10-07 13:52:11 +02003714 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003715 int errcode = 0;
3716
3717 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003718
William Lallemande3af8fb2019-10-08 11:36:53 +02003719 if (!ckchs || !ckchs->ckch)
Emeric Brun054563d2019-10-17 13:16:58 +02003720 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003721
William Lallemande3af8fb2019-10-08 11:36:53 +02003722 ckch = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003723
William Lallemandc9402072019-05-15 15:33:54 +02003724 ctx = SSL_CTX_new(SSLv23_server_method());
3725 if (!ctx) {
3726 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3727 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003728 errcode |= ERR_ALERT | ERR_FATAL;
3729 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003730 }
3731
Emeric Bruna96b5822019-10-17 13:25:14 +02003732 errcode |= ssl_sock_put_ckch_into_ctx(path, ckch, ctx, err);
3733 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003734 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003735
3736 ckch_inst = ckch_inst_new();
3737 if (!ckch_inst) {
3738 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3739 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003740 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003741 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003742 }
3743
William Lallemand36b84632019-07-18 19:28:17 +02003744 pkey = X509_get_pubkey(ckch->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003745 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003746 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003747 switch(EVP_PKEY_base_id(pkey)) {
3748 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003749 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003750 break;
3751 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003752 kinfo.sig = TLSEXT_signature_ecdsa;
3753 break;
3754 case EVP_PKEY_DSA:
3755 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003756 break;
3757 }
3758 EVP_PKEY_free(pkey);
3759 }
3760
Emeric Brun50bcecc2013-04-22 13:05:23 +02003761 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003762 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003763 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 +02003764 if (order < 0) {
3765 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003766 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003767 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003768 }
3769 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003770 }
3771 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003772#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand36b84632019-07-18 19:28:17 +02003773 names = X509_get_ext_d2i(ckch->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003774 if (names) {
3775 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3776 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3777 if (name->type == GEN_DNS) {
3778 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003779 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003780 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003781 if (order < 0) {
3782 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003783 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003784 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003785 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003786 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003787 }
3788 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003789 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003790 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003791#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand36b84632019-07-18 19:28:17 +02003792 xname = X509_get_subject_name(ckch->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003793 i = -1;
3794 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3795 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003796 ASN1_STRING *value;
3797
3798 value = X509_NAME_ENTRY_get_data(entry);
3799 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003800 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003801 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003802 if (order < 0) {
3803 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003804 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003805 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003806 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003807 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003808 }
3809 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003810 /* we must not free the SSL_CTX anymore below, since it's already in
3811 * the tree, so it will be discovered and cleaned in time.
3812 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003813
Emeric Brunfc0421f2012-09-07 17:30:07 +02003814#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003815 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003816 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3817 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003818 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003819 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003820 }
3821#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003822 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003823 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003824 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003825 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003826 SSL_CTX_up_ref(ctx);
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02003827 bind_conf->default_inst = ckch_inst;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003828 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003829
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003830 /* Always keep a reference to the newly constructed SSL_CTX in the
3831 * instance. This way if the instance has no SNIs, the SSL_CTX will
3832 * still be linked. */
3833 SSL_CTX_up_ref(ctx);
3834 ckch_inst->ctx = ctx;
3835
William Lallemand9117de92019-10-04 00:29:42 +02003836 /* everything succeed, the ckch instance can be used */
3837 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003838 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003839 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003840
William Lallemand02e19a52020-04-08 16:11:26 +02003841 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3842
Emeric Brun054563d2019-10-17 13:16:58 +02003843 *ckchi = ckch_inst;
3844 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003845
3846error:
3847 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003848 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003849 if (ckch_inst->is_default)
3850 SSL_CTX_free(ctx);
3851
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003852 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003853 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003854 }
William Lallemandd9199372019-10-04 15:37:05 +02003855 SSL_CTX_free(ctx);
3856
Emeric Brun054563d2019-10-17 13:16:58 +02003857 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003858}
3859
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003860
3861/*
3862 * This function allocate a ckch_inst that will be used on the backend side
3863 * (server line)
3864 *
3865 * Returns a bitfield containing the flags:
3866 * ERR_FATAL in any fatal error case
3867 * ERR_ALERT if the reason of the error is available in err
3868 * ERR_WARN if a warning is available into err
3869 */
3870int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01003871 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003872{
3873 SSL_CTX *ctx;
3874 struct cert_key_and_chain *ckch;
3875 struct ckch_inst *ckch_inst = NULL;
3876 int errcode = 0;
3877
3878 *ckchi = NULL;
3879
3880 if (!ckchs || !ckchs->ckch)
3881 return ERR_FATAL;
3882
3883 ckch = ckchs->ckch;
3884
3885 ctx = SSL_CTX_new(SSLv23_client_method());
3886 if (!ctx) {
3887 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3888 err && *err ? *err : "", path);
3889 errcode |= ERR_ALERT | ERR_FATAL;
3890 goto error;
3891 }
3892
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003893 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, ckch, ctx, err);
3894 if (errcode & ERR_CODE)
3895 goto error;
3896
3897 ckch_inst = ckch_inst_new();
3898 if (!ckch_inst) {
3899 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3900 err && *err ? *err : "", path);
3901 errcode |= ERR_ALERT | ERR_FATAL;
3902 goto error;
3903 }
3904
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003905 /* everything succeed, the ckch instance can be used */
3906 ckch_inst->bind_conf = NULL;
3907 ckch_inst->ssl_conf = NULL;
3908 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01003909 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003910 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003911
3912 *ckchi = ckch_inst;
3913 return errcode;
3914
3915error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003916 SSL_CTX_free(ctx);
3917
3918 return errcode;
3919}
3920
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003921/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003922static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3923 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003924 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003925{
Emeric Brun054563d2019-10-17 13:16:58 +02003926 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003927
3928 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003929 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 +02003930
Emeric Brun054563d2019-10-17 13:16:58 +02003931 if (errcode & ERR_CODE)
3932 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003933
William Lallemand24bde432020-03-09 16:48:43 +01003934 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003935
3936 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003937 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003938 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003939}
3940
William Lallemanddb26e2b2021-01-26 12:01:46 +01003941/* This function generates a <struct ckch_inst *> for a <struct server *>, and
3942 * fill the SSL_CTX of the server.
3943 *
3944 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003945static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01003946 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003947{
3948 int errcode = 0;
3949
3950 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01003951 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003952
3953 if (errcode & ERR_CODE)
3954 return errcode;
3955
William Lallemanddb26e2b2021-01-26 12:01:46 +01003956 (*ckch_inst)->server = server;
3957 /* Keep the reference to the SSL_CTX in the server. */
3958 SSL_CTX_up_ref((*ckch_inst)->ctx);
3959 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003960 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003961 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003962 return errcode;
3963}
3964
William Lallemand6be66ec2020-03-06 22:26:32 +01003965
William Lallemand4c68bba2020-03-30 18:45:10 +02003966
3967
3968/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3969 * done once. Zero is returned if the operation fails. No error is returned
3970 * if the random is said as not implemented, because we expect that openssl
3971 * will use another method once needed.
3972 */
Amaury Denoyellec593bcd2021-05-19 15:35:29 +02003973int ssl_initialize_random(void)
William Lallemand4c68bba2020-03-30 18:45:10 +02003974{
3975 unsigned char random;
3976 static int random_initialized = 0;
3977
3978 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3979 random_initialized = 1;
3980
3981 return random_initialized;
3982}
3983
William Lallemand2954c472020-03-06 21:54:13 +01003984/* Load a crt-list file, this is done in 2 parts:
3985 * - store the content of the file in a crtlist structure with crtlist_entry structures
3986 * - generate the instances by iterating on entries in the crtlist struct
3987 *
3988 * Nothing is locked there, this function is used in the configuration parser.
3989 *
3990 * Returns a set of ERR_* flags possibly with an error in <err>.
3991 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003992int 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 +01003993{
3994 struct crtlist *crtlist = NULL;
3995 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003996 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003997 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003998 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003999 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01004000
William Lallemand79d31ec2020-03-25 15:10:49 +01004001 bind_conf_node = malloc(sizeof(*bind_conf_node));
4002 if (!bind_conf_node) {
4003 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
4004 cfgerr |= ERR_FATAL | ERR_ALERT;
4005 goto error;
4006 }
4007 bind_conf_node->next = NULL;
4008 bind_conf_node->bind_conf = bind_conf;
4009
William Lallemand41ca9302020-04-08 13:15:18 +02004010 /* strip trailing slashes, including first one */
4011 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
4012 *end = 0;
4013
William Lallemand2954c472020-03-06 21:54:13 +01004014 /* look for an existing crtlist or create one */
4015 eb = ebst_lookup(&crtlists_tree, file);
4016 if (eb) {
4017 crtlist = ebmb_entry(eb, struct crtlist, node);
4018 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01004019 /* load a crt-list OR a directory */
4020 if (dir)
4021 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
4022 else
4023 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
4024
William Lallemand2954c472020-03-06 21:54:13 +01004025 if (!(cfgerr & ERR_CODE))
4026 ebst_insert(&crtlists_tree, &crtlist->node);
4027 }
4028
4029 if (cfgerr & ERR_CODE) {
4030 cfgerr |= ERR_FATAL | ERR_ALERT;
4031 goto error;
4032 }
4033
4034 /* generates ckch instance from the crtlist_entry */
4035 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
4036 struct ckch_store *store;
4037 struct ckch_inst *ckch_inst = NULL;
4038
4039 store = entry->node.key;
4040 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
4041 if (cfgerr & ERR_CODE) {
4042 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
4043 goto error;
4044 }
Willy Tarreau2b718102021-04-21 07:32:39 +02004045 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02004046 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01004047 }
William Lallemand2954c472020-03-06 21:54:13 +01004048
William Lallemand79d31ec2020-03-25 15:10:49 +01004049 /* add the bind_conf to the list */
4050 bind_conf_node->next = crtlist->bind_conf;
4051 crtlist->bind_conf = bind_conf_node;
4052
William Lallemand2954c472020-03-06 21:54:13 +01004053 return cfgerr;
4054error:
4055 {
William Lallemand49398312020-03-30 17:01:33 +02004056 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01004057 struct ckch_inst *inst, *s_inst;
4058
William Lallemand49398312020-03-30 17:01:33 +02004059 lastentry = entry; /* which entry we tried to generate last */
4060 if (lastentry) {
4061 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
4062 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
4063 break;
4064
4065 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01004066
William Lallemand49398312020-03-30 17:01:33 +02004067 /* this was not generated for this bind_conf, skip */
4068 if (inst->bind_conf != bind_conf)
4069 continue;
4070
William Lallemandd9d5d1b2020-04-09 16:31:05 +02004071 /* free the sni_ctx and instance */
4072 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02004073 }
William Lallemand2954c472020-03-06 21:54:13 +01004074 }
William Lallemand2954c472020-03-06 21:54:13 +01004075 }
William Lallemand79d31ec2020-03-25 15:10:49 +01004076 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01004077 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01004078 return cfgerr;
4079}
4080
William Lallemand06b22a82020-03-16 14:45:55 +01004081/* Returns a set of ERR_* flags possibly with an error in <err>. */
4082int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
4083{
4084 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01004085 int cfgerr = 0;
4086 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01004087 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01004088 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01004089
4090 if ((ckchs = ckchs_lookup(path))) {
4091 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01004092 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
4093 found++;
4094 } else if (stat(path, &buf) == 0) {
4095 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01004096 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02004097 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01004098 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01004099 cfgerr |= ERR_ALERT | ERR_FATAL;
4100 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01004101 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01004102 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01004103 }
4104 } else {
4105 /* stat failed, could be a bundle */
4106 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02004107 char fp[MAXPATHLEN+1] = {0};
4108 int n = 0;
4109
4110 /* Load all possible certs and keys in separate ckch_store */
4111 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
4112 struct stat buf;
4113 int ret;
4114
4115 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
4116 if (ret > sizeof(fp))
4117 continue;
4118
4119 if ((ckchs = ckchs_lookup(fp))) {
4120 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01004121 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02004122 } else {
4123 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01004124 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02004125 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02004126 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01004127 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02004128 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
4129 }
4130 }
4131 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01004132#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
4133 if (found) {
4134 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
4135 err && *err ? *err : "", path);
4136 cfgerr |= ERR_ALERT | ERR_FATAL;
4137 }
4138#endif
William Lallemand06b22a82020-03-16 14:45:55 +01004139 }
4140 }
William Lallemand06ce84a2020-11-20 15:36:13 +01004141 if (!found) {
4142 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
4143 err && *err ? *err : "", path, strerror(errno));
4144 cfgerr |= ERR_ALERT | ERR_FATAL;
4145 }
William Lallemand06b22a82020-03-16 14:45:55 +01004146
4147 return cfgerr;
4148}
4149
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004150
4151/* Create a full ssl context and ckch instance that will be used for a specific
4152 * backend server (server configuration line).
4153 * Returns a set of ERR_* flags possibly with an error in <err>.
4154 */
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004155int 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 +01004156{
4157 struct stat buf;
4158 int cfgerr = 0;
4159 struct ckch_store *ckchs;
4160 int found = 0; /* did we found a file to load ? */
4161
4162 if ((ckchs = ckchs_lookup(path))) {
4163 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01004164 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004165 found++;
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004166 } else {
4167 if (!create_if_none) {
4168 memprintf(err, "%sunable to stat SSL certificate '%s'.\n",
4169 err && *err ? *err : "", path);
4170 cfgerr |= ERR_ALERT | ERR_FATAL;
4171 goto out;
4172 }
4173
4174 if (stat(path, &buf) == 0) {
4175 /* We do not manage directories on backend side. */
4176 if (S_ISDIR(buf.st_mode) == 0) {
4177 ++found;
4178 ckchs = ckchs_load_cert_file(path, err);
4179 if (!ckchs)
4180 cfgerr |= ERR_ALERT | ERR_FATAL;
4181 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
4182 }
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004183 }
4184 }
4185 if (!found) {
4186 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
4187 err && *err ? *err : "", path, strerror(errno));
4188 cfgerr |= ERR_ALERT | ERR_FATAL;
4189 }
4190
Amaury Denoyelle36aa4512021-05-21 16:22:11 +02004191out:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004192 return cfgerr;
4193}
4194
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004195/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004196static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004197ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004198{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004199 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004200 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004201 SSL_OP_ALL | /* all known workarounds for bugs */
4202 SSL_OP_NO_SSLv2 |
4203 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02004204 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02004205 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004206 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02004207 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02004208 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004209 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02004210 SSL_MODE_ENABLE_PARTIAL_WRITE |
4211 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01004212 SSL_MODE_RELEASE_BUFFERS |
4213 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004214 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004215 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004216 int flags = MC_SSL_O_ALL;
4217 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02004218 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004219
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004220 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004221 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004222
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004223 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004224 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
4225 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4226 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004227 else
4228 flags = conf_ssl_methods->flags;
4229
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004230 min = conf_ssl_methods->min;
4231 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02004232
4233 /* default minimum is TLSV12, */
4234 if (!min) {
4235 if (!max || (max >= default_min_ver)) {
4236 min = default_min_ver;
4237 } else {
4238 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). "
4239 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
4240 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
4241 min = max;
4242 }
4243 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004244 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02004245 if (min)
4246 flags |= (methodVersions[min].flag - 1);
4247 if (max)
4248 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004249 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004250 min = max = CONF_TLSV_NONE;
4251 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004252 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004253 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004254 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004255 if (min) {
4256 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004257 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
4258 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4259 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
4260 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004261 hole = 0;
4262 }
4263 max = i;
4264 }
4265 else {
4266 min = max = i;
4267 }
4268 }
4269 else {
4270 if (min)
4271 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004272 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004273 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004274 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4275 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004276 cfgerr += 1;
4277 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004278 /* save real min/max in bind_conf */
4279 conf_ssl_methods->min = min;
4280 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004281
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004282#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004283 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004284 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004285 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004286 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004287 else
William Lallemandd0712f32020-06-11 17:34:00 +02004288 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
4289 /* clear every version flags in case SSL_CTX_new()
4290 * returns an SSL_CTX with disabled versions */
4291 SSL_CTX_clear_options(ctx, methodVersions[i].option);
4292
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004293 if (flags & methodVersions[i].flag)
4294 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02004295
4296 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004297#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004298 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004299 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4300 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02004301#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004302
4303 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
4304 options |= SSL_OP_NO_TICKET;
4305 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
4306 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08004307
4308#ifdef SSL_OP_NO_RENEGOTIATION
4309 options |= SSL_OP_NO_RENEGOTIATION;
4310#endif
4311
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004312 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004313
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004314#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004315 if (global_ssl.async)
4316 mode |= SSL_MODE_ASYNC;
4317#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004318 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004319 if (global_ssl.life_time)
4320 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004321
4322#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
4323#ifdef OPENSSL_IS_BORINGSSL
4324 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
4325 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Ilya Shipitsine9ff8992020-01-19 12:20:14 +05004326#elif defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01004327 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01004328 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02004329 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
4330 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004331#else
4332 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004333#endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02004334 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004335#endif
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004336 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004337}
4338
William Lallemand4f45bb92017-10-30 20:08:51 +01004339
4340static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
4341{
4342 if (first == block) {
4343 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4344 if (first->len > 0)
4345 sh_ssl_sess_tree_delete(sh_ssl_sess);
4346 }
4347}
4348
4349/* return first block from sh_ssl_sess */
4350static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
4351{
4352 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
4353
4354}
4355
4356/* store a session into the cache
4357 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
4358 * data: asn1 encoded session
4359 * data_len: asn1 encoded session length
4360 * Returns 1 id session was stored (else 0)
4361 */
4362static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
4363{
4364 struct shared_block *first;
4365 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
4366
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004367 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01004368 if (!first) {
4369 /* Could not retrieve enough free blocks to store that session */
4370 return 0;
4371 }
4372
4373 /* STORE the key in the first elem */
4374 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
4375 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
4376 first->len = sizeof(struct sh_ssl_sess_hdr);
4377
4378 /* it returns the already existing node
4379 or current node if none, never returns null */
4380 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
4381 if (oldsh_ssl_sess != sh_ssl_sess) {
4382 /* NOTE: Row couldn't be in use because we lock read & write function */
4383 /* release the reserved row */
4384 shctx_row_dec_hot(ssl_shctx, first);
4385 /* replace the previous session already in the tree */
4386 sh_ssl_sess = oldsh_ssl_sess;
4387 /* ignore the previous session data, only use the header */
4388 first = sh_ssl_sess_first_block(sh_ssl_sess);
4389 shctx_row_inc_hot(ssl_shctx, first);
4390 first->len = sizeof(struct sh_ssl_sess_hdr);
4391 }
4392
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004393 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01004394 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004395 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01004396 }
4397
4398 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004399
4400 return 1;
4401}
William Lallemanded0b5ad2017-10-30 19:36:36 +01004402
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004403/* SSL callback used when a new session is created while connecting to a server */
4404static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4405{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004406 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004407 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004408
Willy Tarreau07d94e42018-09-20 10:57:52 +02004409 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004410
William Lallemand3ce6eed2021-02-08 10:43:44 +01004411 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4412 * one cache per thread, it only prevents to flush it from the CLI in
4413 * another thread */
4414
Olivier Houcharde6060c52017-11-16 17:42:52 +01004415 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4416 int len;
4417 unsigned char *ptr;
William Lallemande18d4e82021-11-17 02:59:21 +01004418 const char *sni;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004419
Olivier Houcharde6060c52017-11-16 17:42:52 +01004420 len = i2d_SSL_SESSION(sess, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01004421 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004422 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004423 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4424 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4425 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004426 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
4427 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004428 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4429 }
4430 if (s->ssl_ctx.reused_sess[tid].ptr) {
4431 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4432 &ptr);
4433 }
William Lallemande18d4e82021-11-17 02:59:21 +01004434
4435 if (s->ssl_ctx.reused_sess[tid].sni) {
4436 /* if the new sni is empty or isn' t the same as the old one */
4437 if ((!sni) || strcmp(s->ssl_ctx.reused_sess[tid].sni, sni) != 0) {
4438 ha_free(&s->ssl_ctx.reused_sess[tid].sni);
4439 if (sni)
4440 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4441 }
4442 } else if (sni) {
4443 /* if there wasn't an old sni but there is a new one */
4444 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4445 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004446 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004447 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004448 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004449 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004450 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004451 }
4452
4453 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004454}
4455
Olivier Houcharde6060c52017-11-16 17:42:52 +01004456
William Lallemanded0b5ad2017-10-30 19:36:36 +01004457/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004458int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004459{
4460 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4461 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4462 unsigned char *p;
4463 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004464 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004465 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004466
4467 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004468 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004469 * note: SSL_SESSION_set1_id is using
4470 * a memcpy so we need to use a different pointer
4471 * than sid_data or sid_ctx_data to avoid valgrind
4472 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004473 */
4474
4475 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004476
4477 /* copy value in an other buffer */
4478 memcpy(encid, sid_data, sid_length);
4479
4480 /* pad with 0 */
4481 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4482 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4483
4484 /* force length to zero to avoid ASN1 encoding */
4485 SSL_SESSION_set1_id(sess, encid, 0);
4486
4487 /* force length to zero to avoid ASN1 encoding */
4488 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004489
4490 /* check if buffer is large enough for the ASN1 encoded session */
4491 data_len = i2d_SSL_SESSION(sess, NULL);
4492 if (data_len > SHSESS_MAX_DATA_LEN)
4493 goto err;
4494
4495 p = encsess;
4496
4497 /* process ASN1 session encoding before the lock */
4498 i2d_SSL_SESSION(sess, &p);
4499
William Lallemanded0b5ad2017-10-30 19:36:36 +01004500
William Lallemanda3c77cf2017-10-30 23:44:40 +01004501 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004502 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004503 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004504 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004505err:
4506 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004507 SSL_SESSION_set1_id(sess, encid, sid_length);
4508 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004509
4510 return 0; /* do not increment session reference count */
4511}
4512
4513/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004514SSL_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 +01004515{
William Lallemand4f45bb92017-10-30 20:08:51 +01004516 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004517 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4518 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004519 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004520 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004521
Willy Tarreau4c19e992021-06-15 16:39:22 +02004522 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004523
4524 /* allow the session to be freed automatically by openssl */
4525 *do_copy = 0;
4526
4527 /* tree key is zeros padded sessionid */
4528 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4529 memcpy(tmpkey, key, key_len);
4530 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4531 key = tmpkey;
4532 }
4533
4534 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004535 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004536
4537 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004538 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4539 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004540 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004541 shctx_unlock(ssl_shctx);
Willy Tarreau4c19e992021-06-15 16:39:22 +02004542 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004543 return NULL;
4544 }
4545
William Lallemand4f45bb92017-10-30 20:08:51 +01004546 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4547 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004548
William Lallemand4f45bb92017-10-30 20:08:51 +01004549 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 +01004550
William Lallemanda3c77cf2017-10-30 23:44:40 +01004551 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004552
4553 /* decode ASN1 session */
4554 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004555 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004556 /* Reset session id and session id contenxt */
4557 if (sess) {
4558 SSL_SESSION_set1_id(sess, key, key_len);
4559 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4560 }
4561
4562 return sess;
4563}
4564
William Lallemand4f45bb92017-10-30 20:08:51 +01004565
William Lallemanded0b5ad2017-10-30 19:36:36 +01004566/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004567void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004568{
William Lallemand4f45bb92017-10-30 20:08:51 +01004569 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004570 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4571 unsigned int sid_length;
4572 const unsigned char *sid_data;
4573 (void)ctx;
4574
4575 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4576 /* tree key is zeros padded sessionid */
4577 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4578 memcpy(tmpkey, sid_data, sid_length);
4579 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4580 sid_data = tmpkey;
4581 }
4582
William Lallemanda3c77cf2017-10-30 23:44:40 +01004583 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004584
4585 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004586 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4587 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004588 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004589 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004590 }
4591
4592 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004593 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004594}
4595
4596/* Set session cache mode to server and disable openssl internal cache.
4597 * Set shared cache callbacks on an ssl context.
4598 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004599void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004600{
4601 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4602
4603 if (!ssl_shctx) {
4604 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4605 return;
4606 }
4607
4608 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4609 SSL_SESS_CACHE_NO_INTERNAL |
4610 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4611
4612 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004613 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4614 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4615 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004616}
William Lallemand7d42ef52020-07-06 11:41:30 +02004617
4618/*
4619 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4620 *
4621 * The format is:
4622 * * <Label> <space> <ClientRandom> <space> <Secret>
4623 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4624 */
4625
William Lallemand722180a2021-06-09 16:46:12 +02004626#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004627void SSL_CTX_keylog(const SSL *ssl, const char *line)
4628{
4629 struct ssl_keylog *keylog;
4630 char *lastarg = NULL;
4631 char *dst = NULL;
4632
4633 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4634 if (!keylog)
4635 return;
4636
4637 lastarg = strrchr(line, ' ');
4638 if (lastarg == NULL || ++lastarg == NULL)
4639 return;
4640
4641 dst = pool_alloc(pool_head_ssl_keylog_str);
4642 if (!dst)
4643 return;
4644
4645 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4646 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4647
4648 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4649 if (keylog->client_random)
4650 goto error;
4651 keylog->client_random = dst;
4652
4653 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4654 if (keylog->client_early_traffic_secret)
4655 goto error;
4656 keylog->client_early_traffic_secret = dst;
4657
4658 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4659 if(keylog->client_handshake_traffic_secret)
4660 goto error;
4661 keylog->client_handshake_traffic_secret = dst;
4662
4663 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4664 if (keylog->server_handshake_traffic_secret)
4665 goto error;
4666 keylog->server_handshake_traffic_secret = dst;
4667
4668 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4669 if (keylog->client_traffic_secret_0)
4670 goto error;
4671 keylog->client_traffic_secret_0 = dst;
4672
4673 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4674 if (keylog->server_traffic_secret_0)
4675 goto error;
4676 keylog->server_traffic_secret_0 = dst;
4677
4678 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4679 if (keylog->early_exporter_secret)
4680 goto error;
4681 keylog->early_exporter_secret = dst;
4682
4683 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4684 if (keylog->exporter_secret)
4685 goto error;
4686 keylog->exporter_secret = dst;
4687 } else {
4688 goto error;
4689 }
4690
4691 return;
4692
4693error:
4694 pool_free(pool_head_ssl_keylog_str, dst);
4695
4696 return;
4697}
4698#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004699
William Lallemand8b453912019-11-21 15:48:10 +01004700/*
4701 * This function applies the SSL configuration on a SSL_CTX
4702 * It returns an error code and fills the <err> buffer
4703 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004704static 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 +01004705{
4706 struct proxy *curproxy = bind_conf->frontend;
4707 int cfgerr = 0;
4708 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004709 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004710 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004711#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004712 const char *conf_ciphersuites;
4713#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004714 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004715
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004716 if (ssl_conf) {
4717 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4718 int i, min, max;
4719 int flags = MC_SSL_O_ALL;
4720
4721 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004722 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4723 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004724 if (min)
4725 flags |= (methodVersions[min].flag - 1);
4726 if (max)
4727 flags |= ~((methodVersions[max].flag << 1) - 1);
4728 min = max = CONF_TLSV_NONE;
4729 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4730 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4731 if (min)
4732 max = i;
4733 else
4734 min = max = i;
4735 }
4736 /* save real min/max */
4737 conf_ssl_methods->min = min;
4738 conf_ssl_methods->max = max;
4739 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004740 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4741 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004742 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004743 }
4744 }
4745
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004746 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004747 case SSL_SOCK_VERIFY_NONE:
4748 verify = SSL_VERIFY_NONE;
4749 break;
4750 case SSL_SOCK_VERIFY_OPTIONAL:
4751 verify = SSL_VERIFY_PEER;
4752 break;
4753 case SSL_SOCK_VERIFY_REQUIRED:
4754 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4755 break;
4756 }
4757 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4758 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004759 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 +01004760 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 +01004761 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 +01004762 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004763 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004764 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004765 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004766 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004767 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004768 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004769 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4770 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4771 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4772 cfgerr |= ERR_ALERT | ERR_FATAL;
4773 }
4774 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004775 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004776 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 +02004777 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004778 }
Emeric Brun850efd52014-01-29 12:24:34 +01004779 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004780 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4781 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004782 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004783 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004784#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004785 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004786 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4787
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004788 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004789 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4790 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004791 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004792 }
Emeric Brun561e5742012-10-02 15:20:55 +02004793 else {
4794 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4795 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004796 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004797#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004798 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004799 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004800#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004801 if(bind_conf->keys_ref) {
Remi Tricot-Le Breton8ea1f5f2022-02-08 17:45:58 +01004802 if (!SSL_CTX_set_tlsext_ticket_key_evp_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004803 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4804 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004805 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004806 }
4807 }
4808#endif
4809
William Lallemand4f45bb92017-10-30 20:08:51 +01004810 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004811 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4812 if (conf_ciphers &&
4813 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004814 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4815 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004816 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004817 }
4818
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004819#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004820 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4821 if (conf_ciphersuites &&
4822 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004823 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4824 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004825 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004826 }
4827#endif
4828
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004829#ifndef OPENSSL_NO_DH
Remi Tricot-Le Breton1d6338e2022-04-12 11:31:55 +02004830 if (!local_dh_1024)
4831 local_dh_1024 = ssl_get_dh_1024();
4832 if (!local_dh_2048)
4833 local_dh_2048 = ssl_get_dh_2048();
4834 if (!local_dh_4096)
4835 local_dh_4096 = ssl_get_dh_4096();
Remi Gacogne8de54152014-07-15 11:36:40 +02004836#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004837
Emeric Brunfc0421f2012-09-07 17:30:07 +02004838 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004839#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004840 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004841#endif
William Lallemand722180a2021-06-09 16:46:12 +02004842#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004843 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
4844#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004845
Bernard Spil13c53f82018-02-15 13:34:58 +01004846#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004847 ssl_conf_cur = NULL;
4848 if (ssl_conf && ssl_conf->npn_str)
4849 ssl_conf_cur = ssl_conf;
4850 else if (bind_conf->ssl_conf.npn_str)
4851 ssl_conf_cur = &bind_conf->ssl_conf;
4852 if (ssl_conf_cur)
4853 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004854#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004855#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004856 ssl_conf_cur = NULL;
4857 if (ssl_conf && ssl_conf->alpn_str)
4858 ssl_conf_cur = ssl_conf;
4859 else if (bind_conf->ssl_conf.alpn_str)
4860 ssl_conf_cur = &bind_conf->ssl_conf;
4861 if (ssl_conf_cur)
4862 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004863#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004864#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004865 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4866 if (conf_curves) {
4867 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004868 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4869 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004870 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004871 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004872 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004873 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004874#endif /* defined(SSL_CTX_set1_curves_list) */
4875
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004876 if (!conf_curves) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004877#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004878#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004879 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004880 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4881 NULL);
4882
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004883 if (ecdhe && SSL_CTX_set1_curves_list(ctx, ecdhe) == 0) {
4884 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4885 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
4886 cfgerr |= ERR_ALERT | ERR_FATAL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02004887 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004888#endif /* defined(SSL_CTX_set1_curves_list) */
Olivier Houchardc2aae742017-09-22 18:26:28 +02004889#else
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004890#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
4891 int i;
4892 EC_KEY *ecdh;
4893
Olivier Houchardc2aae742017-09-22 18:26:28 +02004894 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4895 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4896 ECDHE_DEFAULT_CURVE);
Emeric Brun2b58d042012-09-20 17:10:03 +02004897
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004898 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004899 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004900 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 +01004901 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004902 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004903 }
4904 else {
4905 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4906 EC_KEY_free(ecdh);
4907 }
Remi Tricot-Le Bretonff4c3c42022-02-08 17:45:54 +01004908#endif /* defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH) */
4909#endif /* HA_OPENSSL_VERSION_NUMBER >= 0x10101000L */
Emeric Brun2b58d042012-09-20 17:10:03 +02004910 }
Emeric Brun2b58d042012-09-20 17:10:03 +02004911
Emeric Brunfc0421f2012-09-07 17:30:07 +02004912 return cfgerr;
4913}
4914
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01004915
4916/*
4917 * Prepare the SSL_CTX based on the bind line configuration.
4918 * Since the CA file loading is made depending on the verify option of the bind
4919 * line, the link between the SSL_CTX and the CA file tree entry is made here.
4920 * If we want to create a link between the CA file entry and the corresponding
4921 * ckch instance (for CA file hot update), it needs to be done after
4922 * ssl_sock_prepare_ctx.
4923 * Returns 0 in case of success.
4924 */
4925int ssl_sock_prep_ctx_and_inst(struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
4926 SSL_CTX *ctx, struct ckch_inst *ckch_inst, char **err)
4927{
4928 int errcode = 0;
4929
4930 errcode |= ssl_sock_prepare_ctx(bind_conf, ssl_conf, ctx, err);
4931 if (!errcode && ckch_inst)
4932 ckch_inst_add_cafile_link(ckch_inst, bind_conf, ssl_conf, NULL);
4933
4934 return errcode;
4935}
4936
Evan Broderbe554312013-06-27 00:05:25 -07004937static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4938{
4939 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4940 size_t prefixlen, suffixlen;
4941
4942 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004943 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004944 return 1;
4945
Evan Broderbe554312013-06-27 00:05:25 -07004946 /* The rest of this logic is based on RFC 6125, section 6.4.3
4947 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4948
Emeric Bruna848dae2013-10-08 11:27:28 +02004949 pattern_wildcard = NULL;
4950 pattern_left_label_end = pattern;
4951 while (*pattern_left_label_end != '.') {
4952 switch (*pattern_left_label_end) {
4953 case 0:
4954 /* End of label not found */
4955 return 0;
4956 case '*':
4957 /* If there is more than one wildcards */
4958 if (pattern_wildcard)
4959 return 0;
4960 pattern_wildcard = pattern_left_label_end;
4961 break;
4962 }
4963 pattern_left_label_end++;
4964 }
4965
4966 /* If it's not trivial and there is no wildcard, it can't
4967 * match */
4968 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004969 return 0;
4970
4971 /* Make sure all labels match except the leftmost */
4972 hostname_left_label_end = strchr(hostname, '.');
4973 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004974 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004975 return 0;
4976
4977 /* Make sure the leftmost label of the hostname is long enough
4978 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004979 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004980 return 0;
4981
4982 /* Finally compare the string on either side of the
4983 * wildcard */
4984 prefixlen = pattern_wildcard - pattern;
4985 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004986 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4987 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004988 return 0;
4989
4990 return 1;
4991}
4992
4993static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4994{
4995 SSL *ssl;
4996 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004997 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004998 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004999 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07005000
5001 int depth;
5002 X509 *cert;
5003 STACK_OF(GENERAL_NAME) *alt_names;
5004 int i;
5005 X509_NAME *cert_subject;
5006 char *str;
5007
5008 if (ok == 0)
5009 return ok;
5010
5011 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02005012 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02005013 ssl_ctx = __conn_get_ssl_sock_ctx(conn);
Evan Broderbe554312013-06-27 00:05:25 -07005014
Willy Tarreauad92a9a2017-07-28 11:38:41 +02005015 /* We're checking if the provided hostnames match the desired one. The
5016 * desired hostname comes from the SNI we presented if any, or if not
5017 * provided then it may have been explicitly stated using a "verifyhost"
5018 * directive. If neither is set, we don't care about the name so the
5019 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02005020 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005021 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02005022 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02005023 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02005024 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02005025 if (!servername)
5026 return ok;
5027 }
Evan Broderbe554312013-06-27 00:05:25 -07005028
5029 /* We only need to verify the CN on the actual server cert,
5030 * not the indirect CAs */
5031 depth = X509_STORE_CTX_get_error_depth(ctx);
5032 if (depth != 0)
5033 return ok;
5034
5035 /* At this point, the cert is *not* OK unless we can find a
5036 * hostname match */
5037 ok = 0;
5038
5039 cert = X509_STORE_CTX_get_current_cert(ctx);
5040 /* It seems like this might happen if verify peer isn't set */
5041 if (!cert)
5042 return ok;
5043
5044 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
5045 if (alt_names) {
5046 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
5047 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
5048 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005049#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02005050 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
5051#else
Evan Broderbe554312013-06-27 00:05:25 -07005052 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02005053#endif
Evan Broderbe554312013-06-27 00:05:25 -07005054 ok = ssl_sock_srv_hostcheck(str, servername);
5055 OPENSSL_free(str);
5056 }
5057 }
5058 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02005059 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07005060 }
5061
5062 cert_subject = X509_get_subject_name(cert);
5063 i = -1;
5064 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
5065 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005066 ASN1_STRING *value;
5067 value = X509_NAME_ENTRY_get_data(entry);
5068 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07005069 ok = ssl_sock_srv_hostcheck(str, servername);
5070 OPENSSL_free(str);
5071 }
5072 }
5073
Willy Tarreau71d058c2017-07-26 20:09:56 +02005074 /* report the mismatch and indicate if SNI was used or not */
5075 if (!ok && !conn->err_code)
5076 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07005077 return ok;
5078}
5079
Emeric Brun94324a42012-10-11 14:00:19 +02005080/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01005081int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02005082{
5083 int cfgerr = 0;
William Lallemand2c776f12021-12-28 18:47:17 +01005084 SSL_CTX *ctx;
Willy Tarreaufce03112015-01-15 21:32:40 +01005085 /* Automatic memory computations need to know we use SSL there */
5086 global.ssl_used_backend = 1;
5087
5088 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02005089 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005090 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005091 ha_alert("out of memory.\n");
Emeric Brun821bb9b2017-06-15 16:37:39 +02005092 cfgerr++;
5093 return cfgerr;
5094 }
5095 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01005096 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02005097 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02005098
William Lallemand2c776f12021-12-28 18:47:17 +01005099 if (srv->ssl_ctx.client_crt) {
5100 const int create_if_none = srv->flags & SRV_F_DYNAMIC ? 0 : 1;
5101 char *err = NULL;
5102 int err_code = 0;
5103
5104 /* If there is a crt keyword there, the SSL_CTX will be created here. */
5105 err_code = ssl_sock_load_srv_cert(srv->ssl_ctx.client_crt, srv, create_if_none, &err);
5106 if (err_code != ERR_NONE) {
5107 if ((err_code & ERR_WARN) && !(err_code & ERR_ALERT))
5108 ha_warning("%s", err);
5109 else
5110 ha_alert("%s", err);
5111
5112 if (err_code & (ERR_FATAL|ERR_ABORT))
5113 cfgerr++;
5114 }
5115 ha_free(&err);
5116 }
5117
5118 ctx = srv->ssl_ctx.ctx;
5119
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005120 /* The context will be uninitialized if there wasn't any "cert" option
5121 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005122 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005123 ctx = SSL_CTX_new(SSLv23_client_method());
5124 if (!ctx) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005125 ha_alert("unable to allocate ssl context.\n");
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005126 cfgerr++;
5127 return cfgerr;
5128 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005129
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01005130 srv->ssl_ctx.ctx = ctx;
5131 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005132
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005133 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 +01005134
5135 return cfgerr;
5136}
5137
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005138/* Initialize an SSL context that will be used on the backend side.
5139 * Returns an error count.
5140 */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005141static int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005142{
5143 struct proxy *curproxy = srv->proxy;
5144 int cfgerr = 0;
5145 long options =
5146 SSL_OP_ALL | /* all known workarounds for bugs */
5147 SSL_OP_NO_SSLv2 |
5148 SSL_OP_NO_COMPRESSION;
5149 long mode =
5150 SSL_MODE_ENABLE_PARTIAL_WRITE |
5151 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
5152 SSL_MODE_RELEASE_BUFFERS |
5153 SSL_MODE_SMALL_BUFFERS;
5154 int verify = SSL_VERIFY_NONE;
5155 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
5156 int i, min, max, hole;
5157 int flags = MC_SSL_O_ALL;
5158
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005159 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005160 ha_warning("no-sslv3/no-tlsv1x are ignored for this server. "
5161 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n");
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005162 else
5163 flags = conf_ssl_methods->flags;
5164
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005165 /* Real min and max should be determinate with configuration and openssl's capabilities */
5166 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005167 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005168 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005169 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005170
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005171 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005172 min = max = CONF_TLSV_NONE;
5173 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005174 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005175 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005176 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005177 if (min) {
5178 if (hole) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005179 ha_warning("%s '%s': SSL/TLS versions range not contiguous for server '%s'. "
Christopher Faulet767a84b2017-11-24 16:50:31 +01005180 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
5181 proxy_type_str(curproxy), curproxy->id, srv->id,
5182 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005183 hole = 0;
5184 }
5185 max = i;
5186 }
5187 else {
5188 min = max = i;
5189 }
5190 }
5191 else {
5192 if (min)
5193 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005194 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005195 if (!min) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02005196 ha_alert("%s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01005197 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005198 cfgerr += 1;
5199 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005200
Willy Tarreau9a1ab082019-05-09 13:26:41 +02005201#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005202 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08005203 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005204 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005205 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02005206 else
5207 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
5208 if (flags & methodVersions[i].flag)
5209 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005210#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02005211 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02005212 methodVersions[min].ctx_set_version(ctx, SET_MIN);
5213 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02005214#endif
5215
5216 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
5217 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005218 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005219
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005220#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005221 if (global_ssl.async)
5222 mode |= SSL_MODE_ASYNC;
5223#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005224 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01005225
Emeric Brun850efd52014-01-29 12:24:34 +01005226 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
5227 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01005228 switch (srv->ssl_ctx.verify) {
5229 case SSL_SOCK_VERIFY_NONE:
5230 verify = SSL_VERIFY_NONE;
5231 break;
5232 case SSL_SOCK_VERIFY_REQUIRED:
5233 verify = SSL_VERIFY_PEER;
5234 break;
5235 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005236 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02005237 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01005238 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02005239 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02005240 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005241 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005242 ha_alert("unable to set CA file '%s'.\n",
5243 srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005244 cfgerr++;
5245 }
5246 }
Emeric Brun850efd52014-01-29 12:24:34 +01005247 else {
5248 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005249 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 +01005250 else
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005251 ha_alert("verify is enabled but no CA file specified.\n");
Emeric Brun850efd52014-01-29 12:24:34 +01005252 cfgerr++;
5253 }
Emeric Brunef42d922012-10-11 16:11:36 +02005254#ifdef X509_V_FLAG_CRL_CHECK
5255 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005256 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02005257
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01005258 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005259 ha_alert("unable to configure CRL file '%s'.\n",
5260 srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02005261 cfgerr++;
5262 }
5263 else {
5264 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5265 }
5266 }
5267#endif
5268 }
5269
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005270 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5271 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02005272 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005273 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005274 ha_alert("unable to set SSL cipher list to '%s'.\n",
5275 srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02005276 cfgerr++;
5277 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005278
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05005279#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005280 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005281 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Amaury Denoyellee74cbc32021-05-28 10:34:01 +02005282 ha_alert("unable to set TLS 1.3 cipher suites to '%s'.\n",
5283 srv->ssl_ctx.ciphersuites);
Dirkjan Bussink415150f2018-09-14 11:14:21 +02005284 cfgerr++;
5285 }
5286#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01005287#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
5288 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01005289 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01005290#endif
5291#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5292 if (srv->ssl_ctx.alpn_str)
5293 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
5294#endif
5295
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005296
5297 return cfgerr;
5298}
5299
5300/*
5301 * Prepare the frontend's SSL_CTX based on the server line configuration.
5302 * Since the CA file loading is made depending on the verify option of the
5303 * server line, the link between the SSL_CTX and the CA file tree entry is
5304 * made here.
5305 * If we want to create a link between the CA file entry and the corresponding
5306 * ckch instance (for CA file hot update), it needs to be done after
5307 * ssl_sock_prepare_srv_ssl_ctx.
5308 * Returns an error count.
5309 */
5310int ssl_sock_prep_srv_ctx_and_inst(const struct server *srv, SSL_CTX *ctx,
5311 struct ckch_inst *ckch_inst)
5312{
5313 int cfgerr = 0;
5314
5315 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, ctx);
5316 if (!cfgerr && ckch_inst)
5317 ckch_inst_add_cafile_link(ckch_inst, NULL, NULL, srv);
Emeric Brun94324a42012-10-11 14:00:19 +02005318
5319 return cfgerr;
5320}
5321
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005322
Frédéric Lécailleec216522020-11-23 14:33:30 +01005323/*
5324 * Create an initial CTX used to start the SSL connections.
5325 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
5326 * Returns 0 if succeeded, or something >0 if not.
5327 */
5328#ifdef USE_QUIC
5329static int ssl_initial_ctx(struct bind_conf *bind_conf)
5330{
5331 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
5332 return ssl_quic_initial_ctx(bind_conf);
5333 else
5334 return ssl_sock_initial_ctx(bind_conf);
5335}
5336#else
5337static int ssl_initial_ctx(struct bind_conf *bind_conf)
5338{
5339 return ssl_sock_initial_ctx(bind_conf);
5340}
5341#endif
5342
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005343/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005344 * be NULL, in which case nothing is done. Returns the number of errors
5345 * encountered.
5346 */
Willy Tarreau03209342016-12-22 17:08:28 +01005347int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005348{
5349 struct ebmb_node *node;
5350 struct sni_ctx *sni;
5351 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01005352 int errcode = 0;
5353 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02005354
Willy Tarreaufce03112015-01-15 21:32:40 +01005355 /* Automatic memory computations need to know we use SSL there */
5356 global.ssl_used_frontend = 1;
5357
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005358 /* Create initial_ctx used to start the ssl connection before do switchctx */
5359 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01005360 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005361 /* It should not be necessary to call this function, but it's
5362 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01005363 to initial_ctx in ssl_initial_ctx. */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005364 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, NULL, bind_conf->initial_ctx, NULL, &errmsg);
5365 }
5366 if (bind_conf->default_ctx) {
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005367 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 +01005368 }
Emeric Brun0bed9942014-10-30 19:25:24 +01005369
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005370 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005371 while (node) {
5372 sni = ebmb_entry(node, struct sni_ctx, name);
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005373 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005374 /* only initialize the CTX on its first occurrence and
5375 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005376 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
5377 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005378 node = ebmb_next(node);
5379 }
5380
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005381 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005382 while (node) {
5383 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01005384 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005385 /* only initialize the CTX on its first occurrence and
5386 if it is not the default_ctx */
Remi Tricot-Le Breton4458b972021-02-19 17:41:55 +01005387 errcode |= ssl_sock_prep_ctx_and_inst(bind_conf, sni->conf, sni->ctx, sni->ckch_inst, &errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005388 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005389 node = ebmb_next(node);
5390 }
William Lallemand8b453912019-11-21 15:48:10 +01005391
5392 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005393 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005394 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005395 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005396 err++;
5397 }
5398
5399 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005400 return err;
5401}
5402
Willy Tarreau55d37912016-12-21 23:38:39 +01005403/* Prepares all the contexts for a bind_conf and allocates the shared SSL
5404 * context if needed. Returns < 0 on error, 0 on success. The warnings and
5405 * alerts are directly emitted since the rest of the stack does it below.
5406 */
5407int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
5408{
5409 struct proxy *px = bind_conf->frontend;
5410 int alloc_ctx;
5411 int err;
5412
5413 if (!bind_conf->is_ssl) {
5414 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005415 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
5416 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01005417 }
5418 return 0;
5419 }
5420 if (!bind_conf->default_ctx) {
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005421 if (bind_conf->strict_sni && !bind_conf->generate_certs) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005422 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5423 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005424 }
5425 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005426 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5427 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005428 return -1;
5429 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005430 }
William Lallemandc61c0b32017-12-04 18:46:39 +01005431 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005432 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02005433 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
Willy Tarreau91358592021-06-15 08:08:04 +02005434 sizeof(*sh_ssl_sess_tree), (global.nbthread > 1));
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02005435 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005436 if (alloc_ctx == SHCTX_E_INIT_LOCK)
5437 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");
5438 else
5439 ha_alert("Unable to allocate SSL session cache.\n");
5440 return -1;
5441 }
5442 /* free block callback */
5443 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5444 /* init the root tree within the extra space */
5445 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5446 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01005447 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005448 err = 0;
5449 /* initialize all certificate contexts */
5450 err += ssl_sock_prepare_all_ctx(bind_conf);
5451
5452 /* initialize CA variables if the certificates generation is enabled */
5453 err += ssl_sock_load_ca(bind_conf);
5454
5455 return -err;
5456}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005457
William Lallemand231610a2021-12-30 11:25:43 +01005458/* release ssl context allocated for servers. Most of the field free here
5459 * must also be allocated in srv_ssl_settings_cpy() */
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005460void ssl_sock_free_srv_ctx(struct server *srv)
5461{
Olivier Houchardc7566002018-11-20 23:33:50 +01005462#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
William Lallemand231610a2021-12-30 11:25:43 +01005463 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005464#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005465#ifdef OPENSSL_NPN_NEGOTIATED
William Lallemand231610a2021-12-30 11:25:43 +01005466 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005467#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005468 if (srv->ssl_ctx.reused_sess) {
5469 int i;
5470
William Lallemande18d4e82021-11-17 02:59:21 +01005471 for (i = 0; i < global.nbthread; i++) {
Willy Tarreaue709e822021-02-26 21:06:32 +01005472 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
William Lallemande18d4e82021-11-17 02:59:21 +01005473 ha_free(&srv->ssl_ctx.reused_sess[i].sni);
5474 }
Willy Tarreaue709e822021-02-26 21:06:32 +01005475 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005476 }
5477
Willy Tarreaue709e822021-02-26 21:06:32 +01005478 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005479 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005480 srv->ssl_ctx.ctx = NULL;
5481 }
William Lallemand231610a2021-12-30 11:25:43 +01005482
5483 ha_free(&srv->ssl_ctx.ca_file);
5484 ha_free(&srv->ssl_ctx.crl_file);
5485 ha_free(&srv->ssl_ctx.client_crt);
5486 ha_free(&srv->ssl_ctx.verify_host);
5487#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5488 ha_free(&srv->sni_expr);
William Lallemand43c2ce42022-03-16 17:48:19 +01005489 release_sample_expr(srv->ssl_ctx.sni);
5490 srv->ssl_ctx.sni = NULL;
William Lallemand231610a2021-12-30 11:25:43 +01005491#endif
5492 ha_free(&srv->ssl_ctx.ciphers);
5493#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
5494 ha_free(&srv->ssl_ctx.ciphersuites);
5495#endif
William Lallemande69563f2021-12-30 14:45:19 +01005496 /* If there is a certificate we must unlink the ckch instance */
5497 ckch_inst_free(srv->ssl_ctx.inst);
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005498}
5499
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005500/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005501 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5502 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005503void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005504{
5505 struct ebmb_node *node, *back;
5506 struct sni_ctx *sni;
5507
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005508 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005509 while (node) {
5510 sni = ebmb_entry(node, struct sni_ctx, name);
5511 back = ebmb_next(node);
5512 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005513 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005514 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005515 free(sni);
5516 node = back;
5517 }
5518
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005519 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005520 while (node) {
5521 sni = ebmb_entry(node, struct sni_ctx, name);
5522 back = ebmb_next(node);
5523 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005524 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005525 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005526 free(sni);
5527 node = back;
5528 }
William Lallemandb2408692020-06-24 09:54:29 +02005529
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005530 SSL_CTX_free(bind_conf->initial_ctx);
5531 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005532 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005533 bind_conf->default_ctx = NULL;
Remi Tricot-Le Breton40ddea82021-04-13 16:07:29 +02005534 bind_conf->default_inst = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005535 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005536}
William Lallemandb2408692020-06-24 09:54:29 +02005537
5538
5539void ssl_sock_deinit()
5540{
5541 crtlist_deinit(); /* must be free'd before the ckchs */
5542 ckch_deinit();
5543}
5544REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005545
Willy Tarreau795cdab2016-12-22 17:30:54 +01005546/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5547void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5548{
5549 ssl_sock_free_ca(bind_conf);
5550 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005551 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005552 free(bind_conf->ca_sign_file);
5553 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005554 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005555 free(bind_conf->keys_ref->filename);
5556 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005557 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005558 free(bind_conf->keys_ref);
5559 }
5560 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005561 bind_conf->ca_sign_pass = NULL;
5562 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005563}
5564
Christopher Faulet31af49d2015-06-09 17:29:50 +02005565/* Load CA cert file and private key used to generate certificates */
5566int
Willy Tarreau03209342016-12-22 17:08:28 +01005567ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005568{
Willy Tarreau03209342016-12-22 17:08:28 +01005569 struct proxy *px = bind_conf->frontend;
Shimi Gersner5846c492020-08-23 13:58:12 +03005570 struct cert_key_and_chain *ckch = NULL;
5571 int ret = 0;
5572 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005573
Christopher Fauletf8bb0ce2017-09-15 09:52:49 +02005574 if (!bind_conf->generate_certs)
Shimi Gersner5846c492020-08-23 13:58:12 +03005575 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005576
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005577#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005578 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005579 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005580 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005581 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005582 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005583#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005584
Christopher Faulet31af49d2015-06-09 17:29:50 +02005585 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005586 ha_alert("Proxy '%s': cannot enable certificate generation, "
5587 "no CA certificate File configured at [%s:%d].\n",
5588 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005589 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005590 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005591
Shimi Gersner5846c492020-08-23 13:58:12 +03005592 /* Allocate cert structure */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02005593 ckch = calloc(1, sizeof(*ckch));
Shimi Gersner5846c492020-08-23 13:58:12 +03005594 if (!ckch) {
5595 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5596 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5597 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005598 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005599
5600 /* Try to parse file */
5601 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, ckch, &err)) {
5602 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5603 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005604 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005605 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005606 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005607
5608 /* Fail if missing cert or pkey */
5609 if ((!ckch->cert) || (!ckch->key)) {
5610 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5611 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5612 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005613 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005614
Shimi Gersner5846c492020-08-23 13:58:12 +03005615 /* Final assignment to bind */
5616 bind_conf->ca_sign_ckch = ckch;
5617 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005618
Shimi Gersner5846c492020-08-23 13:58:12 +03005619 failed:
5620 if (ckch) {
5621 ssl_sock_free_cert_key_and_chain_contents(ckch);
5622 free(ckch);
5623 }
5624
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005625 bind_conf->generate_certs = 0;
Shimi Gersner5846c492020-08-23 13:58:12 +03005626 ret++;
5627 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005628}
5629
5630/* Release CA cert and private key used to generate certificated */
5631void
5632ssl_sock_free_ca(struct bind_conf *bind_conf)
5633{
Shimi Gersner5846c492020-08-23 13:58:12 +03005634 if (bind_conf->ca_sign_ckch) {
5635 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005636 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005637 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005638}
5639
Emeric Brun46591952012-05-18 15:47:34 +02005640/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005641 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5642 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5643 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5644 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005645 * 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 +01005646 * as parameters to this function.
5647 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5648 * CO_ER_SSL_NO_MEM.
5649 */
5650int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5651 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5652{
5653 int retry = 1;
5654
5655 retry:
5656 /* Alloc a new SSL session. */
5657 *ssl = SSL_new(ssl_ctx);
5658 if (!*ssl) {
5659 if (!retry--)
5660 goto err;
5661
5662 pool_gc(NULL);
5663 goto retry;
5664 }
5665
5666 *bio = BIO_new(bio_meth);
5667 if (!*bio) {
5668 SSL_free(*ssl);
5669 *ssl = NULL;
5670 if (!retry--)
5671 goto err;
5672
5673 pool_gc(NULL);
5674 goto retry;
5675 }
5676
5677 BIO_set_data(*bio, ctx);
5678 SSL_set_bio(*ssl, *bio, *bio);
5679
5680 /* set connection pointer. */
5681 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5682 SSL_free(*ssl);
5683 *ssl = NULL;
5684 if (!retry--)
5685 goto err;
5686
5687 pool_gc(NULL);
5688 goto retry;
5689 }
5690
5691 return 0;
5692
5693 err:
5694 conn->err_code = CO_ER_SSL_NO_MEM;
5695 return -1;
5696}
5697
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005698/* This function is called when all the XPRT have been initialized. We can
5699 * now attempt to start the SSL handshake.
5700 */
5701static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5702{
5703 struct ssl_sock_ctx *ctx = xprt_ctx;
5704
5705 if (ctx->xprt->start) {
5706 int ret;
5707
5708 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5709 if (ret < 0)
5710 return ret;
5711 }
5712 tasklet_wakeup(ctx->wait_event.tasklet);
5713
5714 return 0;
5715}
5716
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005717/*
Emeric Brun46591952012-05-18 15:47:34 +02005718 * This function is called if SSL * context is not yet allocated. The function
5719 * is designed to be called before any other data-layer operation and sets the
5720 * handshake flag on the connection. It is safe to call it multiple times.
5721 * It returns 0 on success and -1 in error case.
5722 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005723static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005724{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005725 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005726 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005727 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005728 return 0;
5729
Olivier Houchard66ab4982019-02-26 18:37:15 +01005730 ctx = pool_alloc(ssl_sock_ctx_pool);
5731 if (!ctx) {
5732 conn->err_code = CO_ER_SSL_NO_MEM;
5733 return -1;
5734 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005735 ctx->wait_event.tasklet = tasklet_new();
5736 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005737 conn->err_code = CO_ER_SSL_NO_MEM;
5738 pool_free(ssl_sock_ctx_pool, ctx);
5739 return -1;
5740 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005741 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5742 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005743 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005744 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005745 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005746 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005747 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005748 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005749 ctx->xprt_st = 0;
5750 ctx->xprt_ctx = NULL;
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02005751 ctx->error_code = 0;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005752
5753 /* Only work with sockets for now, this should be adapted when we'll
5754 * add QUIC support.
5755 */
5756 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005757 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005758 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5759 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005760 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005761
Willy Tarreau82531f62021-10-06 12:15:18 +02005762 if (global.maxsslconn && global.sslconns >= global.maxsslconn) {
Willy Tarreau20879a02012-12-03 16:32:10 +01005763 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005764 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005765 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005766
Emeric Brun46591952012-05-18 15:47:34 +02005767 /* If it is in client mode initiate SSL session
5768 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005769 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005770 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5771 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005772 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005773
Olivier Houchard66ab4982019-02-26 18:37:15 +01005774 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005775 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005776 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5777 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5778 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 +01005779 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005780 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005781 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005782 } else if (sess) {
5783 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005784 }
5785 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005786 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005787
Emeric Brun46591952012-05-18 15:47:34 +02005788 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005789 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005790
Willy Tarreau82531f62021-10-06 12:15:18 +02005791 _HA_ATOMIC_INC(&global.sslconns);
5792 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005793 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005794 return 0;
5795 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005796 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005797 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005798
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005799 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5800 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005801 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005802
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005803#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005804 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005805 b_alloc(&ctx->early_buf);
5806 SSL_set_max_early_data(ctx->ssl,
5807 /* Only allow early data if we managed to allocate
5808 * a buffer.
5809 */
5810 (!b_is_null(&ctx->early_buf)) ?
5811 global.tune.bufsize - global.tune.maxrewrite : 0);
5812 }
5813#endif
5814
Olivier Houchard66ab4982019-02-26 18:37:15 +01005815 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005816
Emeric Brun46591952012-05-18 15:47:34 +02005817 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005818 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005819#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005820 if (bc->ssl_conf.early_data)
5821 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005822#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005823
Willy Tarreau82531f62021-10-06 12:15:18 +02005824 _HA_ATOMIC_INC(&global.sslconns);
5825 _HA_ATOMIC_INC(&global.totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005826 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005827 return 0;
5828 }
5829 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005830 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005831err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005832 if (ctx && ctx->wait_event.tasklet)
5833 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005834 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005835 return -1;
5836}
5837
5838
5839/* This is the callback which is used when an SSL handshake is pending. It
5840 * updates the FD status if it wants some polling before being called again.
5841 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5842 * otherwise it returns non-zero and removes itself from the connection's
5843 * flags (the bit is provided in <flag> by the caller).
5844 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005845static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005846{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005847 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Emeric Brun46591952012-05-18 15:47:34 +02005848 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005849 struct ssl_counters *counters = NULL;
5850 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005851 struct listener *li;
5852 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005853 socklen_t lskerr;
5854 int skerr;
5855
Emeric Brun46591952012-05-18 15:47:34 +02005856
Willy Tarreau3c728722014-01-23 13:50:42 +01005857 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005858 return 0;
5859
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005860 /* get counters */
5861 switch (obj_type(conn->target)) {
5862 case OBJ_TYPE_LISTENER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005863 li = __objt_listener(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005864 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5865 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5866 &ssl_stats_module);
5867 break;
5868
5869 case OBJ_TYPE_SERVER:
Amaury Denoyelle2bf5d412021-07-26 09:59:06 +02005870 srv = __objt_server(conn->target);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005871 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5872 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5873 &ssl_stats_module);
5874 break;
5875
5876 default:
5877 break;
5878 }
5879
Willy Tarreau939b0bf2022-04-11 11:29:11 +02005880 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005881 goto out_error;
5882
Willy Tarreau06300382021-02-02 15:42:25 +01005883 /* don't start calculating a handshake on a dead connection */
5884 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5885 goto out_error;
5886
5887 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5888 * status from the lower layers, so let's check the FD directly. Ideally
5889 * the xprt layers should provide some status indicating their knowledge
5890 * of shutdowns or error.
5891 */
Willy Tarreau07ecfc52022-04-11 18:07:03 +02005892 BUG_ON(conn->flags & CO_FL_FDLESS);
5893
Willy Tarreau06300382021-02-02 15:42:25 +01005894 skerr = 0;
5895 lskerr = sizeof(skerr);
5896 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5897 skerr != 0)
5898 goto out_error;
5899
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005900#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005901 /*
5902 * Check if we have early data. If we do, we have to read them
5903 * before SSL_do_handshake() is called, And there's no way to
5904 * detect early data, except to try to read them
5905 */
5906 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005907 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005908
Olivier Houchard54907bb2019-12-19 15:02:39 +01005909 while (1) {
5910 ret = SSL_read_early_data(ctx->ssl,
5911 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5912 &read_data);
5913 if (ret == SSL_READ_EARLY_DATA_ERROR)
5914 goto check_error;
5915 if (read_data > 0) {
5916 conn->flags |= CO_FL_EARLY_DATA;
5917 b_add(&ctx->early_buf, read_data);
5918 }
5919 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5920 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5921 if (!b_data(&ctx->early_buf))
5922 b_free(&ctx->early_buf);
5923 break;
5924 }
5925 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005926 }
5927#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005928 /* If we use SSL_do_handshake to process a reneg initiated by
5929 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5930 * Usually SSL_write and SSL_read are used and process implicitly
5931 * the reneg handshake.
5932 * Here we use SSL_peek as a workaround for reneg.
5933 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005934 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005935 char c;
5936
Olivier Houchard66ab4982019-02-26 18:37:15 +01005937 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005938 if (ret <= 0) {
5939 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005940 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005941
Emeric Brun674b7432012-11-08 19:21:55 +01005942 if (ret == SSL_ERROR_WANT_WRITE) {
5943 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005944 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005945 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005946 return 0;
5947 }
5948 else if (ret == SSL_ERROR_WANT_READ) {
5949 /* handshake may have been completed but we have
5950 * no more data to read.
5951 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005952 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005953 ret = 1;
5954 goto reneg_ok;
5955 }
5956 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005957 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005958 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005959 return 0;
5960 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005961#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005962 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005963 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005964 return 0;
5965 }
5966#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005967 else if (ret == SSL_ERROR_SYSCALL) {
5968 /* if errno is null, then connection was successfully established */
5969 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5970 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005971 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005972#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5973 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005974 conn->err_code = CO_ER_SSL_HANDSHAKE;
5975#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005976 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005977#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005978 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005979 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005980 empty_handshake = state == TLS_ST_BEFORE;
5981#else
Lukas Tribus49799162019-07-08 14:29:15 +02005982 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5983 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005984#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005985 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005986 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005987 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005988 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5989 else
5990 conn->err_code = CO_ER_SSL_EMPTY;
5991 }
5992 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005993 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005994 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5995 else
5996 conn->err_code = CO_ER_SSL_ABORT;
5997 }
5998 }
5999 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006000 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006001 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01006002 else
Emeric Brun29f037d2014-04-25 19:05:36 +02006003 conn->err_code = CO_ER_SSL_HANDSHAKE;
6004 }
Lukas Tribus49799162019-07-08 14:29:15 +02006005#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01006006 }
Emeric Brun674b7432012-11-08 19:21:55 +01006007 goto out_error;
6008 }
6009 else {
6010 /* Fail on all other handshake errors */
6011 /* Note: OpenSSL may leave unread bytes in the socket's
6012 * buffer, causing an RST to be emitted upon close() on
6013 * TCP sockets. We first try to drain possibly pending
6014 * data to avoid this as much as possible.
6015 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01006016 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01006017 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006018 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02006019 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01006020 goto out_error;
6021 }
6022 }
6023 /* read some data: consider handshake completed */
6024 goto reneg_ok;
6025 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006026 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006027check_error:
Emeric Brun46591952012-05-18 15:47:34 +02006028 if (ret != 1) {
6029 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006030 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006031
Remi Tricot-Le Breton1fe0fad2021-09-29 18:56:52 +02006032 if (!ctx->error_code)
6033 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton7c6898e2021-07-29 09:45:51 +02006034
Emeric Brun46591952012-05-18 15:47:34 +02006035 if (ret == SSL_ERROR_WANT_WRITE) {
6036 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02006037 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02006038 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02006039 return 0;
6040 }
6041 else if (ret == SSL_ERROR_WANT_READ) {
6042 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02006043 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02006044 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6045 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02006046 return 0;
6047 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006048#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006049 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006050 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006051 return 0;
6052 }
6053#endif
Willy Tarreau89230192012-09-28 20:22:13 +02006054 else if (ret == SSL_ERROR_SYSCALL) {
6055 /* if errno is null, then connection was successfully established */
6056 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
6057 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006058 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02006059#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
6060 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006061 conn->err_code = CO_ER_SSL_HANDSHAKE;
6062#else
6063 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02006064#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02006065 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006066 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006067 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006068#else
Lukas Tribus49799162019-07-08 14:29:15 +02006069 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
6070 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02006071#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006072 if (empty_handshake) {
6073 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006074 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006075 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6076 else
6077 conn->err_code = CO_ER_SSL_EMPTY;
6078 }
6079 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006080 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006081 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6082 else
6083 conn->err_code = CO_ER_SSL_ABORT;
6084 }
Emeric Brun29f037d2014-04-25 19:05:36 +02006085 }
6086 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006087 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02006088 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
6089 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01006090 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02006091 }
Lukas Tribus49799162019-07-08 14:29:15 +02006092#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02006093 }
Willy Tarreau89230192012-09-28 20:22:13 +02006094 goto out_error;
6095 }
Emeric Brun46591952012-05-18 15:47:34 +02006096 else {
6097 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02006098 /* Note: OpenSSL may leave unread bytes in the socket's
6099 * buffer, causing an RST to be emitted upon close() on
6100 * TCP sockets. We first try to drain possibly pending
6101 * data to avoid this as much as possible.
6102 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01006103 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01006104 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006105 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02006106 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006107 goto out_error;
6108 }
6109 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006110#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01006111 else {
6112 /*
6113 * If the server refused the early data, we have to send a
6114 * 425 to the client, as we no longer have the data to sent
6115 * them again.
6116 */
6117 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006118 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006119 conn->err_code = CO_ER_SSL_EARLY_FAILED;
6120 goto out_error;
6121 }
6122 }
6123 }
6124#endif
6125
Emeric Brun46591952012-05-18 15:47:34 +02006126
Emeric Brun674b7432012-11-08 19:21:55 +01006127reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00006128
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006129#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006130 /* ASYNC engine API doesn't support moving read/write
6131 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006132 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00006133 */
6134 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006135 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006136#endif
Emeric Brun46591952012-05-18 15:47:34 +02006137 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006138 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02006139 if (objt_server(conn->target)) {
6140 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
6141 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
6142 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02006143 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02006144 else {
6145 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
6146 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
6147 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
6148 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006149
Willy Tarreau42995282020-11-06 13:19:18 +01006150 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006151 HA_ATOMIC_INC(&counters->sess);
6152 HA_ATOMIC_INC(&counters_px->sess);
Willy Tarreau42995282020-11-06 13:19:18 +01006153 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01006154 }
Willy Tarreau42995282020-11-06 13:19:18 +01006155 else if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006156 HA_ATOMIC_INC(&counters->reused_sess);
6157 HA_ATOMIC_INC(&counters_px->reused_sess);
Emeric Brun46591952012-05-18 15:47:34 +02006158 }
6159
6160 /* The connection is now established at both layers, it's time to leave */
6161 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
6162 return 1;
6163
6164 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006165 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006166 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006167 ERR_clear_error();
6168
Emeric Brun9fa89732012-10-04 17:09:56 +02006169 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01006170 if (objt_server(conn->target)) {
6171 struct server *s = __objt_server(conn->target);
6172 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
6173 * one cache per thread, it only prevents to flush it from the CLI in
6174 * another thread */
6175
6176 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01006177 if (s->ssl_ctx.reused_sess[tid].ptr)
6178 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01006179 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02006180 }
6181
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006182 if (counters) {
Willy Tarreauc5e7cf92021-11-22 17:46:13 +01006183 HA_ATOMIC_INC(&counters->failed_handshake);
6184 HA_ATOMIC_INC(&counters_px->failed_handshake);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01006185 }
6186
Emeric Brun46591952012-05-18 15:47:34 +02006187 /* Fail on all other handshake errors */
6188 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01006189 if (!conn->err_code)
6190 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02006191 return 0;
6192}
6193
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006194/* Called from the upper layer, to subscribe <es> to events <event_type>. The
6195 * event subscriber <es> is not allowed to change from a previous call as long
6196 * as at least one event is still subscribed. The <event_type> must only be a
6197 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
6198 * unless the transport layer was already released.
6199 */
6200static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006201{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006202 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006203
Olivier Houchard0ff28652019-06-24 18:57:39 +02006204 if (!ctx)
6205 return -1;
6206
Willy Tarreau113d52b2020-01-10 09:20:26 +01006207 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006208 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006209
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006210 ctx->subs = es;
6211 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006212
6213 /* we may have to subscribe to lower layers for new events */
6214 event_type &= ~ctx->wait_event.events;
6215 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
6216 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006217 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006218}
6219
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006220/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
6221 * The <es> pointer is not allowed to differ from the one passed to the
6222 * subscribe() call. It always returns zero.
6223 */
6224static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01006225{
Olivier Houchardea8dd942019-05-20 14:02:16 +02006226 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006227
Willy Tarreau113d52b2020-01-10 09:20:26 +01006228 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006229 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006230
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01006231 es->events &= ~event_type;
6232 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01006233 ctx->subs = NULL;
6234
6235 /* If we subscribed, and we're not doing the handshake,
6236 * then we subscribed because the upper layer asked for it,
6237 * as the upper layer is no longer interested, we can
6238 * unsubscribe too.
6239 */
6240 event_type &= ctx->wait_event.events;
6241 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
6242 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006243
6244 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01006245}
6246
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006247/* The connection has been taken over, so destroy the old tasklet and create
6248 * a new one. The original thread ID must be passed into orig_tid
6249 * It should be called with the takeover lock for the old thread held.
6250 * Returns 0 on success, and -1 on failure
6251 */
6252static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
6253{
6254 struct ssl_sock_ctx *ctx = xprt_ctx;
6255 struct tasklet *tl = tasklet_new();
6256
6257 if (!tl)
6258 return -1;
6259
6260 ctx->wait_event.tasklet->context = NULL;
6261 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
6262 ctx->wait_event.tasklet = tl;
6263 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
6264 ctx->wait_event.tasklet->context = ctx;
6265 return 0;
6266}
6267
Willy Tarreau41491682021-03-02 17:29:56 +01006268/* notify the next xprt that the connection is about to become idle and that it
6269 * may be stolen at any time after the function returns and that any tasklet in
6270 * the chain must be careful before dereferencing its context.
6271 */
6272static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
6273{
6274 struct ssl_sock_ctx *ctx = xprt_ctx;
6275
6276 if (!ctx || !ctx->wait_event.tasklet)
6277 return;
6278
6279 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6280 if (ctx->xprt)
6281 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
6282}
6283
6284/* notify the next xprt that the connection is not idle anymore and that it may
6285 * not be stolen before the next xprt_set_idle().
6286 */
6287static void ssl_set_used(struct connection *conn, void *xprt_ctx)
6288{
6289 struct ssl_sock_ctx *ctx = xprt_ctx;
6290
6291 if (!ctx || !ctx->wait_event.tasklet)
6292 return;
6293
6294 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
6295 if (ctx->xprt)
6296 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
6297}
6298
Olivier Houchard2e055482019-05-27 19:50:12 +02006299/* Use the provided XPRT as an underlying XPRT, and provide the old one.
6300 * Returns 0 on success, and non-zero on failure.
6301 */
6302static 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)
6303{
6304 struct ssl_sock_ctx *ctx = xprt_ctx;
6305
6306 if (oldxprt_ops != NULL)
6307 *oldxprt_ops = ctx->xprt;
6308 if (oldxprt_ctx != NULL)
6309 *oldxprt_ctx = ctx->xprt_ctx;
6310 ctx->xprt = toadd_ops;
6311 ctx->xprt_ctx = toadd_ctx;
6312 return 0;
6313}
6314
Olivier Houchard5149b592019-05-23 17:47:36 +02006315/* Remove the specified xprt. If if it our underlying XPRT, remove it and
6316 * return 0, otherwise just call the remove_xprt method from the underlying
6317 * XPRT.
6318 */
6319static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
6320{
6321 struct ssl_sock_ctx *ctx = xprt_ctx;
6322
6323 if (ctx->xprt_ctx == toremove_ctx) {
6324 ctx->xprt_ctx = newctx;
6325 ctx->xprt = newops;
6326 return 0;
6327 }
6328 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
6329}
6330
Willy Tarreau144f84a2021-03-02 16:09:26 +01006331struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02006332{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006333 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006334 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006335 struct connection *conn;
6336 int conn_in_list;
6337 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006338
Willy Tarreau41491682021-03-02 17:29:56 +01006339 if (state & TASK_F_USR1) {
6340 /* the tasklet was idling on an idle connection, it might have
6341 * been stolen, let's be careful!
6342 */
6343 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6344 if (tl->context == NULL) {
6345 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
6346 tasklet_free(tl);
6347 return NULL;
6348 }
6349 conn = ctx->conn;
6350 conn_in_list = conn->flags & CO_FL_LIST_MASK;
6351 if (conn_in_list)
6352 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006353 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01006354 } else {
6355 conn = ctx->conn;
6356 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006357 }
Willy Tarreau41491682021-03-02 17:29:56 +01006358
Olivier Houchardea8dd942019-05-20 14:02:16 +02006359 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01006360 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006361 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006362 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
6363 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01006364 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01006365 }
6366 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006367 /* If we had an error, or the handshake is done and I/O is available,
6368 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01006369 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02006370 * we can't be sure conn_fd_handler() will be called again.
6371 */
6372 if ((ctx->conn->flags & CO_FL_ERROR) ||
6373 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006374 int woke = 0;
6375
6376 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006377 if (ctx->subs) {
6378 tasklet_wakeup(ctx->subs->tasklet);
6379 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006380 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01006381 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006382 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006383
Olivier Houchardea8dd942019-05-20 14:02:16 +02006384 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01006385 * upper layers know. If we have no mux, create it,
6386 * and once we have a mux, call its wake method if we didn't
6387 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02006388 */
6389 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01006390 if (!ctx->conn->mux)
6391 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006392 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006393 ret = ctx->conn->mux->wake(ctx->conn);
6394 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006395 }
6396 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006397#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006398 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006399 else if (b_data(&ctx->early_buf) && ctx->subs &&
6400 ctx->subs->events & SUB_RETRY_RECV) {
6401 tasklet_wakeup(ctx->subs->tasklet);
6402 ctx->subs->events &= ~SUB_RETRY_RECV;
6403 if (!ctx->subs->events)
6404 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01006405 }
6406#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006407leave:
6408 if (!ret && conn_in_list) {
6409 struct server *srv = objt_server(conn->target);
6410
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006411 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006412 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau430bf4a2021-03-04 09:45:32 +01006413 ebmb_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006414 else
Willy Tarreau430bf4a2021-03-04 09:45:32 +01006415 ebmb_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006416 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006417 }
Willy Tarreau74163142021-03-13 11:30:19 +01006418 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006419}
6420
Emeric Brun46591952012-05-18 15:47:34 +02006421/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01006422 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02006423 * buffer wraps, in which case a second call may be performed. The connection's
6424 * flags are updated with whatever special event is detected (error, read0,
6425 * empty). The caller is responsible for taking care of those events and
6426 * avoiding the call if inappropriate. The function does not call the
6427 * connection's polling update function, so the caller is responsible for this.
6428 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006429static 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 +02006430{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006431 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02006432 ssize_t ret;
6433 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02006434
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006435 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006436 goto out_error;
6437
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006438#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006439 if (b_data(&ctx->early_buf)) {
6440 try = b_contig_space(buf);
6441 if (try > b_data(&ctx->early_buf))
6442 try = b_data(&ctx->early_buf);
6443 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
6444 b_add(buf, try);
6445 b_del(&ctx->early_buf, try);
6446 if (b_data(&ctx->early_buf) == 0)
6447 b_free(&ctx->early_buf);
6448 return try;
6449 }
6450#endif
6451
Willy Tarreau911db9b2020-01-23 16:27:54 +01006452 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006453 /* a handshake was requested */
6454 return 0;
6455
Emeric Brun46591952012-05-18 15:47:34 +02006456 /* read the largest possible block. For this, we perform only one call
6457 * to recv() unless the buffer wraps and we exactly fill the first hunk,
6458 * in which case we accept to do it once again. A new attempt is made on
6459 * EINTR too.
6460 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01006461 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006462
Willy Tarreau591d4452018-06-15 17:21:00 +02006463 try = b_contig_space(buf);
6464 if (!try)
6465 break;
6466
Willy Tarreauabf08d92014-01-14 11:31:27 +01006467 if (try > count)
6468 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02006469
Olivier Houchard66ab4982019-02-26 18:37:15 +01006470 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02006471
Emeric Brune1f38db2012-09-03 20:36:47 +02006472 if (conn->flags & CO_FL_ERROR) {
6473 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006474 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006475 }
Emeric Brun46591952012-05-18 15:47:34 +02006476 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006477 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006478 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006479 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006480 }
Emeric Brun46591952012-05-18 15:47:34 +02006481 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006482 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006483 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006484 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006485 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006486 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006487#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006488 /* Async mode can be re-enabled, because we're leaving data state.*/
6489 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006490 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006491#endif
Emeric Brun46591952012-05-18 15:47:34 +02006492 break;
6493 }
6494 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006495 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006496 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6497 SUB_RETRY_RECV,
6498 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006499 /* handshake is running, and it may need to re-enable read */
6500 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006501#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006502 /* Async mode can be re-enabled, because we're leaving data state.*/
6503 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006504 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006505#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006506 break;
6507 }
Emeric Brun46591952012-05-18 15:47:34 +02006508 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006509 } else if (ret == SSL_ERROR_ZERO_RETURN)
6510 goto read0;
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006511 else if (ret == SSL_ERROR_SSL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006512 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6513 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006514 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006515 conn->err_code = CO_ERR_SSL_FATAL;
6516 }
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006517 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6518 * stack before shutting down the connection for
6519 * reading. */
Willy Tarreauacef5e22022-04-25 20:32:15 +02006520 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN || errno == EWOULDBLOCK))
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006521 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006522 /* otherwise it's a real error */
6523 goto out_error;
6524 }
6525 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006526 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006527 return done;
6528
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006529 clear_ssl_error:
6530 /* Clear openssl global errors stack */
6531 ssl_sock_dump_errors(conn);
6532 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006533 read0:
6534 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006535 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006536
Emeric Brun46591952012-05-18 15:47:34 +02006537 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006538 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006539 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006540 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006541 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006542 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006543}
6544
6545
Willy Tarreau787db9a2018-06-14 18:31:46 +02006546/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6547 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6548 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006549 * Only one call to send() is performed, unless the buffer wraps, in which case
6550 * a second call may be performed. The connection's flags are updated with
6551 * whatever special event is detected (error, empty). The caller is responsible
6552 * for taking care of those events and avoiding the call if inappropriate. The
6553 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006554 * is responsible for this. The buffer's output is not adjusted, it's up to the
6555 * caller to take care of this. It's up to the caller to update the buffer's
6556 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006557 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006558static 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 +02006559{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006560 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006561 ssize_t ret;
6562 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006563
6564 done = 0;
6565
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006566 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006567 goto out_error;
6568
Willy Tarreau911db9b2020-01-23 16:27:54 +01006569 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006570 /* a handshake was requested */
6571 return 0;
6572
6573 /* send the largest possible block. For this we perform only one call
6574 * to send() unless the buffer wraps and we exactly fill the first hunk,
6575 * in which case we accept to do it once again.
6576 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006577 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006578#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006579 size_t written_data;
6580#endif
6581
Willy Tarreau787db9a2018-06-14 18:31:46 +02006582 try = b_contig_data(buf, done);
6583 if (try > count)
6584 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006585
Thomas Prückl10243932022-04-27 13:04:54 +02006586 if (global_ssl.hard_max_record && try > global_ssl.hard_max_record)
6587 try = global_ssl.hard_max_record;
6588
Willy Tarreau7bed9452014-02-02 02:00:24 +01006589 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006590 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006591 global_ssl.max_record && try > global_ssl.max_record) {
6592 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006593 }
6594 else {
6595 /* we need to keep the information about the fact that
6596 * we're not limiting the upcoming send(), because if it
6597 * fails, we'll have to retry with at least as many data.
6598 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006599 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006600 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006601
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006602#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006603 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006604 unsigned int max_early;
6605
Olivier Houchard522eea72017-11-03 16:27:47 +01006606 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006607 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006608 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006609 if (SSL_get0_session(ctx->ssl))
6610 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006611 else
6612 max_early = 0;
6613 }
6614
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006615 if (try + ctx->sent_early_data > max_early) {
6616 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006617 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006618 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006619 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006620 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006621 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006622 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006623 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006624 if (ret == 1) {
6625 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006626 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006627 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006628 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006629 /* Initiate the handshake, now */
6630 tasklet_wakeup(ctx->wait_event.tasklet);
6631 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006632
Olivier Houchardc2aae742017-09-22 18:26:28 +02006633 }
6634
6635 } else
6636#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006637 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006638
Emeric Brune1f38db2012-09-03 20:36:47 +02006639 if (conn->flags & CO_FL_ERROR) {
6640 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006641 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006642 }
Emeric Brun46591952012-05-18 15:47:34 +02006643 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006644 /* A send succeeded, so we can consider ourself connected */
6645 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006646 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006647 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006648 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006649 }
6650 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006651 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006652
Emeric Brun46591952012-05-18 15:47:34 +02006653 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006654 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006655 /* handshake is running, and it may need to re-enable write */
6656 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006657 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006658#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006659 /* Async mode can be re-enabled, because we're leaving data state.*/
6660 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006661 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006662#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006663 break;
6664 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006665
Emeric Brun46591952012-05-18 15:47:34 +02006666 break;
6667 }
6668 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006669 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006670 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006671 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6672 SUB_RETRY_RECV,
6673 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006674#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006675 /* Async mode can be re-enabled, because we're leaving data state.*/
6676 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006677 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006678#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006679 break;
6680 }
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006681 else if (ret == SSL_ERROR_SSL || ret == SSL_ERROR_SYSCALL) {
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006682 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
6683
Willy Tarreau3a0a0d62022-04-12 07:31:06 +02006684 if (ctx && !ctx->error_code)
Remi Tricot-Le Breton9543d5a2021-09-29 18:56:53 +02006685 ctx->error_code = ERR_peek_error();
Remi Tricot-Le Breton61944f72021-09-29 18:56:51 +02006686 conn->err_code = CO_ERR_SSL_FATAL;
6687 }
Emeric Brun46591952012-05-18 15:47:34 +02006688 goto out_error;
6689 }
6690 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006691 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006692 return done;
6693
6694 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006695 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006696 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006697 ERR_clear_error();
6698
Emeric Brun46591952012-05-18 15:47:34 +02006699 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006700 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006701}
6702
Willy Tarreau832e2422021-05-13 10:11:03 +02006703void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006704
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006705 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006706
Olivier Houchardea8dd942019-05-20 14:02:16 +02006707
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006708 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006709 if (ctx->wait_event.events != 0)
6710 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6711 ctx->wait_event.events,
6712 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006713 if (ctx->subs) {
6714 ctx->subs->events = 0;
6715 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006716 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006717
Olivier Houchard692c1d02019-05-23 18:41:47 +02006718 if (ctx->xprt->close)
6719 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006720#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006721 if (global_ssl.async) {
6722 OSSL_ASYNC_FD all_fd[32], afd;
6723 size_t num_all_fds = 0;
6724 int i;
6725
Olivier Houchard66ab4982019-02-26 18:37:15 +01006726 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006727 if (num_all_fds > 32) {
6728 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6729 return;
6730 }
6731
Olivier Houchard66ab4982019-02-26 18:37:15 +01006732 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006733
6734 /* If an async job is pending, we must try to
6735 to catch the end using polling before calling
6736 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006737 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006738 for (i=0 ; i < num_all_fds ; i++) {
6739 /* switch on an handler designed to
6740 * handle the SSL_free
6741 */
6742 afd = all_fd[i];
6743 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006744 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006745 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006746 /* To ensure that the fd cache won't be used
6747 * and we'll catch a real RD event.
6748 */
6749 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006750 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006751 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006752 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006753 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006754 return;
6755 }
Emeric Brun3854e012017-05-17 20:42:48 +02006756 /* Else we can remove the fds from the fdtab
6757 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006758 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006759 * because the fd is owned by the engine.
6760 * the engine is responsible to close
6761 */
6762 for (i=0 ; i < num_all_fds ; i++)
Willy Tarreau67672452020-08-26 11:44:17 +02006763 fd_stop_both(all_fd[i]);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006764 }
6765#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006766 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006767 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006768 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006769 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau82531f62021-10-06 12:15:18 +02006770 _HA_ATOMIC_DEC(&global.sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006771 }
Emeric Brun46591952012-05-18 15:47:34 +02006772}
6773
6774/* This function tries to perform a clean shutdown on an SSL connection, and in
6775 * any case, flags the connection as reusable if no handshake was in progress.
6776 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006777static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006778{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006779 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006780
Willy Tarreau911db9b2020-01-23 16:27:54 +01006781 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006782 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006783 if (!clean)
6784 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006785 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006786 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006787 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006788 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006789 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006790 ERR_clear_error();
6791 }
Emeric Brun46591952012-05-18 15:47:34 +02006792}
6793
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006794
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006795/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006796int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6797{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006798 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemandd4f946c2019-12-05 10:26:40 +01006799 X509 *crt;
6800
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006801 if (!ctx)
William Lallemandd4f946c2019-12-05 10:26:40 +01006802 return 0;
William Lallemandd4f946c2019-12-05 10:26:40 +01006803 crt = SSL_get_certificate(ctx->ssl);
6804 if (!crt)
6805 return 0;
6806
6807 return cert_get_pkey_algo(crt, out);
6808}
6809
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006810/* used for ppv2 cert signature (can be used for logging) */
6811const char *ssl_sock_get_cert_sig(struct connection *conn)
6812{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006813 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006814
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006815 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6816 X509 *crt;
6817
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006818 if (!ctx)
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006819 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006820 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006821 if (!crt)
6822 return NULL;
6823 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6824 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6825}
6826
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006827/* used for ppv2 authority */
6828const char *ssl_sock_get_sni(struct connection *conn)
6829{
6830#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006831 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006832
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006833 if (!ctx)
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006834 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006835 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006836#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006837 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006838#endif
6839}
6840
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006841/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006842const char *ssl_sock_get_cipher_name(struct connection *conn)
6843{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006844 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006845
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006846 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006847 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006848 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006849}
6850
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006851/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006852const char *ssl_sock_get_proto_version(struct connection *conn)
6853{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006854 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006855
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006856 if (!ctx)
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006857 return NULL;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006858 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006859}
6860
Olivier Houchardab28a322018-12-21 19:45:40 +01006861void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6862{
6863#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006864 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006865
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006866 if (!ctx)
Olivier Houcharde488ea82019-06-28 14:10:33 +02006867 return;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006868 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006869#endif
6870}
6871
Willy Tarreau119a4082016-12-22 21:58:38 +01006872/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6873 * to disable SNI.
6874 */
Willy Tarreau63076412015-07-10 11:33:32 +02006875void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6876{
6877#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006878 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
William Lallemande18d4e82021-11-17 02:59:21 +01006879 struct server *s;
Willy Tarreau119a4082016-12-22 21:58:38 +01006880 char *prev_name;
6881
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006882 if (!ctx)
Willy Tarreau63076412015-07-10 11:33:32 +02006883 return;
Willy Tarreau77bfa662021-12-23 11:12:13 +01006884
6885 BUG_ON(!(conn->flags & CO_FL_WAIT_L6_CONN));
6886 BUG_ON(!(conn->flags & CO_FL_SSL_WAIT_HS));
6887
William Lallemande18d4e82021-11-17 02:59:21 +01006888 s = __objt_server(conn->target);
Willy Tarreau63076412015-07-10 11:33:32 +02006889
Willy Tarreau119a4082016-12-22 21:58:38 +01006890 /* if the SNI changes, we must destroy the reusable context so that a
William Lallemande18d4e82021-11-17 02:59:21 +01006891 * new connection will present a new SNI. compare with the SNI
6892 * previously stored in the reused_sess */
6893 /* the RWLOCK is used to ensure that we are not trying to flush the
6894 * cache from the CLI */
6895
6896 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
6897 prev_name = s->ssl_ctx.reused_sess[tid].sni;
Willy Tarreau119a4082016-12-22 21:58:38 +01006898 if ((!prev_name && hostname) ||
6899 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006900 SSL_set_session(ctx->ssl, NULL);
William Lallemande18d4e82021-11-17 02:59:21 +01006901 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau119a4082016-12-22 21:58:38 +01006902
Olivier Houchard66ab4982019-02-26 18:37:15 +01006903 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006904#endif
6905}
6906
Emeric Brun0abf8362014-06-24 18:26:41 +02006907/* Extract peer certificate's common name into the chunk dest
6908 * Returns
6909 * the len of the extracted common name
6910 * or 0 if no CN found in DN
6911 * or -1 on error case (i.e. no peer certificate)
6912 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006913int ssl_sock_get_remote_common_name(struct connection *conn,
6914 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006915{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006916 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
David Safb76832014-05-08 23:42:08 -04006917 X509 *crt = NULL;
6918 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006919 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006920 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006921 .area = (char *)&find_cn,
6922 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006923 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006924 int result = -1;
David Safb76832014-05-08 23:42:08 -04006925
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006926 if (!ctx)
Emeric Brun0abf8362014-06-24 18:26:41 +02006927 goto out;
David Safb76832014-05-08 23:42:08 -04006928
6929 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006930 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006931 if (!crt)
6932 goto out;
6933
6934 name = X509_get_subject_name(crt);
6935 if (!name)
6936 goto out;
David Safb76832014-05-08 23:42:08 -04006937
Emeric Brun0abf8362014-06-24 18:26:41 +02006938 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6939out:
David Safb76832014-05-08 23:42:08 -04006940 if (crt)
6941 X509_free(crt);
6942
6943 return result;
6944}
6945
Dave McCowan328fb582014-07-30 10:39:13 -04006946/* returns 1 if client passed a certificate for this session, 0 if not */
6947int ssl_sock_get_cert_used_sess(struct connection *conn)
6948{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006949 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Dave McCowan328fb582014-07-30 10:39:13 -04006950 X509 *crt = NULL;
6951
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006952 if (!ctx)
Dave McCowan328fb582014-07-30 10:39:13 -04006953 return 0;
6954
6955 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006956 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006957 if (!crt)
6958 return 0;
6959
6960 X509_free(crt);
6961 return 1;
6962}
6963
6964/* returns 1 if client passed a certificate for this connection, 0 if not */
6965int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006966{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006967 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006968
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006969 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006970 return 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006971 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006972}
6973
6974/* returns result from SSL verify */
6975unsigned int ssl_sock_get_verify_result(struct connection *conn)
6976{
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006977 struct ssl_sock_ctx *ctx = conn_get_ssl_sock_ctx(conn);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006978
Willy Tarreau939b0bf2022-04-11 11:29:11 +02006979 if (!ctx)
David Safb76832014-05-08 23:42:08 -04006980 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006981 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006982}
6983
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006984/* Returns the application layer protocol name in <str> and <len> when known.
6985 * Zero is returned if the protocol name was not found, otherwise non-zero is
6986 * returned. The string is allocated in the SSL context and doesn't have to be
6987 * freed by the caller. NPN is also checked if available since older versions
6988 * of openssl (1.0.1) which are more common in field only support this one.
6989 */
Amaury Denoyelle71e588c2021-11-12 11:23:29 +01006990int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006991{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006992#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6993 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006994 struct ssl_sock_ctx *ctx = xprt_ctx;
6995 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006996 return 0;
6997
6998 *str = NULL;
6999
7000#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01007001 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007002 if (*str)
7003 return 1;
7004#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01007005#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01007006 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007007 if (*str)
7008 return 1;
7009#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01007010#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007011 return 0;
7012}
7013
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007014/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02007015int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007016{
7017 X509 *ca;
7018 X509_NAME *name = NULL;
7019 ASN1_OCTET_STRING *skid = NULL;
7020 STACK_OF(X509) *chain = NULL;
7021 struct issuer_chain *issuer;
7022 struct eb64_node *node;
7023 char *path;
7024 u64 key;
7025 int ret = 0;
7026
7027 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
7028 if (chain == NULL) {
7029 chain = sk_X509_new_null();
7030 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
7031 name = X509_get_subject_name(ca);
7032 }
7033 if (!sk_X509_push(chain, ca)) {
7034 X509_free(ca);
7035 goto end;
7036 }
7037 }
7038 if (!chain) {
7039 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
7040 goto end;
7041 }
7042 if (!skid) {
7043 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
7044 goto end;
7045 }
7046 if (!name) {
7047 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
7048 goto end;
7049 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01007050 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01007051 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007052 issuer = container_of(node, typeof(*issuer), node);
7053 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
7054 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
7055 goto end;
7056 }
7057 }
7058 issuer = calloc(1, sizeof *issuer);
7059 path = strdup(fp);
7060 if (!issuer || !path) {
7061 free(issuer);
7062 free(path);
7063 goto end;
7064 }
7065 issuer->node.key = key;
7066 issuer->path = path;
7067 issuer->chain = chain;
7068 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01007069 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007070 ret = 1;
7071 end:
7072 if (skid)
7073 ASN1_OCTET_STRING_free(skid);
7074 if (chain)
7075 sk_X509_pop_free(chain, X509_free);
7076 return ret;
7077}
7078
William Lallemandda8584c2020-05-14 10:14:37 +02007079 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007080{
7081 AUTHORITY_KEYID *akid;
7082 struct issuer_chain *issuer = NULL;
7083
7084 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01007085 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007086 struct eb64_node *node;
7087 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01007088 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01007089 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
7090 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
7091 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
7092 issuer = ti;
7093 break;
7094 }
7095 }
7096 AUTHORITY_KEYID_free(akid);
7097 }
7098 return issuer;
7099}
7100
William Lallemanddad31052020-05-14 17:47:32 +02007101void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007102{
7103 struct eb64_node *node, *back;
7104 struct issuer_chain *issuer;
7105
William Lallemande0f3fd52020-02-25 14:53:06 +01007106 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007107 while (node) {
7108 issuer = container_of(node, typeof(*issuer), node);
7109 back = eb64_next(node);
7110 eb64_delete(node);
7111 free(issuer->path);
7112 sk_X509_pop_free(issuer->chain, X509_free);
7113 free(issuer);
7114 node = back;
7115 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007116}
7117
William Lallemandd7bfbe22022-04-11 18:41:24 +02007118#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007119static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01007120 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007121
Emeric Brun3854e012017-05-17 20:42:48 +02007122 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01007123 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007124 err_code = ERR_ABORT;
7125 }
7126 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01007127}
Willy Tarreau9ceda382016-12-21 23:13:03 +01007128#endif
7129
Willy Tarreaude5675a2021-01-20 14:41:29 +01007130/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007131 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01007132 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01007133static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01007134{
7135 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007136 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007137
7138 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007139 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007140
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007141 if (sctx->conn != conn) {
7142 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
7143 ret = 1;
7144 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01007145 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
7146
7147 if (sctx->xprt) {
7148 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
7149 if (sctx->xprt_ctx)
7150 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
7151 }
7152
7153 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007154
7155 /* as soon as a shutdown is reported the lower layer unregisters its
7156 * subscriber, so the situations below are transient and rare enough to
7157 * be reported as suspicious. In any case they shouldn't last.
7158 */
7159 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
7160 ret = 1;
7161 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
7162 ret = 1;
7163
Willy Tarreaude5675a2021-01-20 14:41:29 +01007164 chunk_appendf(&trash, " .subs=%p", sctx->subs);
7165 if (sctx->subs) {
7166 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007167 if (sctx->subs->tasklet->calls >= 1000000)
7168 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007169 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
7170 sctx->subs->tasklet->calls,
7171 sctx->subs->tasklet->context);
7172 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
7173 chunk_appendf(&trash, ")");
7174 }
7175 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
7176 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01007177 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01007178}
7179
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007180#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02007181/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007182 * each reference. The variable <ref> must point to the current node's list
7183 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02007184 */
William Lallemand32af2032016-10-29 18:09:35 +02007185static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007186struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02007187{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007188 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007189 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02007190
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007191 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007192 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01007193 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02007194
Willy Tarreaub6fc5242021-01-05 10:44:30 +01007195 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02007196}
7197
7198static inline
7199struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
7200{
7201 int id;
7202 char *error;
7203
7204 /* If the reference starts by a '#', this is numeric id. */
7205 if (reference[0] == '#') {
7206 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
7207 id = strtol(reference + 1, &error, 10);
7208 if (*error != '\0')
7209 return NULL;
7210
7211 /* Perform the unique id lookup. */
7212 return tlskeys_ref_lookupid(id);
7213 }
7214
7215 /* Perform the string lookup. */
7216 return tlskeys_ref_lookup(reference);
7217}
7218#endif
7219
7220
7221#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7222
Willy Tarreaua9380522022-05-05 08:50:17 +02007223/* dumps all tls keys. Relies on the show_keys_ctx context from the appctx. */
Willy Tarreaubd338642022-05-05 08:59:17 +02007224static int cli_io_handler_tlskeys_files(struct appctx *appctx)
7225{
Willy Tarreaua9380522022-05-05 08:50:17 +02007226 struct show_keys_ctx *ctx = appctx->svcctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02007227 struct conn_stream *cs = appctx_cs(appctx);
William Lallemand32af2032016-10-29 18:09:35 +02007228
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007229 switch (ctx->state) {
7230 case SHOW_KEYS_INIT:
William Lallemand32af2032016-10-29 18:09:35 +02007231 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08007232 * quit the function with returning 0. The function is called
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007233 * later and restart at the state "SHOW_KEYS_INIT".
William Lallemand32af2032016-10-29 18:09:35 +02007234 */
7235 chunk_reset(&trash);
7236
Willy Tarreaubd338642022-05-05 08:59:17 +02007237 if (ctx->dump_entries)
William Lallemand32af2032016-10-29 18:09:35 +02007238 chunk_appendf(&trash, "# id secret\n");
7239 else
7240 chunk_appendf(&trash, "# id (file)\n");
7241
Christopher Faulet908628c2022-03-25 16:43:49 +01007242 if (ci_putchk(cs_ic(cs), &trash) == -1) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02007243 cs_rx_room_blk(cs);
William Lallemand32af2032016-10-29 18:09:35 +02007244 return 0;
7245 }
7246
William Lallemand32af2032016-10-29 18:09:35 +02007247 /* Now, we start the browsing of the references lists.
7248 * Note that the following call to LIST_ELEM return bad pointer. The only
7249 * available field of this pointer is <list>. It is used with the function
7250 * tlskeys_list_get_next() for retruning the first available entry
7251 */
Willy Tarreaua9380522022-05-05 08:50:17 +02007252 if (ctx->next_ref == NULL)
7253 ctx->next_ref = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007254
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007255 ctx->state = SHOW_KEYS_LIST;
William Lallemand32af2032016-10-29 18:09:35 +02007256 /* fall through */
7257
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007258 case SHOW_KEYS_LIST:
Willy Tarreaua9380522022-05-05 08:50:17 +02007259 while (ctx->next_ref) {
7260 struct tls_keys_ref *ref = ctx->next_ref;
William Lallemand32af2032016-10-29 18:09:35 +02007261
7262 chunk_reset(&trash);
Willy Tarreaubd338642022-05-05 08:59:17 +02007263 if (ctx->dump_entries && ctx->next_index == 0)
William Lallemand32af2032016-10-29 18:09:35 +02007264 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007265
Willy Tarreaua9380522022-05-05 08:50:17 +02007266 if (ctx->next_index == 0)
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007267 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
7268
Willy Tarreaubd338642022-05-05 08:59:17 +02007269 if (ctx->dump_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01007270 int head;
7271
7272 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
7273 head = ref->tls_ticket_enc_index;
Willy Tarreaua9380522022-05-05 08:50:17 +02007274 while (ctx->next_index < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02007275 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02007276
7277 chunk_reset(t2);
7278 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01007279 if (ref->key_size_bits == 128) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007280 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007281 sizeof(struct tls_sess_key_128),
7282 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007283 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007284 t2->area);
7285 }
7286 else if (ref->key_size_bits == 256) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007287 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + ctx->next_index) % TLS_TICKETS_NO),
Emeric Brun9e754772019-01-10 17:51:55 +01007288 sizeof(struct tls_sess_key_256),
7289 t2->area, t2->size);
Willy Tarreaua9380522022-05-05 08:50:17 +02007290 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, ctx->next_index,
Emeric Brun9e754772019-01-10 17:51:55 +01007291 t2->area);
7292 }
7293 else {
7294 /* This case should never happen */
Willy Tarreaua9380522022-05-05 08:50:17 +02007295 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, ctx->next_index);
Emeric Brun9e754772019-01-10 17:51:55 +01007296 }
William Lallemand32af2032016-10-29 18:09:35 +02007297
Christopher Faulet908628c2022-03-25 16:43:49 +01007298 if (ci_putchk(cs_ic(cs), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007299 /* let's try again later from this stream. We add ourselves into
7300 * this stream's users so that it can remove us upon termination.
7301 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01007302 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Christopher Fauleta0bdec32022-04-04 07:51:21 +02007303 cs_rx_room_blk(cs);
William Lallemand32af2032016-10-29 18:09:35 +02007304 return 0;
7305 }
Willy Tarreaua9380522022-05-05 08:50:17 +02007306 ctx->next_index++;
William Lallemand32af2032016-10-29 18:09:35 +02007307 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01007308 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaua9380522022-05-05 08:50:17 +02007309 ctx->next_index = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007310 }
Christopher Faulet908628c2022-03-25 16:43:49 +01007311 if (ci_putchk(cs_ic(cs), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02007312 /* let's try again later from this stream. We add ourselves into
7313 * this stream's users so that it can remove us upon termination.
7314 */
Christopher Fauleta0bdec32022-04-04 07:51:21 +02007315 cs_rx_room_blk(cs);
William Lallemand32af2032016-10-29 18:09:35 +02007316 return 0;
7317 }
7318
Willy Tarreaua9380522022-05-05 08:50:17 +02007319 if (ctx->names_only == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02007320 break;
7321
7322 /* get next list entry and check the end of the list */
Willy Tarreaua9380522022-05-05 08:50:17 +02007323 ctx->next_ref = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02007324 }
Willy Tarreau9c5a38c2022-05-05 09:03:44 +02007325 ctx->state = SHOW_KEYS_DONE;
William Lallemand32af2032016-10-29 18:09:35 +02007326 /* fall through */
7327
7328 default:
William Lallemand32af2032016-10-29 18:09:35 +02007329 return 1;
7330 }
7331 return 0;
7332}
7333
Willy Tarreaua9380522022-05-05 08:50:17 +02007334/* Prepares a "show_keys_ctx" and sets the appropriate io_handler if needed */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007335static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007336{
Willy Tarreaua9380522022-05-05 08:50:17 +02007337 struct show_keys_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
7338
William Lallemand32af2032016-10-29 18:09:35 +02007339 /* no parameter, shows only file list */
7340 if (!*args[2]) {
Willy Tarreaua9380522022-05-05 08:50:17 +02007341 ctx->names_only = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007342 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007343 }
7344
7345 if (args[2][0] == '*') {
7346 /* list every TLS ticket keys */
Willy Tarreaua9380522022-05-05 08:50:17 +02007347 ctx->names_only = 1;
William Lallemand32af2032016-10-29 18:09:35 +02007348 } else {
Willy Tarreaua9380522022-05-05 08:50:17 +02007349 ctx->next_ref = tlskeys_ref_lookup_ref(args[2]);
7350 if (!ctx->next_ref)
Willy Tarreau9d008692019-08-09 11:21:01 +02007351 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02007352 }
Willy Tarreaubd338642022-05-05 08:59:17 +02007353
7354 ctx->dump_entries = 1;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01007355 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02007356}
7357
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007358static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007359{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007360 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02007361 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007362
William Lallemand32af2032016-10-29 18:09:35 +02007363 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02007364 if (!*args[3] || !*args[4])
7365 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 +02007366
Willy Tarreauf5f26e82016-12-16 18:47:27 +01007367 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02007368 if (!ref)
7369 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02007370
Willy Tarreau1c913e42018-08-22 05:26:57 +02007371 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02007372 if (ret < 0)
7373 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01007374
Willy Tarreau1c913e42018-08-22 05:26:57 +02007375 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02007376 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
7377 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007378
Willy Tarreau9d008692019-08-09 11:21:01 +02007379 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02007380}
William Lallemandd4f946c2019-12-05 10:26:40 +01007381#endif
William Lallemand419e6342020-04-08 12:05:39 +02007382
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007383static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007384{
7385#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
7386 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02007387 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02007388
7389 if (!payload)
7390 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02007391
7392 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02007393 if (!*payload)
7394 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02007395
7396 /* remove \r and \n from the payload */
7397 for (i = 0, j = 0; payload[i]; i++) {
7398 if (payload[i] == '\r' || payload[i] == '\n')
7399 continue;
7400 payload[j++] = payload[i];
7401 }
7402 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007403
Willy Tarreau1c913e42018-08-22 05:26:57 +02007404 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02007405 if (ret < 0)
7406 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007407
Willy Tarreau1c913e42018-08-22 05:26:57 +02007408 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02007409 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02007410 if (err)
7411 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
7412 else
7413 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007414 }
Willy Tarreau9d008692019-08-09 11:21:01 +02007415
7416 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02007417#else
Willy Tarreau9d008692019-08-09 11:21:01 +02007418 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 +02007419#endif
7420
Elliot Otchet71f82972020-01-15 08:12:14 -05007421}
7422
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007423
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007424#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 +02007425static int cli_io_handler_show_ocspresponse_detail(struct appctx *appctx);
7426#endif
7427
Willy Tarreau170b35b2022-05-05 09:09:15 +02007428/* parsing function for 'show ssl ocsp-response [id]'. If an entry is forced,
7429 * it's set into appctx->svcctx.
7430 */
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007431static int cli_parse_show_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
7432{
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007433#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 +02007434 if (*args[3]) {
7435 struct certificate_ocsp *ocsp = NULL;
7436 char *key = NULL;
7437 int key_length = 0;
7438
7439 if (strlen(args[3]) > OCSP_MAX_CERTID_ASN1_LENGTH*2) {
7440 return cli_err(appctx, "'show ssl ocsp-response' received a too big key.\n");
7441 }
7442
7443 if (parse_binary(args[3], &key, &key_length, NULL)) {
7444
7445 char full_key[OCSP_MAX_CERTID_ASN1_LENGTH] = {};
7446 memcpy(full_key, key, key_length);
7447
7448 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, full_key, OCSP_MAX_CERTID_ASN1_LENGTH);
7449 }
7450 if (key)
7451 ha_free(&key);
7452
7453 if (!ocsp) {
7454 return cli_err(appctx, "Certificate ID does not match any certificate.\n");
7455 }
7456
Willy Tarreau170b35b2022-05-05 09:09:15 +02007457 appctx->svcctx = ocsp;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007458 appctx->io_handler = cli_io_handler_show_ocspresponse_detail;
7459 }
7460
7461 return 0;
7462
7463#else
7464 return cli_err(appctx, "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n");
7465#endif
7466}
7467
7468
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007469#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 +02007470/*
7471 * This function dumps the details of an OCSP_CERTID. It is based on
7472 * ocsp_certid_print in OpenSSL.
7473 */
7474static inline int ocsp_certid_print(BIO *bp, OCSP_CERTID *certid, int indent)
7475{
7476 ASN1_OCTET_STRING *piNameHash = NULL;
7477 ASN1_OCTET_STRING *piKeyHash = NULL;
7478 ASN1_INTEGER *pSerial = NULL;
7479
7480 if (OCSP_id_get0_info(&piNameHash, NULL, &piKeyHash, &pSerial, certid)) {
7481
7482 BIO_printf(bp, "%*sCertificate ID:\n", indent, "");
7483 indent += 2;
Remi Tricot-Le Bretoncc750ef2021-12-17 18:53:23 +01007484 BIO_printf(bp, "%*sIssuer Name Hash: ", indent, "");
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007485 i2a_ASN1_STRING(bp, piNameHash, 0);
7486 BIO_printf(bp, "\n%*sIssuer Key Hash: ", indent, "");
7487 i2a_ASN1_STRING(bp, piKeyHash, 0);
7488 BIO_printf(bp, "\n%*sSerial Number: ", indent, "");
7489 i2a_ASN1_INTEGER(bp, pSerial);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007490 }
7491 return 1;
7492}
7493#endif
7494
7495/*
7496 * IO handler of "show ssl ocsp-response". The command taking a specific ID
7497 * is managed in cli_io_handler_show_ocspresponse_detail.
Willy Tarreau170b35b2022-05-05 09:09:15 +02007498 * The current entry is taken from appctx->svcctx.
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007499 */
7500static int cli_io_handler_show_ocspresponse(struct appctx *appctx)
7501{
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007502#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 +02007503 struct buffer *trash = alloc_trash_chunk();
7504 struct buffer *tmp = NULL;
7505 struct ebmb_node *node;
Willy Tarreau0698c802022-05-11 14:09:57 +02007506 struct conn_stream *cs = appctx_cs(appctx);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007507 struct certificate_ocsp *ocsp = NULL;
7508 BIO *bio = NULL;
7509 int write = -1;
7510
7511 if (trash == NULL)
7512 return 1;
7513
7514 tmp = alloc_trash_chunk();
7515 if (!tmp)
7516 goto end;
7517
7518 if ((bio = BIO_new(BIO_s_mem())) == NULL)
7519 goto end;
7520
Willy Tarreau170b35b2022-05-05 09:09:15 +02007521 if (!appctx->svcctx) {
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007522 chunk_appendf(trash, "# Certificate IDs\n");
7523 node = ebmb_first(&cert_ocsp_tree);
7524 } else {
Willy Tarreau170b35b2022-05-05 09:09:15 +02007525 node = &((struct certificate_ocsp *)appctx->svcctx)->key;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007526 }
7527
7528 while (node) {
7529 OCSP_CERTID *certid = NULL;
7530 const unsigned char *p = NULL;
7531 int i;
7532
7533 ocsp = ebmb_entry(node, struct certificate_ocsp, key);
7534
7535 /* Dump the key in hexadecimal */
7536 chunk_appendf(trash, "Certificate ID key : ");
7537 for (i = 0; i < ocsp->key_length; ++i) {
7538 chunk_appendf(trash, "%02x", ocsp->key_data[i]);
7539 }
7540 chunk_appendf(trash, "\n");
7541
7542 p = ocsp->key_data;
7543
7544 /* Decode the certificate ID (serialized into the key). */
7545 d2i_OCSP_CERTID(&certid, &p, ocsp->key_length);
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007546 if (!certid)
7547 goto end;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007548
7549 /* Dump the CERTID info */
7550 ocsp_certid_print(bio, certid, 1);
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007551 OCSP_CERTID_free(certid);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007552 write = BIO_read(bio, tmp->area, tmp->size-1);
Remi Tricot-Le Bretoncc750ef2021-12-17 18:53:23 +01007553 /* strip trailing LFs */
7554 while (write > 0 && tmp->area[write-1] == '\n')
7555 write--;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007556 tmp->area[write] = '\0';
7557
7558 chunk_appendf(trash, "%s\n", tmp->area);
7559
7560 node = ebmb_next(node);
Christopher Faulet908628c2022-03-25 16:43:49 +01007561 if (ci_putchk(cs_ic(cs), trash) == -1) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02007562 cs_rx_room_blk(cs);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007563 goto yield;
7564 }
7565 }
7566
7567end:
Willy Tarreau170b35b2022-05-05 09:09:15 +02007568 appctx->svcctx = NULL;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007569 if (trash)
7570 free_trash_chunk(trash);
7571 if (tmp)
7572 free_trash_chunk(tmp);
7573 if (bio)
7574 BIO_free(bio);
7575 return 1;
7576
7577yield:
7578
7579 if (trash)
7580 free_trash_chunk(trash);
7581 if (tmp)
7582 free_trash_chunk(tmp);
7583 if (bio)
7584 BIO_free(bio);
Willy Tarreau170b35b2022-05-05 09:09:15 +02007585 appctx->svcctx = ocsp;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007586 return 0;
7587#else
7588 return cli_err(appctx, "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n");
7589#endif
7590}
7591
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007592#ifdef HAVE_SSL_PROVIDERS
7593struct provider_name {
7594 const char *name;
7595 struct list list;
7596};
7597
7598
7599static int ssl_provider_get_name_cb(OSSL_PROVIDER *provider, void *cbdata)
7600{
7601 struct list *provider_names = cbdata;
7602 struct provider_name *item = NULL;
7603 const char *name = OSSL_PROVIDER_get0_name(provider);
7604
7605 if (!provider_names)
7606 return 0;
7607
7608 item = calloc(1, sizeof(*item));
7609
7610 if (!item)
7611 return 0;
7612
7613 item->name = name;
7614 LIST_APPEND(provider_names, &item->list);
7615
7616 return 1;
7617}
7618
7619static void ssl_provider_get_name_list(struct list *provider_names)
7620{
7621 if (!provider_names)
7622 return;
7623
7624 OSSL_PROVIDER_do_all(NULL, ssl_provider_get_name_cb, provider_names);
7625}
7626
7627static void ssl_provider_clear_name_list(struct list *provider_names)
7628{
7629 struct provider_name *item = NULL, *item_s = NULL;
7630
7631 if (provider_names) {
7632 list_for_each_entry_safe(item, item_s, provider_names, list) {
7633 LIST_DELETE(&item->list);
7634 free(item);
7635 }
7636 }
7637}
7638
7639static int cli_io_handler_show_providers(struct appctx *appctx)
7640{
7641 struct buffer *trash = get_trash_chunk();
Willy Tarreau0698c802022-05-11 14:09:57 +02007642 struct conn_stream *cs = appctx_cs(appctx);
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02007643 struct list provider_names;
7644 struct provider_name *name;
7645
7646 LIST_INIT(&provider_names);
7647
7648 chunk_appendf(trash, "Loaded providers : \n");
7649
7650 ssl_provider_get_name_list(&provider_names);
7651
7652 list_for_each_entry(name, &provider_names, list) {
7653 chunk_appendf(trash, "\t- %s\n", name->name);
7654 }
7655
7656 ssl_provider_clear_name_list(&provider_names);
7657
7658 if (ci_putchk(cs_ic(cs), trash) == -1) {
7659 cs_rx_room_blk(cs);
7660 goto yield;
7661 }
7662
7663 return 1;
7664
7665yield:
7666 return 0;
7667}
7668#endif
7669
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007670
Remi Tricot-Le Breton3faf0cb2021-06-10 18:10:32 +02007671#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 +02007672/*
7673 * Dump the details about an OCSP response in DER format stored in
7674 * <ocsp_response> into buffer <out>.
7675 * Returns 0 in case of success.
7676 */
7677int ssl_ocsp_response_print(struct buffer *ocsp_response, struct buffer *out)
7678{
7679 BIO *bio = NULL;
7680 int write = -1;
7681 OCSP_RESPONSE *resp;
7682 const unsigned char *p;
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01007683 int retval = -1;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007684
7685 if (!ocsp_response)
7686 return -1;
7687
7688 if ((bio = BIO_new(BIO_s_mem())) == NULL)
7689 return -1;
7690
7691 p = (const unsigned char*)ocsp_response->area;
7692
7693 resp = d2i_OCSP_RESPONSE(NULL, &p, ocsp_response->data);
7694 if (!resp) {
7695 chunk_appendf(out, "Unable to parse OCSP response");
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007696 goto end;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007697 }
7698
7699 if (OCSP_RESPONSE_print(bio, resp, 0) != 0) {
Remi Tricot-Le Breton2e7d1eb2022-01-11 10:11:10 +01007700 struct buffer *trash = get_trash_chunk();
7701 struct ist ist_block = IST_NULL;
7702 struct ist ist_double_lf = IST_NULL;
7703 static struct ist double_lf = IST("\n\n");
7704
7705 write = BIO_read(bio, trash->area, trash->size - 1);
Remi Tricot-Le Breton1b01b7f2022-02-16 15:17:09 +01007706 if (write <= 0)
7707 goto end;
Remi Tricot-Le Breton2e7d1eb2022-01-11 10:11:10 +01007708 trash->data = write;
7709
7710 /* Look for empty lines in the 'trash' buffer and add a space to
7711 * the beginning to avoid having empty lines in the output
7712 * (without changing the appearance of the information
7713 * displayed).
7714 */
7715 ist_block = ist2(b_orig(trash), b_data(trash));
7716
7717 ist_double_lf = istist(ist_block, double_lf);
7718
7719 while (istlen(ist_double_lf)) {
7720 /* istptr(ist_double_lf) points to the first \n of a
7721 * \n\n pattern.
7722 */
7723 uint empty_line_offset = istptr(ist_double_lf) + 1 - istptr(ist_block);
7724
7725 /* Write up to the first '\n' of the "\n\n" pattern into
7726 * the output buffer.
7727 */
7728 b_putblk(out, istptr(ist_block), empty_line_offset);
7729 /* Add an extra space. */
7730 b_putchr(out, ' ');
7731
7732 /* Keep looking for empty lines in the rest of the data. */
7733 ist_block = istadv(ist_block, empty_line_offset);
7734
7735 ist_double_lf = istist(ist_block, double_lf);
7736 }
7737
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01007738 retval = (b_istput(out, ist_block) <= 0);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007739 }
7740
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007741end:
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007742 if (bio)
7743 BIO_free(bio);
7744
Remi Tricot-Le Breton8081b672022-02-16 15:03:51 +01007745 OCSP_RESPONSE_free(resp);
7746
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01007747 return retval;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007748}
7749
7750/*
7751 * Dump the details of the OCSP response of ID <ocsp_certid> into buffer <out>.
7752 * Returns 0 in case of success.
7753 */
7754int ssl_get_ocspresponse_detail(unsigned char *ocsp_certid, struct buffer *out)
7755{
7756 struct certificate_ocsp *ocsp;
7757
7758 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, ocsp_certid, OCSP_MAX_CERTID_ASN1_LENGTH);
7759 if (!ocsp)
7760 return -1;
7761
7762 return ssl_ocsp_response_print(&ocsp->response, out);
7763}
7764
7765
Willy Tarreau170b35b2022-05-05 09:09:15 +02007766/* IO handler of details "show ssl ocsp-response <id>".
7767 * The current entry is taken from appctx->svcctx.
7768 */
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007769static int cli_io_handler_show_ocspresponse_detail(struct appctx *appctx)
7770{
7771 struct buffer *trash = alloc_trash_chunk();
Willy Tarreau170b35b2022-05-05 09:09:15 +02007772 struct certificate_ocsp *ocsp = appctx->svcctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02007773 struct conn_stream *cs = appctx_cs(appctx);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007774
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007775 if (trash == NULL)
7776 return 1;
7777
Remi Tricot-Le Bretona9a591a2022-02-16 14:42:22 +01007778 if (ssl_ocsp_response_print(&ocsp->response, trash)) {
7779 free_trash_chunk(trash);
7780 return 1;
7781 }
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007782
Christopher Faulet908628c2022-03-25 16:43:49 +01007783 if (ci_putchk(cs_ic(cs), trash) == -1) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02007784 cs_rx_room_blk(cs);
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007785 goto yield;
7786 }
Willy Tarreau170b35b2022-05-05 09:09:15 +02007787
7788 appctx->svcctx = NULL;
Remi Tricot-Le Bretond92fd112021-06-10 13:51:13 +02007789 if (trash)
7790 free_trash_chunk(trash);
7791 return 1;
7792
7793yield:
7794 if (trash)
7795 free_trash_chunk(trash);
7796
7797 return 0;
7798}
7799#endif
7800
William Lallemand32af2032016-10-29 18:09:35 +02007801/* register cli keywords */
7802static struct cli_kw_list cli_kws = {{ },{
7803#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Willy Tarreaubd338642022-05-05 08:59:17 +02007804 { { "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 +02007805 { { "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 +02007806#endif
Willy Tarreaub205bfd2021-05-07 11:38:37 +02007807 { { "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 +02007808
7809 { { "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 +02007810#ifdef HAVE_SSL_PROVIDERS
7811 { { "show", "ssl", "providers", NULL }, "show ssl providers : show loaded SSL providers", NULL, cli_io_handler_show_providers },
7812#endif
William Lallemand32af2032016-10-29 18:09:35 +02007813 { { NULL }, NULL, NULL, NULL }
7814}};
7815
Willy Tarreau0108d902018-11-25 19:14:37 +01007816INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02007817
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02007818/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02007819struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02007820 .snd_buf = ssl_sock_from_buf,
7821 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01007822 .subscribe = ssl_subscribe,
7823 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02007824 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02007825 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02007826 .rcv_pipe = NULL,
7827 .snd_pipe = NULL,
7828 .shutr = NULL,
7829 .shutw = ssl_sock_shutw,
7830 .close = ssl_sock_close,
7831 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01007832 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01007833 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01007834 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01007835 .prepare_srv = ssl_sock_prepare_srv_ctx,
7836 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007837 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02007838 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01007839 .set_idle = ssl_set_idle,
7840 .set_used = ssl_set_used,
Willy Tarreaude827952022-04-11 10:43:28 +02007841 .get_ssl_sock_ctx = ssl_sock_get_ctx,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01007842 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01007843 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02007844};
7845
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007846enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
7847 struct session *sess, struct stream *s, int flags)
7848{
7849 struct connection *conn;
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007850 struct conn_stream *cs;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007851
7852 conn = objt_conn(sess->origin);
Christopher Faulet95a61e82021-12-22 14:22:03 +01007853 cs = s->csf;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007854
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007855 if (conn && cs) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007856 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Christopher Faulete9e48202022-03-22 18:13:29 +01007857 cs->endp->flags |= CS_EP_WAIT_FOR_HS;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007858 s->req.flags |= CF_READ_NULL;
7859 return ACT_RET_YIELD;
7860 }
7861 }
7862 return (ACT_RET_CONT);
7863}
7864
7865static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
7866{
7867 rule->action_ptr = ssl_action_wait_for_hs;
7868
7869 return ACT_RET_PRS_OK;
7870}
7871
7872static struct action_kw_list http_req_actions = {ILH, {
7873 { "wait-for-handshake", ssl_parse_wait_for_hs },
7874 { /* END */ }
7875}};
7876
Willy Tarreau0108d902018-11-25 19:14:37 +01007877INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
7878
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007879#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007880
7881static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7882{
7883 if (ptr) {
7884 chunk_destroy(ptr);
7885 free(ptr);
7886 }
7887}
7888
7889#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007890
7891#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7892static void ssl_sock_ocsp_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7893{
7894 struct ocsp_cbk_arg *ocsp_arg;
7895
7896 if (ptr) {
7897 ocsp_arg = ptr;
7898
7899 if (ocsp_arg->is_single) {
7900 ssl_sock_free_ocsp(ocsp_arg->s_ocsp);
7901 ocsp_arg->s_ocsp = NULL;
7902 } else {
7903 int i;
7904
7905 for (i = 0; i < SSL_SOCK_NUM_KEYTYPES; i++) {
7906 ssl_sock_free_ocsp(ocsp_arg->m_ocsp[i]);
7907 ocsp_arg->m_ocsp[i] = NULL;
7908 }
7909 }
7910 free(ocsp_arg);
7911 }
7912}
7913#endif
7914
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007915static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7916{
Willy Tarreaubafbe012017-11-24 17:34:44 +01007917 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007918}
William Lallemand7d42ef52020-07-06 11:41:30 +02007919
William Lallemand722180a2021-06-09 16:46:12 +02007920#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007921static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7922{
7923 struct ssl_keylog *keylog;
7924
7925 if (!ptr)
7926 return;
7927
7928 keylog = ptr;
7929
7930 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7931 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7932 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7933 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7934 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7935 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7936 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7937 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7938
7939 pool_free(pool_head_ssl_keylog, ptr);
7940}
7941#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007942
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02007943static void ssl_sock_clt_crt_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7944{
7945 if (!ptr)
7946 return;
7947
7948 X509_free((X509*)ptr);
7949}
7950
Remi Tricot-Le Bretona9967632022-01-07 17:12:01 +01007951static void ssl_sock_clt_sni_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7952{
7953 pool_free(ssl_sock_client_sni_pool, ptr);
7954}
7955
Willy Tarreau92faadf2012-10-10 23:04:25 +02007956static void __ssl_sock_init(void)
7957{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007958#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007959 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007960 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007961#endif
Emeric Brun46591952012-05-18 15:47:34 +02007962
Willy Tarreauef934602016-12-22 23:12:01 +01007963 if (global_ssl.listen_default_ciphers)
7964 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7965 if (global_ssl.connect_default_ciphers)
7966 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007967#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007968 if (global_ssl.listen_default_ciphersuites)
7969 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7970 if (global_ssl.connect_default_ciphersuites)
7971 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7972#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007973
Willy Tarreau13e14102016-12-22 20:25:26 +01007974 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007975#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007976 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007977#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007978#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007979 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007980 n = sk_SSL_COMP_num(cm);
7981 while (n--) {
7982 (void) sk_SSL_COMP_pop(cm);
7983 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007984#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007985
Willy Tarreau5db847a2019-05-09 14:13:35 +02007986#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007987 ssl_locking_init();
7988#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007989#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007990 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
7991#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007992
7993#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7994 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
7995#endif
7996
Thierry FOURNIER28962c92018-06-17 21:37:05 +02007997 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02007998 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 +01007999#ifdef USE_QUIC
8000 ssl_qc_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
8001#endif /* USE_QUIC */
William Lallemand722180a2021-06-09 16:46:12 +02008002#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02008003 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
8004#endif
Remi Tricot-Le Breton74f6ab62021-08-19 18:06:30 +02008005 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 +01008006 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 +02008007#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00008008 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00008009 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02008010#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01008011#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
8012 hap_register_post_check(tlskeys_finalize_config);
8013#endif
Willy Tarreau80713382018-11-26 10:19:54 +01008014
8015 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
8016 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
8017
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01008018 hap_register_post_deinit(ssl_free_global_issuers);
8019
Willy Tarreau80713382018-11-26 10:19:54 +01008020#ifndef OPENSSL_NO_DH
8021 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
8022 hap_register_post_deinit(ssl_free_dh);
8023#endif
William Lallemandd7bfbe22022-04-11 18:41:24 +02008024#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Willy Tarreau80713382018-11-26 10:19:54 +01008025 hap_register_post_deinit(ssl_free_engines);
8026#endif
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01008027#if HA_OPENSSL_VERSION_NUMBER < 0x3000000fL
Willy Tarreau80713382018-11-26 10:19:54 +01008028 /* Load SSL string for the verbose & debug mode. */
8029 ERR_load_SSL_strings();
Remi Tricot-Le Breton78a36e32022-02-11 12:04:45 +01008030#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02008031 ha_meth = BIO_meth_new(0x666, "ha methods");
8032 BIO_meth_set_write(ha_meth, ha_ssl_write);
8033 BIO_meth_set_read(ha_meth, ha_ssl_read);
8034 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
8035 BIO_meth_set_create(ha_meth, ha_ssl_new);
8036 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
8037 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
8038 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02008039
8040 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02008041
Dragan Dosen9ac98092020-05-11 15:51:45 +02008042 /* Try to register dedicated SSL/TLS protocol message callbacks for
8043 * heartbleed attack (CVE-2014-0160) and clienthello.
8044 */
8045 hap_register_post_check(ssl_sock_register_msg_callbacks);
8046
Dragan Dosen1e7ed042020-05-08 18:30:00 +02008047 /* Try to free all callbacks that were registered by using
8048 * ssl_sock_register_msg_callback().
8049 */
8050 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01008051}
Willy Tarreau79367f92022-04-25 19:18:24 +02008052INITCALL0(STG_REGISTER, __ssl_sock_init);
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01008053
Willy Tarreau80713382018-11-26 10:19:54 +01008054/* Compute and register the version string */
8055static void ssl_register_build_options()
8056{
8057 char *ptr = NULL;
8058 int i;
8059
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008060 memprintf(&ptr, "Built with OpenSSL version : "
8061#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01008062 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008063#else /* OPENSSL_IS_BORINGSSL */
8064 OPENSSL_VERSION_TEXT
8065 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08008066 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02008067 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008068#endif
8069 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02008070#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008071 "no (library version too old)"
8072#elif defined(OPENSSL_NO_TLSEXT)
8073 "no (disabled via OPENSSL_NO_TLSEXT)"
8074#else
8075 "yes"
8076#endif
8077 "", ptr);
8078
8079 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
8080#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
8081 "yes"
8082#else
8083#ifdef OPENSSL_NO_TLSEXT
8084 "no (because of OPENSSL_NO_TLSEXT)"
8085#else
8086 "no (version might be too old, 0.9.8f min needed)"
8087#endif
8088#endif
8089 "", ptr);
8090
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02008091 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
8092 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
8093 if (methodVersions[i].option)
8094 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01008095
Remi Tricot-Le Bretonf87c67e2022-04-21 12:06:41 +02008096#ifdef HAVE_SSL_PROVIDERS
8097 {
8098 struct list provider_names;
8099 struct provider_name *name;
8100 LIST_INIT(&provider_names);
8101 ssl_provider_get_name_list(&provider_names);
8102
8103 memprintf(&ptr, "%s\nOpenSSL providers loaded :", ptr);
8104
8105 list_for_each_entry(name, &provider_names, list) {
8106 memprintf(&ptr, "%s %s", ptr, name->name);
8107 }
8108
8109 ssl_provider_clear_name_list(&provider_names);
8110 }
8111#endif
8112
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008113 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01008114}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01008115
Willy Tarreau80713382018-11-26 10:19:54 +01008116INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02008117
William Lallemandd7bfbe22022-04-11 18:41:24 +02008118#if defined(USE_ENGINE) && !defined(OPENSSL_NO_ENGINE)
Grant Zhang872f9c22017-01-21 01:10:18 +00008119void ssl_free_engines(void) {
8120 struct ssl_engine_list *wl, *wlb;
8121 /* free up engine list */
8122 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
8123 ENGINE_finish(wl->e);
8124 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02008125 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00008126 free(wl);
8127 }
8128}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02008129#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02008130
Remi Gacogned3a23c32015-05-28 16:39:47 +02008131#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00008132void ssl_free_dh(void) {
8133 if (local_dh_1024) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008134 HASSL_DH_free(local_dh_1024);
Grant Zhang872f9c22017-01-21 01:10:18 +00008135 local_dh_1024 = NULL;
8136 }
8137 if (local_dh_2048) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008138 HASSL_DH_free(local_dh_2048);
Grant Zhang872f9c22017-01-21 01:10:18 +00008139 local_dh_2048 = NULL;
8140 }
8141 if (local_dh_4096) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008142 HASSL_DH_free(local_dh_4096);
Grant Zhang872f9c22017-01-21 01:10:18 +00008143 local_dh_4096 = NULL;
8144 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02008145 if (global_dh) {
Remi Tricot-Le Bretonc76c3c42022-02-11 12:04:55 +01008146 HASSL_DH_free(global_dh);
Remi Gacogne47783ef2015-05-29 15:53:22 +02008147 global_dh = NULL;
8148 }
Grant Zhang872f9c22017-01-21 01:10:18 +00008149}
8150#endif
8151
Grant Zhang872f9c22017-01-21 01:10:18 +00008152static void __ssl_sock_deinit(void)
8153{
8154#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02008155 if (ssl_ctx_lru_tree) {
8156 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01008157 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02008158 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02008159#endif
8160
Willy Tarreau5db847a2019-05-09 14:13:35 +02008161#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02008162 ERR_remove_state(0);
8163 ERR_free_strings();
8164
8165 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08008166#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02008167
Willy Tarreau5db847a2019-05-09 14:13:35 +02008168#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02008169 CRYPTO_cleanup_all_ex_data();
8170#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02008171 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02008172}
Willy Tarreau79367f92022-04-25 19:18:24 +02008173REGISTER_POST_DEINIT(__ssl_sock_deinit);
Remi Gacogned3a23c32015-05-28 16:39:47 +02008174
William Dauchyf6370442020-11-14 19:25:33 +01008175
Emeric Brun46591952012-05-18 15:47:34 +02008176/*
8177 * Local variables:
8178 * c-indent-level: 8
8179 * c-basic-offset: 8
8180 * End:
8181 */