blob: 0554ef5a5030890954a6b7fc8f5b2c2b1a343638 [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>
31#include <fcntl.h>
32#include <stdio.h>
33#include <stdlib.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020034#include <string.h>
35#include <unistd.h>
Emeric Brun46591952012-05-18 15:47:34 +020036
37#include <sys/socket.h>
38#include <sys/stat.h>
39#include <sys/types.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020040#include <netdb.h>
Emeric Brun46591952012-05-18 15:47:34 +020041#include <netinet/tcp.h>
42
Willy Tarreaub2551052020-06-09 09:07:15 +020043#include <import/ebpttree.h>
44#include <import/ebsttree.h>
Christopher Faulet31af49d2015-06-09 17:29:50 +020045#include <import/lru.h>
46#include <import/xxhash.h>
47
Willy Tarreaub2551052020-06-09 09:07:15 +020048#include <haproxy/api.h>
49#include <haproxy/arg.h>
50#include <haproxy/base64.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020051#include <haproxy/channel.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020052#include <haproxy/chunk.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020053#include <haproxy/cli.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020054#include <haproxy/connection.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020055#include <haproxy/dynbuf.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020056#include <haproxy/errors.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020057#include <haproxy/fd.h>
58#include <haproxy/freq_ctr.h>
Willy Tarreau762d7a52020-06-04 11:23:07 +020059#include <haproxy/frontend.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020060#include <haproxy/global.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020061#include <haproxy/http_rules.h>
Willy Tarreauaeed4a82020-06-04 22:01:04 +020062#include <haproxy/log.h>
Willy Tarreau6019fab2020-05-27 16:26:00 +020063#include <haproxy/openssl-compat.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020064#include <haproxy/pattern-t.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020065#include <haproxy/proto_tcp.h>
Willy Tarreaua264d962020-06-04 22:29:18 +020066#include <haproxy/proxy.h>
Willy Tarreau1e56f922020-06-04 23:20:13 +020067#include <haproxy/server.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020068#include <haproxy/shctx.h>
Willy Tarreau47d7f902020-06-04 14:25:47 +020069#include <haproxy/ssl_ckch.h>
Willy Tarreau52d88722020-06-04 14:29:23 +020070#include <haproxy/ssl_crtlist.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020071#include <haproxy/ssl_sock.h>
Willy Tarreaub2bd8652020-06-04 14:21:22 +020072#include <haproxy/ssl_utils.h>
William Lallemand17d0caa2022-03-16 17:48:19 +010073#include <haproxy/sample.h>
Amaury Denoyelle9963fa72020-11-03 17:10:00 +010074#include <haproxy/stats.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020075#include <haproxy/stream-t.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020076#include <haproxy/stream_interface.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>
Emeric Brun46591952012-05-18 15:47:34 +020083
Emeric Brun46591952012-05-18 15:47:34 +020084
Willy Tarreau9356dac2019-05-10 09:22:53 +020085/* ***** READ THIS before adding code here! *****
86 *
87 * Due to API incompatibilities between multiple OpenSSL versions and their
88 * derivatives, it's often tempting to add macros to (re-)define certain
89 * symbols. Please do not do this here, and do it in common/openssl-compat.h
90 * exclusively so that the whole code consistently uses the same macros.
91 *
92 * Whenever possible if a macro is missing in certain versions, it's better
93 * to conditionally define it in openssl-compat.h than using lots of ifdefs.
94 */
95
Willy Tarreau71b734c2014-01-28 15:19:44 +010096int sslconns = 0;
97int totalsslconns = 0;
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
126 .default_dh_param = SSL_DEFAULT_DH_PARAM,
127 .ctx_cache = DEFAULT_SSL_CTX_CACHE,
Thierry FOURNIER5bf77322017-02-25 12:45:22 +0100128 .capture_cipherlist = 0,
William Lallemand3af48e72020-02-03 17:15:52 +0100129 .extra_files = SSL_GF_ALL,
William Lallemand8e8581e2020-10-20 17:36:46 +0200130 .extra_files_noext = 0,
William Lallemandca5cf0a2021-06-09 16:46:12 +0200131#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200132 .keylog = 0
133#endif
Willy Tarreauef934602016-12-22 23:12:01 +0100134};
135
Olivier Houcharda8955d52019-04-07 22:00:38 +0200136static BIO_METHOD *ha_meth;
137
Olivier Houchard66ab4982019-02-26 18:37:15 +0100138DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx_pool", sizeof(struct ssl_sock_ctx));
139
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100140/* ssl stats module */
141enum {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100142 SSL_ST_SESS,
143 SSL_ST_REUSED_SESS,
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100144 SSL_ST_FAILED_HANDSHAKE,
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100145
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100146 SSL_ST_STATS_COUNT /* must be the last member of the enum */
147};
148
149static struct name_desc ssl_stats[] = {
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100150 [SSL_ST_SESS] = { .name = "ssl_sess",
151 .desc = "Total number of ssl sessions established" },
152 [SSL_ST_REUSED_SESS] = { .name = "ssl_reused_sess",
153 .desc = "Total number of ssl sessions reused" },
154 [SSL_ST_FAILED_HANDSHAKE] = { .name = "ssl_failed_handshake",
155 .desc = "Total number of failed handshake" },
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100156};
157
158static struct ssl_counters {
Amaury Denoyelled0447a72020-11-03 17:10:02 +0100159 long long sess;
160 long long reused_sess;
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100161 long long failed_handshake;
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100162} ssl_counters;
163
164static void ssl_fill_stats(void *data, struct field *stats)
165{
Amaury Denoyellefbc33772020-11-03 17:10:01 +0100166 struct ssl_counters *counters = data;
167
Amaury Denoyelle034c1622020-11-13 16:05:00 +0100168 stats[SSL_ST_SESS] = mkf_u64(FN_COUNTER, counters->sess);
169 stats[SSL_ST_REUSED_SESS] = mkf_u64(FN_COUNTER, counters->reused_sess);
170 stats[SSL_ST_FAILED_HANDSHAKE] = mkf_u64(FN_COUNTER, counters->failed_handshake);
Amaury Denoyelle9963fa72020-11-03 17:10:00 +0100171}
172
173static struct stats_module ssl_stats_module = {
174 .name = "ssl",
175 .fill_stats = ssl_fill_stats,
176 .stats = ssl_stats,
177 .stats_count = SSL_ST_STATS_COUNT,
178 .counters = &ssl_counters,
179 .counters_size = sizeof(ssl_counters),
180 .domain_flags = MK_STATS_PROXY_DOMAIN(STATS_PX_CAP_FE|STATS_PX_CAP_LI|STATS_PX_CAP_BE|STATS_PX_CAP_SRV),
181 .clearable = 1,
182};
183
184INITCALL1(STG_REGISTER, stats_register_module, &ssl_stats_module);
185
Willy Tarreau691d5032021-01-20 14:55:01 +0100186/* ssl_sock_io_cb is exported to see it resolved in "show fd" */
Willy Tarreau144f84a2021-03-02 16:09:26 +0100187struct task *ssl_sock_io_cb(struct task *, void *, unsigned int);
Olivier Houchard000694c2019-05-23 14:45:12 +0200188static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
Olivier Houchardea8dd942019-05-20 14:02:16 +0200189
Olivier Houcharda8955d52019-04-07 22:00:38 +0200190/* Methods to implement OpenSSL BIO */
191static int ha_ssl_write(BIO *h, const char *buf, int num)
192{
193 struct buffer tmpbuf;
194 struct ssl_sock_ctx *ctx;
195 int ret;
196
197 ctx = BIO_get_data(h);
198 tmpbuf.size = num;
199 tmpbuf.area = (void *)(uintptr_t)buf;
200 tmpbuf.data = num;
201 tmpbuf.head = 0;
202 ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, 0);
Olivier Houchardd292e562024-01-27 22:58:29 +0100203 BIO_clear_retry_flags(h);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200204 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200205 BIO_set_retry_write(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200206 ret = -1;
Olivier Houchardd292e562024-01-27 22:58:29 +0100207 }
Olivier Houcharda8955d52019-04-07 22:00:38 +0200208 return ret;
209}
210
211static int ha_ssl_gets(BIO *h, char *buf, int size)
212{
213
214 return 0;
215}
216
217static int ha_ssl_puts(BIO *h, const char *str)
218{
219
220 return ha_ssl_write(h, str, strlen(str));
221}
222
223static int ha_ssl_read(BIO *h, char *buf, int size)
224{
225 struct buffer tmpbuf;
226 struct ssl_sock_ctx *ctx;
227 int ret;
228
229 ctx = BIO_get_data(h);
230 tmpbuf.size = size;
231 tmpbuf.area = buf;
232 tmpbuf.data = 0;
233 tmpbuf.head = 0;
234 ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
Olivier Houchardd292e562024-01-27 22:58:29 +0100235 BIO_clear_retry_flags(h);
Olivier Houchardb51937e2019-05-01 17:24:36 +0200236 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200237 BIO_set_retry_read(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200238 ret = -1;
Olivier Houchardd292e562024-01-27 22:58:29 +0100239 }
Olivier Houcharda8955d52019-04-07 22:00:38 +0200240
241 return ret;
242}
243
244static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
245{
246 int ret = 0;
247 switch (cmd) {
248 case BIO_CTRL_DUP:
249 case BIO_CTRL_FLUSH:
250 ret = 1;
251 break;
252 }
253 return ret;
254}
255
256static int ha_ssl_new(BIO *h)
257{
258 BIO_set_init(h, 1);
259 BIO_set_data(h, NULL);
260 BIO_clear_flags(h, ~0);
261 return 1;
262}
263
264static int ha_ssl_free(BIO *data)
265{
266
267 return 1;
268}
269
270
Willy Tarreau5db847a2019-05-09 14:13:35 +0200271#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100272
Emeric Brun821bb9b2017-06-15 16:37:39 +0200273static HA_RWLOCK_T *ssl_rwlocks;
274
275
276unsigned long ssl_id_function(void)
277{
278 return (unsigned long)tid;
279}
280
281void ssl_locking_function(int mode, int n, const char * file, int line)
282{
283 if (mode & CRYPTO_LOCK) {
284 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100285 HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200286 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100287 HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200288 }
289 else {
290 if (mode & CRYPTO_READ)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100291 HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200292 else
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100293 HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200294 }
295}
296
297static int ssl_locking_init(void)
298{
299 int i;
300
301 ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
302 if (!ssl_rwlocks)
303 return -1;
304
305 for (i = 0 ; i < CRYPTO_num_locks() ; i++)
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100306 HA_RWLOCK_INIT(&ssl_rwlocks[i]);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200307
308 CRYPTO_set_id_callback(ssl_id_function);
309 CRYPTO_set_locking_callback(ssl_locking_function);
310
311 return 0;
312}
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100313
Emeric Brun821bb9b2017-06-15 16:37:39 +0200314#endif
315
Willy Tarreauaf613e82020-06-05 08:40:51 +0200316__decl_thread(HA_SPINLOCK_T ckch_lock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200317
William Lallemandbc6ca7c2019-10-29 23:48:19 +0100318
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200319/*
Emmanuel Hocdetb270e812019-11-21 19:09:31 +0100320 * deduplicate cafile (and crlfile)
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200321 */
322struct cafile_entry {
323 X509_STORE *ca_store;
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200324 STACK_OF(X509_NAME) *ca_list;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200325 struct ebmb_node node;
326 char path[0];
327};
328
329static struct eb_root cafile_tree = EB_ROOT_UNIQUE;
330
331static X509_STORE* ssl_store_get0_locations_file(char *path)
332{
333 struct ebmb_node *eb;
334
335 eb = ebst_lookup(&cafile_tree, path);
336 if (eb) {
337 struct cafile_entry *ca_e;
338 ca_e = ebmb_entry(eb, struct cafile_entry, node);
339 return ca_e->ca_store;
340 }
341 return NULL;
342}
343
Remi Tricot-Le Bretonfb00f312021-03-23 16:41:53 +0100344int ssl_store_load_locations_file(char *path, int create_if_none)
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200345{
Remi Tricot-Le Bretonfb00f312021-03-23 16:41:53 +0100346 X509_STORE *store = ssl_store_get0_locations_file(path);
347
348 /* If this function is called by the CLI, we should not call the
349 * X509_STORE_load_locations function because it performs forbidden disk
350 * accesses. */
351 if (!store && create_if_none) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200352 struct cafile_entry *ca_e;
Remi Tricot-Le Bretonfb00f312021-03-23 16:41:53 +0100353 store = X509_STORE_new();
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200354 if (X509_STORE_load_locations(store, path, NULL)) {
355 int pathlen;
356 pathlen = strlen(path);
357 ca_e = calloc(1, sizeof(*ca_e) + pathlen + 1);
358 if (ca_e) {
359 memcpy(ca_e->path, path, pathlen + 1);
360 ca_e->ca_store = store;
361 ebst_insert(&cafile_tree, &ca_e->node);
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200362 }
Remi Tricot-Le Bretonfb00f312021-03-23 16:41:53 +0100363 } else {
364 X509_STORE_free(store);
365 store = NULL;
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200366 }
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200367 }
Remi Tricot-Le Bretonfb00f312021-03-23 16:41:53 +0100368 return (store != NULL);
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200369}
370
371/* mimic what X509_STORE_load_locations do with store_ctx */
372static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
373{
374 X509_STORE *store;
375 store = ssl_store_get0_locations_file(path);
376 if (store_ctx && store) {
377 int i;
378 X509_OBJECT *obj;
379 STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
380 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
381 obj = sk_X509_OBJECT_value(objs, i);
382 switch (X509_OBJECT_get_type(obj)) {
383 case X509_LU_X509:
384 X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
385 break;
386 case X509_LU_CRL:
387 X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
388 break;
389 default:
390 break;
391 }
392 }
393 return 1;
394 }
395 return 0;
396}
397
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +0500398/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +0200399static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
400{
401 X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
402 return ssl_set_cert_crl_file(store_ctx, path);
403}
404
Emmanuel Hocdet129d3282019-10-24 18:08:51 +0200405/*
406 Extract CA_list from CA_file already in tree.
407 Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
408 Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
409*/
410static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
411{
412 struct ebmb_node *eb;
413 struct cafile_entry *ca_e;
414
415 eb = ebst_lookup(&cafile_tree, path);
416 if (!eb)
417 return NULL;
418 ca_e = ebmb_entry(eb, struct cafile_entry, node);
419
420 if (ca_e->ca_list == NULL) {
421 int i;
422 unsigned long key;
423 struct eb_root ca_name_tree = EB_ROOT;
424 struct eb64_node *node, *back;
425 struct {
426 struct eb64_node node;
427 X509_NAME *xname;
428 } *ca_name;
429 STACK_OF(X509_OBJECT) *objs;
430 STACK_OF(X509_NAME) *skn;
431 X509 *x;
432 X509_NAME *xn;
433
434 skn = sk_X509_NAME_new_null();
435 /* take x509 from cafile_tree */
436 objs = X509_STORE_get0_objects(ca_e->ca_store);
437 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
438 x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
439 if (!x)
440 continue;
441 xn = X509_get_subject_name(x);
442 if (!xn)
443 continue;
444 /* Check for duplicates. */
445 key = X509_NAME_hash(xn);
446 for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
447 node && ca_name == NULL;
448 node = eb64_next(node)) {
449 ca_name = container_of(node, typeof(*ca_name), node);
450 if (X509_NAME_cmp(xn, ca_name->xname) != 0)
451 ca_name = NULL;
452 }
453 /* find a duplicate */
454 if (ca_name)
455 continue;
456 ca_name = calloc(1, sizeof *ca_name);
457 xn = X509_NAME_dup(xn);
458 if (!ca_name ||
459 !xn ||
460 !sk_X509_NAME_push(skn, xn)) {
461 free(ca_name);
462 X509_NAME_free(xn);
463 sk_X509_NAME_pop_free(skn, X509_NAME_free);
464 sk_X509_NAME_free(skn);
465 skn = NULL;
466 break;
467 }
468 ca_name->node.key = key;
469 ca_name->xname = xn;
470 eb64_insert(&ca_name_tree, &ca_name->node);
471 }
472 ca_e->ca_list = skn;
473 /* remove temporary ca_name tree */
474 node = eb64_first(&ca_name_tree);
475 while (node) {
476 ca_name = container_of(node, typeof(*ca_name), node);
477 back = eb64_next(node);
478 eb64_delete(node);
479 free(ca_name);
480 node = back;
481 }
482 }
483 return ca_e->ca_list;
484}
485
Willy Tarreauff882702021-04-10 17:23:00 +0200486struct pool_head *pool_head_ssl_capture __read_mostly = NULL;
William Lallemand15e16942020-05-15 00:25:08 +0200487int ssl_capture_ptr_index = -1;
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +0100488int ssl_app_data_index = -1;
Willy Tarreauef934602016-12-22 23:12:01 +0100489
William Lallemandca5cf0a2021-06-09 16:46:12 +0200490#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200491int ssl_keylog_index = -1;
Willy Tarreauff882702021-04-10 17:23:00 +0200492struct pool_head *pool_head_ssl_keylog __read_mostly = NULL;
493struct pool_head *pool_head_ssl_keylog_str __read_mostly = NULL;
William Lallemand7d42ef52020-07-06 11:41:30 +0200494#endif
495
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +0200496#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
497struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
498#endif
499
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200500#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200501unsigned int openssl_engines_initialized;
Grant Zhang872f9c22017-01-21 01:10:18 +0000502struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
503struct ssl_engine_list {
504 struct list list;
505 ENGINE *e;
506};
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200507#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000508
Remi Gacogne8de54152014-07-15 11:36:40 +0200509#ifndef OPENSSL_NO_DH
Remi Gacogne4f902b82015-05-28 16:23:00 +0200510static int ssl_dh_ptr_index = -1;
Remi Gacogne47783ef2015-05-29 15:53:22 +0200511static DH *global_dh = NULL;
Remi Gacogne8de54152014-07-15 11:36:40 +0200512static DH *local_dh_1024 = NULL;
513static DH *local_dh_2048 = NULL;
514static DH *local_dh_4096 = NULL;
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +0100515static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen);
Remi Gacogne8de54152014-07-15 11:36:40 +0200516#endif /* OPENSSL_NO_DH */
517
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100518#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Christopher Faulet31af49d2015-06-09 17:29:50 +0200519/* X509V3 Extensions that will be added on generated certificates */
520#define X509V3_EXT_SIZE 5
521static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
522 "basicConstraints",
523 "nsComment",
524 "subjectKeyIdentifier",
525 "authorityKeyIdentifier",
526 "keyUsage",
527};
528static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
529 "CA:FALSE",
530 "\"OpenSSL Generated Certificate\"",
531 "hash",
532 "keyid,issuer:always",
533 "nonRepudiation,digitalSignature,keyEncipherment"
534};
Christopher Faulet31af49d2015-06-09 17:29:50 +0200535/* LRU cache to store generated certificate */
536static struct lru64_head *ssl_ctx_lru_tree = NULL;
537static unsigned int ssl_ctx_lru_seed = 0;
Emeric Brun821bb9b2017-06-15 16:37:39 +0200538static unsigned int ssl_ctx_serial;
Willy Tarreau86abe442018-11-25 20:12:18 +0100539__decl_rwlock(ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +0200540
Willy Tarreauc8ad3be2015-06-17 15:48:26 +0200541#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
542
yanbzhube2774d2015-12-10 15:07:30 -0500543/* The order here matters for picking a default context,
544 * keep the most common keytype at the bottom of the list
545 */
546const char *SSL_SOCK_KEYTYPE_NAMES[] = {
547 "dsa",
548 "ecdsa",
549 "rsa"
550};
yanbzhube2774d2015-12-10 15:07:30 -0500551
William Lallemandc3cd35f2017-11-28 11:04:43 +0100552static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
William Lallemand4f45bb92017-10-30 20:08:51 +0100553static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
554
Dragan Dosen9ac98092020-05-11 15:51:45 +0200555/* Dedicated callback functions for heartbeat and clienthello.
556 */
557#ifdef TLS1_RT_HEARTBEAT
558static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
559 int content_type, const void *buf, size_t len,
560 SSL *ssl);
561#endif
562static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
563 int content_type, const void *buf, size_t len,
564 SSL *ssl);
565
William Lallemandca5cf0a2021-06-09 16:46:12 +0200566#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200567static void ssl_init_keylog(struct connection *conn, int write_p, int version,
568 int content_type, const void *buf, size_t len,
569 SSL *ssl);
570#endif
571
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200572/* List head of all registered SSL/TLS protocol message callbacks. */
573struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
574
575/* Registers the function <func> in order to be called on SSL/TLS protocol
576 * message processing. It will return 0 if the function <func> is not set
577 * or if it fails to allocate memory.
578 */
579int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
580{
581 struct ssl_sock_msg_callback *cbk;
582
583 if (!func)
584 return 0;
585
586 cbk = calloc(1, sizeof(*cbk));
587 if (!cbk) {
588 ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
589 return 0;
590 }
591
592 cbk->func = func;
593
Willy Tarreau2b718102021-04-21 07:32:39 +0200594 LIST_APPEND(&ssl_sock_msg_callbacks, &cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200595
596 return 1;
597}
598
Dragan Dosen9ac98092020-05-11 15:51:45 +0200599/* Used to register dedicated SSL/TLS protocol message callbacks.
600 */
601static int ssl_sock_register_msg_callbacks(void)
602{
603#ifdef TLS1_RT_HEARTBEAT
604 if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
605 return ERR_ABORT;
606#endif
607 if (global_ssl.capture_cipherlist > 0) {
608 if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
609 return ERR_ABORT;
610 }
William Lallemandca5cf0a2021-06-09 16:46:12 +0200611#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +0200612 if (global_ssl.keylog > 0) {
613 if (!ssl_sock_register_msg_callback(ssl_init_keylog))
614 return ERR_ABORT;
615 }
616#endif
617
Christopher Fauletfc633b62020-11-06 15:24:23 +0100618 return ERR_NONE;
Dragan Dosen9ac98092020-05-11 15:51:45 +0200619}
620
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200621/* Used to free all SSL/TLS protocol message callbacks that were
622 * registered by using ssl_sock_register_msg_callback().
623 */
624static void ssl_sock_unregister_msg_callbacks(void)
625{
626 struct ssl_sock_msg_callback *cbk, *cbkback;
627
628 list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +0200629 LIST_DELETE(&cbk->list);
Dragan Dosen1e7ed042020-05-08 18:30:00 +0200630 free(cbk);
631 }
632}
633
Dragan Doseneb607fe2020-05-11 17:17:06 +0200634SSL *ssl_sock_get_ssl_object(struct connection *conn)
635{
636 if (!ssl_sock_is_ssl(conn))
637 return NULL;
638
639 return ((struct ssl_sock_ctx *)(conn->xprt_ctx))->ssl;
640}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100641/*
642 * This function gives the detail of the SSL error. It is used only
643 * if the debug mode and the verbose mode are activated. It dump all
644 * the SSL error until the stack was empty.
645 */
646static forceinline void ssl_sock_dump_errors(struct connection *conn)
647{
648 unsigned long ret;
649
650 if (unlikely(global.mode & MODE_DEBUG)) {
651 while(1) {
652 ret = ERR_get_error();
653 if (ret == 0)
654 return;
Willy Tarreau566cebc2021-03-02 19:32:39 +0100655 fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
656 conn->handle.fd, ret,
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +0100657 ERR_func_error_string(ret), ERR_reason_error_string(ret));
658 }
659 }
660}
661
yanbzhube2774d2015-12-10 15:07:30 -0500662
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200663#ifndef OPENSSL_NO_ENGINE
William Lallemanddad31052020-05-14 17:47:32 +0200664int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
Grant Zhang872f9c22017-01-21 01:10:18 +0000665{
666 int err_code = ERR_ABORT;
667 ENGINE *engine;
668 struct ssl_engine_list *el;
669
670 /* grab the structural reference to the engine */
671 engine = ENGINE_by_id(engine_id);
672 if (engine == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100673 ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000674 goto fail_get;
675 }
676
677 if (!ENGINE_init(engine)) {
678 /* the engine couldn't initialise, release it */
Christopher Faulet767a84b2017-11-24 16:50:31 +0100679 ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000680 goto fail_init;
681 }
682
683 if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100684 ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
Grant Zhang872f9c22017-01-21 01:10:18 +0000685 goto fail_set_method;
686 }
687
688 el = calloc(1, sizeof(*el));
Remi Tricot-Le Breton46697c82021-05-12 17:45:21 +0200689 if (!el)
690 goto fail_alloc;
Grant Zhang872f9c22017-01-21 01:10:18 +0000691 el->e = engine;
Willy Tarreau2b718102021-04-21 07:32:39 +0200692 LIST_INSERT(&openssl_engines, &el->list);
Emeric Brunece0c332017-12-06 13:51:49 +0100693 nb_engines++;
694 if (global_ssl.async)
695 global.ssl_used_async_engines = nb_engines;
Grant Zhang872f9c22017-01-21 01:10:18 +0000696 return 0;
697
Remi Tricot-Le Breton46697c82021-05-12 17:45:21 +0200698fail_alloc:
Grant Zhang872f9c22017-01-21 01:10:18 +0000699fail_set_method:
700 /* release the functional reference from ENGINE_init() */
701 ENGINE_finish(engine);
702
703fail_init:
704 /* release the structural reference from ENGINE_by_id() */
705 ENGINE_free(engine);
706
707fail_get:
708 return err_code;
709}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +0200710#endif
Grant Zhang872f9c22017-01-21 01:10:18 +0000711
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +0500712#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +0200713/*
714 * openssl async fd handler
715 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200716void ssl_async_fd_handler(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000717{
Olivier Houchardea8dd942019-05-20 14:02:16 +0200718 struct ssl_sock_ctx *ctx = fdtab[fd].owner;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000719
Emeric Brun3854e012017-05-17 20:42:48 +0200720 /* fd is an async enfine fd, we must stop
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000721 * to poll this fd until it is requested
722 */
Emeric Brunbbc16542017-06-02 15:54:06 +0000723 fd_stop_recv(fd);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000724 fd_cant_recv(fd);
725
726 /* crypto engine is available, let's notify the associated
727 * connection that it can pursue its processing.
728 */
Olivier Houcharda4598262020-09-15 22:16:02 +0200729 tasklet_wakeup(ctx->wait_event.tasklet);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000730}
731
Emeric Brun3854e012017-05-17 20:42:48 +0200732/*
733 * openssl async delayed SSL_free handler
734 */
Emeric Brund0e095c2019-04-19 17:15:28 +0200735void ssl_async_fd_free(int fd)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000736{
737 SSL *ssl = fdtab[fd].owner;
Emeric Brun3854e012017-05-17 20:42:48 +0200738 OSSL_ASYNC_FD all_fd[32];
739 size_t num_all_fds = 0;
740 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000741
Emeric Brun3854e012017-05-17 20:42:48 +0200742 /* We suppose that the async job for a same SSL *
743 * are serialized. So if we are awake it is
744 * because the running job has just finished
745 * and we can remove all async fds safely
746 */
747 SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
748 if (num_all_fds > 32) {
749 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
750 return;
751 }
752
753 SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
Emeric Brun64ff81b2022-07-01 17:36:50 +0200754 for (i=0 ; i < num_all_fds ; i++) {
755 /* We want to remove the fd from the fdtab
756 * but we flag it to disown because the
757 * close is performed by the engine itself
758 */
759 fdtab[all_fd[i]].state |= FD_DISOWN;
760 fd_delete(all_fd[i]);
761 }
Emeric Brun3854e012017-05-17 20:42:48 +0200762
763 /* Now we can safely call SSL_free, no more pending job in engines */
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000764 SSL_free(ssl);
Willy Tarreau4781b152021-04-06 13:53:36 +0200765 _HA_ATOMIC_DEC(&sslconns);
766 _HA_ATOMIC_DEC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000767}
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000768/*
Emeric Brun3854e012017-05-17 20:42:48 +0200769 * function used to manage a returned SSL_ERROR_WANT_ASYNC
770 * and enable/disable polling for async fds
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000771 */
Olivier Houchardea8dd942019-05-20 14:02:16 +0200772static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000773{
Willy Tarreaua9786b62018-01-25 07:22:13 +0100774 OSSL_ASYNC_FD add_fd[32];
Emeric Brun3854e012017-05-17 20:42:48 +0200775 OSSL_ASYNC_FD del_fd[32];
Olivier Houchardea8dd942019-05-20 14:02:16 +0200776 SSL *ssl = ctx->ssl;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000777 size_t num_add_fds = 0;
778 size_t num_del_fds = 0;
Emeric Brun3854e012017-05-17 20:42:48 +0200779 int i;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000780
781 SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
782 &num_del_fds);
Emeric Brun3854e012017-05-17 20:42:48 +0200783 if (num_add_fds > 32 || num_del_fds > 32) {
784 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 +0000785 return;
786 }
787
Emeric Brun3854e012017-05-17 20:42:48 +0200788 SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000789
Emeric Brun3854e012017-05-17 20:42:48 +0200790 /* We remove unused fds from the fdtab */
Emeric Brun64ff81b2022-07-01 17:36:50 +0200791 for (i=0 ; i < num_del_fds ; i++) {
792 /* We want to remove the fd from the fdtab
793 * but we flag it to disown because the
794 * close is performed by the engine itself
795 */
796 fdtab[del_fd[i]].state |= FD_DISOWN;
797 fd_delete(del_fd[i]);
798 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000799
Emeric Brun3854e012017-05-17 20:42:48 +0200800 /* We add new fds to the fdtab */
801 for (i=0 ; i < num_add_fds ; i++) {
Olivier Houchardea8dd942019-05-20 14:02:16 +0200802 fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tid_bit);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000803 }
804
Emeric Brun3854e012017-05-17 20:42:48 +0200805 num_add_fds = 0;
806 SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
807 if (num_add_fds > 32) {
808 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
809 return;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000810 }
Emeric Brun3854e012017-05-17 20:42:48 +0200811
812 /* We activate the polling for all known async fds */
813 SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000814 for (i=0 ; i < num_add_fds ; i++) {
Emeric Brun3854e012017-05-17 20:42:48 +0200815 fd_want_recv(add_fd[i]);
Emeric Brunce9e01c2017-05-31 10:02:53 +0000816 /* To ensure that the fd cache won't be used
817 * We'll prefer to catch a real RD event
818 * because handling an EAGAIN on this fd will
819 * result in a context switch and also
820 * some engines uses a fd in blocking mode.
821 */
822 fd_cant_recv(add_fd[i]);
823 }
Emeric Brun3854e012017-05-17 20:42:48 +0200824
Grant Zhangfa6c7ee2017-01-14 01:42:15 +0000825}
826#endif
827
William Lallemand104a7a62019-10-14 14:14:59 +0200828#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200829/*
830 * This function returns the number of seconds elapsed
831 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
832 * date presented un ASN1_GENERALIZEDTIME.
833 *
834 * In parsing error case, it returns -1.
835 */
836static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
837{
838 long epoch;
839 char *p, *end;
840 const unsigned short month_offset[12] = {
841 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
842 };
Remi Tricot-Le Breton1adb4392021-06-09 17:16:18 +0200843 unsigned long year, month;
Emeric Brun4f3c87a2014-06-20 15:46:13 +0200844
845 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
846
847 p = (char *)d->data;
848 end = p + d->length;
849
850 if (end - p < 4) return -1;
851 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
852 p += 4;
853 if (end - p < 2) return -1;
854 month = 10 * (p[0] - '0') + p[1] - '0';
855 if (month < 1 || month > 12) return -1;
856 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
857 We consider leap years and the current month (<marsh or not) */
858 epoch = ( ((year - 1970) * 365)
859 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
860 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
861 + month_offset[month-1]
862 ) * 24 * 60 * 60;
863 p += 2;
864 if (end - p < 2) return -1;
865 /* Add the number of seconds of completed days of current month */
866 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
867 p += 2;
868 if (end - p < 2) return -1;
869 /* Add the completed hours of the current day */
870 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
871 p += 2;
872 if (end - p < 2) return -1;
873 /* Add the completed minutes of the current hour */
874 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
875 p += 2;
876 if (p == end) return -1;
877 /* Test if there is available seconds */
878 if (p[0] < '0' || p[0] > '9')
879 goto nosec;
880 if (end - p < 2) return -1;
881 /* Add the seconds of the current minute */
882 epoch += 10 * (p[0] - '0') + p[1] - '0';
883 p += 2;
884 if (p == end) return -1;
885 /* Ignore seconds float part if present */
886 if (p[0] == '.') {
887 do {
888 if (++p == end) return -1;
889 } while (p[0] >= '0' && p[0] <= '9');
890 }
891
892nosec:
893 if (p[0] == 'Z') {
894 if (end - p != 1) return -1;
895 return epoch;
896 }
897 else if (p[0] == '+') {
898 if (end - p != 5) return -1;
899 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700900 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 +0200901 }
902 else if (p[0] == '-') {
903 if (end - p != 5) return -1;
904 /* Apply timezone offset */
Frederik Deweerdt953917a2017-10-16 07:37:31 -0700905 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 +0200906 }
907
908 return -1;
909}
910
William Lallemand104a7a62019-10-14 14:14:59 +0200911/*
912 * struct alignment works here such that the key.key is the same as key_data
913 * Do not change the placement of key_data
914 */
915struct certificate_ocsp {
916 struct ebmb_node key;
917 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
918 struct buffer response;
William Lallemand76b4a122020-08-04 17:41:39 +0200919 int refcount;
William Lallemand104a7a62019-10-14 14:14:59 +0200920 long expire;
921};
922
923struct ocsp_cbk_arg {
924 int is_single;
925 int single_kt;
926 union {
927 struct certificate_ocsp *s_ocsp;
928 /*
929 * m_ocsp will have multiple entries dependent on key type
930 * Entry 0 - DSA
931 * Entry 1 - ECDSA
932 * Entry 2 - RSA
933 */
934 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
935 };
936};
937
Emeric Brun1d3865b2014-06-20 15:37:32 +0200938static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200939
940/* This function starts to check if the OCSP response (in DER format) contained
941 * in chunk 'ocsp_response' is valid (else exits on error).
942 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
943 * contained in the OCSP Response and exits on error if no match.
944 * If it's a valid OCSP Response:
945 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
946 * pointed by 'ocsp'.
947 * If 'ocsp' is NULL, the function looks up into the OCSP response's
948 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
949 * from the response) and exits on error if not found. Finally, If an OCSP response is
950 * already present in the container, it will be overwritten.
951 *
952 * Note: OCSP response containing more than one OCSP Single response is not
953 * considered valid.
954 *
955 * Returns 0 on success, 1 in error case.
956 */
Willy Tarreau83061a82018-07-13 11:56:34 +0200957static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
958 struct certificate_ocsp *ocsp,
959 OCSP_CERTID *cid, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +0200960{
961 OCSP_RESPONSE *resp;
962 OCSP_BASICRESP *bs = NULL;
963 OCSP_SINGLERESP *sr;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +0200964 OCSP_CERTID *id;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200965 unsigned char *p = (unsigned char *) ocsp_response->area;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200966 int rc , count_sr;
Emeric Brun13a6b482014-06-20 15:44:34 +0200967 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +0200968 int reason;
969 int ret = 1;
970
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200971 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
972 ocsp_response->data);
Emeric Brun4147b2e2014-06-16 18:36:30 +0200973 if (!resp) {
974 memprintf(err, "Unable to parse OCSP response");
975 goto out;
976 }
977
978 rc = OCSP_response_status(resp);
979 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
980 memprintf(err, "OCSP response status not successful");
981 goto out;
982 }
983
984 bs = OCSP_response_get1_basic(resp);
985 if (!bs) {
986 memprintf(err, "Failed to get basic response from OCSP Response");
987 goto out;
988 }
989
990 count_sr = OCSP_resp_count(bs);
991 if (count_sr > 1) {
992 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
993 goto out;
994 }
995
996 sr = OCSP_resp_get0(bs, 0);
997 if (!sr) {
998 memprintf(err, "Failed to get OCSP single response");
999 goto out;
1000 }
1001
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001002 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
1003
Emeric Brun4147b2e2014-06-16 18:36:30 +02001004 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
Emmanuel Hocdetef607052017-10-24 14:57:16 +02001005 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
Emmanuel Hocdet872085c2017-10-10 15:18:52 +02001006 memprintf(err, "OCSP single response: certificate status is unknown");
Emeric Brun4147b2e2014-06-16 18:36:30 +02001007 goto out;
1008 }
1009
Emeric Brun13a6b482014-06-20 15:44:34 +02001010 if (!nextupd) {
1011 memprintf(err, "OCSP single response: missing nextupdate");
1012 goto out;
1013 }
1014
Emeric Brunc8b27b62014-06-19 14:16:17 +02001015 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001016 if (!rc) {
1017 memprintf(err, "OCSP single response: no longer valid.");
1018 goto out;
1019 }
1020
1021 if (cid) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001022 if (OCSP_id_cmp(id, cid)) {
Emeric Brun4147b2e2014-06-16 18:36:30 +02001023 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
1024 goto out;
1025 }
1026 }
1027
1028 if (!ocsp) {
1029 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
1030 unsigned char *p;
1031
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001032 rc = i2d_OCSP_CERTID(id, NULL);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001033 if (!rc) {
1034 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
1035 goto out;
1036 }
1037
1038 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
1039 memprintf(err, "OCSP single response: Certificate ID too long");
1040 goto out;
1041 }
1042
1043 p = key;
1044 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001045 i2d_OCSP_CERTID(id, &p);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001046 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
1047 if (!ocsp) {
1048 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
1049 goto out;
1050 }
1051 }
1052
1053 /* According to comments on "chunk_dup", the
1054 previous chunk buffer will be freed */
1055 if (!chunk_dup(&ocsp->response, ocsp_response)) {
1056 memprintf(err, "OCSP response: Memory allocation error");
1057 goto out;
1058 }
1059
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001060 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
Remi Tricot-Le Breton1adb4392021-06-09 17:16:18 +02001061 if (ocsp->expire < 0) {
1062 memprintf(err, "OCSP single response: Invalid \"Next Update\" time");
1063 goto out;
1064 }
Emeric Brun4f3c87a2014-06-20 15:46:13 +02001065
Emeric Brun4147b2e2014-06-16 18:36:30 +02001066 ret = 0;
1067out:
Janusz Dziemidowicz8d710492017-03-08 16:59:41 +01001068 ERR_clear_error();
1069
Emeric Brun4147b2e2014-06-16 18:36:30 +02001070 if (bs)
1071 OCSP_BASICRESP_free(bs);
1072
1073 if (resp)
1074 OCSP_RESPONSE_free(resp);
1075
1076 return ret;
1077}
1078/*
1079 * External function use to update the OCSP response in the OCSP response's
1080 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
1081 * to update in DER format.
1082 *
1083 * Returns 0 on success, 1 in error case.
1084 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001085int ssl_sock_update_ocsp_response(struct buffer *ocsp_response, char **err)
Emeric Brun4147b2e2014-06-16 18:36:30 +02001086{
1087 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
1088}
1089
William Lallemand4a660132019-10-14 14:51:41 +02001090#endif
1091
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001092#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
1093static int ssl_tlsext_ticket_key_cb(SSL *s, unsigned char key_name[16], unsigned char *iv, EVP_CIPHER_CTX *ectx, HMAC_CTX *hctx, int enc)
1094{
Christopher Faulet16f45c82018-02-16 11:23:49 +01001095 struct tls_keys_ref *ref;
Emeric Brun9e754772019-01-10 17:51:55 +01001096 union tls_sess_key *keys;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001097 struct connection *conn;
1098 int head;
1099 int i;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001100 int ret = -1; /* error by default */
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001101
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001102 conn = SSL_get_ex_data(s, ssl_app_data_index);
Willy Tarreau07d94e42018-09-20 10:57:52 +02001103 ref = __objt_listener(conn->target)->bind_conf->keys_ref;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001104 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1105
1106 keys = ref->tlskeys;
1107 head = ref->tls_ticket_enc_index;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001108
1109 if (enc) {
1110 memcpy(key_name, keys[head].name, 16);
1111
1112 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
Christopher Faulet16f45c82018-02-16 11:23:49 +01001113 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001114
Emeric Brun9e754772019-01-10 17:51:55 +01001115 if (ref->key_size_bits == 128) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001116
Emeric Brun9e754772019-01-10 17:51:55 +01001117 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].key_128.aes_key, iv))
1118 goto end;
1119
Willy Tarreau9356dac2019-05-10 09:22:53 +02001120 HMAC_Init_ex(hctx, keys[head].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001121 ret = 1;
1122 }
1123 else if (ref->key_size_bits == 256 ) {
1124
1125 if(!EVP_EncryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[head].key_256.aes_key, iv))
1126 goto end;
1127
Willy Tarreau9356dac2019-05-10 09:22:53 +02001128 HMAC_Init_ex(hctx, keys[head].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001129 ret = 1;
1130 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001131 } else {
1132 for (i = 0; i < TLS_TICKETS_NO; i++) {
1133 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
1134 goto found;
1135 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01001136 ret = 0;
1137 goto end;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001138
Christopher Faulet16f45c82018-02-16 11:23:49 +01001139 found:
Emeric Brun9e754772019-01-10 17:51:55 +01001140 if (ref->key_size_bits == 128) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001141 HMAC_Init_ex(hctx, keys[(head + i) % TLS_TICKETS_NO].key_128.hmac_key, 16, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001142 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_128.aes_key, iv))
1143 goto end;
1144 /* 2 for key renewal, 1 if current key is still valid */
1145 ret = i ? 2 : 1;
1146 }
1147 else if (ref->key_size_bits == 256) {
Willy Tarreau9356dac2019-05-10 09:22:53 +02001148 HMAC_Init_ex(hctx, keys[(head + i) % TLS_TICKETS_NO].key_256.hmac_key, 32, TLS_TICKET_HASH_FUNCT(), NULL);
Emeric Brun9e754772019-01-10 17:51:55 +01001149 if(!EVP_DecryptInit_ex(ectx, EVP_aes_256_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].key_256.aes_key, iv))
1150 goto end;
1151 /* 2 for key renewal, 1 if current key is still valid */
1152 ret = i ? 2 : 1;
1153 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001154 }
Emeric Brun9e754772019-01-10 17:51:55 +01001155
Christopher Faulet16f45c82018-02-16 11:23:49 +01001156 end:
1157 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
1158 return ret;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001159}
1160
1161struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
1162{
1163 struct tls_keys_ref *ref;
1164
1165 list_for_each_entry(ref, &tlskeys_reference, list)
1166 if (ref->filename && strcmp(filename, ref->filename) == 0)
1167 return ref;
1168 return NULL;
1169}
1170
1171struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
1172{
1173 struct tls_keys_ref *ref;
1174
1175 list_for_each_entry(ref, &tlskeys_reference, list)
1176 if (ref->unique_id == unique_id)
1177 return ref;
1178 return NULL;
1179}
1180
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001181/* Update the key into ref: if keysize doesn't
Emeric Brun9e754772019-01-10 17:51:55 +01001182 * match existing ones, this function returns -1
1183 * else it returns 0 on success.
1184 */
1185int ssl_sock_update_tlskey_ref(struct tls_keys_ref *ref,
Willy Tarreau83061a82018-07-13 11:56:34 +02001186 struct buffer *tlskey)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001187{
Emeric Brun9e754772019-01-10 17:51:55 +01001188 if (ref->key_size_bits == 128) {
1189 if (tlskey->data != sizeof(struct tls_sess_key_128))
1190 return -1;
1191 }
1192 else if (ref->key_size_bits == 256) {
1193 if (tlskey->data != sizeof(struct tls_sess_key_256))
1194 return -1;
1195 }
1196 else
1197 return -1;
1198
Christopher Faulet16f45c82018-02-16 11:23:49 +01001199 HA_RWLOCK_WRLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001200 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)),
1201 tlskey->area, tlskey->data);
Christopher Faulet16f45c82018-02-16 11:23:49 +01001202 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
1203 HA_RWLOCK_WRUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Emeric Brun9e754772019-01-10 17:51:55 +01001204
1205 return 0;
Christopher Faulet16f45c82018-02-16 11:23:49 +01001206}
1207
Willy Tarreau83061a82018-07-13 11:56:34 +02001208int ssl_sock_update_tlskey(char *filename, struct buffer *tlskey, char **err)
Christopher Faulet16f45c82018-02-16 11:23:49 +01001209{
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001210 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
1211
1212 if(!ref) {
1213 memprintf(err, "Unable to locate the referenced filename: %s", filename);
1214 return 1;
1215 }
Emeric Brun9e754772019-01-10 17:51:55 +01001216 if (ssl_sock_update_tlskey_ref(ref, tlskey) < 0) {
1217 memprintf(err, "Invalid key size");
1218 return 1;
1219 }
1220
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001221 return 0;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001222}
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001223
1224/* This function finalize the configuration parsing. Its set all the
Willy Tarreaud1c57502016-12-22 22:46:15 +01001225 * automatic ids. It's called just after the basic checks. It returns
1226 * 0 on success otherwise ERR_*.
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001227 */
Willy Tarreaud1c57502016-12-22 22:46:15 +01001228static int tlskeys_finalize_config(void)
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001229{
1230 int i = 0;
1231 struct tls_keys_ref *ref, *ref2, *ref3;
1232 struct list tkr = LIST_HEAD_INIT(tkr);
1233
1234 list_for_each_entry(ref, &tlskeys_reference, list) {
1235 if (ref->unique_id == -1) {
1236 /* Look for the first free id. */
1237 while (1) {
1238 list_for_each_entry(ref2, &tlskeys_reference, list) {
1239 if (ref2->unique_id == i) {
1240 i++;
1241 break;
1242 }
1243 }
1244 if (&ref2->list == &tlskeys_reference)
1245 break;
1246 }
1247
1248 /* Uses the unique id and increment it for the next entry. */
1249 ref->unique_id = i;
1250 i++;
1251 }
1252 }
1253
1254 /* This sort the reference list by id. */
1255 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001256 LIST_DELETE(&ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001257 list_for_each_entry(ref3, &tkr, list) {
1258 if (ref->unique_id < ref3->unique_id) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001259 LIST_APPEND(&ref3->list, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001260 break;
1261 }
1262 }
1263 if (&ref3->list == &tkr)
Willy Tarreau2b718102021-04-21 07:32:39 +02001264 LIST_APPEND(&tkr, &ref->list);
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001265 }
1266
1267 /* swap root */
William Lallemand1ffc3782023-05-09 14:15:57 +02001268 LIST_SPLICE(&tlskeys_reference, &tkr);
Christopher Fauletfc633b62020-11-06 15:24:23 +01001269 return ERR_NONE;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001270}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001271#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1272
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001273#ifndef OPENSSL_NO_OCSP
William Lallemand76b4a122020-08-04 17:41:39 +02001274int ocsp_ex_index = -1;
1275
yanbzhube2774d2015-12-10 15:07:30 -05001276int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1277{
1278 switch (evp_keytype) {
1279 case EVP_PKEY_RSA:
1280 return 2;
1281 case EVP_PKEY_DSA:
1282 return 0;
1283 case EVP_PKEY_EC:
1284 return 1;
1285 }
1286
1287 return -1;
1288}
1289
Emeric Brun4147b2e2014-06-16 18:36:30 +02001290/*
1291 * Callback used to set OCSP status extension content in server hello.
1292 */
1293int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1294{
yanbzhube2774d2015-12-10 15:07:30 -05001295 struct certificate_ocsp *ocsp;
1296 struct ocsp_cbk_arg *ocsp_arg;
1297 char *ssl_buf;
William Lallemand76b4a122020-08-04 17:41:39 +02001298 SSL_CTX *ctx;
yanbzhube2774d2015-12-10 15:07:30 -05001299 EVP_PKEY *ssl_pkey;
1300 int key_type;
1301 int index;
1302
William Lallemand76b4a122020-08-04 17:41:39 +02001303 ctx = SSL_get_SSL_CTX(ssl);
1304 if (!ctx)
1305 return SSL_TLSEXT_ERR_NOACK;
1306
1307 ocsp_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
1308 if (!ocsp_arg)
1309 return SSL_TLSEXT_ERR_NOACK;
yanbzhube2774d2015-12-10 15:07:30 -05001310
1311 ssl_pkey = SSL_get_privatekey(ssl);
1312 if (!ssl_pkey)
1313 return SSL_TLSEXT_ERR_NOACK;
1314
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001315 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001316
1317 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1318 ocsp = ocsp_arg->s_ocsp;
1319 else {
1320 /* For multiple certs per context, we have to find the correct OCSP response based on
1321 * the certificate type
1322 */
1323 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1324
1325 if (index < 0)
1326 return SSL_TLSEXT_ERR_NOACK;
1327
1328 ocsp = ocsp_arg->m_ocsp[index];
1329
1330 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001331
1332 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001333 !ocsp->response.area ||
1334 !ocsp->response.data ||
Remi Tricot-Le Bretonc5eaae92023-03-02 15:49:55 +01001335 (ocsp->expire < date.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001336 return SSL_TLSEXT_ERR_NOACK;
1337
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001338 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001339 if (!ssl_buf)
1340 return SSL_TLSEXT_ERR_NOACK;
1341
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001342 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
1343 SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001344
1345 return SSL_TLSEXT_ERR_OK;
1346}
1347
William Lallemand4a660132019-10-14 14:51:41 +02001348#endif
1349
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001350#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
William Lallemand76b4a122020-08-04 17:41:39 +02001351
1352
1353/*
1354 * Decrease the refcount of the struct ocsp_response and frees it if it's not
1355 * used anymore. Also removes it from the tree if free'd.
1356 */
1357static void ssl_sock_free_ocsp(struct certificate_ocsp *ocsp)
1358{
1359 if (!ocsp)
1360 return;
1361
1362 ocsp->refcount--;
1363 if (ocsp->refcount <= 0) {
1364 ebmb_delete(&ocsp->key);
1365 chunk_destroy(&ocsp->response);
1366 free(ocsp);
1367 }
1368}
1369
1370
Emeric Brun4147b2e2014-06-16 18:36:30 +02001371/*
1372 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001373 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1374 * status extension, the issuer's certificate is mandatory. It should be
1375 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001376 *
William Lallemand246c0242019-10-11 08:59:13 +02001377 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1378 * OCSP response. If file is empty or content is not a valid OCSP response,
1379 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1380 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001381 *
1382 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001383 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001384 */
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001385static 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 +02001386{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001387 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001388 OCSP_CERTID *cid = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001389 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001390 struct certificate_ocsp *ocsp = NULL, *iocsp;
1391 char *warn = NULL;
1392 unsigned char *p;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001393 void (*callback) (void);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001394
Emeric Brun4147b2e2014-06-16 18:36:30 +02001395
William Lallemand246c0242019-10-11 08:59:13 +02001396 x = ckch->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001397 if (!x)
1398 goto out;
1399
William Lallemand246c0242019-10-11 08:59:13 +02001400 issuer = ckch->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001401 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1402 if (chain) {
1403 /* check if one of the certificate of the chain is the issuer */
1404 for (i = 0; i < sk_X509_num(chain); i++) {
1405 X509 *ti = sk_X509_value(chain, i);
1406 if (X509_check_issued(ti, x) == X509_V_OK) {
1407 issuer = ti;
1408 break;
1409 }
1410 }
1411 }
William Lallemand246c0242019-10-11 08:59:13 +02001412 if (!issuer)
1413 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001414
1415 cid = OCSP_cert_to_id(0, x, issuer);
1416 if (!cid)
1417 goto out;
1418
1419 i = i2d_OCSP_CERTID(cid, NULL);
1420 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1421 goto out;
1422
Vincent Bernat02779b62016-04-03 13:48:43 +02001423 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001424 if (!ocsp)
1425 goto out;
1426
1427 p = ocsp->key_data;
1428 i2d_OCSP_CERTID(cid, &p);
1429
1430 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1431 if (iocsp == ocsp)
1432 ocsp = NULL;
1433
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001434#ifndef SSL_CTX_get_tlsext_status_cb
1435# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1436 *cb = (void (*) (void))ctx->tlsext_status_cb;
1437#endif
1438 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1439
1440 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001441 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001442 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001443
William Lallemanda560c062020-07-31 11:43:20 +02001444 cb_arg = calloc(1, sizeof(*cb_arg));
1445 if (!cb_arg)
1446 goto out;
1447
yanbzhube2774d2015-12-10 15:07:30 -05001448 cb_arg->is_single = 1;
1449 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001450 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001451
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001452 pkey = X509_get_pubkey(x);
1453 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1454 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001455
1456 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001457 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 */
1458
yanbzhube2774d2015-12-10 15:07:30 -05001459 } else {
1460 /*
1461 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1462 * Update that cb_arg with the new cert's staple
1463 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001464 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001465 struct certificate_ocsp *tmp_ocsp;
1466 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001467 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001468 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001469
William Lallemand76b4a122020-08-04 17:41:39 +02001470 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001471
1472 /*
1473 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1474 * the order of operations below matter, take care when changing it
1475 */
1476 tmp_ocsp = cb_arg->s_ocsp;
1477 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1478 cb_arg->s_ocsp = NULL;
1479 cb_arg->m_ocsp[index] = tmp_ocsp;
1480 cb_arg->is_single = 0;
1481 cb_arg->single_kt = 0;
1482
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001483 pkey = X509_get_pubkey(x);
1484 key_type = EVP_PKEY_base_id(pkey);
1485 EVP_PKEY_free(pkey);
1486
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001487 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001488 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001489 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001490 iocsp->refcount++;
1491 }
yanbzhube2774d2015-12-10 15:07:30 -05001492 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001493
1494 ret = 0;
1495
1496 warn = NULL;
William Lallemand86e4d632020-08-07 00:44:32 +02001497 if (ssl_sock_load_ocsp_response(ckch->ocsp_response, iocsp, cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001498 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001499 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001500 }
1501
1502out:
Emeric Brun4147b2e2014-06-16 18:36:30 +02001503 if (cid)
1504 OCSP_CERTID_free(cid);
1505
1506 if (ocsp)
Remi Tricot-Le Breton15838972022-11-03 15:16:49 +01001507 ssl_sock_free_ocsp(ocsp);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001508
1509 if (warn)
1510 free(warn);
1511
Emeric Brun4147b2e2014-06-16 18:36:30 +02001512 return ret;
1513}
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001514#endif
1515
1516#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001517static 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 +02001518{
William Lallemand4a660132019-10-14 14:51:41 +02001519 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 +02001520}
1521#endif
1522
William Lallemand4a660132019-10-14 14:51:41 +02001523
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001524#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001525
1526#define CT_EXTENSION_TYPE 18
1527
William Lallemand03c331c2020-05-13 10:10:01 +02001528int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001529
1530int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1531{
Willy Tarreau83061a82018-07-13 11:56:34 +02001532 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001533
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001534 *out = (unsigned char *) sctl->area;
1535 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001536
1537 return 1;
1538}
1539
1540int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1541{
1542 return 1;
1543}
1544
William Lallemanda17f4112019-10-10 15:16:44 +02001545static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001546{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001547 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001548
William Lallemanda17f4112019-10-10 15:16:44 +02001549 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 +01001550 goto out;
1551
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001552 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1553
1554 ret = 0;
1555
1556out:
1557 return ret;
1558}
1559
1560#endif
1561
Emeric Brune1f38db2012-09-03 20:36:47 +02001562void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1563{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001564 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001565 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001566 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001567 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001568
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001569#ifndef SSL_OP_NO_RENEGOTIATION
1570 /* Please note that BoringSSL defines this macro to zero so don't
1571 * change this to #if and do not assign a default value to this macro!
1572 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001573 if (where & SSL_CB_HANDSHAKE_START) {
1574 /* Disable renegotiation (CVE-2009-3555) */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01001575 if ((conn->flags & (CO_FL_WAIT_L6_CONN | CO_FL_EARLY_SSL_HS | CO_FL_EARLY_DATA)) == 0) {
Emeric Brune1f38db2012-09-03 20:36:47 +02001576 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001577 conn->err_code = CO_ER_SSL_RENEG;
1578 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001579 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001580#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001581
1582 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001583 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001584 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001585 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001586 consider that the buffering was activated,
1587 so we rise the output buffer size from 4k
1588 to 16k */
1589 write_bio = SSL_get_wbio(ssl);
1590 if (write_bio != SSL_get_rbio(ssl)) {
1591 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001592 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001593 }
1594 }
1595 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001596}
1597
Emeric Brune64aef12012-09-21 13:15:06 +02001598/* Callback is called for each certificate of the chain during a verify
1599 ok is set to 1 if preverify detect no error on current certificate.
1600 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001601int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001602{
1603 SSL *ssl;
1604 struct connection *conn;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001605 struct ssl_sock_ctx *ctx;
Emeric Brun81c00f02012-09-21 14:31:21 +02001606 int err, depth;
Emeric Brune64aef12012-09-21 13:15:06 +02001607
1608 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001609 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001610
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001611 ctx = conn->xprt_ctx;
1612
1613 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001614
Emeric Brun81c00f02012-09-21 14:31:21 +02001615 if (ok) /* no errors */
1616 return ok;
1617
1618 depth = X509_STORE_CTX_get_error_depth(x_store);
1619 err = X509_STORE_CTX_get_error(x_store);
1620
1621 /* check if CA error needs to be ignored */
1622 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001623 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1624 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1625 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001626 }
1627
Remi Tricot-Le Breton99e45262022-11-10 10:48:58 +01001628 if (err <= SSL_MAX_VFY_ERROR_CODE &&
1629 cert_ignerr_bitfield_get(__objt_listener(conn->target)->bind_conf->ca_ignerr_bitfield, err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001630 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001631 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001632 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001633 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001634
Willy Tarreau20879a02012-12-03 16:32:10 +01001635 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001636 return 0;
1637 }
1638
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001639 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1640 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001641
Emeric Brun81c00f02012-09-21 14:31:21 +02001642 /* check if certificate error needs to be ignored */
Remi Tricot-Le Breton99e45262022-11-10 10:48:58 +01001643 if (err <= SSL_MAX_VFY_ERROR_CODE &&
1644 cert_ignerr_bitfield_get(__objt_listener(conn->target)->bind_conf->crt_ignerr_bitfield, err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001645 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001646 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001647 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001648 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001649
Willy Tarreau20879a02012-12-03 16:32:10 +01001650 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001651 return 0;
Emeric Brune64aef12012-09-21 13:15:06 +02001652}
1653
Dragan Dosen9ac98092020-05-11 15:51:45 +02001654#ifdef TLS1_RT_HEARTBEAT
1655static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1656 int content_type, const void *buf, size_t len,
1657 SSL *ssl)
1658{
1659 /* test heartbeat received (write_p is set to 0
1660 for a received record) */
1661 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
1662 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
1663 const unsigned char *p = buf;
1664 unsigned int payload;
1665
1666 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1667
1668 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1669 if (*p != TLS1_HB_REQUEST)
1670 return;
1671
1672 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1673 goto kill_it;
1674
1675 payload = (p[1] * 256) + p[2];
1676 if (3 + payload + 16 <= len)
1677 return; /* OK no problem */
1678 kill_it:
1679 /* We have a clear heartbleed attack (CVE-2014-0160), the
1680 * advertised payload is larger than the advertised packet
1681 * length, so we have garbage in the buffer between the
1682 * payload and the end of the buffer (p+len). We can't know
1683 * if the SSL stack is patched, and we don't know if we can
1684 * safely wipe out the area between p+3+len and payload.
1685 * So instead, we prevent the response from being sent by
1686 * setting the max_send_fragment to 0 and we report an SSL
1687 * error, which will kill this connection. It will be reported
1688 * above as SSL_ERROR_SSL while an other handshake failure with
1689 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1690 */
1691 ssl->max_send_fragment = 0;
1692 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1693 }
1694}
1695#endif
1696
1697static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1698 int content_type, const void *buf, size_t len,
1699 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001700{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001701 struct ssl_capture *capture;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001702 unsigned char *msg;
1703 unsigned char *end;
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001704 size_t rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001705
1706 /* This function is called for "from client" and "to server"
1707 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001708 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001709 */
1710
1711 /* "write_p" is set to 0 is the bytes are received messages,
1712 * otherwise it is set to 1.
1713 */
1714 if (write_p != 0)
1715 return;
1716
1717 /* content_type contains the type of message received or sent
1718 * according with the SSL/TLS protocol spec. This message is
1719 * encoded with one byte. The value 256 (two bytes) is used
1720 * for designing the SSL/TLS record layer. According with the
1721 * rfc6101, the expected message (other than 256) are:
1722 * - change_cipher_spec(20)
1723 * - alert(21)
1724 * - handshake(22)
1725 * - application_data(23)
1726 * - (255)
1727 * We are interessed by the handshake and specially the client
1728 * hello.
1729 */
1730 if (content_type != 22)
1731 return;
1732
1733 /* The message length is at least 4 bytes, containing the
1734 * message type and the message length.
1735 */
1736 if (len < 4)
1737 return;
1738
1739 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001740 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001741 * - hello_request(0)
1742 * - client_hello(1)
1743 * - server_hello(2)
1744 * - certificate(11)
1745 * - server_key_exchange (12)
1746 * - certificate_request(13)
1747 * - server_hello_done(14)
1748 * We are interested by the client hello.
1749 */
1750 msg = (unsigned char *)buf;
1751 if (msg[0] != 1)
1752 return;
1753
1754 /* Next three bytes are the length of the message. The total length
1755 * must be this decoded length + 4. If the length given as argument
1756 * is not the same, we abort the protocol dissector.
1757 */
1758 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1759 if (len < rec_len + 4)
1760 return;
1761 msg += 4;
1762 end = msg + rec_len;
1763 if (end < msg)
1764 return;
1765
1766 /* Expect 2 bytes for protocol version (1 byte for major and 1 byte
1767 * for minor, the random, composed by 4 bytes for the unix time and
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001768 * 28 bytes for unix payload. So we jump 1 + 1 + 4 + 28.
1769 */
1770 msg += 1 + 1 + 4 + 28;
1771 if (msg > end)
1772 return;
1773
1774 /* Next, is session id:
1775 * if present, we have to jump by length + 1 for the size information
1776 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001777 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001778 if (msg[0] > 0)
1779 msg += msg[0];
1780 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001781 if (msg > end)
1782 return;
1783
1784 /* Next two bytes are the ciphersuite length. */
1785 if (msg + 2 > end)
1786 return;
1787 rec_len = (msg[0] << 8) + msg[1];
1788 msg += 2;
1789 if (msg + rec_len > end || msg + rec_len < msg)
1790 return;
1791
Willy Tarreaub454e902021-03-22 15:09:41 +01001792 capture = pool_alloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001793 if (!capture)
1794 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001795 /* Compute the xxh64 of the ciphersuite. */
1796 capture->xxh64 = XXH64(msg, rec_len, 0);
1797
1798 /* Capture the ciphersuite. */
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001799 capture->ciphersuite_len = (global_ssl.capture_cipherlist < rec_len) ?
1800 global_ssl.capture_cipherlist : rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001801 memcpy(capture->ciphersuite, msg, capture->ciphersuite_len);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001802
1803 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001804}
William Lallemand7d42ef52020-07-06 11:41:30 +02001805
1806
William Lallemandca5cf0a2021-06-09 16:46:12 +02001807#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001808static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1809 int content_type, const void *buf, size_t len,
1810 SSL *ssl)
1811{
1812 struct ssl_keylog *keylog;
1813
1814 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1815 return;
1816
Willy Tarreauf208ac02021-03-22 21:10:12 +01001817 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02001818 if (!keylog)
1819 return;
1820
William Lallemand7d42ef52020-07-06 11:41:30 +02001821 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
1822 pool_free(pool_head_ssl_keylog, keylog);
1823 return;
1824 }
1825}
1826#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001827
Emeric Brun29f037d2014-04-25 19:05:36 +02001828/* Callback is called for ssl protocol analyse */
1829void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1830{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001831 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1832 struct ssl_sock_msg_callback *cbk;
1833
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001834 /* Try to call all callback functions that were registered by using
1835 * ssl_sock_register_msg_callback().
1836 */
1837 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1838 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1839 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001840}
1841
Bernard Spil13c53f82018-02-15 13:34:58 +01001842#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001843static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1844 const unsigned char *in, unsigned int inlen,
1845 void *arg)
1846{
1847 struct server *srv = arg;
1848
1849 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1850 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1851 return SSL_TLSEXT_ERR_OK;
1852 return SSL_TLSEXT_ERR_NOACK;
1853}
1854#endif
1855
1856#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001857/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001858 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001859 */
1860static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1861 unsigned int *len, void *arg)
1862{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001863 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001864
1865 *data = (const unsigned char *)conf->npn_str;
1866 *len = conf->npn_len;
1867 return SSL_TLSEXT_ERR_OK;
1868}
1869#endif
1870
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001871#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001872/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001873 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001874 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001875static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1876 unsigned char *outlen,
1877 const unsigned char *server,
1878 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001879{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001880 struct ssl_bind_conf *conf = arg;
Willy Tarreauab861d32013-04-02 02:30:41 +02001881
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001882 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1883 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
1884 return SSL_TLSEXT_ERR_NOACK;
1885 }
Willy Tarreauab861d32013-04-02 02:30:41 +02001886 return SSL_TLSEXT_ERR_OK;
1887}
1888#endif
1889
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001890#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001891#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001892
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001893/* Configure a DNS SAN extenion on a certificate. */
1894int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
1895 int failure = 0;
1896 X509_EXTENSION *san_ext = NULL;
1897 CONF *conf = NULL;
1898 struct buffer *san_name = get_trash_chunk();
1899
1900 conf = NCONF_new(NULL);
1901 if (!conf) {
1902 failure = 1;
1903 goto cleanup;
1904 }
1905
1906 /* Build an extension based on the DNS entry above */
1907 chunk_appendf(san_name, "DNS:%s", servername);
1908 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
1909 if (!san_ext) {
1910 failure = 1;
1911 goto cleanup;
1912 }
1913
1914 /* Add the extension */
1915 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
1916 failure = 1;
1917 goto cleanup;
1918 }
1919
1920 /* Success */
1921 failure = 0;
1922
1923cleanup:
1924 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
1925 if (NULL != conf) NCONF_free(conf);
1926
1927 return failure;
1928}
1929
Christopher Faulet30548802015-06-11 13:39:32 +02001930/* Create a X509 certificate with the specified servername and serial. This
1931 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001932static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001933ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001934{
Shimi Gersner5846c492020-08-23 13:58:12 +03001935 X509 *cacert = bind_conf->ca_sign_ckch->cert;
1936 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001937 SSL_CTX *ssl_ctx = NULL;
1938 X509 *newcrt = NULL;
1939 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001940 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001941 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001942 X509_NAME *name;
1943 const EVP_MD *digest;
1944 X509V3_CTX ctx;
1945 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001946 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001947
Christopher Faulet48a83322017-07-28 16:56:09 +02001948 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05001949#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001950 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1951#else
1952 tmp_ssl = SSL_new(bind_conf->default_ctx);
1953 if (tmp_ssl)
1954 pkey = SSL_get_privatekey(tmp_ssl);
1955#endif
1956 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001957 goto mkcert_error;
1958
1959 /* Create the certificate */
1960 if (!(newcrt = X509_new()))
1961 goto mkcert_error;
1962
1963 /* Set version number for the certificate (X509v3) and the serial
1964 * number */
1965 if (X509_set_version(newcrt, 2L) != 1)
1966 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02001967 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001968
1969 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001970 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1971 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001972 goto mkcert_error;
1973
1974 /* set public key in the certificate */
1975 if (X509_set_pubkey(newcrt, pkey) != 1)
1976 goto mkcert_error;
1977
1978 /* Set issuer name from the CA */
1979 if (!(name = X509_get_subject_name(cacert)))
1980 goto mkcert_error;
1981 if (X509_set_issuer_name(newcrt, name) != 1)
1982 goto mkcert_error;
1983
1984 /* Set the subject name using the same, but the CN */
1985 name = X509_NAME_dup(name);
1986 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1987 (const unsigned char *)servername,
1988 -1, -1, 0) != 1) {
1989 X509_NAME_free(name);
1990 goto mkcert_error;
1991 }
1992 if (X509_set_subject_name(newcrt, name) != 1) {
1993 X509_NAME_free(name);
1994 goto mkcert_error;
1995 }
1996 X509_NAME_free(name);
1997
1998 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001999 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002000 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
2001 for (i = 0; i < X509V3_EXT_SIZE; i++) {
2002 X509_EXTENSION *ext;
2003
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002004 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02002005 goto mkcert_error;
2006 if (!X509_add_ext(newcrt, ext, -1)) {
2007 X509_EXTENSION_free(ext);
2008 goto mkcert_error;
2009 }
2010 X509_EXTENSION_free(ext);
2011 }
2012
Shimi Gersneradabbfe2020-08-23 13:58:13 +03002013 /* Add SAN extension */
2014 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
2015 goto mkcert_error;
2016 }
2017
Christopher Faulet31af49d2015-06-09 17:29:50 +02002018 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002019
2020 key_type = EVP_PKEY_base_id(capkey);
2021
2022 if (key_type == EVP_PKEY_DSA)
2023 digest = EVP_sha1();
2024 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002025 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002026 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02002027 digest = EVP_sha256();
2028 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05002029#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02002030 int nid;
2031
2032 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
2033 goto mkcert_error;
2034 if (!(digest = EVP_get_digestbynid(nid)))
2035 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02002036#else
2037 goto mkcert_error;
2038#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02002039 }
2040
Christopher Faulet31af49d2015-06-09 17:29:50 +02002041 if (!(X509_sign(newcrt, capkey, digest)))
2042 goto mkcert_error;
2043
2044 /* Create and set the new SSL_CTX */
2045 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
2046 goto mkcert_error;
2047 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
2048 goto mkcert_error;
2049 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
2050 goto mkcert_error;
2051 if (!SSL_CTX_check_private_key(ssl_ctx))
2052 goto mkcert_error;
2053
Shimi Gersner5846c492020-08-23 13:58:12 +03002054 /* Build chaining the CA cert and the rest of the chain, keep these order */
2055#if defined(SSL_CTX_add1_chain_cert)
2056 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
2057 goto mkcert_error;
2058 }
2059
2060 if (bind_conf->ca_sign_ckch->chain) {
2061 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2062 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2063 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2064 goto mkcert_error;
2065 }
2066 }
2067 }
2068#endif
2069
Christopher Faulet31af49d2015-06-09 17:29:50 +02002070 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002071
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002072#ifndef OPENSSL_NO_DH
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002073 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh);
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002074#endif
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002075#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2076 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002077 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002078 EC_KEY *ecc;
2079 int nid;
2080
2081 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2082 goto end;
2083 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2084 goto end;
2085 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2086 EC_KEY_free(ecc);
2087 }
2088#endif
2089 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002090 return ssl_ctx;
2091
2092 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002093 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002094 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002095 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2096 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002097 return NULL;
2098}
2099
Christopher Faulet7969a332015-10-09 11:15:03 +02002100SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002101ssl_sock_create_cert(struct connection *conn, const char *servername, unsigned int key)
Christopher Faulet7969a332015-10-09 11:15:03 +02002102{
Willy Tarreau07d94e42018-09-20 10:57:52 +02002103 struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
Olivier Houchard66ab4982019-02-26 18:37:15 +01002104 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002105
Olivier Houchard66ab4982019-02-26 18:37:15 +01002106 return ssl_sock_do_create_cert(servername, bind_conf, ctx->ssl);
Christopher Faulet7969a332015-10-09 11:15:03 +02002107}
2108
Christopher Faulet30548802015-06-11 13:39:32 +02002109/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002110 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002111SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002112ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002113{
2114 struct lru64 *lru = NULL;
2115
2116 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002117 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002118 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002119 if (lru && lru->domain) {
2120 if (ssl)
2121 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002122 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002123 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002124 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002125 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002126 }
2127 return NULL;
2128}
2129
Emeric Brun821bb9b2017-06-15 16:37:39 +02002130/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2131 * function is not thread-safe, it should only be used to check if a certificate
2132 * exists in the lru cache (with no warranty it will not be removed by another
2133 * thread). It is kept for backward compatibility. */
2134SSL_CTX *
2135ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2136{
2137 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2138}
2139
Christopher Fauletd2cab922015-07-28 16:03:47 +02002140/* Set a certificate int the LRU cache used to store generated
2141 * certificate. Return 0 on success, otherwise -1 */
2142int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002143ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002144{
2145 struct lru64 *lru = NULL;
2146
2147 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002148 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002149 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002150 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002151 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002152 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002153 }
Christopher Faulet30548802015-06-11 13:39:32 +02002154 if (lru->domain && lru->data)
2155 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002156 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002157 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002158 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002159 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002160 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002161}
2162
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002163/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002164unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002165ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002166{
2167 return XXH32(data, len, ssl_ctx_lru_seed);
2168}
2169
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002170/* Generate a cert and immediately assign it to the SSL session so that the cert's
2171 * refcount is maintained regardless of the cert's presence in the LRU cache.
2172 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002173static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002174ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002175{
Shimi Gersner5846c492020-08-23 13:58:12 +03002176 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002177 SSL_CTX *ssl_ctx = NULL;
2178 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002179 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002180
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002181 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002182 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002183 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002184 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002185 if (lru && lru->domain)
2186 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002187 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002188 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002189 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002190 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002191 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002192 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002193 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002194 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002195 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002196 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002197 SSL_set_SSL_CTX(ssl, ssl_ctx);
2198 /* No LRU cache, this CTX will be released as soon as the session dies */
2199 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002200 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002201 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002202 return 0;
2203}
2204static int
2205ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2206{
2207 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002208 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002209
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002210 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002211 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002212 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002213 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002214 }
2215 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002216}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002217#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002218
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002219#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002220
2221static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002222{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002223#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002224 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002225 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2226#endif
2227}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002228static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2229 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002230 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2231}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002232static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002233#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002234 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002235 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2236#endif
2237}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002238static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002239#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002240 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002241 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2242#endif
2243}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002244/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002245static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2246/* Unusable in this context. */
2247static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2248static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2249static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2250static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2251static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002252#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002253
2254static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2255 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002256 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2257}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002258static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2259 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2260 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2261}
2262static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2263 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002264 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2265}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002266static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2267 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2268 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2269}
2270static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2271 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002272 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2273}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002274static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2275 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2276 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2277}
2278static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2279 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002280 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2281}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002282static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2283 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2284 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2285}
2286static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
William Lallemande8a8aa42021-06-02 16:09:11 +02002287#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002288 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002289 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2290#endif
2291}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002292static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
William Lallemande8a8aa42021-06-02 16:09:11 +02002293#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002294 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2295 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002296#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002297}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002298#endif
2299static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2300static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002301
William Lallemand7fd8b452020-05-07 15:20:43 +02002302struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002303 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2304 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2305 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2306 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2307 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2308 {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 +02002309};
2310
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002311static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2312{
2313 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2314 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2315 SSL_set_SSL_CTX(ssl, ctx);
2316}
2317
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002318#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002319
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002320int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002321{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002322 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002323 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002324
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002325 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || s->generate_certs)
2326 return SSL_TLSEXT_ERR_OK;
2327 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002328}
2329
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002330#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002331int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002332{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002333 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002334#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002335int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002336{
2337#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002338 struct connection *conn;
2339 struct bind_conf *s;
2340 const uint8_t *extension_data;
2341 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002342 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002343
2344 char *wildp = NULL;
2345 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002346 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002347 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002348 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002349 int i;
2350
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002351 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreaua8825522018-10-15 13:20:07 +02002352 s = __objt_listener(conn->target)->bind_conf;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002353
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002354#ifdef USE_QUIC
2355 if (conn->qc) {
2356 /* Look for the QUIC transport parameters. */
2357#ifdef OPENSSL_IS_BORINGSSL
2358 if (!SSL_early_callback_ctx_extension_get(ctx, TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS,
2359 &extension_data, &extension_len))
2360#else
2361 if (!SSL_client_hello_get0_ext(ssl, TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS,
2362 &extension_data, &extension_len))
2363#endif
2364 goto abort;
2365
2366 if (!quic_transport_params_store(conn->qc, 0, extension_data,
2367 extension_data + extension_len))
2368 goto abort;
2369 }
2370#endif
2371
Olivier Houchard9679ac92017-10-27 14:58:08 +02002372 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002373 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002374#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002375 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2376 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002377#else
2378 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2379#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002380 /*
2381 * The server_name extension was given too much extensibility when it
2382 * was written, so parsing the normal case is a bit complex.
2383 */
2384 size_t len;
2385 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002386 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002387 /* Extract the length of the supplied list of names. */
2388 len = (*extension_data++) << 8;
2389 len |= *extension_data++;
2390 if (len + 2 != extension_len)
2391 goto abort;
2392 /*
2393 * The list in practice only has a single element, so we only consider
2394 * the first one.
2395 */
2396 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2397 goto abort;
2398 extension_len = len - 1;
2399 /* Now we can finally pull out the byte array with the actual hostname. */
2400 if (extension_len <= 2)
2401 goto abort;
2402 len = (*extension_data++) << 8;
2403 len |= *extension_data++;
2404 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2405 || memchr(extension_data, 0, len) != NULL)
2406 goto abort;
2407 servername = extension_data;
2408 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002409 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002410#if (!defined SSL_NO_GENERATE_CERTIFICATES)
2411 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002412 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002413 }
2414#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002415 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002416 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002417 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002418 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002419 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002420 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002421 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002422 goto abort;
2423 }
2424
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002425 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002426#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002427 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002428#else
2429 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2430#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002431 uint8_t sign;
2432 size_t len;
2433 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002434 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002435 len = (*extension_data++) << 8;
2436 len |= *extension_data++;
2437 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002438 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002439 if (len % 2 != 0)
2440 goto abort;
2441 for (; len > 0; len -= 2) {
2442 extension_data++; /* hash */
2443 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002444 switch (sign) {
2445 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002446 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002447 break;
2448 case TLSEXT_signature_ecdsa:
2449 has_ecdsa_sig = 1;
2450 break;
2451 default:
2452 continue;
2453 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002454 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002455 break;
2456 }
2457 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002458 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002459 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002460 }
2461 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002462 const SSL_CIPHER *cipher;
William Lallemand539bfaa2023-10-24 23:58:02 +02002463 uint32_t cipher_id;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002464 size_t len;
2465 const uint8_t *cipher_suites;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002466 has_ecdsa_sig = 0;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002467#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002468 len = ctx->cipher_suites_len;
2469 cipher_suites = ctx->cipher_suites;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002470#else
2471 len = SSL_client_hello_get0_ciphers(ssl, &cipher_suites);
2472#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002473 if (len % 2 != 0)
2474 goto abort;
2475 for (; len != 0; len -= 2, cipher_suites += 2) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002476#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002477 uint16_t cipher_suite = (cipher_suites[0] << 8) | cipher_suites[1];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002478 cipher = SSL_get_cipher_by_value(cipher_suite);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002479#else
2480 cipher = SSL_CIPHER_find(ssl, cipher_suites);
2481#endif
William Lallemand05bf68b2023-10-30 18:08:16 +01002482 if (!cipher)
2483 continue;
2484
William Lallemand539bfaa2023-10-24 23:58:02 +02002485 cipher_id = SSL_CIPHER_get_id(cipher);
2486 /* skip the SCSV "fake" signaling ciphersuites because they are NID_auth_any (RFC 7507) */
2487 if (cipher_id == SSL3_CK_SCSV || cipher_id == SSL3_CK_FALLBACK_SCSV)
2488 continue;
2489
William Lallemand05bf68b2023-10-30 18:08:16 +01002490 if (SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa
2491 || SSL_CIPHER_get_auth_nid(cipher) == NID_auth_any) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002492 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002493 break;
2494 }
2495 }
2496 }
2497
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002498 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002499 trash.area[i] = tolower(servername[i]);
2500 if (!wildp && (trash.area[i] == '.'))
2501 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002502 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002503 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002504
William Lallemand150bfa82019-09-19 17:12:49 +02002505 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002506
William Lallemand94bd3192020-08-14 14:43:35 +02002507 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2508 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002509 for (i = 0; i < 2; i++) {
2510 if (i == 0) /* lookup in full qualified names */
2511 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002512 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002513 node = ebst_lookup(&s->sni_w_ctx, wildp);
2514 else
2515 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002516
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002517 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002518
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002519 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002520 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002521 struct sni_ctx *sni, *sni_tmp;
2522 int skip = 0;
2523
2524 if (i == 1 && wildp) { /* wildcard */
2525 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2526 sni = container_of(n, struct sni_ctx, name);
2527 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002528 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002529 skip = 1;
2530 break;
2531 }
2532 }
2533 if (skip)
2534 continue;
2535 }
2536
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002537 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002538 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002539 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002540 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002541 break;
2542 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002543 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002544 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002545 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002546 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002547 if (!node_anonymous)
2548 node_anonymous = n;
2549 break;
2550 }
2551 }
2552 }
William Lallemand94bd3192020-08-14 14:43:35 +02002553 }
2554 /* Once the certificates are found, select them depending on what is
2555 * supported in the client and by key_signature priority order: EDSA >
2556 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002557 if (has_ecdsa_sig && node_ecdsa)
2558 node = node_ecdsa;
2559 else if (has_rsa_sig && node_rsa)
2560 node = node_rsa;
2561 else if (node_anonymous)
2562 node = node_anonymous;
2563 else if (node_ecdsa)
2564 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2565 else
2566 node = node_rsa; /* no rsa signature case (far far away) */
2567
William Lallemand94bd3192020-08-14 14:43:35 +02002568 if (node) {
2569 /* switch ctx */
2570 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2571 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2572 if (conf) {
2573 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2574 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2575 if (conf->early_data)
2576 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002577 }
William Lallemand94bd3192020-08-14 14:43:35 +02002578 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2579 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002580 }
William Lallemand150bfa82019-09-19 17:12:49 +02002581
William Lallemand02010472019-10-18 11:02:19 +02002582 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002583#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002584 if (s->generate_certs && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002585 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002586 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002587 }
2588#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002589 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002590 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002591 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002592 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002593 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
William Lallemand0f2291b2021-11-18 17:46:26 +01002594 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002595 }
William Lallemand0f2291b2021-11-18 17:46:26 +01002596
2597 /* other cases fallback on abort, if strict-sni is set but no node was found */
2598
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002599 abort:
2600 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
2601 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002602#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002603 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002604#else
2605 *al = SSL_AD_UNRECOGNIZED_NAME;
2606 return 0;
2607#endif
William Lallemand0f2291b2021-11-18 17:46:26 +01002608
2609allow_early:
2610#ifdef OPENSSL_IS_BORINGSSL
2611 if (allow_early)
2612 SSL_set_early_data_enabled(ssl, 1);
2613#else
2614 if (!allow_early)
2615 SSL_set_max_early_data(ssl, 0);
2616#endif
2617 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002618}
2619
William Lallemand0faf5262021-11-18 15:25:16 +01002620#else /* ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002621
Emeric Brunfc0421f2012-09-07 17:30:07 +02002622/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2623 * warning when no match is found, which implies the default (first) cert
2624 * will keep being used.
2625 */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002626static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002627{
2628 const char *servername;
2629 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002630 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002631 struct bind_conf *s = priv;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002632 int i;
2633 (void)al; /* shut gcc stupid warning */
2634
2635 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002636 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002637#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002638 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl))
2639 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002640#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002641 if (s->strict_sni)
2642 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002643 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002644 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002645 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002646 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002647 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002648
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002649 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002650 if (!servername[i])
2651 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002652 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002653 if (!wildp && (trash.area[i] == '.'))
2654 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002655 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002656 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002657
William Lallemand150bfa82019-09-19 17:12:49 +02002658 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002659 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002660 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002661 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2662 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002663 if (!container_of(n, struct sni_ctx, name)->neg) {
2664 node = n;
2665 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002666 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002667 }
2668 if (!node && wildp) {
2669 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002670 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2671 /* lookup a not neg filter */
2672 if (!container_of(n, struct sni_ctx, name)->neg) {
2673 node = n;
2674 break;
2675 }
2676 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002677 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002678 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002679#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002680 if (s->generate_certs && ssl_sock_generate_certificate(servername, s, ssl)) {
2681 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002682 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002683 return SSL_TLSEXT_ERR_OK;
2684 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002685#endif
William Lallemand21724f02019-11-04 17:56:13 +01002686 if (s->strict_sni) {
2687 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002688 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002689 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002690 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002691 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002692 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002693 }
2694
2695 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002696 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002697 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002698 return SSL_TLSEXT_ERR_OK;
2699}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002700#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002701#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2702
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002703#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002704
2705static DH * ssl_get_dh_1024(void)
2706{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002707 static unsigned char dh1024_p[]={
2708 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2709 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2710 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2711 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2712 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2713 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2714 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2715 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2716 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2717 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2718 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2719 };
2720 static unsigned char dh1024_g[]={
2721 0x02,
2722 };
2723
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002724 BIGNUM *p;
2725 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002726 DH *dh = DH_new();
2727 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002728 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2729 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002730
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002731 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002732 DH_free(dh);
2733 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002734 } else {
2735 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002736 }
2737 }
2738 return dh;
2739}
2740
2741static DH *ssl_get_dh_2048(void)
2742{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002743 static unsigned char dh2048_p[]={
2744 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2745 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2746 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2747 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2748 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2749 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2750 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2751 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2752 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2753 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2754 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2755 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2756 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2757 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2758 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2759 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2760 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2761 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2762 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2763 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2764 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2765 0xB7,0x1F,0x77,0xF3,
2766 };
2767 static unsigned char dh2048_g[]={
2768 0x02,
2769 };
2770
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002771 BIGNUM *p;
2772 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002773 DH *dh = DH_new();
2774 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002775 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2776 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002777
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002778 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002779 DH_free(dh);
2780 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002781 } else {
2782 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002783 }
2784 }
2785 return dh;
2786}
2787
2788static DH *ssl_get_dh_4096(void)
2789{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002790 static unsigned char dh4096_p[]={
2791 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2792 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2793 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2794 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2795 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2796 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2797 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2798 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2799 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2800 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2801 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2802 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2803 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2804 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2805 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2806 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2807 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2808 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2809 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2810 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2811 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2812 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2813 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2814 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2815 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2816 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2817 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2818 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2819 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2820 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2821 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2822 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2823 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2824 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2825 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2826 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2827 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2828 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2829 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2830 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2831 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2832 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2833 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002834 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002835 static unsigned char dh4096_g[]={
2836 0x02,
2837 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002838
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002839 BIGNUM *p;
2840 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002841 DH *dh = DH_new();
2842 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002843 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2844 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002845
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002846 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002847 DH_free(dh);
2848 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002849 } else {
2850 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002851 }
2852 }
2853 return dh;
2854}
2855
2856/* Returns Diffie-Hellman parameters matching the private key length
Willy Tarreauef934602016-12-22 23:12:01 +01002857 but not exceeding global_ssl.default_dh_param */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002858static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen)
2859{
2860 DH *dh = NULL;
2861 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002862 int type;
2863
2864 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002865
2866 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2867 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2868 */
2869 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2870 keylen = EVP_PKEY_bits(pkey);
2871 }
2872
Willy Tarreauef934602016-12-22 23:12:01 +01002873 if (keylen > global_ssl.default_dh_param) {
2874 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002875 }
2876
Remi Gacogned3a341a2015-05-29 16:26:17 +02002877 if (keylen >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002878 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002879 }
2880 else if (keylen >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002881 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002882 }
2883 else {
Remi Gacogne8de54152014-07-15 11:36:40 +02002884 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002885 }
2886
2887 return dh;
2888}
2889
Remi Gacogne47783ef2015-05-29 15:53:22 +02002890static DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002891{
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002892 DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02002893 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002894
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002895 if (in == NULL)
2896 goto end;
2897
Remi Gacogne47783ef2015-05-29 15:53:22 +02002898 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002899 goto end;
2900
Remi Gacogne47783ef2015-05-29 15:53:22 +02002901 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
2902
2903end:
2904 if (in)
2905 BIO_free(in);
2906
Emeric Brune1b4ed42018-08-16 15:14:12 +02002907 ERR_clear_error();
2908
Remi Gacogne47783ef2015-05-29 15:53:22 +02002909 return dh;
2910}
2911
2912int ssl_sock_load_global_dh_param_from_file(const char *filename)
2913{
2914 global_dh = ssl_sock_get_dh_from_file(filename);
2915
2916 if (global_dh) {
2917 return 0;
2918 }
2919
2920 return -1;
2921}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002922#endif
2923
William Lallemand9117de92019-10-04 00:29:42 +02002924/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02002925static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02002926 struct bind_conf *s, struct ssl_bind_conf *conf,
2927 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002928{
2929 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002930 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002931
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002932 if (*name == '!') {
2933 neg = 1;
2934 name++;
2935 }
2936 if (*name == '*') {
2937 wild = 1;
2938 name++;
2939 }
2940 /* !* filter is a nop */
2941 if (neg && wild)
2942 return order;
2943 if (*name) {
2944 int j, len;
2945 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002946 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02002947 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002948 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02002949 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002950 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002951
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002952 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02002953 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02002954 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002955 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02002956 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002957 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002958 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002959 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002960 sc->order = order++;
2961 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02002962 sc->wild = wild;
2963 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01002964 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02002965 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002966 }
2967 return order;
2968}
2969
William Lallemand6af03992019-07-23 15:00:54 +02002970/*
William Lallemand1d29c742019-10-04 00:53:29 +02002971 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
2972 * This function can't return an error.
2973 *
2974 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
2975 */
William Lallemandc756bbd2020-05-13 17:23:59 +02002976void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02002977{
2978
2979 struct sni_ctx *sc0, *sc0b, *sc1;
2980 struct ebmb_node *node;
2981
2982 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
2983
2984 /* ignore if sc0 was already inserted in a tree */
2985 if (sc0->name.node.leaf_p)
2986 continue;
2987
2988 /* Check for duplicates. */
2989 if (sc0->wild)
2990 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
2991 else
2992 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
2993
2994 for (; node; node = ebmb_next_dup(node)) {
2995 sc1 = ebmb_entry(node, struct sni_ctx, name);
2996 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
2997 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
2998 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02002999 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02003000 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003001 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02003002 break;
William Lallemand1d29c742019-10-04 00:53:29 +02003003 }
3004 }
3005
3006 /* if duplicate, ignore the insertion */
3007 if (!sc0)
3008 continue;
3009
3010 if (sc0->wild)
3011 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
3012 else
3013 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003014 }
William Lallemand21724f02019-11-04 17:56:13 +01003015
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003016 /* replace the default_ctx if required with the instance's ctx. */
3017 if (ckch_inst->is_default) {
3018 SSL_CTX_free(bind_conf->default_ctx);
3019 SSL_CTX_up_ref(ckch_inst->ctx);
3020 bind_conf->default_ctx = ckch_inst->ctx;
William Lallemand1d29c742019-10-04 00:53:29 +02003021 }
3022}
3023
3024/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003025 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02003026 */
William Lallemande3af8fb2019-10-08 11:36:53 +02003027struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02003028
William Lallemand2954c472020-03-06 21:54:13 +01003029/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02003030struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02003031
Emeric Brun7a883362019-10-17 13:27:40 +02003032/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003033 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02003034 * DH parameter is loaded into the SSL_CTX and if there is no
3035 * DH parameter available in ckchs nor in global, the default
3036 * DH parameters are applied on the SSL_CTX.
3037 * Returns a bitfield containing the flags:
3038 * ERR_FATAL in any fatal error case
3039 * ERR_ALERT if a reason of the error is availabine in err
3040 * ERR_WARN if a warning is available into err
3041 * The value 0 means there is no error nor warning and
3042 * the operation succeed.
3043 */
William Lallemandfa892222019-07-23 16:06:08 +02003044#ifndef OPENSSL_NO_DH
Emeric Brun7a883362019-10-17 13:27:40 +02003045static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct cert_key_and_chain *ckch,
3046 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02003047{
Emeric Brun7a883362019-10-17 13:27:40 +02003048 int ret = 0;
William Lallemandfa892222019-07-23 16:06:08 +02003049 DH *dh = NULL;
3050
William Lallemanda8c73742019-07-31 18:31:34 +02003051 if (ckch && ckch->dh) {
William Lallemandfa892222019-07-23 16:06:08 +02003052 dh = ckch->dh;
Emeric Bruna9363eb2019-10-17 14:53:03 +02003053 if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
3054 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
3055 err && *err ? *err : "", path);
3056#if defined(SSL_CTX_set_dh_auto)
3057 SSL_CTX_set_dh_auto(ctx, 1);
3058 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3059 err && *err ? *err : "");
3060#else
3061 memprintf(err, "%s, DH ciphers won't be available.\n",
3062 err && *err ? *err : "");
3063#endif
3064 ret |= ERR_WARN;
3065 goto end;
3066 }
William Lallemandfa892222019-07-23 16:06:08 +02003067
3068 if (ssl_dh_ptr_index >= 0) {
3069 /* store a pointer to the DH params to avoid complaining about
3070 ssl-default-dh-param not being set for this SSL_CTX */
3071 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
3072 }
3073 }
3074 else if (global_dh) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003075 if (!SSL_CTX_set_tmp_dh(ctx, global_dh)) {
3076 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
3077 err && *err ? *err : "", path);
3078#if defined(SSL_CTX_set_dh_auto)
3079 SSL_CTX_set_dh_auto(ctx, 1);
3080 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3081 err && *err ? *err : "");
3082#else
3083 memprintf(err, "%s, DH ciphers won't be available.\n",
3084 err && *err ? *err : "");
3085#endif
3086 ret |= ERR_WARN;
3087 goto end;
3088 }
William Lallemandfa892222019-07-23 16:06:08 +02003089 }
3090 else {
3091 /* Clear openssl global errors stack */
3092 ERR_clear_error();
3093
Willy Tarreau6d27a922020-11-05 19:38:05 +01003094 if (global_ssl.default_dh_param && global_ssl.default_dh_param <= 1024) {
William Lallemandfa892222019-07-23 16:06:08 +02003095 /* we are limited to DH parameter of 1024 bits anyway */
3096 if (local_dh_1024 == NULL)
3097 local_dh_1024 = ssl_get_dh_1024();
3098
Emeric Brun7a883362019-10-17 13:27:40 +02003099 if (local_dh_1024 == NULL) {
3100 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3101 err && *err ? *err : "", path);
3102 ret |= ERR_ALERT | ERR_FATAL;
William Lallemandfa892222019-07-23 16:06:08 +02003103 goto end;
Emeric Brun7a883362019-10-17 13:27:40 +02003104 }
William Lallemandfa892222019-07-23 16:06:08 +02003105
Emeric Bruna9363eb2019-10-17 14:53:03 +02003106 if (!SSL_CTX_set_tmp_dh(ctx, local_dh_1024)) {
3107 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3108 err && *err ? *err : "", path);
3109#if defined(SSL_CTX_set_dh_auto)
3110 SSL_CTX_set_dh_auto(ctx, 1);
3111 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3112 err && *err ? *err : "");
3113#else
3114 memprintf(err, "%s, DH ciphers won't be available.\n",
3115 err && *err ? *err : "");
3116#endif
3117 ret |= ERR_WARN;
3118 goto end;
3119 }
William Lallemandfa892222019-07-23 16:06:08 +02003120 }
3121 else {
3122 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh);
3123 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003124 }
3125
William Lallemandf9568fc2019-10-16 18:27:58 +02003126end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003127 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003128 return ret;
3129}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003130#endif
William Lallemandfa892222019-07-23 16:06:08 +02003131
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003132
3133/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003134 * Returns a bitfield containing the flags:
3135 * ERR_FATAL in any fatal error case
3136 * ERR_ALERT if the reason of the error is available in err
3137 * ERR_WARN if a warning is available into err
Remi Tricot-Le Bretond417c252022-12-15 15:44:37 +01003138 * The caller is responsible of freeing the newly built or newly refcounted
3139 * find_chain element.
Emeric Bruna96b5822019-10-17 13:25:14 +02003140 * The value 0 means there is no error nor warning and
3141 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003142 */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003143static int ssl_sock_load_cert_chain(const char *path, const struct cert_key_and_chain *ckch,
3144 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003145{
Emeric Bruna96b5822019-10-17 13:25:14 +02003146 int errcode = 0;
3147
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003148 if (find_chain == NULL) {
3149 errcode |= ERR_FATAL;
3150 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003151 }
3152
3153 if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
3154 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
3155 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003156 errcode |= ERR_ALERT | ERR_FATAL;
3157 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003158 }
3159
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003160 if (ckch->chain) {
Remi Tricot-Le Bretond417c252022-12-15 15:44:37 +01003161 *find_chain = X509_chain_up_ref(ckch->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003162 } else {
3163 /* Find Certificate Chain in global */
3164 struct issuer_chain *issuer;
Emmanuel Hocdetef87e0a2020-03-23 11:29:11 +01003165 issuer = ssl_get0_issuer_chain(ckch->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003166 if (issuer)
Remi Tricot-Le Bretond417c252022-12-15 15:44:37 +01003167 *find_chain = X509_chain_up_ref(issuer->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003168 }
William Lallemand85888572020-02-27 14:48:35 +01003169
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003170 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003171 /* always put a null chain stack in the SSL_CTX so it does not
3172 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003173 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003174 }
3175
William Lallemandf187ce62020-06-02 18:27:20 +02003176 /* Load all certs in the ckch into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003177#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003178 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand935d8292020-08-12 20:02:10 +02003179 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'. Make sure you are linking against Openssl >= 1.0.2.\n",
3180 err && *err ? *err : "", path);
3181 errcode |= ERR_ALERT | ERR_FATAL;
3182 goto end;
3183 }
William Lallemandf187ce62020-06-02 18:27:20 +02003184#else
3185 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003186 X509 *ca;
Remi Tricot-Le Bretond417c252022-12-15 15:44:37 +01003187 while ((ca = sk_X509_shift(*find_chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003188 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003189 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3190 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003191 X509_free(ca);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003192 errcode |= ERR_ALERT | ERR_FATAL;
3193 goto end;
3194 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003195 }
William Lallemandf187ce62020-06-02 18:27:20 +02003196#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003197
William Lallemand9a1d8392020-08-10 17:28:23 +02003198#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003199 /* remove the Root CA from the SSL_CTX if the option is activated */
3200 if (global_ssl.skip_self_issued_ca) {
3201 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3202 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3203 err && *err ? *err : "", path);
3204 errcode |= ERR_ALERT | ERR_FATAL;
3205 goto end;
3206 }
3207 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003208#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003209
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003210end:
3211 return errcode;
3212}
3213
3214
3215/* Loads the info in ckch into ctx
3216 * Returns a bitfield containing the flags:
3217 * ERR_FATAL in any fatal error case
3218 * ERR_ALERT if the reason of the error is available in err
3219 * ERR_WARN if a warning is available into err
3220 * The value 0 means there is no error nor warning and
3221 * the operation succeed.
3222 */
3223static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
3224{
3225 int errcode = 0;
3226 STACK_OF(X509) *find_chain = NULL;
3227
3228 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3229 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3230 err && *err ? *err : "", path);
3231 errcode |= ERR_ALERT | ERR_FATAL;
3232 return errcode;
3233 }
3234
3235 /* Load certificate chain */
3236 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3237 if (errcode & ERR_CODE)
3238 goto end;
3239
William Lallemandfa892222019-07-23 16:06:08 +02003240#ifndef OPENSSL_NO_DH
3241 /* store a NULL pointer to indicate we have not yet loaded
3242 a custom DH param file */
3243 if (ssl_dh_ptr_index >= 0) {
3244 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3245 }
3246
Emeric Brun7a883362019-10-17 13:27:40 +02003247 errcode |= ssl_sock_load_dh_params(ctx, ckch, path, err);
3248 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003249 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3250 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003251 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003252 }
3253#endif
3254
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003255#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemanda17f4112019-10-10 15:16:44 +02003256 if (sctl_ex_index >= 0 && ckch->sctl) {
3257 if (ssl_sock_load_sctl(ctx, ckch->sctl) < 0) {
3258 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003259 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003260 errcode |= ERR_ALERT | ERR_FATAL;
3261 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003262 }
3263 }
3264#endif
3265
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003266#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
William Lallemand246c0242019-10-11 08:59:13 +02003267 /* Load OCSP Info into context */
3268 if (ckch->ocsp_response) {
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01003269 if (ssl_sock_load_ocsp(ctx, ckch, find_chain) < 0) {
Tim Duesterhus93128532019-11-23 23:45:10 +01003270 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",
3271 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003272 errcode |= ERR_ALERT | ERR_FATAL;
3273 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003274 }
3275 }
William Lallemand246c0242019-10-11 08:59:13 +02003276#endif
3277
Emeric Bruna96b5822019-10-17 13:25:14 +02003278 end:
Remi Tricot-Le Bretond417c252022-12-15 15:44:37 +01003279 sk_X509_pop_free(find_chain, X509_free);
Emeric Bruna96b5822019-10-17 13:25:14 +02003280 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003281}
3282
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003283
3284/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
3285 * Returns a bitfield containing the flags:
3286 * ERR_FATAL in any fatal error case
3287 * ERR_ALERT if the reason of the error is available in err
3288 * ERR_WARN if a warning is available into err
3289 * The value 0 means there is no error nor warning and
3290 * the operation succeed.
3291 */
3292static int ssl_sock_put_srv_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch,
3293 SSL_CTX *ctx, char **err)
3294{
3295 int errcode = 0;
3296 STACK_OF(X509) *find_chain = NULL;
3297
3298 /* Load the private key */
3299 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3300 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3301 err && *err ? *err : "", path);
3302 errcode |= ERR_ALERT | ERR_FATAL;
3303 }
3304
3305 /* Load certificate chain */
3306 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3307 if (errcode & ERR_CODE)
3308 goto end;
3309
3310 if (SSL_CTX_check_private_key(ctx) <= 0) {
3311 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3312 err && *err ? *err : "", path);
3313 errcode |= ERR_ALERT | ERR_FATAL;
3314 }
3315
3316end:
Remi Tricot-Le Bretond417c252022-12-15 15:44:37 +01003317 sk_X509_pop_free(find_chain, X509_free);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003318 return errcode;
3319}
3320
3321
William Lallemand614ca0d2019-10-07 13:52:11 +02003322/*
3323 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003324 *
3325 * Returns a bitfield containing the flags:
3326 * ERR_FATAL in any fatal error case
3327 * ERR_ALERT if the reason of the error is available in err
3328 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003329 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003330int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003331 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003332{
William Lallemandc9402072019-05-15 15:33:54 +02003333 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003334 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003335 int order = 0;
3336 X509_NAME *xname;
3337 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003338 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003339 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003340#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3341 STACK_OF(GENERAL_NAME) *names;
3342#endif
William Lallemand36b84632019-07-18 19:28:17 +02003343 struct cert_key_and_chain *ckch;
William Lallemand614ca0d2019-10-07 13:52:11 +02003344 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003345 int errcode = 0;
3346
3347 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003348
William Lallemande3af8fb2019-10-08 11:36:53 +02003349 if (!ckchs || !ckchs->ckch)
Emeric Brun054563d2019-10-17 13:16:58 +02003350 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003351
William Lallemande3af8fb2019-10-08 11:36:53 +02003352 ckch = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003353
William Lallemandc9402072019-05-15 15:33:54 +02003354 ctx = SSL_CTX_new(SSLv23_server_method());
3355 if (!ctx) {
3356 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3357 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003358 errcode |= ERR_ALERT | ERR_FATAL;
3359 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003360 }
3361
Emeric Bruna96b5822019-10-17 13:25:14 +02003362 errcode |= ssl_sock_put_ckch_into_ctx(path, ckch, ctx, err);
3363 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003364 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003365
3366 ckch_inst = ckch_inst_new();
3367 if (!ckch_inst) {
3368 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3369 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003370 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003371 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003372 }
3373
William Lallemand36b84632019-07-18 19:28:17 +02003374 pkey = X509_get_pubkey(ckch->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003375 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003376 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003377 switch(EVP_PKEY_base_id(pkey)) {
3378 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003379 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003380 break;
3381 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003382 kinfo.sig = TLSEXT_signature_ecdsa;
3383 break;
3384 case EVP_PKEY_DSA:
3385 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003386 break;
3387 }
3388 EVP_PKEY_free(pkey);
3389 }
3390
Emeric Brun50bcecc2013-04-22 13:05:23 +02003391 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003392 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003393 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 +02003394 if (order < 0) {
3395 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003396 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003397 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003398 }
3399 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003400 }
3401 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003402#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand36b84632019-07-18 19:28:17 +02003403 names = X509_get_ext_d2i(ckch->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003404 if (names) {
3405 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3406 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3407 if (name->type == GEN_DNS) {
3408 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003409 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003410 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003411 if (order < 0) {
3412 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003413 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003414 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003415 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003416 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003417 }
3418 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003419 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003420 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003421#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand36b84632019-07-18 19:28:17 +02003422 xname = X509_get_subject_name(ckch->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003423 i = -1;
3424 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3425 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003426 ASN1_STRING *value;
3427
3428 value = X509_NAME_ENTRY_get_data(entry);
3429 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003430 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003431 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003432 if (order < 0) {
3433 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003434 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003435 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003436 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003437 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003438 }
3439 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003440 /* we must not free the SSL_CTX anymore below, since it's already in
3441 * the tree, so it will be discovered and cleaned in time.
3442 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003443
Emeric Brunfc0421f2012-09-07 17:30:07 +02003444#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003445 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003446 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3447 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003448 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003449 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003450 }
3451#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003452 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003453 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003454 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003455 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003456 SSL_CTX_up_ref(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003457 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003458
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003459 /* Always keep a reference to the newly constructed SSL_CTX in the
3460 * instance. This way if the instance has no SNIs, the SSL_CTX will
3461 * still be linked. */
3462 SSL_CTX_up_ref(ctx);
3463 ckch_inst->ctx = ctx;
3464
William Lallemand9117de92019-10-04 00:29:42 +02003465 /* everything succeed, the ckch instance can be used */
3466 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003467 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003468 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003469
William Lallemand02e19a52020-04-08 16:11:26 +02003470 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3471
Emeric Brun054563d2019-10-17 13:16:58 +02003472 *ckchi = ckch_inst;
3473 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003474
3475error:
3476 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003477 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003478 if (ckch_inst->is_default)
3479 SSL_CTX_free(ctx);
3480
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003481 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003482 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003483 }
William Lallemandd9199372019-10-04 15:37:05 +02003484 SSL_CTX_free(ctx);
3485
Emeric Brun054563d2019-10-17 13:16:58 +02003486 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003487}
3488
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003489
3490/*
3491 * This function allocate a ckch_inst that will be used on the backend side
3492 * (server line)
3493 *
3494 * Returns a bitfield containing the flags:
3495 * ERR_FATAL in any fatal error case
3496 * ERR_ALERT if the reason of the error is available in err
3497 * ERR_WARN if a warning is available into err
3498 */
3499int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01003500 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003501{
3502 SSL_CTX *ctx;
3503 struct cert_key_and_chain *ckch;
3504 struct ckch_inst *ckch_inst = NULL;
3505 int errcode = 0;
3506
3507 *ckchi = NULL;
3508
3509 if (!ckchs || !ckchs->ckch)
3510 return ERR_FATAL;
3511
3512 ckch = ckchs->ckch;
3513
3514 ctx = SSL_CTX_new(SSLv23_client_method());
3515 if (!ctx) {
3516 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3517 err && *err ? *err : "", path);
3518 errcode |= ERR_ALERT | ERR_FATAL;
3519 goto error;
3520 }
3521
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003522 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, ckch, ctx, err);
3523 if (errcode & ERR_CODE)
3524 goto error;
3525
3526 ckch_inst = ckch_inst_new();
3527 if (!ckch_inst) {
3528 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3529 err && *err ? *err : "", path);
3530 errcode |= ERR_ALERT | ERR_FATAL;
3531 goto error;
3532 }
3533
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003534 /* everything succeed, the ckch instance can be used */
3535 ckch_inst->bind_conf = NULL;
3536 ckch_inst->ssl_conf = NULL;
3537 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01003538 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003539 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003540
3541 *ckchi = ckch_inst;
3542 return errcode;
3543
3544error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003545 SSL_CTX_free(ctx);
3546
3547 return errcode;
3548}
3549
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003550/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003551static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3552 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003553 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003554{
Emeric Brun054563d2019-10-17 13:16:58 +02003555 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003556
3557 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003558 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 +02003559
Emeric Brun054563d2019-10-17 13:16:58 +02003560 if (errcode & ERR_CODE)
3561 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003562
William Lallemand24bde432020-03-09 16:48:43 +01003563 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003564
3565 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003566 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003567 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003568}
3569
William Lallemanddb26e2b2021-01-26 12:01:46 +01003570/* This function generates a <struct ckch_inst *> for a <struct server *>, and
3571 * fill the SSL_CTX of the server.
3572 *
3573 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003574static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01003575 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003576{
3577 int errcode = 0;
3578
3579 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01003580 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003581
3582 if (errcode & ERR_CODE)
3583 return errcode;
3584
William Lallemanddb26e2b2021-01-26 12:01:46 +01003585 (*ckch_inst)->server = server;
3586 /* Keep the reference to the SSL_CTX in the server. */
3587 SSL_CTX_up_ref((*ckch_inst)->ctx);
3588 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003589 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003590 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003591 return errcode;
3592}
3593
William Lallemand6be66ec2020-03-06 22:26:32 +01003594
William Lallemand4c68bba2020-03-30 18:45:10 +02003595
3596
3597/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3598 * done once. Zero is returned if the operation fails. No error is returned
3599 * if the random is said as not implemented, because we expect that openssl
3600 * will use another method once needed.
3601 */
3602static int ssl_initialize_random()
3603{
3604 unsigned char random;
3605 static int random_initialized = 0;
3606
3607 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3608 random_initialized = 1;
3609
3610 return random_initialized;
3611}
3612
William Lallemand2954c472020-03-06 21:54:13 +01003613/* Load a crt-list file, this is done in 2 parts:
3614 * - store the content of the file in a crtlist structure with crtlist_entry structures
3615 * - generate the instances by iterating on entries in the crtlist struct
3616 *
3617 * Nothing is locked there, this function is used in the configuration parser.
3618 *
3619 * Returns a set of ERR_* flags possibly with an error in <err>.
3620 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003621int 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 +01003622{
3623 struct crtlist *crtlist = NULL;
3624 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003625 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003626 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003627 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003628 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003629
William Lallemand79d31ec2020-03-25 15:10:49 +01003630 bind_conf_node = malloc(sizeof(*bind_conf_node));
3631 if (!bind_conf_node) {
3632 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3633 cfgerr |= ERR_FATAL | ERR_ALERT;
3634 goto error;
3635 }
3636 bind_conf_node->next = NULL;
3637 bind_conf_node->bind_conf = bind_conf;
3638
William Lallemand41ca9302020-04-08 13:15:18 +02003639 /* strip trailing slashes, including first one */
3640 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3641 *end = 0;
3642
William Lallemand2954c472020-03-06 21:54:13 +01003643 /* look for an existing crtlist or create one */
3644 eb = ebst_lookup(&crtlists_tree, file);
3645 if (eb) {
3646 crtlist = ebmb_entry(eb, struct crtlist, node);
3647 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003648 /* load a crt-list OR a directory */
3649 if (dir)
3650 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3651 else
3652 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3653
William Lallemand2954c472020-03-06 21:54:13 +01003654 if (!(cfgerr & ERR_CODE))
3655 ebst_insert(&crtlists_tree, &crtlist->node);
3656 }
3657
3658 if (cfgerr & ERR_CODE) {
3659 cfgerr |= ERR_FATAL | ERR_ALERT;
3660 goto error;
3661 }
3662
3663 /* generates ckch instance from the crtlist_entry */
3664 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3665 struct ckch_store *store;
3666 struct ckch_inst *ckch_inst = NULL;
3667
3668 store = entry->node.key;
3669 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3670 if (cfgerr & ERR_CODE) {
3671 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3672 goto error;
3673 }
Willy Tarreau2b718102021-04-21 07:32:39 +02003674 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003675 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003676 }
William Lallemand2954c472020-03-06 21:54:13 +01003677
William Lallemand79d31ec2020-03-25 15:10:49 +01003678 /* add the bind_conf to the list */
3679 bind_conf_node->next = crtlist->bind_conf;
3680 crtlist->bind_conf = bind_conf_node;
3681
William Lallemand2954c472020-03-06 21:54:13 +01003682 return cfgerr;
3683error:
3684 {
William Lallemand49398312020-03-30 17:01:33 +02003685 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003686 struct ckch_inst *inst, *s_inst;
3687
William Lallemand49398312020-03-30 17:01:33 +02003688 lastentry = entry; /* which entry we tried to generate last */
3689 if (lastentry) {
3690 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3691 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3692 break;
3693
3694 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003695
William Lallemand49398312020-03-30 17:01:33 +02003696 /* this was not generated for this bind_conf, skip */
3697 if (inst->bind_conf != bind_conf)
3698 continue;
3699
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003700 /* free the sni_ctx and instance */
3701 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003702 }
William Lallemand2954c472020-03-06 21:54:13 +01003703 }
William Lallemand2954c472020-03-06 21:54:13 +01003704 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003705 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003706 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003707 return cfgerr;
3708}
3709
William Lallemand06b22a82020-03-16 14:45:55 +01003710/* Returns a set of ERR_* flags possibly with an error in <err>. */
3711int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3712{
3713 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01003714 int cfgerr = 0;
3715 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003716 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01003717 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01003718
3719 if ((ckchs = ckchs_lookup(path))) {
3720 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01003721 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3722 found++;
3723 } else if (stat(path, &buf) == 0) {
3724 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01003725 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003726 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003727 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003728 cfgerr |= ERR_ALERT | ERR_FATAL;
3729 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003730 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01003731 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003732 }
3733 } else {
3734 /* stat failed, could be a bundle */
3735 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02003736 char fp[MAXPATHLEN+1] = {0};
3737 int n = 0;
3738
3739 /* Load all possible certs and keys in separate ckch_store */
3740 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3741 struct stat buf;
3742 int ret;
3743
3744 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3745 if (ret > sizeof(fp))
3746 continue;
3747
3748 if ((ckchs = ckchs_lookup(fp))) {
3749 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01003750 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02003751 } else {
3752 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01003753 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003754 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02003755 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003756 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02003757 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3758 }
3759 }
3760 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01003761#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
3762 if (found) {
3763 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
3764 err && *err ? *err : "", path);
3765 cfgerr |= ERR_ALERT | ERR_FATAL;
3766 }
3767#endif
William Lallemand06b22a82020-03-16 14:45:55 +01003768 }
3769 }
William Lallemand06ce84a2020-11-20 15:36:13 +01003770 if (!found) {
3771 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3772 err && *err ? *err : "", path, strerror(errno));
3773 cfgerr |= ERR_ALERT | ERR_FATAL;
3774 }
William Lallemand06b22a82020-03-16 14:45:55 +01003775
3776 return cfgerr;
3777}
3778
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003779
3780/* Create a full ssl context and ckch instance that will be used for a specific
3781 * backend server (server configuration line).
3782 * Returns a set of ERR_* flags possibly with an error in <err>.
3783 */
3784int ssl_sock_load_srv_cert(char *path, struct server *server, char **err)
3785{
3786 struct stat buf;
3787 int cfgerr = 0;
3788 struct ckch_store *ckchs;
3789 int found = 0; /* did we found a file to load ? */
3790
3791 if ((ckchs = ckchs_lookup(path))) {
3792 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01003793 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003794 found++;
3795 } else if (stat(path, &buf) == 0) {
3796 /* We do not manage directories on backend side. */
3797 if (S_ISDIR(buf.st_mode) == 0) {
3798 ++found;
3799 ckchs = ckchs_load_cert_file(path, err);
3800 if (!ckchs)
3801 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003802 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003803 }
3804 }
3805 if (!found) {
3806 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3807 err && *err ? *err : "", path, strerror(errno));
3808 cfgerr |= ERR_ALERT | ERR_FATAL;
3809 }
3810
3811 return cfgerr;
3812}
3813
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003814/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003815static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003816ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003817{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003818 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003819 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003820 SSL_OP_ALL | /* all known workarounds for bugs */
3821 SSL_OP_NO_SSLv2 |
3822 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003823 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02003824 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003825 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02003826 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003827 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003828 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003829 SSL_MODE_ENABLE_PARTIAL_WRITE |
3830 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01003831 SSL_MODE_RELEASE_BUFFERS |
3832 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02003833 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003834 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003835 int flags = MC_SSL_O_ALL;
3836 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02003837 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003838
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003839 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003840 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003841
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003842 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01003843 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
3844 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3845 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003846 else
3847 flags = conf_ssl_methods->flags;
3848
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003849 min = conf_ssl_methods->min;
3850 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02003851
3852 /* default minimum is TLSV12, */
3853 if (!min) {
3854 if (!max || (max >= default_min_ver)) {
3855 min = default_min_ver;
3856 } else {
3857 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). "
3858 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
3859 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
3860 min = max;
3861 }
3862 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003863 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003864 if (min)
3865 flags |= (methodVersions[min].flag - 1);
3866 if (max)
3867 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003868 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003869 min = max = CONF_TLSV_NONE;
3870 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003871 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003872 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003873 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003874 if (min) {
3875 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003876 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
3877 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3878 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
3879 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003880 hole = 0;
3881 }
3882 max = i;
3883 }
3884 else {
3885 min = max = i;
3886 }
3887 }
3888 else {
3889 if (min)
3890 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003891 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003892 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003893 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
3894 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003895 cfgerr += 1;
3896 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02003897 /* save real min/max in bind_conf */
3898 conf_ssl_methods->min = min;
3899 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003900
Willy Tarreau9a1ab082019-05-09 13:26:41 +02003901#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003902 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08003903 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003904 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003905 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003906 else
William Lallemandd0712f32020-06-11 17:34:00 +02003907 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
3908 /* clear every version flags in case SSL_CTX_new()
3909 * returns an SSL_CTX with disabled versions */
3910 SSL_CTX_clear_options(ctx, methodVersions[i].option);
3911
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003912 if (flags & methodVersions[i].flag)
3913 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02003914
3915 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003916#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003917 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003918 methodVersions[min].ctx_set_version(ctx, SET_MIN);
3919 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02003920#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003921
3922 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
3923 options |= SSL_OP_NO_TICKET;
3924 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
3925 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08003926
3927#ifdef SSL_OP_NO_RENEGOTIATION
3928 options |= SSL_OP_NO_RENEGOTIATION;
3929#endif
3930
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003931 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003932
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05003933#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003934 if (global_ssl.async)
3935 mode |= SSL_MODE_ASYNC;
3936#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003937 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003938 if (global_ssl.life_time)
3939 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003940
3941#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3942#ifdef OPENSSL_IS_BORINGSSL
3943 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
3944 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Ilya Shipitsine9ff8992020-01-19 12:20:14 +05003945#elif defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01003946 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01003947 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003948 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
3949 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003950#else
3951 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003952#endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003953 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003954#endif
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003955 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003956}
3957
William Lallemand4f45bb92017-10-30 20:08:51 +01003958
3959static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
3960{
3961 if (first == block) {
3962 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3963 if (first->len > 0)
3964 sh_ssl_sess_tree_delete(sh_ssl_sess);
3965 }
3966}
3967
3968/* return first block from sh_ssl_sess */
3969static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
3970{
3971 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
3972
3973}
3974
3975/* store a session into the cache
3976 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
3977 * data: asn1 encoded session
3978 * data_len: asn1 encoded session length
3979 * Returns 1 id session was stored (else 0)
3980 */
3981static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
3982{
3983 struct shared_block *first;
3984 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
3985
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003986 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01003987 if (!first) {
3988 /* Could not retrieve enough free blocks to store that session */
3989 return 0;
3990 }
3991
3992 /* STORE the key in the first elem */
3993 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3994 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
3995 first->len = sizeof(struct sh_ssl_sess_hdr);
3996
3997 /* it returns the already existing node
3998 or current node if none, never returns null */
3999 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
4000 if (oldsh_ssl_sess != sh_ssl_sess) {
4001 /* NOTE: Row couldn't be in use because we lock read & write function */
4002 /* release the reserved row */
William Lallemand52a61cc2023-01-31 14:12:28 +01004003 first->len = 0; /* the len must be liberated in order not to call the release callback on it */
William Lallemand4f45bb92017-10-30 20:08:51 +01004004 shctx_row_dec_hot(ssl_shctx, first);
4005 /* replace the previous session already in the tree */
4006 sh_ssl_sess = oldsh_ssl_sess;
4007 /* ignore the previous session data, only use the header */
4008 first = sh_ssl_sess_first_block(sh_ssl_sess);
4009 shctx_row_inc_hot(ssl_shctx, first);
4010 first->len = sizeof(struct sh_ssl_sess_hdr);
4011 }
4012
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004013 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01004014 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004015 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01004016 }
4017
4018 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004019
4020 return 1;
4021}
William Lallemanded0b5ad2017-10-30 19:36:36 +01004022
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004023/* SSL callback used when a new session is created while connecting to a server */
4024static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4025{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004026 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004027 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004028
Willy Tarreau07d94e42018-09-20 10:57:52 +02004029 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004030
William Lallemand3ce6eed2021-02-08 10:43:44 +01004031 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4032 * one cache per thread, it only prevents to flush it from the CLI in
4033 * another thread */
4034
Olivier Houcharde6060c52017-11-16 17:42:52 +01004035 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4036 int len;
4037 unsigned char *ptr;
William Lallemandc78ac5a2021-11-17 02:59:21 +01004038 const char *sni;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004039
Olivier Houcharde6060c52017-11-16 17:42:52 +01004040 len = i2d_SSL_SESSION(sess, NULL);
William Lallemandc78ac5a2021-11-17 02:59:21 +01004041 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004042 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004043 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4044 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4045 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004046 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
Willy Tarreau90f3cd22023-08-21 08:45:35 +02004047 if (!ptr)
4048 free(s->ssl_ctx.reused_sess[tid].ptr);
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004049 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004050 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4051 }
4052 if (s->ssl_ctx.reused_sess[tid].ptr) {
4053 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4054 &ptr);
4055 }
William Lallemandc78ac5a2021-11-17 02:59:21 +01004056
4057 if (s->ssl_ctx.reused_sess[tid].sni) {
4058 /* if the new sni is empty or isn' t the same as the old one */
4059 if ((!sni) || strcmp(s->ssl_ctx.reused_sess[tid].sni, sni) != 0) {
4060 ha_free(&s->ssl_ctx.reused_sess[tid].sni);
4061 if (sni)
4062 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4063 }
4064 } else if (sni) {
4065 /* if there wasn't an old sni but there is a new one */
4066 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4067 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004068 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004069 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004070 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004071 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004072 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004073 }
4074
4075 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004076}
4077
Olivier Houcharde6060c52017-11-16 17:42:52 +01004078
William Lallemanded0b5ad2017-10-30 19:36:36 +01004079/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004080int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004081{
4082 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4083 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4084 unsigned char *p;
4085 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004086 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004087 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004088
4089 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004090 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004091 * note: SSL_SESSION_set1_id is using
4092 * a memcpy so we need to use a different pointer
4093 * than sid_data or sid_ctx_data to avoid valgrind
4094 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004095 */
4096
4097 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004098
4099 /* copy value in an other buffer */
4100 memcpy(encid, sid_data, sid_length);
4101
4102 /* pad with 0 */
4103 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4104 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4105
4106 /* force length to zero to avoid ASN1 encoding */
4107 SSL_SESSION_set1_id(sess, encid, 0);
4108
4109 /* force length to zero to avoid ASN1 encoding */
4110 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004111
4112 /* check if buffer is large enough for the ASN1 encoded session */
4113 data_len = i2d_SSL_SESSION(sess, NULL);
4114 if (data_len > SHSESS_MAX_DATA_LEN)
4115 goto err;
4116
4117 p = encsess;
4118
4119 /* process ASN1 session encoding before the lock */
4120 i2d_SSL_SESSION(sess, &p);
4121
William Lallemanded0b5ad2017-10-30 19:36:36 +01004122
William Lallemanda3c77cf2017-10-30 23:44:40 +01004123 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004124 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004125 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004126 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004127err:
4128 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004129 SSL_SESSION_set1_id(sess, encid, sid_length);
4130 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004131
4132 return 0; /* do not increment session reference count */
4133}
4134
4135/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004136SSL_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 +01004137{
William Lallemand4f45bb92017-10-30 20:08:51 +01004138 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004139 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4140 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004141 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004142 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004143
Willy Tarreau37d69392021-06-15 16:39:22 +02004144 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004145
4146 /* allow the session to be freed automatically by openssl */
4147 *do_copy = 0;
4148
4149 /* tree key is zeros padded sessionid */
4150 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4151 memcpy(tmpkey, key, key_len);
4152 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4153 key = tmpkey;
4154 }
4155
4156 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004157 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004158
4159 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004160 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4161 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004162 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004163 shctx_unlock(ssl_shctx);
Willy Tarreau37d69392021-06-15 16:39:22 +02004164 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004165 return NULL;
4166 }
4167
William Lallemand4f45bb92017-10-30 20:08:51 +01004168 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4169 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004170
William Lallemand4f45bb92017-10-30 20:08:51 +01004171 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 +01004172
William Lallemanda3c77cf2017-10-30 23:44:40 +01004173 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004174
4175 /* decode ASN1 session */
4176 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004177 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004178 /* Reset session id and session id contenxt */
4179 if (sess) {
4180 SSL_SESSION_set1_id(sess, key, key_len);
4181 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4182 }
4183
4184 return sess;
4185}
4186
William Lallemand4f45bb92017-10-30 20:08:51 +01004187
William Lallemanded0b5ad2017-10-30 19:36:36 +01004188/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004189void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004190{
William Lallemand4f45bb92017-10-30 20:08:51 +01004191 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004192 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4193 unsigned int sid_length;
4194 const unsigned char *sid_data;
4195 (void)ctx;
4196
4197 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4198 /* tree key is zeros padded sessionid */
4199 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4200 memcpy(tmpkey, sid_data, sid_length);
4201 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4202 sid_data = tmpkey;
4203 }
4204
William Lallemanda3c77cf2017-10-30 23:44:40 +01004205 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004206
4207 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004208 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4209 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004210 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004211 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004212 }
4213
4214 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004215 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004216}
4217
4218/* Set session cache mode to server and disable openssl internal cache.
4219 * Set shared cache callbacks on an ssl context.
4220 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004221void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004222{
4223 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4224
4225 if (!ssl_shctx) {
4226 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4227 return;
4228 }
4229
4230 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4231 SSL_SESS_CACHE_NO_INTERNAL |
4232 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4233
4234 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004235 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4236 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4237 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004238}
William Lallemand7d42ef52020-07-06 11:41:30 +02004239
4240/*
4241 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4242 *
4243 * The format is:
4244 * * <Label> <space> <ClientRandom> <space> <Secret>
4245 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4246 */
4247
William Lallemandca5cf0a2021-06-09 16:46:12 +02004248#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004249void SSL_CTX_keylog(const SSL *ssl, const char *line)
4250{
4251 struct ssl_keylog *keylog;
4252 char *lastarg = NULL;
4253 char *dst = NULL;
4254
4255 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4256 if (!keylog)
4257 return;
4258
4259 lastarg = strrchr(line, ' ');
4260 if (lastarg == NULL || ++lastarg == NULL)
4261 return;
4262
4263 dst = pool_alloc(pool_head_ssl_keylog_str);
4264 if (!dst)
4265 return;
4266
4267 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4268 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4269
4270 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4271 if (keylog->client_random)
4272 goto error;
4273 keylog->client_random = dst;
4274
4275 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4276 if (keylog->client_early_traffic_secret)
4277 goto error;
4278 keylog->client_early_traffic_secret = dst;
4279
4280 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4281 if(keylog->client_handshake_traffic_secret)
4282 goto error;
4283 keylog->client_handshake_traffic_secret = dst;
4284
4285 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4286 if (keylog->server_handshake_traffic_secret)
4287 goto error;
4288 keylog->server_handshake_traffic_secret = dst;
4289
4290 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4291 if (keylog->client_traffic_secret_0)
4292 goto error;
4293 keylog->client_traffic_secret_0 = dst;
4294
4295 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4296 if (keylog->server_traffic_secret_0)
4297 goto error;
4298 keylog->server_traffic_secret_0 = dst;
4299
4300 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4301 if (keylog->early_exporter_secret)
4302 goto error;
4303 keylog->early_exporter_secret = dst;
4304
4305 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4306 if (keylog->exporter_secret)
4307 goto error;
4308 keylog->exporter_secret = dst;
4309 } else {
4310 goto error;
4311 }
4312
4313 return;
4314
4315error:
4316 pool_free(pool_head_ssl_keylog_str, dst);
4317
4318 return;
4319}
4320#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004321
William Lallemand8b453912019-11-21 15:48:10 +01004322/*
4323 * This function applies the SSL configuration on a SSL_CTX
4324 * It returns an error code and fills the <err> buffer
4325 */
4326int 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 +01004327{
4328 struct proxy *curproxy = bind_conf->frontend;
4329 int cfgerr = 0;
4330 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004331 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004332 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004333#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004334 const char *conf_ciphersuites;
4335#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004336 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004337
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004338 if (ssl_conf) {
4339 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4340 int i, min, max;
4341 int flags = MC_SSL_O_ALL;
4342
4343 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004344 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4345 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004346 if (min)
4347 flags |= (methodVersions[min].flag - 1);
4348 if (max)
4349 flags |= ~((methodVersions[max].flag << 1) - 1);
4350 min = max = CONF_TLSV_NONE;
4351 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4352 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4353 if (min)
4354 max = i;
4355 else
4356 min = max = i;
4357 }
4358 /* save real min/max */
4359 conf_ssl_methods->min = min;
4360 conf_ssl_methods->max = max;
4361 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004362 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4363 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004364 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004365 }
4366 }
4367
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004368 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004369 case SSL_SOCK_VERIFY_NONE:
4370 verify = SSL_VERIFY_NONE;
4371 break;
4372 case SSL_SOCK_VERIFY_OPTIONAL:
4373 verify = SSL_VERIFY_PEER;
4374 break;
4375 case SSL_SOCK_VERIFY_REQUIRED:
4376 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4377 break;
4378 }
4379 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4380 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004381 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 +01004382 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 +01004383 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 +01004384 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004385 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004386 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004387 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004388 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004389 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004390 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004391 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4392 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4393 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4394 cfgerr |= ERR_ALERT | ERR_FATAL;
4395 }
4396 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004397 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004398 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 +02004399 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004400 }
Emeric Brun850efd52014-01-29 12:24:34 +01004401 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004402 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4403 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004404 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004405 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004406#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004407 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004408 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4409
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004410 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004411 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4412 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004413 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004414 }
Emeric Brun561e5742012-10-02 15:20:55 +02004415 else {
4416 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4417 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004418 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004419#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004420 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004421 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004422#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004423 if(bind_conf->keys_ref) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004424 if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004425 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4426 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004427 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004428 }
4429 }
4430#endif
4431
William Lallemand4f45bb92017-10-30 20:08:51 +01004432 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004433 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4434 if (conf_ciphers &&
4435 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004436 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4437 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004438 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004439 }
4440
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004441#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004442 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4443 if (conf_ciphersuites &&
4444 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004445 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4446 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004447 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004448 }
4449#endif
4450
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004451#ifndef OPENSSL_NO_DH
Remi Gacogne47783ef2015-05-29 15:53:22 +02004452 /* If tune.ssl.default-dh-param has not been set,
4453 neither has ssl-default-dh-file and no static DH
4454 params were in the certificate file. */
Willy Tarreauef934602016-12-22 23:12:01 +01004455 if (global_ssl.default_dh_param == 0 &&
Remi Gacogne47783ef2015-05-29 15:53:22 +02004456 global_dh == NULL &&
Remi Gacogne4f902b82015-05-28 16:23:00 +02004457 (ssl_dh_ptr_index == -1 ||
4458 SSL_CTX_get_ex_data(ctx, ssl_dh_ptr_index) == NULL)) {
Willy Tarreau3ba77d22020-05-08 09:31:18 +02004459 /* default to dh-param 2048 */
4460 global_ssl.default_dh_param = 2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004461 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004462
Willy Tarreauef934602016-12-22 23:12:01 +01004463 if (global_ssl.default_dh_param >= 1024) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004464 if (local_dh_1024 == NULL) {
4465 local_dh_1024 = ssl_get_dh_1024();
4466 }
Willy Tarreauef934602016-12-22 23:12:01 +01004467 if (global_ssl.default_dh_param >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004468 if (local_dh_2048 == NULL) {
4469 local_dh_2048 = ssl_get_dh_2048();
4470 }
Willy Tarreauef934602016-12-22 23:12:01 +01004471 if (global_ssl.default_dh_param >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004472 if (local_dh_4096 == NULL) {
4473 local_dh_4096 = ssl_get_dh_4096();
4474 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004475 }
4476 }
4477 }
4478#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004479
Emeric Brunfc0421f2012-09-07 17:30:07 +02004480 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004481#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004482 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004483#endif
William Lallemandca5cf0a2021-06-09 16:46:12 +02004484#ifdef HAVE_SSL_KEYLOG
William Lallemand2cb86e72022-11-18 15:00:15 +01004485 /* only activate the keylog callback if it was required to prevent performance loss */
4486 if (global_ssl.keylog > 0)
4487 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02004488#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004489
Bernard Spil13c53f82018-02-15 13:34:58 +01004490#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004491 ssl_conf_cur = NULL;
4492 if (ssl_conf && ssl_conf->npn_str)
4493 ssl_conf_cur = ssl_conf;
4494 else if (bind_conf->ssl_conf.npn_str)
4495 ssl_conf_cur = &bind_conf->ssl_conf;
4496 if (ssl_conf_cur)
4497 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004498#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004499#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004500 ssl_conf_cur = NULL;
4501 if (ssl_conf && ssl_conf->alpn_str)
4502 ssl_conf_cur = ssl_conf;
4503 else if (bind_conf->ssl_conf.alpn_str)
4504 ssl_conf_cur = &bind_conf->ssl_conf;
4505 if (ssl_conf_cur)
4506 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004507#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004508#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004509 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4510 if (conf_curves) {
4511 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004512 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4513 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004514 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004515 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004516 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004517 }
4518#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004519#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004520 if (!conf_curves) {
Emeric Brun2b58d042012-09-20 17:10:03 +02004521 int i;
4522 EC_KEY *ecdh;
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004523#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004524 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004525 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4526 NULL);
4527
4528 if (ecdhe == NULL) {
Eric Salama3c8bde82019-11-20 11:33:40 +01004529 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Olivier Houchardc2aae742017-09-22 18:26:28 +02004530 return cfgerr;
4531 }
4532#else
4533 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4534 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4535 ECDHE_DEFAULT_CURVE);
4536#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004537
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004538 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004539 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004540 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4541 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004542 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004543 }
4544 else {
4545 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4546 EC_KEY_free(ecdh);
4547 }
4548 }
4549#endif
4550
Emeric Brunfc0421f2012-09-07 17:30:07 +02004551 return cfgerr;
4552}
4553
Evan Broderbe554312013-06-27 00:05:25 -07004554static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4555{
4556 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4557 size_t prefixlen, suffixlen;
4558
4559 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004560 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004561 return 1;
4562
Evan Broderbe554312013-06-27 00:05:25 -07004563 /* The rest of this logic is based on RFC 6125, section 6.4.3
4564 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4565
Emeric Bruna848dae2013-10-08 11:27:28 +02004566 pattern_wildcard = NULL;
4567 pattern_left_label_end = pattern;
4568 while (*pattern_left_label_end != '.') {
4569 switch (*pattern_left_label_end) {
4570 case 0:
4571 /* End of label not found */
4572 return 0;
4573 case '*':
4574 /* If there is more than one wildcards */
4575 if (pattern_wildcard)
4576 return 0;
4577 pattern_wildcard = pattern_left_label_end;
4578 break;
4579 }
4580 pattern_left_label_end++;
4581 }
4582
4583 /* If it's not trivial and there is no wildcard, it can't
4584 * match */
4585 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004586 return 0;
4587
4588 /* Make sure all labels match except the leftmost */
4589 hostname_left_label_end = strchr(hostname, '.');
4590 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004591 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004592 return 0;
4593
4594 /* Make sure the leftmost label of the hostname is long enough
4595 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004596 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004597 return 0;
4598
4599 /* Finally compare the string on either side of the
4600 * wildcard */
4601 prefixlen = pattern_wildcard - pattern;
4602 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004603 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4604 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004605 return 0;
4606
4607 return 1;
4608}
4609
4610static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4611{
4612 SSL *ssl;
4613 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004614 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004615 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004616 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004617
4618 int depth;
4619 X509 *cert;
4620 STACK_OF(GENERAL_NAME) *alt_names;
4621 int i;
4622 X509_NAME *cert_subject;
4623 char *str;
4624
4625 if (ok == 0)
4626 return ok;
4627
4628 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004629 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard66ab4982019-02-26 18:37:15 +01004630 ssl_ctx = conn->xprt_ctx;
Evan Broderbe554312013-06-27 00:05:25 -07004631
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004632 /* We're checking if the provided hostnames match the desired one. The
4633 * desired hostname comes from the SNI we presented if any, or if not
4634 * provided then it may have been explicitly stated using a "verifyhost"
4635 * directive. If neither is set, we don't care about the name so the
4636 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004637 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004638 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004639 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004640 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004641 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004642 if (!servername)
4643 return ok;
4644 }
Evan Broderbe554312013-06-27 00:05:25 -07004645
4646 /* We only need to verify the CN on the actual server cert,
4647 * not the indirect CAs */
4648 depth = X509_STORE_CTX_get_error_depth(ctx);
4649 if (depth != 0)
4650 return ok;
4651
4652 /* At this point, the cert is *not* OK unless we can find a
4653 * hostname match */
4654 ok = 0;
4655
4656 cert = X509_STORE_CTX_get_current_cert(ctx);
4657 /* It seems like this might happen if verify peer isn't set */
4658 if (!cert)
4659 return ok;
4660
4661 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4662 if (alt_names) {
4663 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4664 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4665 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004666#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004667 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4668#else
Evan Broderbe554312013-06-27 00:05:25 -07004669 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004670#endif
Evan Broderbe554312013-06-27 00:05:25 -07004671 ok = ssl_sock_srv_hostcheck(str, servername);
4672 OPENSSL_free(str);
4673 }
4674 }
4675 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004676 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004677 }
4678
4679 cert_subject = X509_get_subject_name(cert);
4680 i = -1;
4681 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4682 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004683 ASN1_STRING *value;
4684 value = X509_NAME_ENTRY_get_data(entry);
4685 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004686 ok = ssl_sock_srv_hostcheck(str, servername);
4687 OPENSSL_free(str);
4688 }
4689 }
4690
Willy Tarreau71d058c2017-07-26 20:09:56 +02004691 /* report the mismatch and indicate if SNI was used or not */
4692 if (!ok && !conn->err_code)
4693 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004694 return ok;
4695}
4696
Emeric Brun94324a42012-10-11 14:00:19 +02004697/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004698int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004699{
Willy Tarreau03209342016-12-22 17:08:28 +01004700 struct proxy *curproxy = srv->proxy;
Emeric Brun94324a42012-10-11 14:00:19 +02004701 int cfgerr = 0;
William Lallemand6338b7d2021-12-28 18:47:17 +01004702 SSL_CTX *ctx;
Emeric Brun94324a42012-10-11 14:00:19 +02004703
Thierry Fournier383085f2013-01-24 14:15:43 +01004704 /* Make sure openssl opens /dev/urandom before the chroot */
4705 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004706 ha_alert("OpenSSL random data generator initialization failed.\n");
Thierry Fournier383085f2013-01-24 14:15:43 +01004707 cfgerr++;
4708 }
4709
Willy Tarreaufce03112015-01-15 21:32:40 +01004710 /* Automatic memory computations need to know we use SSL there */
4711 global.ssl_used_backend = 1;
4712
4713 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004714 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004715 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004716 ha_alert("Proxy '%s', server '%s' [%s:%d] out of memory.\n",
4717 curproxy->id, srv->id,
4718 srv->conf.file, srv->conf.line);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004719 cfgerr++;
4720 return cfgerr;
4721 }
4722 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004723 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004724 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004725
William Lallemand6338b7d2021-12-28 18:47:17 +01004726 if (srv->ssl_ctx.client_crt) {
4727 char *err = NULL;
4728 int err_code = 0;
4729
4730 /* If there is a crt keyword there, the SSL_CTX will be created here. */
4731 err_code = ssl_sock_load_srv_cert(srv->ssl_ctx.client_crt, srv, &err);
4732 if (err_code != ERR_NONE) {
4733 if ((err_code & ERR_WARN) && !(err_code & ERR_ALERT))
4734 ha_warning("%s", err);
4735 else
4736 ha_alert("%s", err);
4737
4738 if (err_code & (ERR_FATAL|ERR_ABORT))
4739 cfgerr++;
4740 }
4741 ha_free(&err);
4742 }
4743
4744 ctx = srv->ssl_ctx.ctx;
4745
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004746 /* The context will be uninitialized if there wasn't any "cert" option
4747 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004748 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004749 ctx = SSL_CTX_new(SSLv23_client_method());
4750 if (!ctx) {
4751 ha_alert("config : %s '%s', server '%s': unable to allocate ssl context.\n",
4752 proxy_type_str(curproxy), curproxy->id,
4753 srv->id);
4754 cfgerr++;
4755 return cfgerr;
4756 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004757
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004758 srv->ssl_ctx.ctx = ctx;
4759 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004760
4761 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, srv->ssl_ctx.ctx);
4762
4763 return cfgerr;
4764}
4765
4766
4767/* Initialize an SSL context that will be used on the backend side.
4768 * Returns an error count.
4769 */
4770int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
4771{
4772 struct proxy *curproxy = srv->proxy;
4773 int cfgerr = 0;
4774 long options =
4775 SSL_OP_ALL | /* all known workarounds for bugs */
4776 SSL_OP_NO_SSLv2 |
4777 SSL_OP_NO_COMPRESSION;
4778 long mode =
4779 SSL_MODE_ENABLE_PARTIAL_WRITE |
4780 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
4781 SSL_MODE_RELEASE_BUFFERS |
4782 SSL_MODE_SMALL_BUFFERS;
4783 int verify = SSL_VERIFY_NONE;
4784 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
4785 int i, min, max, hole;
4786 int flags = MC_SSL_O_ALL;
4787
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004788 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004789 ha_warning("config : %s '%s': no-sslv3/no-tlsv1x are ignored for server '%s'. "
4790 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4791 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004792 else
4793 flags = conf_ssl_methods->flags;
4794
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004795 /* Real min and max should be determinate with configuration and openssl's capabilities */
4796 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004797 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004798 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004799 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004800
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004801 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004802 min = max = CONF_TLSV_NONE;
4803 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004804 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004805 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004806 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004807 if (min) {
4808 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004809 ha_warning("config : %s '%s': SSL/TLS versions range not contiguous for server '%s'. "
4810 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4811 proxy_type_str(curproxy), curproxy->id, srv->id,
4812 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004813 hole = 0;
4814 }
4815 max = i;
4816 }
4817 else {
4818 min = max = i;
4819 }
4820 }
4821 else {
4822 if (min)
4823 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004824 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004825 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004826 ha_alert("config : %s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
4827 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004828 cfgerr += 1;
4829 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004830
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004831#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004832 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004833 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004834 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004835 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004836 else
4837 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4838 if (flags & methodVersions[i].flag)
4839 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004840#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004841 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004842 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4843 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004844#endif
4845
4846 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
4847 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004848 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004849
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004850#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004851 if (global_ssl.async)
4852 mode |= SSL_MODE_ASYNC;
4853#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004854 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004855
Emeric Brun850efd52014-01-29 12:24:34 +01004856 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
4857 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01004858 switch (srv->ssl_ctx.verify) {
4859 case SSL_SOCK_VERIFY_NONE:
4860 verify = SSL_VERIFY_NONE;
4861 break;
4862 case SSL_SOCK_VERIFY_REQUIRED:
4863 verify = SSL_VERIFY_PEER;
4864 break;
4865 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004866 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02004867 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01004868 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02004869 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004870 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004871 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004872 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to set CA file '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01004873 curproxy->id, srv->id,
4874 srv->conf.file, srv->conf.line, srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004875 cfgerr++;
4876 }
4877 }
Emeric Brun850efd52014-01-29 12:24:34 +01004878 else {
4879 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Christopher Faulet767a84b2017-11-24 16:50:31 +01004880 ha_alert("Proxy '%s', server '%s' [%s:%d] 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",
4881 curproxy->id, srv->id,
4882 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004883 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01004884 ha_alert("Proxy '%s', server '%s' [%s:%d] verify is enabled but no CA file specified.\n",
4885 curproxy->id, srv->id,
4886 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004887 cfgerr++;
4888 }
Emeric Brunef42d922012-10-11 16:11:36 +02004889#ifdef X509_V_FLAG_CRL_CHECK
4890 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004891 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02004892
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004893 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004894 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to configure CRL file '%s'.\n",
4895 curproxy->id, srv->id,
4896 srv->conf.file, srv->conf.line, srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004897 cfgerr++;
4898 }
4899 else {
4900 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4901 }
4902 }
4903#endif
4904 }
4905
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004906 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
4907 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02004908 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004909 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004910 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set SSL cipher list to '%s'.\n",
4911 curproxy->id, srv->id,
4912 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02004913 cfgerr++;
4914 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004915
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004916#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004917 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004918 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004919 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set TLS 1.3 cipher suites to '%s'.\n",
4920 curproxy->id, srv->id,
4921 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphersuites);
4922 cfgerr++;
4923 }
4924#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01004925#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
4926 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004927 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01004928#endif
4929#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4930 if (srv->ssl_ctx.alpn_str)
4931 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
4932#endif
4933
Emeric Brun94324a42012-10-11 14:00:19 +02004934
4935 return cfgerr;
4936}
4937
Frédéric Lécailleec216522020-11-23 14:33:30 +01004938/*
4939 * Create an initial CTX used to start the SSL connections.
4940 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
4941 * Returns 0 if succeeded, or something >0 if not.
4942 */
4943#ifdef USE_QUIC
4944static int ssl_initial_ctx(struct bind_conf *bind_conf)
4945{
4946 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
4947 return ssl_quic_initial_ctx(bind_conf);
4948 else
4949 return ssl_sock_initial_ctx(bind_conf);
4950}
4951#else
4952static int ssl_initial_ctx(struct bind_conf *bind_conf)
4953{
4954 return ssl_sock_initial_ctx(bind_conf);
4955}
4956#endif
4957
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004958/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004959 * be NULL, in which case nothing is done. Returns the number of errors
4960 * encountered.
4961 */
Willy Tarreau03209342016-12-22 17:08:28 +01004962int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004963{
4964 struct ebmb_node *node;
4965 struct sni_ctx *sni;
4966 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01004967 int errcode = 0;
4968 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004969
Willy Tarreaufce03112015-01-15 21:32:40 +01004970 /* Automatic memory computations need to know we use SSL there */
4971 global.ssl_used_frontend = 1;
4972
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004973 /* Make sure openssl opens /dev/urandom before the chroot */
4974 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004975 ha_alert("OpenSSL random data generator initialization failed.\n");
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004976 err++;
4977 }
4978 /* Create initial_ctx used to start the ssl connection before do switchctx */
4979 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01004980 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004981 /* It should not be necessary to call this function, but it's
4982 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01004983 to initial_ctx in ssl_initial_ctx. */
William Lallemand8b453912019-11-21 15:48:10 +01004984 errcode |= ssl_sock_prepare_ctx(bind_conf, NULL, bind_conf->initial_ctx, &errmsg);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004985 }
Emeric Brun0bed9942014-10-30 19:25:24 +01004986 if (bind_conf->default_ctx)
William Lallemand8b453912019-11-21 15:48:10 +01004987 errcode |= ssl_sock_prepare_ctx(bind_conf, bind_conf->default_ssl_conf, bind_conf->default_ctx, &errmsg);
Emeric Brun0bed9942014-10-30 19:25:24 +01004988
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004989 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004990 while (node) {
4991 sni = ebmb_entry(node, struct sni_ctx, name);
Emeric Brun0bed9942014-10-30 19:25:24 +01004992 if (!sni->order && sni->ctx != bind_conf->default_ctx)
4993 /* only initialize the CTX on its first occurrence and
4994 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004995 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004996 node = ebmb_next(node);
4997 }
4998
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004999 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005000 while (node) {
5001 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01005002 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01005003 /* only initialize the CTX on its first occurrence and
5004 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01005005 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
5006 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02005007 node = ebmb_next(node);
5008 }
William Lallemand8b453912019-11-21 15:48:10 +01005009
5010 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005011 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005012 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005013 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005014 err++;
5015 }
5016
5017 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005018 return err;
5019}
5020
Willy Tarreau55d37912016-12-21 23:38:39 +01005021/* Prepares all the contexts for a bind_conf and allocates the shared SSL
5022 * context if needed. Returns < 0 on error, 0 on success. The warnings and
5023 * alerts are directly emitted since the rest of the stack does it below.
5024 */
5025int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
5026{
5027 struct proxy *px = bind_conf->frontend;
5028 int alloc_ctx;
5029 int err;
5030
5031 if (!bind_conf->is_ssl) {
5032 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005033 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
5034 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01005035 }
5036 return 0;
5037 }
5038 if (!bind_conf->default_ctx) {
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005039 if (bind_conf->strict_sni && !bind_conf->generate_certs) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005040 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5041 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005042 }
5043 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005044 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5045 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005046 return -1;
5047 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005048 }
William Lallemandc61c0b32017-12-04 18:46:39 +01005049 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005050 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02005051 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
William Lallemandc3cd35f2017-11-28 11:04:43 +01005052 sizeof(*sh_ssl_sess_tree),
5053 ((global.nbthread > 1) || (!global_ssl.private_cache && (global.nbproc > 1))) ? 1 : 0);
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02005054 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005055 if (alloc_ctx == SHCTX_E_INIT_LOCK)
5056 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");
5057 else
5058 ha_alert("Unable to allocate SSL session cache.\n");
5059 return -1;
5060 }
5061 /* free block callback */
5062 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5063 /* init the root tree within the extra space */
5064 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5065 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01005066 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005067 err = 0;
5068 /* initialize all certificate contexts */
5069 err += ssl_sock_prepare_all_ctx(bind_conf);
5070
5071 /* initialize CA variables if the certificates generation is enabled */
5072 err += ssl_sock_load_ca(bind_conf);
5073
5074 return -err;
5075}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005076
William Lallemand9d118682021-12-30 11:25:43 +01005077/* release ssl context allocated for servers. Most of the field free here
5078 * must also be allocated in srv_ssl_settings_cpy() */
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005079void ssl_sock_free_srv_ctx(struct server *srv)
5080{
Olivier Houchardc7566002018-11-20 23:33:50 +01005081#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
William Lallemand9d118682021-12-30 11:25:43 +01005082 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005083#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005084#ifdef OPENSSL_NPN_NEGOTIATED
William Lallemand9d118682021-12-30 11:25:43 +01005085 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005086#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005087 if (srv->ssl_ctx.reused_sess) {
5088 int i;
5089
William Lallemandc78ac5a2021-11-17 02:59:21 +01005090 for (i = 0; i < global.nbthread; i++) {
Willy Tarreaue709e822021-02-26 21:06:32 +01005091 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
William Lallemandc78ac5a2021-11-17 02:59:21 +01005092 ha_free(&srv->ssl_ctx.reused_sess[i].sni);
5093 }
Willy Tarreaue709e822021-02-26 21:06:32 +01005094 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005095 }
5096
Willy Tarreaue709e822021-02-26 21:06:32 +01005097 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005098 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005099 srv->ssl_ctx.ctx = NULL;
5100 }
William Lallemand9d118682021-12-30 11:25:43 +01005101
5102 ha_free(&srv->ssl_ctx.ca_file);
5103 ha_free(&srv->ssl_ctx.crl_file);
5104 ha_free(&srv->ssl_ctx.client_crt);
5105 ha_free(&srv->ssl_ctx.verify_host);
5106#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5107 ha_free(&srv->sni_expr);
William Lallemand17d0caa2022-03-16 17:48:19 +01005108 release_sample_expr(srv->ssl_ctx.sni);
5109 srv->ssl_ctx.sni = NULL;
William Lallemand9d118682021-12-30 11:25:43 +01005110#endif
5111 ha_free(&srv->ssl_ctx.ciphers);
5112#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
5113 ha_free(&srv->ssl_ctx.ciphersuites);
5114#endif
William Lallemandec3d2d62021-12-30 14:45:19 +01005115 /* If there is a certificate we must unlink the ckch instance */
5116 ckch_inst_free(srv->ssl_ctx.inst);
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005117}
5118
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005119/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005120 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5121 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005122void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005123{
5124 struct ebmb_node *node, *back;
5125 struct sni_ctx *sni;
5126
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005127 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005128 while (node) {
5129 sni = ebmb_entry(node, struct sni_ctx, name);
5130 back = ebmb_next(node);
5131 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005132 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005133 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005134 free(sni);
5135 node = back;
5136 }
5137
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005138 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005139 while (node) {
5140 sni = ebmb_entry(node, struct sni_ctx, name);
5141 back = ebmb_next(node);
5142 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005143 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005144 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005145 free(sni);
5146 node = back;
5147 }
William Lallemandb2408692020-06-24 09:54:29 +02005148
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005149 SSL_CTX_free(bind_conf->initial_ctx);
5150 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005151 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005152 bind_conf->default_ctx = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005153 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005154}
William Lallemandb2408692020-06-24 09:54:29 +02005155
5156
5157void ssl_sock_deinit()
5158{
5159 crtlist_deinit(); /* must be free'd before the ckchs */
5160 ckch_deinit();
5161}
5162REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005163
Willy Tarreau795cdab2016-12-22 17:30:54 +01005164/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5165void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5166{
5167 ssl_sock_free_ca(bind_conf);
5168 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005169 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005170 free(bind_conf->ca_sign_file);
5171 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005172 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005173 free(bind_conf->keys_ref->filename);
5174 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005175 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005176 free(bind_conf->keys_ref);
5177 }
5178 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005179 bind_conf->ca_sign_pass = NULL;
5180 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005181}
5182
Christopher Faulet31af49d2015-06-09 17:29:50 +02005183/* Load CA cert file and private key used to generate certificates */
5184int
Willy Tarreau03209342016-12-22 17:08:28 +01005185ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005186{
Willy Tarreau03209342016-12-22 17:08:28 +01005187 struct proxy *px = bind_conf->frontend;
Shimi Gersner5846c492020-08-23 13:58:12 +03005188 struct cert_key_and_chain *ckch = NULL;
5189 int ret = 0;
5190 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005191
Christopher Fauletf8bb0ce2017-09-15 09:52:49 +02005192 if (!bind_conf->generate_certs)
Shimi Gersner5846c492020-08-23 13:58:12 +03005193 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005194
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005195#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005196 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005197 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005198 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005199 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005200 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005201#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005202
Christopher Faulet31af49d2015-06-09 17:29:50 +02005203 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005204 ha_alert("Proxy '%s': cannot enable certificate generation, "
5205 "no CA certificate File configured at [%s:%d].\n",
5206 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005207 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005208 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005209
Shimi Gersner5846c492020-08-23 13:58:12 +03005210 /* Allocate cert structure */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02005211 ckch = calloc(1, sizeof(*ckch));
Shimi Gersner5846c492020-08-23 13:58:12 +03005212 if (!ckch) {
5213 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5214 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5215 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005216 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005217
5218 /* Try to parse file */
5219 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, ckch, &err)) {
5220 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5221 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005222 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005223 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005224 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005225
5226 /* Fail if missing cert or pkey */
5227 if ((!ckch->cert) || (!ckch->key)) {
5228 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5229 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5230 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005231 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005232
Shimi Gersner5846c492020-08-23 13:58:12 +03005233 /* Final assignment to bind */
5234 bind_conf->ca_sign_ckch = ckch;
5235 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005236
Shimi Gersner5846c492020-08-23 13:58:12 +03005237 failed:
5238 if (ckch) {
5239 ssl_sock_free_cert_key_and_chain_contents(ckch);
5240 free(ckch);
5241 }
5242
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005243 bind_conf->generate_certs = 0;
Shimi Gersner5846c492020-08-23 13:58:12 +03005244 ret++;
5245 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005246}
5247
5248/* Release CA cert and private key used to generate certificated */
5249void
5250ssl_sock_free_ca(struct bind_conf *bind_conf)
5251{
Shimi Gersner5846c492020-08-23 13:58:12 +03005252 if (bind_conf->ca_sign_ckch) {
5253 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005254 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005255 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005256}
5257
Emeric Brun46591952012-05-18 15:47:34 +02005258/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005259 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5260 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5261 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5262 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005263 * 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 +01005264 * as parameters to this function.
5265 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5266 * CO_ER_SSL_NO_MEM.
5267 */
5268int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5269 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5270{
5271 int retry = 1;
5272
5273 retry:
5274 /* Alloc a new SSL session. */
5275 *ssl = SSL_new(ssl_ctx);
5276 if (!*ssl) {
5277 if (!retry--)
5278 goto err;
5279
5280 pool_gc(NULL);
5281 goto retry;
5282 }
5283
5284 *bio = BIO_new(bio_meth);
5285 if (!*bio) {
5286 SSL_free(*ssl);
5287 *ssl = NULL;
5288 if (!retry--)
5289 goto err;
5290
5291 pool_gc(NULL);
5292 goto retry;
5293 }
5294
5295 BIO_set_data(*bio, ctx);
5296 SSL_set_bio(*ssl, *bio, *bio);
5297
5298 /* set connection pointer. */
5299 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5300 SSL_free(*ssl);
5301 *ssl = NULL;
5302 if (!retry--)
5303 goto err;
5304
5305 pool_gc(NULL);
5306 goto retry;
5307 }
5308
5309 return 0;
5310
5311 err:
5312 conn->err_code = CO_ER_SSL_NO_MEM;
5313 return -1;
5314}
5315
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005316/* This function is called when all the XPRT have been initialized. We can
5317 * now attempt to start the SSL handshake.
5318 */
5319static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5320{
5321 struct ssl_sock_ctx *ctx = xprt_ctx;
5322
5323 if (ctx->xprt->start) {
5324 int ret;
5325
5326 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5327 if (ret < 0)
5328 return ret;
5329 }
5330 tasklet_wakeup(ctx->wait_event.tasklet);
5331
5332 return 0;
5333}
5334
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005335/*
Emeric Brun46591952012-05-18 15:47:34 +02005336 * This function is called if SSL * context is not yet allocated. The function
5337 * is designed to be called before any other data-layer operation and sets the
5338 * handshake flag on the connection. It is safe to call it multiple times.
5339 * It returns 0 on success and -1 in error case.
5340 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005341static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005342{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005343 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005344 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005345 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005346 return 0;
5347
Olivier Houchard66ab4982019-02-26 18:37:15 +01005348 ctx = pool_alloc(ssl_sock_ctx_pool);
5349 if (!ctx) {
5350 conn->err_code = CO_ER_SSL_NO_MEM;
5351 return -1;
5352 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005353 ctx->wait_event.tasklet = tasklet_new();
5354 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005355 conn->err_code = CO_ER_SSL_NO_MEM;
5356 pool_free(ssl_sock_ctx_pool, ctx);
5357 return -1;
5358 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005359 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5360 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005361 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005362 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005363 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005364 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005365 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005366 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005367 ctx->xprt_st = 0;
5368 ctx->xprt_ctx = NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005369
5370 /* Only work with sockets for now, this should be adapted when we'll
5371 * add QUIC support.
5372 */
5373 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005374 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005375 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5376 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005377 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005378
Willy Tarreau20879a02012-12-03 16:32:10 +01005379 if (global.maxsslconn && sslconns >= global.maxsslconn) {
5380 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005381 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005382 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005383
Emeric Brun46591952012-05-18 15:47:34 +02005384 /* If it is in client mode initiate SSL session
5385 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005386 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005387 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5388 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005389 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005390
Olivier Houchard66ab4982019-02-26 18:37:15 +01005391 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005392 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005393 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5394 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5395 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 +01005396 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005397 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005398 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005399 } else if (sess) {
5400 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005401 }
5402 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005403 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005404
Emeric Brun46591952012-05-18 15:47:34 +02005405 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005406 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005407
Willy Tarreau4781b152021-04-06 13:53:36 +02005408 _HA_ATOMIC_INC(&sslconns);
5409 _HA_ATOMIC_INC(&totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005410 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005411 return 0;
5412 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005413 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005414 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005415
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005416 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5417 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005418 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005419
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005420#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005421 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005422 b_alloc(&ctx->early_buf);
5423 SSL_set_max_early_data(ctx->ssl,
5424 /* Only allow early data if we managed to allocate
5425 * a buffer.
5426 */
5427 (!b_is_null(&ctx->early_buf)) ?
5428 global.tune.bufsize - global.tune.maxrewrite : 0);
5429 }
5430#endif
5431
Olivier Houchard66ab4982019-02-26 18:37:15 +01005432 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005433
Emeric Brun46591952012-05-18 15:47:34 +02005434 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005435 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005436#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005437 if (bc->ssl_conf.early_data)
5438 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005439#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005440
Willy Tarreau4781b152021-04-06 13:53:36 +02005441 _HA_ATOMIC_INC(&sslconns);
5442 _HA_ATOMIC_INC(&totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005443 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005444 return 0;
5445 }
5446 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005447 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005448err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005449 if (ctx && ctx->wait_event.tasklet)
5450 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005451 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005452 return -1;
5453}
5454
5455
5456/* This is the callback which is used when an SSL handshake is pending. It
5457 * updates the FD status if it wants some polling before being called again.
5458 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5459 * otherwise it returns non-zero and removes itself from the connection's
5460 * flags (the bit is provided in <flag> by the caller).
5461 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005462static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005463{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005464 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005465 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005466 struct ssl_counters *counters = NULL;
5467 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005468 struct listener *li;
5469 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005470 socklen_t lskerr;
5471 int skerr;
5472
Emeric Brun46591952012-05-18 15:47:34 +02005473
Willy Tarreau3c728722014-01-23 13:50:42 +01005474 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005475 return 0;
5476
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005477 /* get counters */
5478 switch (obj_type(conn->target)) {
5479 case OBJ_TYPE_LISTENER:
5480 li = objt_listener(conn->target);
5481 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5482 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5483 &ssl_stats_module);
5484 break;
5485
5486 case OBJ_TYPE_SERVER:
5487 srv = objt_server(conn->target);
5488 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5489 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5490 &ssl_stats_module);
5491 break;
5492
5493 default:
5494 break;
5495 }
5496
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02005497 if (!conn->xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005498 goto out_error;
5499
Willy Tarreau06300382021-02-02 15:42:25 +01005500 /* don't start calculating a handshake on a dead connection */
5501 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5502 goto out_error;
5503
5504 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5505 * status from the lower layers, so let's check the FD directly. Ideally
5506 * the xprt layers should provide some status indicating their knowledge
5507 * of shutdowns or error.
5508 */
5509 skerr = 0;
5510 lskerr = sizeof(skerr);
5511 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5512 skerr != 0)
5513 goto out_error;
5514
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005515#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005516 /*
5517 * Check if we have early data. If we do, we have to read them
5518 * before SSL_do_handshake() is called, And there's no way to
5519 * detect early data, except to try to read them
5520 */
5521 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005522 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005523
Olivier Houchard54907bb2019-12-19 15:02:39 +01005524 while (1) {
5525 ret = SSL_read_early_data(ctx->ssl,
5526 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5527 &read_data);
5528 if (ret == SSL_READ_EARLY_DATA_ERROR)
5529 goto check_error;
5530 if (read_data > 0) {
5531 conn->flags |= CO_FL_EARLY_DATA;
5532 b_add(&ctx->early_buf, read_data);
5533 }
5534 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5535 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5536 if (!b_data(&ctx->early_buf))
5537 b_free(&ctx->early_buf);
5538 break;
5539 }
5540 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005541 }
5542#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005543 /* If we use SSL_do_handshake to process a reneg initiated by
5544 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5545 * Usually SSL_write and SSL_read are used and process implicitly
5546 * the reneg handshake.
5547 * Here we use SSL_peek as a workaround for reneg.
5548 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005549 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005550 char c;
5551
Olivier Houchard66ab4982019-02-26 18:37:15 +01005552 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005553 if (ret <= 0) {
5554 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005555 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005556
Emeric Brun674b7432012-11-08 19:21:55 +01005557 if (ret == SSL_ERROR_WANT_WRITE) {
5558 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005559 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005560 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005561 return 0;
5562 }
5563 else if (ret == SSL_ERROR_WANT_READ) {
5564 /* handshake may have been completed but we have
5565 * no more data to read.
5566 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005567 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005568 ret = 1;
5569 goto reneg_ok;
5570 }
5571 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005572 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005573 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005574 return 0;
5575 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005576#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005577 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005578 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005579 return 0;
5580 }
5581#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005582 else if (ret == SSL_ERROR_SYSCALL) {
5583 /* if errno is null, then connection was successfully established */
5584 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5585 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005586 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005587#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5588 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005589 conn->err_code = CO_ER_SSL_HANDSHAKE;
5590#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005591 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005592#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005593 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005594 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005595 empty_handshake = state == TLS_ST_BEFORE;
5596#else
Lukas Tribus49799162019-07-08 14:29:15 +02005597 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5598 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005599#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005600 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005601 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005602 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005603 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5604 else
5605 conn->err_code = CO_ER_SSL_EMPTY;
5606 }
5607 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005608 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005609 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5610 else
5611 conn->err_code = CO_ER_SSL_ABORT;
5612 }
5613 }
5614 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005615 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005616 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005617 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005618 conn->err_code = CO_ER_SSL_HANDSHAKE;
5619 }
Lukas Tribus49799162019-07-08 14:29:15 +02005620#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005621 }
Emeric Brun674b7432012-11-08 19:21:55 +01005622 goto out_error;
5623 }
5624 else {
5625 /* Fail on all other handshake errors */
5626 /* Note: OpenSSL may leave unread bytes in the socket's
5627 * buffer, causing an RST to be emitted upon close() on
5628 * TCP sockets. We first try to drain possibly pending
5629 * data to avoid this as much as possible.
5630 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005631 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005632 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005633 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005634 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005635 goto out_error;
5636 }
5637 }
5638 /* read some data: consider handshake completed */
5639 goto reneg_ok;
5640 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005641 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005642check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005643 if (ret != 1) {
5644 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005645 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005646
5647 if (ret == SSL_ERROR_WANT_WRITE) {
5648 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005649 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005650 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005651 return 0;
5652 }
5653 else if (ret == SSL_ERROR_WANT_READ) {
5654 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005655 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005656 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5657 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005658 return 0;
5659 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005660#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005661 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005662 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005663 return 0;
5664 }
5665#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005666 else if (ret == SSL_ERROR_SYSCALL) {
5667 /* if errno is null, then connection was successfully established */
5668 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5669 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005670 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005671#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5672 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005673 conn->err_code = CO_ER_SSL_HANDSHAKE;
5674#else
5675 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005676#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005677 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005678 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005679 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005680#else
Lukas Tribus49799162019-07-08 14:29:15 +02005681 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5682 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005683#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005684 if (empty_handshake) {
5685 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005686 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005687 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5688 else
5689 conn->err_code = CO_ER_SSL_EMPTY;
5690 }
5691 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005692 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005693 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5694 else
5695 conn->err_code = CO_ER_SSL_ABORT;
5696 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005697 }
5698 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005699 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005700 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5701 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005702 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005703 }
Lukas Tribus49799162019-07-08 14:29:15 +02005704#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005705 }
Willy Tarreau89230192012-09-28 20:22:13 +02005706 goto out_error;
5707 }
Emeric Brun46591952012-05-18 15:47:34 +02005708 else {
5709 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005710 /* Note: OpenSSL may leave unread bytes in the socket's
5711 * buffer, causing an RST to be emitted upon close() on
5712 * TCP sockets. We first try to drain possibly pending
5713 * data to avoid this as much as possible.
5714 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005715 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005716 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005717 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005718 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005719 goto out_error;
5720 }
5721 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005722#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005723 else {
5724 /*
5725 * If the server refused the early data, we have to send a
5726 * 425 to the client, as we no longer have the data to sent
5727 * them again.
5728 */
5729 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005730 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005731 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5732 goto out_error;
5733 }
5734 }
5735 }
5736#endif
5737
Emeric Brun46591952012-05-18 15:47:34 +02005738
Emeric Brun674b7432012-11-08 19:21:55 +01005739reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005740
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005741#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00005742 /* ASYNC engine API doesn't support moving read/write
5743 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005744 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005745 */
5746 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005747 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005748#endif
Emeric Brun46591952012-05-18 15:47:34 +02005749 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005750 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005751 if (objt_server(conn->target)) {
5752 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5753 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5754 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005755 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005756 else {
5757 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5758 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5759 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5760 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005761
Willy Tarreau42995282020-11-06 13:19:18 +01005762 if (counters) {
Willy Tarreau41736ab2021-11-22 17:46:13 +01005763 HA_ATOMIC_INC(&counters->sess);
5764 HA_ATOMIC_INC(&counters_px->sess);
Willy Tarreau42995282020-11-06 13:19:18 +01005765 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005766 }
Willy Tarreau42995282020-11-06 13:19:18 +01005767 else if (counters) {
Willy Tarreau41736ab2021-11-22 17:46:13 +01005768 HA_ATOMIC_INC(&counters->reused_sess);
5769 HA_ATOMIC_INC(&counters_px->reused_sess);
Emeric Brun46591952012-05-18 15:47:34 +02005770 }
5771
5772 /* The connection is now established at both layers, it's time to leave */
5773 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5774 return 1;
5775
5776 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005777 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005778 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005779 ERR_clear_error();
5780
Emeric Brun9fa89732012-10-04 17:09:56 +02005781 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01005782 if (objt_server(conn->target)) {
5783 struct server *s = __objt_server(conn->target);
5784 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
5785 * one cache per thread, it only prevents to flush it from the CLI in
5786 * another thread */
5787
5788 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005789 if (s->ssl_ctx.reused_sess[tid].ptr)
5790 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005791 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02005792 }
5793
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005794 if (counters) {
Willy Tarreau41736ab2021-11-22 17:46:13 +01005795 HA_ATOMIC_INC(&counters->failed_handshake);
5796 HA_ATOMIC_INC(&counters_px->failed_handshake);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005797 }
5798
Emeric Brun46591952012-05-18 15:47:34 +02005799 /* Fail on all other handshake errors */
5800 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01005801 if (!conn->err_code)
5802 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005803 return 0;
5804}
5805
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005806/* Called from the upper layer, to subscribe <es> to events <event_type>. The
5807 * event subscriber <es> is not allowed to change from a previous call as long
5808 * as at least one event is still subscribed. The <event_type> must only be a
5809 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
5810 * unless the transport layer was already released.
5811 */
5812static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005813{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005814 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005815
Olivier Houchard0ff28652019-06-24 18:57:39 +02005816 if (!ctx)
5817 return -1;
5818
Willy Tarreau113d52b2020-01-10 09:20:26 +01005819 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005820 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005821
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005822 ctx->subs = es;
5823 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005824
5825 /* we may have to subscribe to lower layers for new events */
5826 event_type &= ~ctx->wait_event.events;
5827 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
5828 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005829 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005830}
5831
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005832/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
5833 * The <es> pointer is not allowed to differ from the one passed to the
5834 * subscribe() call. It always returns zero.
5835 */
5836static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005837{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005838 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005839
Willy Tarreau113d52b2020-01-10 09:20:26 +01005840 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005841 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005842
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005843 es->events &= ~event_type;
5844 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01005845 ctx->subs = NULL;
5846
5847 /* If we subscribed, and we're not doing the handshake,
5848 * then we subscribed because the upper layer asked for it,
5849 * as the upper layer is no longer interested, we can
5850 * unsubscribe too.
5851 */
5852 event_type &= ctx->wait_event.events;
5853 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
5854 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005855
5856 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005857}
5858
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005859/* The connection has been taken over, so destroy the old tasklet and create
5860 * a new one. The original thread ID must be passed into orig_tid
5861 * It should be called with the takeover lock for the old thread held.
5862 * Returns 0 on success, and -1 on failure
5863 */
5864static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
5865{
5866 struct ssl_sock_ctx *ctx = xprt_ctx;
5867 struct tasklet *tl = tasklet_new();
5868
5869 if (!tl)
5870 return -1;
5871
5872 ctx->wait_event.tasklet->context = NULL;
5873 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
5874 ctx->wait_event.tasklet = tl;
5875 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5876 ctx->wait_event.tasklet->context = ctx;
5877 return 0;
5878}
5879
Willy Tarreau41491682021-03-02 17:29:56 +01005880/* notify the next xprt that the connection is about to become idle and that it
5881 * may be stolen at any time after the function returns and that any tasklet in
5882 * the chain must be careful before dereferencing its context.
5883 */
5884static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
5885{
5886 struct ssl_sock_ctx *ctx = xprt_ctx;
5887
5888 if (!ctx || !ctx->wait_event.tasklet)
5889 return;
5890
5891 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
5892 if (ctx->xprt)
5893 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
5894}
5895
5896/* notify the next xprt that the connection is not idle anymore and that it may
5897 * not be stolen before the next xprt_set_idle().
5898 */
5899static void ssl_set_used(struct connection *conn, void *xprt_ctx)
5900{
5901 struct ssl_sock_ctx *ctx = xprt_ctx;
5902
5903 if (!ctx || !ctx->wait_event.tasklet)
5904 return;
5905
5906 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
5907 if (ctx->xprt)
5908 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
5909}
5910
Olivier Houchard2e055482019-05-27 19:50:12 +02005911/* Use the provided XPRT as an underlying XPRT, and provide the old one.
5912 * Returns 0 on success, and non-zero on failure.
5913 */
5914static 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)
5915{
5916 struct ssl_sock_ctx *ctx = xprt_ctx;
5917
5918 if (oldxprt_ops != NULL)
5919 *oldxprt_ops = ctx->xprt;
5920 if (oldxprt_ctx != NULL)
5921 *oldxprt_ctx = ctx->xprt_ctx;
5922 ctx->xprt = toadd_ops;
5923 ctx->xprt_ctx = toadd_ctx;
5924 return 0;
5925}
5926
Olivier Houchard5149b592019-05-23 17:47:36 +02005927/* Remove the specified xprt. If if it our underlying XPRT, remove it and
5928 * return 0, otherwise just call the remove_xprt method from the underlying
5929 * XPRT.
5930 */
5931static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
5932{
5933 struct ssl_sock_ctx *ctx = xprt_ctx;
5934
5935 if (ctx->xprt_ctx == toremove_ctx) {
5936 ctx->xprt_ctx = newctx;
5937 ctx->xprt = newops;
5938 return 0;
5939 }
5940 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
5941}
5942
Willy Tarreau144f84a2021-03-02 16:09:26 +01005943struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02005944{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005945 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005946 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005947 struct connection *conn;
5948 int conn_in_list;
5949 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005950
Willy Tarreau41491682021-03-02 17:29:56 +01005951 if (state & TASK_F_USR1) {
5952 /* the tasklet was idling on an idle connection, it might have
5953 * been stolen, let's be careful!
5954 */
5955 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
5956 if (tl->context == NULL) {
5957 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
5958 tasklet_free(tl);
5959 return NULL;
5960 }
5961 conn = ctx->conn;
Christopher Fauletc5fd15d2023-03-16 11:43:05 +01005962 conn_in_list = conn_get_idle_flag(conn);
Willy Tarreau41491682021-03-02 17:29:56 +01005963 if (conn_in_list)
5964 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01005965 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01005966 } else {
5967 conn = ctx->conn;
5968 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005969 }
Willy Tarreau41491682021-03-02 17:29:56 +01005970
Olivier Houchardea8dd942019-05-20 14:02:16 +02005971 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01005972 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005973 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01005974 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
5975 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01005976 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01005977 }
5978 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005979 /* If we had an error, or the handshake is done and I/O is available,
5980 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01005981 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02005982 * we can't be sure conn_fd_handler() will be called again.
5983 */
5984 if ((ctx->conn->flags & CO_FL_ERROR) ||
5985 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005986 int woke = 0;
5987
5988 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005989 if (ctx->subs) {
5990 tasklet_wakeup(ctx->subs->tasklet);
5991 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005992 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005993 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005994 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005995
Olivier Houchardea8dd942019-05-20 14:02:16 +02005996 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01005997 * upper layers know. If we have no mux, create it,
5998 * and once we have a mux, call its wake method if we didn't
5999 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02006000 */
6001 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01006002 if (!ctx->conn->mux)
6003 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006004 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006005 ret = ctx->conn->mux->wake(ctx->conn);
6006 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006007 }
6008 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006009#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006010 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006011 else if (b_data(&ctx->early_buf) && ctx->subs &&
6012 ctx->subs->events & SUB_RETRY_RECV) {
6013 tasklet_wakeup(ctx->subs->tasklet);
6014 ctx->subs->events &= ~SUB_RETRY_RECV;
6015 if (!ctx->subs->events)
6016 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01006017 }
6018#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006019leave:
6020 if (!ret && conn_in_list) {
6021 struct server *srv = objt_server(conn->target);
6022
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006023 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006024 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau430bf4a2021-03-04 09:45:32 +01006025 ebmb_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006026 else
Willy Tarreau430bf4a2021-03-04 09:45:32 +01006027 ebmb_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006028 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006029 }
Willy Tarreau74163142021-03-13 11:30:19 +01006030 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006031}
6032
Emeric Brun46591952012-05-18 15:47:34 +02006033/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01006034 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02006035 * buffer wraps, in which case a second call may be performed. The connection's
6036 * flags are updated with whatever special event is detected (error, read0,
6037 * empty). The caller is responsible for taking care of those events and
6038 * avoiding the call if inappropriate. The function does not call the
6039 * connection's polling update function, so the caller is responsible for this.
6040 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006041static 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 +02006042{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006043 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02006044 ssize_t ret;
6045 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02006046
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006047 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006048 goto out_error;
6049
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006050#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006051 if (b_data(&ctx->early_buf)) {
6052 try = b_contig_space(buf);
6053 if (try > b_data(&ctx->early_buf))
6054 try = b_data(&ctx->early_buf);
6055 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
6056 b_add(buf, try);
6057 b_del(&ctx->early_buf, try);
6058 if (b_data(&ctx->early_buf) == 0)
6059 b_free(&ctx->early_buf);
6060 return try;
6061 }
6062#endif
6063
Willy Tarreau911db9b2020-01-23 16:27:54 +01006064 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006065 /* a handshake was requested */
6066 return 0;
6067
Emeric Brun46591952012-05-18 15:47:34 +02006068 /* read the largest possible block. For this, we perform only one call
6069 * to recv() unless the buffer wraps and we exactly fill the first hunk,
6070 * in which case we accept to do it once again. A new attempt is made on
6071 * EINTR too.
6072 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01006073 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006074
Willy Tarreau591d4452018-06-15 17:21:00 +02006075 try = b_contig_space(buf);
6076 if (!try)
6077 break;
6078
Willy Tarreauabf08d92014-01-14 11:31:27 +01006079 if (try > count)
6080 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02006081
Olivier Houchard66ab4982019-02-26 18:37:15 +01006082 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02006083
Emeric Brune1f38db2012-09-03 20:36:47 +02006084 if (conn->flags & CO_FL_ERROR) {
6085 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006086 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006087 }
Emeric Brun46591952012-05-18 15:47:34 +02006088 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006089 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006090 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006091 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006092 }
Emeric Brun46591952012-05-18 15:47:34 +02006093 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006094 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006095 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006096 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006097 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006098 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006099#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006100 /* Async mode can be re-enabled, because we're leaving data state.*/
6101 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006102 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006103#endif
Emeric Brun46591952012-05-18 15:47:34 +02006104 break;
6105 }
6106 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006107 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006108 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6109 SUB_RETRY_RECV,
6110 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006111 /* handshake is running, and it may need to re-enable read */
6112 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006113#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006114 /* Async mode can be re-enabled, because we're leaving data state.*/
6115 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006116 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006117#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006118 break;
6119 }
Emeric Brun46591952012-05-18 15:47:34 +02006120 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006121 } else if (ret == SSL_ERROR_ZERO_RETURN)
6122 goto read0;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006123 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6124 * stack before shutting down the connection for
6125 * reading. */
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006126 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN))
6127 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006128 /* otherwise it's a real error */
6129 goto out_error;
6130 }
6131 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006132 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006133 return done;
6134
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006135 clear_ssl_error:
6136 /* Clear openssl global errors stack */
6137 ssl_sock_dump_errors(conn);
6138 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006139 read0:
6140 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006141 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006142
Emeric Brun46591952012-05-18 15:47:34 +02006143 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006144 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006145 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006146 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006147 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006148 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006149}
6150
6151
Willy Tarreau787db9a2018-06-14 18:31:46 +02006152/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6153 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6154 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006155 * Only one call to send() is performed, unless the buffer wraps, in which case
6156 * a second call may be performed. The connection's flags are updated with
6157 * whatever special event is detected (error, empty). The caller is responsible
6158 * for taking care of those events and avoiding the call if inappropriate. The
6159 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006160 * is responsible for this. The buffer's output is not adjusted, it's up to the
6161 * caller to take care of this. It's up to the caller to update the buffer's
6162 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006163 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006164static 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 +02006165{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006166 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006167 ssize_t ret;
6168 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006169
6170 done = 0;
6171
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006172 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006173 goto out_error;
6174
Willy Tarreau911db9b2020-01-23 16:27:54 +01006175 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006176 /* a handshake was requested */
6177 return 0;
6178
6179 /* send the largest possible block. For this we perform only one call
6180 * to send() unless the buffer wraps and we exactly fill the first hunk,
6181 * in which case we accept to do it once again.
6182 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006183 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006184#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006185 size_t written_data;
6186#endif
6187
Willy Tarreau787db9a2018-06-14 18:31:46 +02006188 try = b_contig_data(buf, done);
6189 if (try > count)
6190 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006191
Willy Tarreau7bed9452014-02-02 02:00:24 +01006192 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006193 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006194 global_ssl.max_record && try > global_ssl.max_record) {
6195 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006196 }
6197 else {
6198 /* we need to keep the information about the fact that
6199 * we're not limiting the upcoming send(), because if it
6200 * fails, we'll have to retry with at least as many data.
6201 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006202 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006203 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006204
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006205#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006206 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006207 unsigned int max_early;
6208
Olivier Houchard522eea72017-11-03 16:27:47 +01006209 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006210 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006211 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006212 if (SSL_get0_session(ctx->ssl))
6213 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006214 else
6215 max_early = 0;
6216 }
6217
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006218 if (try + ctx->sent_early_data > max_early) {
6219 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006220 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006221 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006222 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006223 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006224 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006225 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006226 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006227 if (ret == 1) {
6228 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006229 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006230 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006231 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006232 /* Initiate the handshake, now */
6233 tasklet_wakeup(ctx->wait_event.tasklet);
6234 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006235
Olivier Houchardc2aae742017-09-22 18:26:28 +02006236 }
6237
6238 } else
6239#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006240 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006241
Emeric Brune1f38db2012-09-03 20:36:47 +02006242 if (conn->flags & CO_FL_ERROR) {
6243 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006244 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006245 }
Emeric Brun46591952012-05-18 15:47:34 +02006246 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006247 /* A send succeeded, so we can consider ourself connected */
6248 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006249 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006250 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006251 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006252 }
6253 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006254 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006255
Emeric Brun46591952012-05-18 15:47:34 +02006256 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006257 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006258 /* handshake is running, and it may need to re-enable write */
6259 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006260 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006261#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006262 /* Async mode can be re-enabled, because we're leaving data state.*/
6263 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006264 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006265#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006266 break;
6267 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006268
Emeric Brun46591952012-05-18 15:47:34 +02006269 break;
6270 }
6271 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006272 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006273 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006274 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6275 SUB_RETRY_RECV,
6276 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006277#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006278 /* Async mode can be re-enabled, because we're leaving data state.*/
6279 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006280 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006281#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006282 break;
6283 }
Emeric Brun46591952012-05-18 15:47:34 +02006284 goto out_error;
6285 }
6286 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006287 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006288 return done;
6289
6290 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006291 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006292 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006293 ERR_clear_error();
6294
Emeric Brun46591952012-05-18 15:47:34 +02006295 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006296 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006297}
6298
Willy Tarreau832e2422021-05-13 10:11:03 +02006299void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006300
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006301 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006302
Olivier Houchardea8dd942019-05-20 14:02:16 +02006303
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006304 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006305 if (ctx->wait_event.events != 0)
6306 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6307 ctx->wait_event.events,
6308 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006309 if (ctx->subs) {
6310 ctx->subs->events = 0;
6311 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006312 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006313
Olivier Houchard692c1d02019-05-23 18:41:47 +02006314 if (ctx->xprt->close)
6315 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006316#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006317 if (global_ssl.async) {
6318 OSSL_ASYNC_FD all_fd[32], afd;
6319 size_t num_all_fds = 0;
6320 int i;
6321
Olivier Houchard66ab4982019-02-26 18:37:15 +01006322 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006323 if (num_all_fds > 32) {
6324 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6325 return;
6326 }
6327
Olivier Houchard66ab4982019-02-26 18:37:15 +01006328 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006329
6330 /* If an async job is pending, we must try to
6331 to catch the end using polling before calling
6332 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006333 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006334 for (i=0 ; i < num_all_fds ; i++) {
6335 /* switch on an handler designed to
6336 * handle the SSL_free
6337 */
6338 afd = all_fd[i];
6339 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006340 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006341 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006342 /* To ensure that the fd cache won't be used
6343 * and we'll catch a real RD event.
6344 */
6345 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006346 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006347 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006348 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006349 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006350 return;
6351 }
Emeric Brun3854e012017-05-17 20:42:48 +02006352 /* Else we can remove the fds from the fdtab
6353 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006354 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006355 * because the fd is owned by the engine.
6356 * the engine is responsible to close
6357 */
Emeric Brun64ff81b2022-07-01 17:36:50 +02006358 for (i=0 ; i < num_all_fds ; i++) {
6359 /* We want to remove the fd from the fdtab
6360 * but we flag it to disown because the
6361 * close is performed by the engine itself
6362 */
6363 fdtab[all_fd[i]].state |= FD_DISOWN;
6364 fd_delete(all_fd[i]);
6365 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006366 }
6367#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006368 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006369 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006370 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006371 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006372 _HA_ATOMIC_DEC(&sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006373 }
Emeric Brun46591952012-05-18 15:47:34 +02006374}
6375
6376/* This function tries to perform a clean shutdown on an SSL connection, and in
6377 * any case, flags the connection as reusable if no handshake was in progress.
6378 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006379static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006380{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006381 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006382
Willy Tarreau911db9b2020-01-23 16:27:54 +01006383 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006384 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006385 if (!clean)
6386 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006387 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006388 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006389 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006390 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006391 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006392 ERR_clear_error();
6393 }
Emeric Brun46591952012-05-18 15:47:34 +02006394}
6395
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006396
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006397/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006398int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6399{
6400 struct ssl_sock_ctx *ctx;
6401 X509 *crt;
6402
6403 if (!ssl_sock_is_ssl(conn))
6404 return 0;
6405
6406 ctx = conn->xprt_ctx;
6407
6408 crt = SSL_get_certificate(ctx->ssl);
6409 if (!crt)
6410 return 0;
6411
6412 return cert_get_pkey_algo(crt, out);
6413}
6414
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006415/* used for ppv2 cert signature (can be used for logging) */
6416const char *ssl_sock_get_cert_sig(struct connection *conn)
6417{
Christopher Faulet82004142019-09-10 10:12:03 +02006418 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006419
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006420 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6421 X509 *crt;
6422
6423 if (!ssl_sock_is_ssl(conn))
6424 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006425 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006426 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006427 if (!crt)
6428 return NULL;
6429 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6430 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6431}
6432
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006433/* used for ppv2 authority */
6434const char *ssl_sock_get_sni(struct connection *conn)
6435{
6436#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006437 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006438
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006439 if (!ssl_sock_is_ssl(conn))
6440 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006441 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006442 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006443#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006444 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006445#endif
6446}
6447
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006448/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006449const char *ssl_sock_get_cipher_name(struct connection *conn)
6450{
Christopher Faulet82004142019-09-10 10:12:03 +02006451 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006452
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006453 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006454 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006455 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006456 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006457}
6458
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006459/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006460const char *ssl_sock_get_proto_version(struct connection *conn)
6461{
Christopher Faulet82004142019-09-10 10:12:03 +02006462 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006463
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006464 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006465 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006466 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006467 return SSL_get_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006468}
6469
Olivier Houchardab28a322018-12-21 19:45:40 +01006470void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6471{
6472#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christopher Faulet82004142019-09-10 10:12:03 +02006473 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006474
Olivier Houcharde488ea82019-06-28 14:10:33 +02006475 if (!ssl_sock_is_ssl(conn))
6476 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006477 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006478 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006479#endif
6480}
6481
Willy Tarreau119a4082016-12-22 21:58:38 +01006482/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6483 * to disable SNI.
6484 */
Willy Tarreau63076412015-07-10 11:33:32 +02006485void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6486{
6487#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006488 struct ssl_sock_ctx *ctx;
William Lallemandc78ac5a2021-11-17 02:59:21 +01006489 struct server *s;
Willy Tarreau119a4082016-12-22 21:58:38 +01006490 char *prev_name;
6491
Willy Tarreau63076412015-07-10 11:33:32 +02006492 if (!ssl_sock_is_ssl(conn))
6493 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006494 ctx = conn->xprt_ctx;
William Lallemandc78ac5a2021-11-17 02:59:21 +01006495 s = __objt_server(conn->target);
Willy Tarreau63076412015-07-10 11:33:32 +02006496
Willy Tarreau119a4082016-12-22 21:58:38 +01006497 /* if the SNI changes, we must destroy the reusable context so that a
William Lallemandc78ac5a2021-11-17 02:59:21 +01006498 * new connection will present a new SNI. compare with the SNI
6499 * previously stored in the reused_sess */
6500 /* the RWLOCK is used to ensure that we are not trying to flush the
6501 * cache from the CLI */
6502
6503 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
6504 prev_name = s->ssl_ctx.reused_sess[tid].sni;
Willy Tarreau119a4082016-12-22 21:58:38 +01006505 if ((!prev_name && hostname) ||
6506 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006507 SSL_set_session(ctx->ssl, NULL);
William Lallemandc78ac5a2021-11-17 02:59:21 +01006508 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau119a4082016-12-22 21:58:38 +01006509
Olivier Houchard66ab4982019-02-26 18:37:15 +01006510 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006511#endif
6512}
6513
Emeric Brun0abf8362014-06-24 18:26:41 +02006514/* Extract peer certificate's common name into the chunk dest
6515 * Returns
6516 * the len of the extracted common name
6517 * or 0 if no CN found in DN
6518 * or -1 on error case (i.e. no peer certificate)
6519 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006520int ssl_sock_get_remote_common_name(struct connection *conn,
6521 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006522{
Christopher Faulet82004142019-09-10 10:12:03 +02006523 struct ssl_sock_ctx *ctx;
David Safb76832014-05-08 23:42:08 -04006524 X509 *crt = NULL;
6525 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006526 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006527 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006528 .area = (char *)&find_cn,
6529 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006530 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006531 int result = -1;
David Safb76832014-05-08 23:42:08 -04006532
6533 if (!ssl_sock_is_ssl(conn))
Emeric Brun0abf8362014-06-24 18:26:41 +02006534 goto out;
Christopher Faulet82004142019-09-10 10:12:03 +02006535 ctx = conn->xprt_ctx;
David Safb76832014-05-08 23:42:08 -04006536
6537 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006538 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006539 if (!crt)
6540 goto out;
6541
6542 name = X509_get_subject_name(crt);
6543 if (!name)
6544 goto out;
David Safb76832014-05-08 23:42:08 -04006545
Emeric Brun0abf8362014-06-24 18:26:41 +02006546 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6547out:
David Safb76832014-05-08 23:42:08 -04006548 if (crt)
6549 X509_free(crt);
6550
6551 return result;
6552}
6553
Dave McCowan328fb582014-07-30 10:39:13 -04006554/* returns 1 if client passed a certificate for this session, 0 if not */
6555int ssl_sock_get_cert_used_sess(struct connection *conn)
6556{
Christopher Faulet82004142019-09-10 10:12:03 +02006557 struct ssl_sock_ctx *ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006558 X509 *crt = NULL;
6559
6560 if (!ssl_sock_is_ssl(conn))
6561 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006562 ctx = conn->xprt_ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006563
6564 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006565 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006566 if (!crt)
6567 return 0;
6568
6569 X509_free(crt);
6570 return 1;
6571}
6572
6573/* returns 1 if client passed a certificate for this connection, 0 if not */
6574int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006575{
Christopher Faulet82004142019-09-10 10:12:03 +02006576 struct ssl_sock_ctx *ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006577
David Safb76832014-05-08 23:42:08 -04006578 if (!ssl_sock_is_ssl(conn))
6579 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006580 ctx = conn->xprt_ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006581 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006582}
6583
6584/* returns result from SSL verify */
6585unsigned int ssl_sock_get_verify_result(struct connection *conn)
6586{
Christopher Faulet82004142019-09-10 10:12:03 +02006587 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006588
David Safb76832014-05-08 23:42:08 -04006589 if (!ssl_sock_is_ssl(conn))
6590 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Christopher Faulet82004142019-09-10 10:12:03 +02006591 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006592 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006593}
6594
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006595/* Returns the application layer protocol name in <str> and <len> when known.
6596 * Zero is returned if the protocol name was not found, otherwise non-zero is
6597 * returned. The string is allocated in the SSL context and doesn't have to be
6598 * freed by the caller. NPN is also checked if available since older versions
6599 * of openssl (1.0.1) which are more common in field only support this one.
6600 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006601static int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006602{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006603#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6604 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006605 struct ssl_sock_ctx *ctx = xprt_ctx;
6606 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006607 return 0;
6608
6609 *str = NULL;
6610
6611#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006612 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006613 if (*str)
6614 return 1;
6615#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006616#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006617 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006618 if (*str)
6619 return 1;
6620#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006621#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006622 return 0;
6623}
6624
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006625/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006626int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006627{
6628 X509 *ca;
6629 X509_NAME *name = NULL;
6630 ASN1_OCTET_STRING *skid = NULL;
6631 STACK_OF(X509) *chain = NULL;
6632 struct issuer_chain *issuer;
6633 struct eb64_node *node;
6634 char *path;
6635 u64 key;
6636 int ret = 0;
6637
6638 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6639 if (chain == NULL) {
6640 chain = sk_X509_new_null();
6641 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6642 name = X509_get_subject_name(ca);
6643 }
6644 if (!sk_X509_push(chain, ca)) {
6645 X509_free(ca);
6646 goto end;
6647 }
6648 }
6649 if (!chain) {
6650 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6651 goto end;
6652 }
6653 if (!skid) {
6654 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6655 goto end;
6656 }
6657 if (!name) {
6658 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6659 goto end;
6660 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01006661 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006662 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006663 issuer = container_of(node, typeof(*issuer), node);
6664 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6665 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6666 goto end;
6667 }
6668 }
6669 issuer = calloc(1, sizeof *issuer);
6670 path = strdup(fp);
6671 if (!issuer || !path) {
6672 free(issuer);
6673 free(path);
6674 goto end;
6675 }
6676 issuer->node.key = key;
6677 issuer->path = path;
6678 issuer->chain = chain;
6679 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006680 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006681 ret = 1;
6682 end:
6683 if (skid)
6684 ASN1_OCTET_STRING_free(skid);
6685 if (chain)
6686 sk_X509_pop_free(chain, X509_free);
6687 return ret;
6688}
6689
William Lallemandda8584c2020-05-14 10:14:37 +02006690 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006691{
6692 AUTHORITY_KEYID *akid;
6693 struct issuer_chain *issuer = NULL;
6694
6695 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01006696 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006697 struct eb64_node *node;
6698 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01006699 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006700 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6701 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6702 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6703 issuer = ti;
6704 break;
6705 }
6706 }
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006707 }
Remi Tricot-Le Breton172da592022-11-03 15:16:48 +01006708 AUTHORITY_KEYID_free(akid);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006709 return issuer;
6710}
6711
William Lallemanddad31052020-05-14 17:47:32 +02006712void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006713{
6714 struct eb64_node *node, *back;
6715 struct issuer_chain *issuer;
6716
William Lallemande0f3fd52020-02-25 14:53:06 +01006717 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006718 while (node) {
6719 issuer = container_of(node, typeof(*issuer), node);
6720 back = eb64_next(node);
6721 eb64_delete(node);
6722 free(issuer->path);
6723 sk_X509_pop_free(issuer->chain, X509_free);
6724 free(issuer);
6725 node = back;
6726 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006727}
6728
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006729#ifndef OPENSSL_NO_ENGINE
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006730static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01006731 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006732
Emeric Brun3854e012017-05-17 20:42:48 +02006733 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006734 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006735 err_code = ERR_ABORT;
6736 }
6737 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006738}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006739#endif
6740
Willy Tarreaude5675a2021-01-20 14:41:29 +01006741/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006742 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01006743 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01006744static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01006745{
6746 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006747 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006748
6749 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006750 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006751
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006752 if (sctx->conn != conn) {
6753 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
6754 ret = 1;
6755 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01006756 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
6757
6758 if (sctx->xprt) {
6759 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
6760 if (sctx->xprt_ctx)
6761 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
6762 }
6763
6764 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006765
6766 /* as soon as a shutdown is reported the lower layer unregisters its
6767 * subscriber, so the situations below are transient and rare enough to
6768 * be reported as suspicious. In any case they shouldn't last.
6769 */
6770 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
6771 ret = 1;
6772 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
6773 ret = 1;
6774
Willy Tarreaude5675a2021-01-20 14:41:29 +01006775 chunk_appendf(&trash, " .subs=%p", sctx->subs);
6776 if (sctx->subs) {
6777 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006778 if (sctx->subs->tasklet->calls >= 1000000)
6779 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006780 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
6781 sctx->subs->tasklet->calls,
6782 sctx->subs->tasklet->context);
6783 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
6784 chunk_appendf(&trash, ")");
6785 }
6786 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
6787 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006788 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006789}
6790
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006791#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02006792/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006793 * each reference. The variable <ref> must point to the current node's list
6794 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02006795 */
William Lallemand32af2032016-10-29 18:09:35 +02006796static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006797struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02006798{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006799 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006800 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02006801
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006802 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006803 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006804 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02006805
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006806 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02006807}
6808
6809static inline
6810struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
6811{
6812 int id;
6813 char *error;
6814
6815 /* If the reference starts by a '#', this is numeric id. */
6816 if (reference[0] == '#') {
6817 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
6818 id = strtol(reference + 1, &error, 10);
6819 if (*error != '\0')
6820 return NULL;
6821
6822 /* Perform the unique id lookup. */
6823 return tlskeys_ref_lookupid(id);
6824 }
6825
6826 /* Perform the string lookup. */
6827 return tlskeys_ref_lookup(reference);
6828}
6829#endif
6830
6831
6832#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6833
6834static int cli_io_handler_tlskeys_files(struct appctx *appctx);
6835
6836static inline int cli_io_handler_tlskeys_entries(struct appctx *appctx) {
6837 return cli_io_handler_tlskeys_files(appctx);
6838}
6839
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006840/* dumps all tls keys. Relies on cli.i0 (non-null = only list file names), cli.i1
6841 * (next index to be dumped), and cli.p0 (next key reference).
6842 */
William Lallemand32af2032016-10-29 18:09:35 +02006843static int cli_io_handler_tlskeys_files(struct appctx *appctx) {
6844
6845 struct stream_interface *si = appctx->owner;
6846
6847 switch (appctx->st2) {
6848 case STAT_ST_INIT:
6849 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08006850 * quit the function with returning 0. The function is called
William Lallemand32af2032016-10-29 18:09:35 +02006851 * later and restart at the state "STAT_ST_INIT".
6852 */
6853 chunk_reset(&trash);
6854
6855 if (appctx->io_handler == cli_io_handler_tlskeys_entries)
6856 chunk_appendf(&trash, "# id secret\n");
6857 else
6858 chunk_appendf(&trash, "# id (file)\n");
6859
Willy Tarreau06d80a92017-10-19 14:32:15 +02006860 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01006861 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006862 return 0;
6863 }
6864
William Lallemand32af2032016-10-29 18:09:35 +02006865 /* Now, we start the browsing of the references lists.
6866 * Note that the following call to LIST_ELEM return bad pointer. The only
6867 * available field of this pointer is <list>. It is used with the function
6868 * tlskeys_list_get_next() for retruning the first available entry
6869 */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006870 if (appctx->ctx.cli.p0 == NULL)
6871 appctx->ctx.cli.p0 = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006872
6873 appctx->st2 = STAT_ST_LIST;
6874 /* fall through */
6875
6876 case STAT_ST_LIST:
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006877 while (appctx->ctx.cli.p0) {
6878 struct tls_keys_ref *ref = appctx->ctx.cli.p0;
William Lallemand32af2032016-10-29 18:09:35 +02006879
6880 chunk_reset(&trash);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006881 if (appctx->io_handler == cli_io_handler_tlskeys_entries && appctx->ctx.cli.i1 == 0)
William Lallemand32af2032016-10-29 18:09:35 +02006882 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006883
6884 if (appctx->ctx.cli.i1 == 0)
6885 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
6886
William Lallemand32af2032016-10-29 18:09:35 +02006887 if (appctx->io_handler == cli_io_handler_tlskeys_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01006888 int head;
6889
6890 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
6891 head = ref->tls_ticket_enc_index;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006892 while (appctx->ctx.cli.i1 < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02006893 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02006894
6895 chunk_reset(t2);
6896 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01006897 if (ref->key_size_bits == 128) {
6898 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6899 sizeof(struct tls_sess_key_128),
6900 t2->area, t2->size);
6901 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6902 t2->area);
6903 }
6904 else if (ref->key_size_bits == 256) {
6905 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6906 sizeof(struct tls_sess_key_256),
6907 t2->area, t2->size);
6908 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6909 t2->area);
6910 }
6911 else {
6912 /* This case should never happen */
6913 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, appctx->ctx.cli.i1);
6914 }
William Lallemand32af2032016-10-29 18:09:35 +02006915
Willy Tarreau06d80a92017-10-19 14:32:15 +02006916 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006917 /* let's try again later from this stream. We add ourselves into
6918 * this stream's users so that it can remove us upon termination.
6919 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01006920 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaudb398432018-11-15 11:08:52 +01006921 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006922 return 0;
6923 }
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006924 appctx->ctx.cli.i1++;
William Lallemand32af2032016-10-29 18:09:35 +02006925 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01006926 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006927 appctx->ctx.cli.i1 = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006928 }
Willy Tarreau06d80a92017-10-19 14:32:15 +02006929 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006930 /* let's try again later from this stream. We add ourselves into
6931 * this stream's users so that it can remove us upon termination.
6932 */
Willy Tarreaudb398432018-11-15 11:08:52 +01006933 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006934 return 0;
6935 }
6936
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006937 if (appctx->ctx.cli.i0 == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02006938 break;
6939
6940 /* get next list entry and check the end of the list */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006941 appctx->ctx.cli.p0 = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006942 }
6943
6944 appctx->st2 = STAT_ST_FIN;
6945 /* fall through */
6946
6947 default:
6948 appctx->st2 = STAT_ST_FIN;
6949 return 1;
6950 }
6951 return 0;
6952}
6953
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006954/* sets cli.i0 to non-zero if only file lists should be dumped */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006955static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006956{
William Lallemand32af2032016-10-29 18:09:35 +02006957 /* no parameter, shows only file list */
6958 if (!*args[2]) {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006959 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006960 appctx->io_handler = cli_io_handler_tlskeys_files;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006961 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006962 }
6963
6964 if (args[2][0] == '*') {
6965 /* list every TLS ticket keys */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006966 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006967 } else {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006968 appctx->ctx.cli.p0 = tlskeys_ref_lookup_ref(args[2]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006969 if (!appctx->ctx.cli.p0)
6970 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006971 }
William Lallemand32af2032016-10-29 18:09:35 +02006972 appctx->io_handler = cli_io_handler_tlskeys_entries;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006973 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006974}
6975
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006976static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006977{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006978 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006979 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006980
William Lallemand32af2032016-10-29 18:09:35 +02006981 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006982 if (!*args[3] || !*args[4])
6983 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 +02006984
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006985 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006986 if (!ref)
6987 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006988
Willy Tarreau1c913e42018-08-22 05:26:57 +02006989 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006990 if (ret < 0)
6991 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01006992
Willy Tarreau1c913e42018-08-22 05:26:57 +02006993 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02006994 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
6995 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006996
Willy Tarreau9d008692019-08-09 11:21:01 +02006997 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006998}
William Lallemandd4f946c2019-12-05 10:26:40 +01006999#endif
William Lallemand419e6342020-04-08 12:05:39 +02007000
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007001static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02007002{
7003#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
7004 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02007005 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02007006
7007 if (!payload)
7008 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02007009
7010 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02007011 if (!*payload)
7012 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02007013
7014 /* remove \r and \n from the payload */
7015 for (i = 0, j = 0; payload[i]; i++) {
7016 if (payload[i] == '\r' || payload[i] == '\n')
7017 continue;
7018 payload[j++] = payload[i];
7019 }
7020 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007021
Willy Tarreau1c913e42018-08-22 05:26:57 +02007022 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02007023 if (ret < 0)
7024 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007025
Willy Tarreau1c913e42018-08-22 05:26:57 +02007026 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02007027 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02007028 if (err)
7029 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
7030 else
7031 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007032 }
Willy Tarreau9d008692019-08-09 11:21:01 +02007033
7034 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02007035#else
Willy Tarreau9d008692019-08-09 11:21:01 +02007036 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 +02007037#endif
7038
Elliot Otchet71f82972020-01-15 08:12:14 -05007039}
7040
William Lallemand32af2032016-10-29 18:09:35 +02007041/* register cli keywords */
7042static struct cli_kw_list cli_kws = {{ },{
7043#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Willy Tarreaub205bfd2021-05-07 11:38:37 +02007044 { { "show", "tls-keys", NULL }, "show tls-keys [id|*] : show tls keys references or dump tls ticket keys when id specified", cli_parse_show_tlskeys, NULL },
7045 { { "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 +02007046#endif
Willy Tarreaub205bfd2021-05-07 11:38:37 +02007047 { { "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 },
William Lallemand32af2032016-10-29 18:09:35 +02007048 { { NULL }, NULL, NULL, NULL }
7049}};
7050
Willy Tarreau0108d902018-11-25 19:14:37 +01007051INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02007052
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02007053/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02007054struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02007055 .snd_buf = ssl_sock_from_buf,
7056 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01007057 .subscribe = ssl_subscribe,
7058 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02007059 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02007060 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02007061 .rcv_pipe = NULL,
7062 .snd_pipe = NULL,
7063 .shutr = NULL,
7064 .shutw = ssl_sock_shutw,
7065 .close = ssl_sock_close,
7066 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01007067 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01007068 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01007069 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01007070 .prepare_srv = ssl_sock_prepare_srv_ctx,
7071 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007072 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02007073 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01007074 .set_idle = ssl_set_idle,
7075 .set_used = ssl_set_used,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01007076 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01007077 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02007078};
7079
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007080enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
7081 struct session *sess, struct stream *s, int flags)
7082{
7083 struct connection *conn;
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007084 struct conn_stream *cs;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007085
7086 conn = objt_conn(sess->origin);
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007087 cs = objt_cs(s->si[0].end);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007088
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007089 if (conn && cs) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007090 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007091 cs->flags |= CS_FL_WAIT_FOR_HS;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007092 s->req.flags |= CF_READ_NULL;
7093 return ACT_RET_YIELD;
7094 }
7095 }
7096 return (ACT_RET_CONT);
7097}
7098
7099static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
7100{
7101 rule->action_ptr = ssl_action_wait_for_hs;
7102
7103 return ACT_RET_PRS_OK;
7104}
7105
7106static struct action_kw_list http_req_actions = {ILH, {
7107 { "wait-for-handshake", ssl_parse_wait_for_hs },
7108 { /* END */ }
7109}};
7110
Willy Tarreau0108d902018-11-25 19:14:37 +01007111INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
7112
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007113#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007114
7115static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7116{
7117 if (ptr) {
7118 chunk_destroy(ptr);
7119 free(ptr);
7120 }
7121}
7122
7123#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007124
7125#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7126static void ssl_sock_ocsp_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7127{
7128 struct ocsp_cbk_arg *ocsp_arg;
7129
7130 if (ptr) {
7131 ocsp_arg = ptr;
7132
7133 if (ocsp_arg->is_single) {
7134 ssl_sock_free_ocsp(ocsp_arg->s_ocsp);
7135 ocsp_arg->s_ocsp = NULL;
7136 } else {
7137 int i;
7138
7139 for (i = 0; i < SSL_SOCK_NUM_KEYTYPES; i++) {
7140 ssl_sock_free_ocsp(ocsp_arg->m_ocsp[i]);
7141 ocsp_arg->m_ocsp[i] = NULL;
7142 }
7143 }
7144 free(ocsp_arg);
7145 }
7146}
7147#endif
7148
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007149static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7150{
Willy Tarreaubafbe012017-11-24 17:34:44 +01007151 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007152}
William Lallemand7d42ef52020-07-06 11:41:30 +02007153
William Lallemandca5cf0a2021-06-09 16:46:12 +02007154#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007155static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7156{
7157 struct ssl_keylog *keylog;
7158
7159 if (!ptr)
7160 return;
7161
7162 keylog = ptr;
7163
7164 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7165 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7166 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7167 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7168 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7169 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7170 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7171 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7172
7173 pool_free(pool_head_ssl_keylog, ptr);
7174}
7175#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007176
Emeric Brun46591952012-05-18 15:47:34 +02007177__attribute__((constructor))
Willy Tarreau92faadf2012-10-10 23:04:25 +02007178static void __ssl_sock_init(void)
7179{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007180#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007181 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007182 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007183#endif
Emeric Brun46591952012-05-18 15:47:34 +02007184
Willy Tarreauef934602016-12-22 23:12:01 +01007185 if (global_ssl.listen_default_ciphers)
7186 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7187 if (global_ssl.connect_default_ciphers)
7188 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007189#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007190 if (global_ssl.listen_default_ciphersuites)
7191 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7192 if (global_ssl.connect_default_ciphersuites)
7193 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7194#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007195
Willy Tarreau13e14102016-12-22 20:25:26 +01007196 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007197#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007198 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007199#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007200#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007201 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007202 n = sk_SSL_COMP_num(cm);
7203 while (n--) {
7204 (void) sk_SSL_COMP_pop(cm);
7205 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007206#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007207
Willy Tarreau5db847a2019-05-09 14:13:35 +02007208#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007209 ssl_locking_init();
7210#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007211#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007212 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
7213#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007214
7215#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7216 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
7217#endif
7218
Thierry FOURNIER28962c92018-06-17 21:37:05 +02007219 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02007220 ssl_capture_ptr_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_capture_free_func);
William Lallemandca5cf0a2021-06-09 16:46:12 +02007221#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007222 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
7223#endif
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007224#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00007225 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007226 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007227#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01007228#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7229 hap_register_post_check(tlskeys_finalize_config);
7230#endif
Willy Tarreau80713382018-11-26 10:19:54 +01007231
7232 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
7233 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
7234
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007235 hap_register_post_deinit(ssl_free_global_issuers);
7236
Willy Tarreau80713382018-11-26 10:19:54 +01007237#ifndef OPENSSL_NO_DH
7238 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7239 hap_register_post_deinit(ssl_free_dh);
7240#endif
7241#ifndef OPENSSL_NO_ENGINE
7242 hap_register_post_deinit(ssl_free_engines);
7243#endif
7244 /* Load SSL string for the verbose & debug mode. */
7245 ERR_load_SSL_strings();
Olivier Houcharda8955d52019-04-07 22:00:38 +02007246 ha_meth = BIO_meth_new(0x666, "ha methods");
7247 BIO_meth_set_write(ha_meth, ha_ssl_write);
7248 BIO_meth_set_read(ha_meth, ha_ssl_read);
7249 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
7250 BIO_meth_set_create(ha_meth, ha_ssl_new);
7251 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
7252 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
7253 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02007254
7255 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007256
Dragan Dosen9ac98092020-05-11 15:51:45 +02007257 /* Try to register dedicated SSL/TLS protocol message callbacks for
7258 * heartbleed attack (CVE-2014-0160) and clienthello.
7259 */
7260 hap_register_post_check(ssl_sock_register_msg_callbacks);
7261
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007262 /* Try to free all callbacks that were registered by using
7263 * ssl_sock_register_msg_callback().
7264 */
7265 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01007266}
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01007267
Willy Tarreau80713382018-11-26 10:19:54 +01007268/* Compute and register the version string */
7269static void ssl_register_build_options()
7270{
7271 char *ptr = NULL;
7272 int i;
7273
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007274 memprintf(&ptr, "Built with OpenSSL version : "
7275#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007276 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007277#else /* OPENSSL_IS_BORINGSSL */
7278 OPENSSL_VERSION_TEXT
7279 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08007280 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02007281 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007282#endif
7283 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007284#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007285 "no (library version too old)"
7286#elif defined(OPENSSL_NO_TLSEXT)
7287 "no (disabled via OPENSSL_NO_TLSEXT)"
7288#else
7289 "yes"
7290#endif
7291 "", ptr);
7292
7293 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
7294#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
7295 "yes"
7296#else
7297#ifdef OPENSSL_NO_TLSEXT
7298 "no (because of OPENSSL_NO_TLSEXT)"
7299#else
7300 "no (version might be too old, 0.9.8f min needed)"
7301#endif
7302#endif
7303 "", ptr);
7304
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02007305 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
7306 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
7307 if (methodVersions[i].option)
7308 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007309
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007310 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01007311}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007312
Willy Tarreau80713382018-11-26 10:19:54 +01007313INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02007314
Emeric Brun46591952012-05-18 15:47:34 +02007315
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007316#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00007317void ssl_free_engines(void) {
7318 struct ssl_engine_list *wl, *wlb;
7319 /* free up engine list */
7320 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
7321 ENGINE_finish(wl->e);
7322 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02007323 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00007324 free(wl);
7325 }
7326}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007327#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02007328
Remi Gacogned3a23c32015-05-28 16:39:47 +02007329#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00007330void ssl_free_dh(void) {
7331 if (local_dh_1024) {
7332 DH_free(local_dh_1024);
7333 local_dh_1024 = NULL;
7334 }
7335 if (local_dh_2048) {
7336 DH_free(local_dh_2048);
7337 local_dh_2048 = NULL;
7338 }
7339 if (local_dh_4096) {
7340 DH_free(local_dh_4096);
7341 local_dh_4096 = NULL;
7342 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02007343 if (global_dh) {
7344 DH_free(global_dh);
7345 global_dh = NULL;
7346 }
Grant Zhang872f9c22017-01-21 01:10:18 +00007347}
7348#endif
7349
7350__attribute__((destructor))
7351static void __ssl_sock_deinit(void)
7352{
7353#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007354 if (ssl_ctx_lru_tree) {
7355 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007356 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02007357 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02007358#endif
7359
Willy Tarreau5db847a2019-05-09 14:13:35 +02007360#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007361 ERR_remove_state(0);
7362 ERR_free_strings();
7363
7364 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08007365#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007366
Willy Tarreau5db847a2019-05-09 14:13:35 +02007367#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007368 CRYPTO_cleanup_all_ex_data();
7369#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007370 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02007371}
7372
William Dauchyf6370442020-11-14 19:25:33 +01007373/* Activate ssl on server <s>.
7374 * do nothing if there is no change to apply
7375 *
7376 * Must be called with the server lock held.
7377 */
7378void ssl_sock_set_srv(struct server *s, signed char use_ssl)
7379{
7380 if (s->use_ssl == use_ssl)
7381 return;
7382
7383 s->use_ssl = use_ssl;
7384 if (s->use_ssl == 1)
7385 s->xprt = &ssl_sock;
7386 else
William Dauchyf5186442022-01-06 16:57:15 +01007387 s->xprt = xprt_get(XPRT_RAW);
William Dauchyf6370442020-11-14 19:25:33 +01007388}
7389
Emeric Brun46591952012-05-18 15:47:34 +02007390/*
7391 * Local variables:
7392 * c-indent-level: 8
7393 * c-basic-offset: 8
7394 * End:
7395 */