blob: e69812f146f20bea83a53e97b1d88d27a77cd81f [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 Houchardb51937e2019-05-01 17:24:36 +0200203 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200204 BIO_set_retry_write(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200205 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200206 } else if (ret == 0)
207 BIO_clear_retry_flags(h);
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 Houchardb51937e2019-05-01 17:24:36 +0200235 if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
Olivier Houcharda8955d52019-04-07 22:00:38 +0200236 BIO_set_retry_read(h);
Olivier Houcharda28454e2019-04-24 12:04:36 +0200237 ret = -1;
Olivier Houchardb51937e2019-05-01 17:24:36 +0200238 } else if (ret == 0)
239 BIO_clear_retry_flags(h);
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 */
Willy Tarreau2b718102021-04-21 07:32:39 +02001268 LIST_INSERT(&tkr, &tlskeys_reference);
1269 LIST_DELETE(&tkr);
Christopher Fauletfc633b62020-11-06 15:24:23 +01001270 return ERR_NONE;
Nenad Merdanovic200b0fa2015-05-09 08:46:01 +02001271}
Nenad Merdanovic05552d42015-02-27 19:56:49 +01001272#endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
1273
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001274#ifndef OPENSSL_NO_OCSP
William Lallemand76b4a122020-08-04 17:41:39 +02001275int ocsp_ex_index = -1;
1276
yanbzhube2774d2015-12-10 15:07:30 -05001277int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
1278{
1279 switch (evp_keytype) {
1280 case EVP_PKEY_RSA:
1281 return 2;
1282 case EVP_PKEY_DSA:
1283 return 0;
1284 case EVP_PKEY_EC:
1285 return 1;
1286 }
1287
1288 return -1;
1289}
1290
Emeric Brun4147b2e2014-06-16 18:36:30 +02001291/*
1292 * Callback used to set OCSP status extension content in server hello.
1293 */
1294int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
1295{
yanbzhube2774d2015-12-10 15:07:30 -05001296 struct certificate_ocsp *ocsp;
1297 struct ocsp_cbk_arg *ocsp_arg;
1298 char *ssl_buf;
William Lallemand76b4a122020-08-04 17:41:39 +02001299 SSL_CTX *ctx;
yanbzhube2774d2015-12-10 15:07:30 -05001300 EVP_PKEY *ssl_pkey;
1301 int key_type;
1302 int index;
1303
William Lallemand76b4a122020-08-04 17:41:39 +02001304 ctx = SSL_get_SSL_CTX(ssl);
1305 if (!ctx)
1306 return SSL_TLSEXT_ERR_NOACK;
1307
1308 ocsp_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
1309 if (!ocsp_arg)
1310 return SSL_TLSEXT_ERR_NOACK;
yanbzhube2774d2015-12-10 15:07:30 -05001311
1312 ssl_pkey = SSL_get_privatekey(ssl);
1313 if (!ssl_pkey)
1314 return SSL_TLSEXT_ERR_NOACK;
1315
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001316 key_type = EVP_PKEY_base_id(ssl_pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001317
1318 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
1319 ocsp = ocsp_arg->s_ocsp;
1320 else {
1321 /* For multiple certs per context, we have to find the correct OCSP response based on
1322 * the certificate type
1323 */
1324 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
1325
1326 if (index < 0)
1327 return SSL_TLSEXT_ERR_NOACK;
1328
1329 ocsp = ocsp_arg->m_ocsp[index];
1330
1331 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001332
1333 if (!ocsp ||
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001334 !ocsp->response.area ||
1335 !ocsp->response.data ||
Remi Tricot-Le Bretonc5eaae92023-03-02 15:49:55 +01001336 (ocsp->expire < date.tv_sec))
Emeric Brun4147b2e2014-06-16 18:36:30 +02001337 return SSL_TLSEXT_ERR_NOACK;
1338
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001339 ssl_buf = OPENSSL_malloc(ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001340 if (!ssl_buf)
1341 return SSL_TLSEXT_ERR_NOACK;
1342
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001343 memcpy(ssl_buf, ocsp->response.area, ocsp->response.data);
1344 SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.data);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001345
1346 return SSL_TLSEXT_ERR_OK;
1347}
1348
William Lallemand4a660132019-10-14 14:51:41 +02001349#endif
1350
Ilya Shipitsinb3201a32020-10-18 09:11:50 +05001351#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
William Lallemand76b4a122020-08-04 17:41:39 +02001352
1353
1354/*
1355 * Decrease the refcount of the struct ocsp_response and frees it if it's not
1356 * used anymore. Also removes it from the tree if free'd.
1357 */
1358static void ssl_sock_free_ocsp(struct certificate_ocsp *ocsp)
1359{
1360 if (!ocsp)
1361 return;
1362
1363 ocsp->refcount--;
1364 if (ocsp->refcount <= 0) {
1365 ebmb_delete(&ocsp->key);
1366 chunk_destroy(&ocsp->response);
1367 free(ocsp);
1368 }
1369}
1370
1371
Emeric Brun4147b2e2014-06-16 18:36:30 +02001372/*
1373 * This function enables the handling of OCSP status extension on 'ctx' if a
William Lallemand246c0242019-10-11 08:59:13 +02001374 * ocsp_response buffer was found in the cert_key_and_chain. To enable OCSP
1375 * status extension, the issuer's certificate is mandatory. It should be
1376 * present in ckch->ocsp_issuer.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001377 *
William Lallemand246c0242019-10-11 08:59:13 +02001378 * In addition, the ckch->ocsp_reponse buffer is loaded as a DER format of an
1379 * OCSP response. If file is empty or content is not a valid OCSP response,
1380 * OCSP status extension is enabled but OCSP response is ignored (a warning is
1381 * displayed).
Emeric Brun4147b2e2014-06-16 18:36:30 +02001382 *
1383 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
Joseph Herlant017b3da2018-11-15 09:07:59 -08001384 * successfully enabled, or -1 in other error case.
Emeric Brun4147b2e2014-06-16 18:36:30 +02001385 */
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001386static 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 +02001387{
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001388 X509 *x, *issuer;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001389 OCSP_CERTID *cid = NULL;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001390 int i, ret = -1;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001391 struct certificate_ocsp *ocsp = NULL, *iocsp;
1392 char *warn = NULL;
1393 unsigned char *p;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001394 void (*callback) (void);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001395
Emeric Brun4147b2e2014-06-16 18:36:30 +02001396
William Lallemand246c0242019-10-11 08:59:13 +02001397 x = ckch->cert;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001398 if (!x)
1399 goto out;
1400
William Lallemand246c0242019-10-11 08:59:13 +02001401 issuer = ckch->ocsp_issuer;
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001402 /* take issuer from chain over ocsp_issuer, is what is done historicaly */
1403 if (chain) {
1404 /* check if one of the certificate of the chain is the issuer */
1405 for (i = 0; i < sk_X509_num(chain); i++) {
1406 X509 *ti = sk_X509_value(chain, i);
1407 if (X509_check_issued(ti, x) == X509_V_OK) {
1408 issuer = ti;
1409 break;
1410 }
1411 }
1412 }
William Lallemand246c0242019-10-11 08:59:13 +02001413 if (!issuer)
1414 goto out;
Emeric Brun4147b2e2014-06-16 18:36:30 +02001415
1416 cid = OCSP_cert_to_id(0, x, issuer);
1417 if (!cid)
1418 goto out;
1419
1420 i = i2d_OCSP_CERTID(cid, NULL);
1421 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
1422 goto out;
1423
Vincent Bernat02779b62016-04-03 13:48:43 +02001424 ocsp = calloc(1, sizeof(*ocsp));
Emeric Brun4147b2e2014-06-16 18:36:30 +02001425 if (!ocsp)
1426 goto out;
1427
1428 p = ocsp->key_data;
1429 i2d_OCSP_CERTID(cid, &p);
1430
1431 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
1432 if (iocsp == ocsp)
1433 ocsp = NULL;
1434
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001435#ifndef SSL_CTX_get_tlsext_status_cb
1436# define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
1437 *cb = (void (*) (void))ctx->tlsext_status_cb;
1438#endif
1439 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
1440
1441 if (!callback) {
William Lallemanda560c062020-07-31 11:43:20 +02001442 struct ocsp_cbk_arg *cb_arg;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001443 EVP_PKEY *pkey;
yanbzhube2774d2015-12-10 15:07:30 -05001444
William Lallemanda560c062020-07-31 11:43:20 +02001445 cb_arg = calloc(1, sizeof(*cb_arg));
1446 if (!cb_arg)
1447 goto out;
1448
yanbzhube2774d2015-12-10 15:07:30 -05001449 cb_arg->is_single = 1;
1450 cb_arg->s_ocsp = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001451 iocsp->refcount++;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001452
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001453 pkey = X509_get_pubkey(x);
1454 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
1455 EVP_PKEY_free(pkey);
yanbzhube2774d2015-12-10 15:07:30 -05001456
1457 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
William Lallemand76b4a122020-08-04 17:41:39 +02001458 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 */
1459
yanbzhube2774d2015-12-10 15:07:30 -05001460 } else {
1461 /*
1462 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
1463 * Update that cb_arg with the new cert's staple
1464 */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001465 struct ocsp_cbk_arg *cb_arg;
yanbzhube2774d2015-12-10 15:07:30 -05001466 struct certificate_ocsp *tmp_ocsp;
1467 int index;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001468 int key_type;
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001469 EVP_PKEY *pkey;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001470
William Lallemand76b4a122020-08-04 17:41:39 +02001471 cb_arg = SSL_CTX_get_ex_data(ctx, ocsp_ex_index);
yanbzhube2774d2015-12-10 15:07:30 -05001472
1473 /*
1474 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
1475 * the order of operations below matter, take care when changing it
1476 */
1477 tmp_ocsp = cb_arg->s_ocsp;
1478 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
1479 cb_arg->s_ocsp = NULL;
1480 cb_arg->m_ocsp[index] = tmp_ocsp;
1481 cb_arg->is_single = 0;
1482 cb_arg->single_kt = 0;
1483
Emmanuel Hocdetb7a4c342017-01-06 12:57:46 +01001484 pkey = X509_get_pubkey(x);
1485 key_type = EVP_PKEY_base_id(pkey);
1486 EVP_PKEY_free(pkey);
1487
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001488 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
William Lallemand76b4a122020-08-04 17:41:39 +02001489 if (index >= 0 && !cb_arg->m_ocsp[index]) {
yanbzhube2774d2015-12-10 15:07:30 -05001490 cb_arg->m_ocsp[index] = iocsp;
William Lallemand76b4a122020-08-04 17:41:39 +02001491 iocsp->refcount++;
1492 }
yanbzhube2774d2015-12-10 15:07:30 -05001493 }
Emeric Brun4147b2e2014-06-16 18:36:30 +02001494
1495 ret = 0;
1496
1497 warn = NULL;
William Lallemand86e4d632020-08-07 00:44:32 +02001498 if (ssl_sock_load_ocsp_response(ckch->ocsp_response, iocsp, cid, &warn)) {
William Lallemand3b5f3602019-10-16 18:05:05 +02001499 memprintf(&warn, "Loading: %s. Content will be ignored", warn ? warn : "failure");
Christopher Faulet767a84b2017-11-24 16:50:31 +01001500 ha_warning("%s.\n", warn);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001501 }
1502
1503out:
Emeric Brun4147b2e2014-06-16 18:36:30 +02001504 if (cid)
1505 OCSP_CERTID_free(cid);
1506
1507 if (ocsp)
Remi Tricot-Le Breton15838972022-11-03 15:16:49 +01001508 ssl_sock_free_ocsp(ocsp);
Emeric Brun4147b2e2014-06-16 18:36:30 +02001509
1510 if (warn)
1511 free(warn);
1512
Emeric Brun4147b2e2014-06-16 18:36:30 +02001513 return ret;
1514}
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01001515#endif
1516
1517#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01001518static 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 +02001519{
William Lallemand4a660132019-10-14 14:51:41 +02001520 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 +02001521}
1522#endif
1523
William Lallemand4a660132019-10-14 14:51:41 +02001524
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05001525#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001526
1527#define CT_EXTENSION_TYPE 18
1528
William Lallemand03c331c2020-05-13 10:10:01 +02001529int sctl_ex_index = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001530
1531int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
1532{
Willy Tarreau83061a82018-07-13 11:56:34 +02001533 struct buffer *sctl = add_arg;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001534
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001535 *out = (unsigned char *) sctl->area;
1536 *outlen = sctl->data;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001537
1538 return 1;
1539}
1540
1541int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
1542{
1543 return 1;
1544}
1545
William Lallemanda17f4112019-10-10 15:16:44 +02001546static int ssl_sock_load_sctl(SSL_CTX *ctx, struct buffer *sctl)
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001547{
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001548 int ret = -1;
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001549
William Lallemanda17f4112019-10-10 15:16:44 +02001550 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 +01001551 goto out;
1552
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01001553 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1554
1555 ret = 0;
1556
1557out:
1558 return ret;
1559}
1560
1561#endif
1562
Emeric Brune1f38db2012-09-03 20:36:47 +02001563void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1564{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001565 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001566 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001567 BIO *write_bio;
Willy Tarreau622317d2015-02-27 16:36:16 +01001568 (void)ret; /* shut gcc stupid warning */
Emeric Brune1f38db2012-09-03 20:36:47 +02001569
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001570#ifndef SSL_OP_NO_RENEGOTIATION
1571 /* Please note that BoringSSL defines this macro to zero so don't
1572 * change this to #if and do not assign a default value to this macro!
1573 */
Emeric Brune1f38db2012-09-03 20:36:47 +02001574 if (where & SSL_CB_HANDSHAKE_START) {
1575 /* Disable renegotiation (CVE-2009-3555) */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01001576 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 +02001577 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01001578 conn->err_code = CO_ER_SSL_RENEG;
1579 }
Emeric Brune1f38db2012-09-03 20:36:47 +02001580 }
Dirkjan Bussink526894f2019-01-21 09:35:03 -08001581#endif
Emeric Brund8b2bb52014-01-28 15:43:53 +01001582
1583 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001584 if (!(ctx->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
Emeric Brund8b2bb52014-01-28 15:43:53 +01001585 /* Long certificate chains optimz
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001586 If write and read bios are different, we
Emeric Brund8b2bb52014-01-28 15:43:53 +01001587 consider that the buffering was activated,
1588 so we rise the output buffer size from 4k
1589 to 16k */
1590 write_bio = SSL_get_wbio(ssl);
1591 if (write_bio != SSL_get_rbio(ssl)) {
1592 BIO_set_write_buffer_size(write_bio, 16384);
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001593 ctx->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
Emeric Brund8b2bb52014-01-28 15:43:53 +01001594 }
1595 }
1596 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02001597}
1598
Emeric Brune64aef12012-09-21 13:15:06 +02001599/* Callback is called for each certificate of the chain during a verify
1600 ok is set to 1 if preverify detect no error on current certificate.
1601 Returns 0 to break the handshake, 1 otherwise. */
Evan Broderbe554312013-06-27 00:05:25 -07001602int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
Emeric Brune64aef12012-09-21 13:15:06 +02001603{
1604 SSL *ssl;
1605 struct connection *conn;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001606 struct ssl_sock_ctx *ctx;
Emeric Brun81c00f02012-09-21 14:31:21 +02001607 int err, depth;
Emeric Brune64aef12012-09-21 13:15:06 +02001608
1609 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02001610 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emeric Brune64aef12012-09-21 13:15:06 +02001611
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001612 ctx = conn->xprt_ctx;
1613
1614 ctx->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
Emeric Brune64aef12012-09-21 13:15:06 +02001615
Emeric Brun81c00f02012-09-21 14:31:21 +02001616 if (ok) /* no errors */
1617 return ok;
1618
1619 depth = X509_STORE_CTX_get_error_depth(x_store);
1620 err = X509_STORE_CTX_get_error(x_store);
1621
1622 /* check if CA error needs to be ignored */
1623 if (depth > 0) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001624 if (!SSL_SOCK_ST_TO_CA_ERROR(ctx->xprt_st)) {
1625 ctx->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1626 ctx->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
Emeric Brunf282a812012-09-21 15:27:54 +02001627 }
1628
Remi Tricot-Le Breton99e45262022-11-10 10:48:58 +01001629 if (err <= SSL_MAX_VFY_ERROR_CODE &&
1630 cert_ignerr_bitfield_get(__objt_listener(conn->target)->bind_conf->ca_ignerr_bitfield, err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001631 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001632 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001633 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001634 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001635
Willy Tarreau20879a02012-12-03 16:32:10 +01001636 conn->err_code = CO_ER_SSL_CA_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001637 return 0;
1638 }
1639
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01001640 if (!SSL_SOCK_ST_TO_CRTERROR(ctx->xprt_st))
1641 ctx->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
Emeric Brunf282a812012-09-21 15:27:54 +02001642
Emeric Brun81c00f02012-09-21 14:31:21 +02001643 /* check if certificate error needs to be ignored */
Remi Tricot-Le Breton99e45262022-11-10 10:48:58 +01001644 if (err <= SSL_MAX_VFY_ERROR_CODE &&
1645 cert_ignerr_bitfield_get(__objt_listener(conn->target)->bind_conf->crt_ignerr_bitfield, err)) {
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02001646 ssl_sock_dump_errors(conn);
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001647 ERR_clear_error();
Emeric Brun81c00f02012-09-21 14:31:21 +02001648 return 1;
Emeric Brun1eb20ef2012-12-03 13:24:29 +01001649 }
Emeric Brun81c00f02012-09-21 14:31:21 +02001650
Willy Tarreau20879a02012-12-03 16:32:10 +01001651 conn->err_code = CO_ER_SSL_CRT_FAIL;
Emeric Brun81c00f02012-09-21 14:31:21 +02001652 return 0;
Emeric Brune64aef12012-09-21 13:15:06 +02001653}
1654
Dragan Dosen9ac98092020-05-11 15:51:45 +02001655#ifdef TLS1_RT_HEARTBEAT
1656static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
1657 int content_type, const void *buf, size_t len,
1658 SSL *ssl)
1659{
1660 /* test heartbeat received (write_p is set to 0
1661 for a received record) */
1662 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
1663 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
1664 const unsigned char *p = buf;
1665 unsigned int payload;
1666
1667 ctx->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1668
1669 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1670 if (*p != TLS1_HB_REQUEST)
1671 return;
1672
1673 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1674 goto kill_it;
1675
1676 payload = (p[1] * 256) + p[2];
1677 if (3 + payload + 16 <= len)
1678 return; /* OK no problem */
1679 kill_it:
1680 /* We have a clear heartbleed attack (CVE-2014-0160), the
1681 * advertised payload is larger than the advertised packet
1682 * length, so we have garbage in the buffer between the
1683 * payload and the end of the buffer (p+len). We can't know
1684 * if the SSL stack is patched, and we don't know if we can
1685 * safely wipe out the area between p+3+len and payload.
1686 * So instead, we prevent the response from being sent by
1687 * setting the max_send_fragment to 0 and we report an SSL
1688 * error, which will kill this connection. It will be reported
1689 * above as SSL_ERROR_SSL while an other handshake failure with
1690 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1691 */
1692 ssl->max_send_fragment = 0;
1693 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1694 }
1695}
1696#endif
1697
1698static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
1699 int content_type, const void *buf, size_t len,
1700 SSL *ssl)
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001701{
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001702 struct ssl_capture *capture;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001703 unsigned char *msg;
1704 unsigned char *end;
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001705 size_t rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001706
1707 /* This function is called for "from client" and "to server"
1708 * connections. The combination of write_p == 0 and content_type == 22
Joseph Herlant017b3da2018-11-15 09:07:59 -08001709 * is only available during "from client" connection.
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001710 */
1711
1712 /* "write_p" is set to 0 is the bytes are received messages,
1713 * otherwise it is set to 1.
1714 */
1715 if (write_p != 0)
1716 return;
1717
1718 /* content_type contains the type of message received or sent
1719 * according with the SSL/TLS protocol spec. This message is
1720 * encoded with one byte. The value 256 (two bytes) is used
1721 * for designing the SSL/TLS record layer. According with the
1722 * rfc6101, the expected message (other than 256) are:
1723 * - change_cipher_spec(20)
1724 * - alert(21)
1725 * - handshake(22)
1726 * - application_data(23)
1727 * - (255)
1728 * We are interessed by the handshake and specially the client
1729 * hello.
1730 */
1731 if (content_type != 22)
1732 return;
1733
1734 /* The message length is at least 4 bytes, containing the
1735 * message type and the message length.
1736 */
1737 if (len < 4)
1738 return;
1739
1740 /* First byte of the handshake message id the type of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001741 * message. The known types are:
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001742 * - hello_request(0)
1743 * - client_hello(1)
1744 * - server_hello(2)
1745 * - certificate(11)
1746 * - server_key_exchange (12)
1747 * - certificate_request(13)
1748 * - server_hello_done(14)
1749 * We are interested by the client hello.
1750 */
1751 msg = (unsigned char *)buf;
1752 if (msg[0] != 1)
1753 return;
1754
1755 /* Next three bytes are the length of the message. The total length
1756 * must be this decoded length + 4. If the length given as argument
1757 * is not the same, we abort the protocol dissector.
1758 */
1759 rec_len = (msg[1] << 16) + (msg[2] << 8) + msg[3];
1760 if (len < rec_len + 4)
1761 return;
1762 msg += 4;
1763 end = msg + rec_len;
1764 if (end < msg)
1765 return;
1766
1767 /* Expect 2 bytes for protocol version (1 byte for major and 1 byte
1768 * for minor, the random, composed by 4 bytes for the unix time and
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001769 * 28 bytes for unix payload. So we jump 1 + 1 + 4 + 28.
1770 */
1771 msg += 1 + 1 + 4 + 28;
1772 if (msg > end)
1773 return;
1774
1775 /* Next, is session id:
1776 * if present, we have to jump by length + 1 for the size information
1777 * if not present, we have to jump by 1 only
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001778 */
Baptiste Assmann6be139f2018-11-28 15:20:25 +01001779 if (msg[0] > 0)
1780 msg += msg[0];
1781 msg += 1;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001782 if (msg > end)
1783 return;
1784
1785 /* Next two bytes are the ciphersuite length. */
1786 if (msg + 2 > end)
1787 return;
1788 rec_len = (msg[0] << 8) + msg[1];
1789 msg += 2;
1790 if (msg + rec_len > end || msg + rec_len < msg)
1791 return;
1792
Willy Tarreaub454e902021-03-22 15:09:41 +01001793 capture = pool_alloc(pool_head_ssl_capture);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001794 if (!capture)
1795 return;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001796 /* Compute the xxh64 of the ciphersuite. */
1797 capture->xxh64 = XXH64(msg, rec_len, 0);
1798
1799 /* Capture the ciphersuite. */
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001800 capture->ciphersuite_len = (global_ssl.capture_cipherlist < rec_len) ?
1801 global_ssl.capture_cipherlist : rec_len;
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001802 memcpy(capture->ciphersuite, msg, capture->ciphersuite_len);
Emmanuel Hocdete3804742017-03-08 11:07:10 +01001803
1804 SSL_set_ex_data(ssl, ssl_capture_ptr_index, capture);
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001805}
William Lallemand7d42ef52020-07-06 11:41:30 +02001806
1807
William Lallemandca5cf0a2021-06-09 16:46:12 +02001808#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02001809static void ssl_init_keylog(struct connection *conn, int write_p, int version,
1810 int content_type, const void *buf, size_t len,
1811 SSL *ssl)
1812{
1813 struct ssl_keylog *keylog;
1814
1815 if (SSL_get_ex_data(ssl, ssl_keylog_index))
1816 return;
1817
Willy Tarreauf208ac02021-03-22 21:10:12 +01001818 keylog = pool_zalloc(pool_head_ssl_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02001819 if (!keylog)
1820 return;
1821
William Lallemand7d42ef52020-07-06 11:41:30 +02001822 if (!SSL_set_ex_data(ssl, ssl_keylog_index, keylog)) {
1823 pool_free(pool_head_ssl_keylog, keylog);
1824 return;
1825 }
1826}
1827#endif
Thierry FOURNIER5bf77322017-02-25 12:45:22 +01001828
Emeric Brun29f037d2014-04-25 19:05:36 +02001829/* Callback is called for ssl protocol analyse */
1830void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1831{
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001832 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
1833 struct ssl_sock_msg_callback *cbk;
1834
Dragan Dosen1e7ed042020-05-08 18:30:00 +02001835 /* Try to call all callback functions that were registered by using
1836 * ssl_sock_register_msg_callback().
1837 */
1838 list_for_each_entry(cbk, &ssl_sock_msg_callbacks, list) {
1839 cbk->func(conn, write_p, version, content_type, buf, len, ssl);
1840 }
Emeric Brun29f037d2014-04-25 19:05:36 +02001841}
1842
Bernard Spil13c53f82018-02-15 13:34:58 +01001843#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchardc7566002018-11-20 23:33:50 +01001844static int ssl_sock_srv_select_protos(SSL *s, unsigned char **out, unsigned char *outlen,
1845 const unsigned char *in, unsigned int inlen,
1846 void *arg)
1847{
1848 struct server *srv = arg;
1849
1850 if (SSL_select_next_proto(out, outlen, in, inlen, (unsigned char *)srv->ssl_ctx.npn_str,
1851 srv->ssl_ctx.npn_len) == OPENSSL_NPN_NEGOTIATED)
1852 return SSL_TLSEXT_ERR_OK;
1853 return SSL_TLSEXT_ERR_NOACK;
1854}
1855#endif
1856
1857#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001858/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001859 * negotiable protocols for NPN.
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001860 */
1861static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1862 unsigned int *len, void *arg)
1863{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001864 struct ssl_bind_conf *conf = arg;
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02001865
1866 *data = (const unsigned char *)conf->npn_str;
1867 *len = conf->npn_len;
1868 return SSL_TLSEXT_ERR_OK;
1869}
1870#endif
1871
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001872#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Willy Tarreauab861d32013-04-02 02:30:41 +02001873/* This callback is used so that the server advertises the list of
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05001874 * negotiable protocols for ALPN.
Willy Tarreauab861d32013-04-02 02:30:41 +02001875 */
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001876static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1877 unsigned char *outlen,
1878 const unsigned char *server,
1879 unsigned int server_len, void *arg)
Willy Tarreauab861d32013-04-02 02:30:41 +02001880{
Emmanuel Hocdet98263292016-12-29 18:26:15 +01001881 struct ssl_bind_conf *conf = arg;
Willy Tarreauab861d32013-04-02 02:30:41 +02001882
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01001883 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1884 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
1885 return SSL_TLSEXT_ERR_NOACK;
1886 }
Willy Tarreauab861d32013-04-02 02:30:41 +02001887 return SSL_TLSEXT_ERR_OK;
1888}
1889#endif
1890
Willy Tarreauc8ad3be2015-06-17 15:48:26 +02001891#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01001892#ifndef SSL_NO_GENERATE_CERTIFICATES
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02001893
Shimi Gersneradabbfe2020-08-23 13:58:13 +03001894/* Configure a DNS SAN extenion on a certificate. */
1895int ssl_sock_add_san_ext(X509V3_CTX* ctx, X509* cert, const char *servername) {
1896 int failure = 0;
1897 X509_EXTENSION *san_ext = NULL;
1898 CONF *conf = NULL;
1899 struct buffer *san_name = get_trash_chunk();
1900
1901 conf = NCONF_new(NULL);
1902 if (!conf) {
1903 failure = 1;
1904 goto cleanup;
1905 }
1906
1907 /* Build an extension based on the DNS entry above */
1908 chunk_appendf(san_name, "DNS:%s", servername);
1909 san_ext = X509V3_EXT_nconf_nid(conf, ctx, NID_subject_alt_name, san_name->area);
1910 if (!san_ext) {
1911 failure = 1;
1912 goto cleanup;
1913 }
1914
1915 /* Add the extension */
1916 if (!X509_add_ext(cert, san_ext, -1 /* Add to end */)) {
1917 failure = 1;
1918 goto cleanup;
1919 }
1920
1921 /* Success */
1922 failure = 0;
1923
1924cleanup:
1925 if (NULL != san_ext) X509_EXTENSION_free(san_ext);
1926 if (NULL != conf) NCONF_free(conf);
1927
1928 return failure;
1929}
1930
Christopher Faulet30548802015-06-11 13:39:32 +02001931/* Create a X509 certificate with the specified servername and serial. This
1932 * function returns a SSL_CTX object or NULL if an error occurs. */
Christopher Faulet7969a332015-10-09 11:15:03 +02001933static SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01001934ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001935{
Shimi Gersner5846c492020-08-23 13:58:12 +03001936 X509 *cacert = bind_conf->ca_sign_ckch->cert;
1937 EVP_PKEY *capkey = bind_conf->ca_sign_ckch->key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001938 SSL_CTX *ssl_ctx = NULL;
1939 X509 *newcrt = NULL;
1940 EVP_PKEY *pkey = NULL;
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001941 SSL *tmp_ssl = NULL;
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02001942 CONF *ctmp = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001943 X509_NAME *name;
1944 const EVP_MD *digest;
1945 X509V3_CTX ctx;
1946 unsigned int i;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02001947 int key_type;
Christopher Faulet31af49d2015-06-09 17:29:50 +02001948
Christopher Faulet48a83322017-07-28 16:56:09 +02001949 /* Get the private key of the default certificate and use it */
Ilya Shipitsinaf204882020-12-19 03:12:12 +05001950#ifdef HAVE_SSL_CTX_get0_privatekey
Emmanuel Hocdet15969292017-08-11 10:56:00 +02001951 pkey = SSL_CTX_get0_privatekey(bind_conf->default_ctx);
1952#else
1953 tmp_ssl = SSL_new(bind_conf->default_ctx);
1954 if (tmp_ssl)
1955 pkey = SSL_get_privatekey(tmp_ssl);
1956#endif
1957 if (!pkey)
Christopher Faulet31af49d2015-06-09 17:29:50 +02001958 goto mkcert_error;
1959
1960 /* Create the certificate */
1961 if (!(newcrt = X509_new()))
1962 goto mkcert_error;
1963
1964 /* Set version number for the certificate (X509v3) and the serial
1965 * number */
1966 if (X509_set_version(newcrt, 2L) != 1)
1967 goto mkcert_error;
Willy Tarreau1db42732021-04-06 11:44:07 +02001968 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), _HA_ATOMIC_ADD_FETCH(&ssl_ctx_serial, 1));
Christopher Faulet31af49d2015-06-09 17:29:50 +02001969
1970 /* Set duration for the certificate */
Rosen Penev68185952018-12-14 08:47:02 -08001971 if (!X509_gmtime_adj(X509_getm_notBefore(newcrt), (long)-60*60*24) ||
1972 !X509_gmtime_adj(X509_getm_notAfter(newcrt),(long)60*60*24*365))
Christopher Faulet31af49d2015-06-09 17:29:50 +02001973 goto mkcert_error;
1974
1975 /* set public key in the certificate */
1976 if (X509_set_pubkey(newcrt, pkey) != 1)
1977 goto mkcert_error;
1978
1979 /* Set issuer name from the CA */
1980 if (!(name = X509_get_subject_name(cacert)))
1981 goto mkcert_error;
1982 if (X509_set_issuer_name(newcrt, name) != 1)
1983 goto mkcert_error;
1984
1985 /* Set the subject name using the same, but the CN */
1986 name = X509_NAME_dup(name);
1987 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1988 (const unsigned char *)servername,
1989 -1, -1, 0) != 1) {
1990 X509_NAME_free(name);
1991 goto mkcert_error;
1992 }
1993 if (X509_set_subject_name(newcrt, name) != 1) {
1994 X509_NAME_free(name);
1995 goto mkcert_error;
1996 }
1997 X509_NAME_free(name);
1998
1999 /* Add x509v3 extensions as specified */
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002000 ctmp = NCONF_new(NULL);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002001 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
2002 for (i = 0; i < X509V3_EXT_SIZE; i++) {
2003 X509_EXTENSION *ext;
2004
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002005 if (!(ext = X509V3_EXT_nconf(ctmp, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
Christopher Faulet31af49d2015-06-09 17:29:50 +02002006 goto mkcert_error;
2007 if (!X509_add_ext(newcrt, ext, -1)) {
2008 X509_EXTENSION_free(ext);
2009 goto mkcert_error;
2010 }
2011 X509_EXTENSION_free(ext);
2012 }
2013
Shimi Gersneradabbfe2020-08-23 13:58:13 +03002014 /* Add SAN extension */
2015 if (ssl_sock_add_san_ext(&ctx, newcrt, servername)) {
2016 goto mkcert_error;
2017 }
2018
Christopher Faulet31af49d2015-06-09 17:29:50 +02002019 /* Sign the certificate with the CA private key */
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002020
2021 key_type = EVP_PKEY_base_id(capkey);
2022
2023 if (key_type == EVP_PKEY_DSA)
2024 digest = EVP_sha1();
2025 else if (key_type == EVP_PKEY_RSA)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002026 digest = EVP_sha256();
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002027 else if (key_type == EVP_PKEY_EC)
Christopher Faulet7969a332015-10-09 11:15:03 +02002028 digest = EVP_sha256();
2029 else {
Ilya Shipitsinec36c912021-01-07 11:57:42 +05002030#ifdef ASN1_PKEY_CTRL_DEFAULT_MD_NID
Christopher Faulet7969a332015-10-09 11:15:03 +02002031 int nid;
2032
2033 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
2034 goto mkcert_error;
2035 if (!(digest = EVP_get_digestbynid(nid)))
2036 goto mkcert_error;
Christopher Faulete7db2162015-10-19 13:59:24 +02002037#else
2038 goto mkcert_error;
2039#endif
Christopher Faulet7969a332015-10-09 11:15:03 +02002040 }
2041
Christopher Faulet31af49d2015-06-09 17:29:50 +02002042 if (!(X509_sign(newcrt, capkey, digest)))
2043 goto mkcert_error;
2044
2045 /* Create and set the new SSL_CTX */
2046 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
2047 goto mkcert_error;
2048 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
2049 goto mkcert_error;
2050 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
2051 goto mkcert_error;
2052 if (!SSL_CTX_check_private_key(ssl_ctx))
2053 goto mkcert_error;
2054
Shimi Gersner5846c492020-08-23 13:58:12 +03002055 /* Build chaining the CA cert and the rest of the chain, keep these order */
2056#if defined(SSL_CTX_add1_chain_cert)
2057 if (!SSL_CTX_add1_chain_cert(ssl_ctx, bind_conf->ca_sign_ckch->cert)) {
2058 goto mkcert_error;
2059 }
2060
2061 if (bind_conf->ca_sign_ckch->chain) {
2062 for (i = 0; i < sk_X509_num(bind_conf->ca_sign_ckch->chain); i++) {
2063 X509 *chain_cert = sk_X509_value(bind_conf->ca_sign_ckch->chain, i);
2064 if (!SSL_CTX_add1_chain_cert(ssl_ctx, chain_cert)) {
2065 goto mkcert_error;
2066 }
2067 }
2068 }
2069#endif
2070
Christopher Faulet31af49d2015-06-09 17:29:50 +02002071 if (newcrt) X509_free(newcrt);
Christopher Faulet7969a332015-10-09 11:15:03 +02002072
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002073#ifndef OPENSSL_NO_DH
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002074 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh);
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01002075#endif
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002076#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2077 {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002078 const char *ecdhe = (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe : ECDHE_DEFAULT_CURVE);
Christopher Faulet85b5a1a2015-10-09 11:46:32 +02002079 EC_KEY *ecc;
2080 int nid;
2081
2082 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
2083 goto end;
2084 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
2085 goto end;
2086 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
2087 EC_KEY_free(ecc);
2088 }
2089#endif
2090 end:
Christopher Faulet31af49d2015-06-09 17:29:50 +02002091 return ssl_ctx;
2092
2093 mkcert_error:
Emmanuel Hocdeta9b84022018-10-01 18:41:36 +02002094 if (ctmp) NCONF_free(ctmp);
Emmanuel Hocdet15969292017-08-11 10:56:00 +02002095 if (tmp_ssl) SSL_free(tmp_ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002096 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
2097 if (newcrt) X509_free(newcrt);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002098 return NULL;
2099}
2100
Christopher Faulet7969a332015-10-09 11:15:03 +02002101SSL_CTX *
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002102ssl_sock_create_cert(struct connection *conn, const char *servername, unsigned int key)
Christopher Faulet7969a332015-10-09 11:15:03 +02002103{
Willy Tarreau07d94e42018-09-20 10:57:52 +02002104 struct bind_conf *bind_conf = __objt_listener(conn->target)->bind_conf;
Olivier Houchard66ab4982019-02-26 18:37:15 +01002105 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002106
Olivier Houchard66ab4982019-02-26 18:37:15 +01002107 return ssl_sock_do_create_cert(servername, bind_conf, ctx->ssl);
Christopher Faulet7969a332015-10-09 11:15:03 +02002108}
2109
Christopher Faulet30548802015-06-11 13:39:32 +02002110/* Do a lookup for a certificate in the LRU cache used to store generated
Emeric Brun821bb9b2017-06-15 16:37:39 +02002111 * certificates and immediately assign it to the SSL session if not null. */
Christopher Faulet30548802015-06-11 13:39:32 +02002112SSL_CTX *
Emeric Brun821bb9b2017-06-15 16:37:39 +02002113ssl_sock_assign_generated_cert(unsigned int key, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet30548802015-06-11 13:39:32 +02002114{
2115 struct lru64 *lru = NULL;
2116
2117 if (ssl_ctx_lru_tree) {
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002118 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002119 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002120 if (lru && lru->domain) {
2121 if (ssl)
2122 SSL_set_SSL_CTX(ssl, (SSL_CTX *)lru->data);
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002123 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002124 return (SSL_CTX *)lru->data;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002125 }
Willy Tarreau03f4ec42018-05-17 10:56:47 +02002126 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet30548802015-06-11 13:39:32 +02002127 }
2128 return NULL;
2129}
2130
Emeric Brun821bb9b2017-06-15 16:37:39 +02002131/* Same as <ssl_sock_assign_generated_cert> but without SSL session. This
2132 * function is not thread-safe, it should only be used to check if a certificate
2133 * exists in the lru cache (with no warranty it will not be removed by another
2134 * thread). It is kept for backward compatibility. */
2135SSL_CTX *
2136ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
2137{
2138 return ssl_sock_assign_generated_cert(key, bind_conf, NULL);
2139}
2140
Christopher Fauletd2cab922015-07-28 16:03:47 +02002141/* Set a certificate int the LRU cache used to store generated
2142 * certificate. Return 0 on success, otherwise -1 */
2143int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002144ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
Christopher Faulet30548802015-06-11 13:39:32 +02002145{
2146 struct lru64 *lru = NULL;
2147
2148 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002149 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Shimi Gersner5846c492020-08-23 13:58:12 +03002150 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_ckch->cert, 0);
Emeric Brun821bb9b2017-06-15 16:37:39 +02002151 if (!lru) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002152 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002153 return -1;
Emeric Brun821bb9b2017-06-15 16:37:39 +02002154 }
Christopher Faulet30548802015-06-11 13:39:32 +02002155 if (lru->domain && lru->data)
2156 lru->free((SSL_CTX *)lru->data);
Shimi Gersner5846c492020-08-23 13:58:12 +03002157 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_ckch->cert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002158 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002159 return 0;
Christopher Faulet30548802015-06-11 13:39:32 +02002160 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02002161 return -1;
Christopher Faulet30548802015-06-11 13:39:32 +02002162}
2163
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002164/* Compute the key of the certificate. */
Christopher Faulet30548802015-06-11 13:39:32 +02002165unsigned int
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002166ssl_sock_generated_cert_key(const void *data, size_t len)
Christopher Faulet30548802015-06-11 13:39:32 +02002167{
2168 return XXH32(data, len, ssl_ctx_lru_seed);
2169}
2170
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002171/* Generate a cert and immediately assign it to the SSL session so that the cert's
2172 * refcount is maintained regardless of the cert's presence in the LRU cache.
2173 */
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002174static int
Christopher Faulet7969a332015-10-09 11:15:03 +02002175ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
Christopher Faulet31af49d2015-06-09 17:29:50 +02002176{
Shimi Gersner5846c492020-08-23 13:58:12 +03002177 X509 *cacert = bind_conf->ca_sign_ckch->cert;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002178 SSL_CTX *ssl_ctx = NULL;
2179 struct lru64 *lru = NULL;
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002180 unsigned int key;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002181
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002182 key = ssl_sock_generated_cert_key(servername, strlen(servername));
Christopher Faulet31af49d2015-06-09 17:29:50 +02002183 if (ssl_ctx_lru_tree) {
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002184 HA_RWLOCK_WRLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002185 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002186 if (lru && lru->domain)
2187 ssl_ctx = (SSL_CTX *)lru->data;
Christopher Fauletd2cab922015-07-28 16:03:47 +02002188 if (!ssl_ctx && lru) {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002189 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002190 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
Christopher Fauletd2cab922015-07-28 16:03:47 +02002191 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002192 SSL_set_SSL_CTX(ssl, ssl_ctx);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002193 HA_RWLOCK_WRUNLOCK(SSL_GEN_CERTS_LOCK, &ssl_ctx_lru_rwlock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002194 return 1;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002195 }
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002196 else {
Christopher Faulet635c0ad2015-11-12 11:35:51 +01002197 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002198 SSL_set_SSL_CTX(ssl, ssl_ctx);
2199 /* No LRU cache, this CTX will be released as soon as the session dies */
2200 SSL_CTX_free(ssl_ctx);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002201 return 1;
Willy Tarreau2f63ef42015-10-20 15:16:01 +02002202 }
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002203 return 0;
2204}
2205static int
2206ssl_sock_generate_certificate_from_conn(struct bind_conf *bind_conf, SSL *ssl)
2207{
2208 unsigned int key;
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002209 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002210
Willy Tarreauf5bdb642019-07-17 11:29:32 +02002211 if (conn_get_dst(conn)) {
Willy Tarreau085a1512019-07-17 14:47:35 +02002212 key = ssl_sock_generated_cert_key(conn->dst, get_addr_len(conn->dst));
Emeric Brun821bb9b2017-06-15 16:37:39 +02002213 if (ssl_sock_assign_generated_cert(key, bind_conf, ssl))
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002214 return 1;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002215 }
2216 return 0;
Christopher Faulet31af49d2015-06-09 17:29:50 +02002217}
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002218#endif /* !defined SSL_NO_GENERATE_CERTIFICATES */
Christopher Faulet31af49d2015-06-09 17:29:50 +02002219
Willy Tarreau9a1ab082019-05-09 13:26:41 +02002220#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002221
2222static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002223{
Emmanuel Hocdet23877ab2017-07-12 12:53:02 +02002224#if SSL_OP_NO_SSLv3
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002225 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, SSLv3_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002226 : SSL_CTX_set_ssl_version(ctx, SSLv3_client_method());
2227#endif
2228}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002229static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2230 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002231 : SSL_CTX_set_ssl_version(ctx, TLSv1_client_method());
2232}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002233static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002234#if SSL_OP_NO_TLSv1_1
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002235 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002236 : SSL_CTX_set_ssl_version(ctx, TLSv1_1_client_method());
2237#endif
2238}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002239static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002240#if SSL_OP_NO_TLSv1_2
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002241 c == SET_SERVER ? SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method())
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002242 : SSL_CTX_set_ssl_version(ctx, TLSv1_2_client_method());
2243#endif
2244}
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002245/* TLSv1.2 is the last supported version in this context. */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002246static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {}
2247/* Unusable in this context. */
2248static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {}
2249static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {}
2250static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {}
2251static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {}
2252static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {}
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002253#else /* openssl >= 1.1.0 */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002254
2255static void ctx_set_SSLv3_func(SSL_CTX *ctx, set_context_func c) {
2256 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002257 : SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2258}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002259static void ssl_set_SSLv3_func(SSL *ssl, set_context_func c) {
2260 c == SET_MAX ? SSL_set_max_proto_version(ssl, SSL3_VERSION)
2261 : SSL_set_min_proto_version(ssl, SSL3_VERSION);
2262}
2263static void ctx_set_TLSv10_func(SSL_CTX *ctx, set_context_func c) {
2264 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002265 : SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
2266}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002267static void ssl_set_TLSv10_func(SSL *ssl, set_context_func c) {
2268 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_VERSION)
2269 : SSL_set_min_proto_version(ssl, TLS1_VERSION);
2270}
2271static void ctx_set_TLSv11_func(SSL_CTX *ctx, set_context_func c) {
2272 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002273 : SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
2274}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002275static void ssl_set_TLSv11_func(SSL *ssl, set_context_func c) {
2276 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_1_VERSION)
2277 : SSL_set_min_proto_version(ssl, TLS1_1_VERSION);
2278}
2279static void ctx_set_TLSv12_func(SSL_CTX *ctx, set_context_func c) {
2280 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002281 : SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
2282}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002283static void ssl_set_TLSv12_func(SSL *ssl, set_context_func c) {
2284 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_2_VERSION)
2285 : SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
2286}
2287static void ctx_set_TLSv13_func(SSL_CTX *ctx, set_context_func c) {
William Lallemande8a8aa42021-06-02 16:09:11 +02002288#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002289 c == SET_MAX ? SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION)
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002290 : SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
2291#endif
2292}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002293static void ssl_set_TLSv13_func(SSL *ssl, set_context_func c) {
William Lallemande8a8aa42021-06-02 16:09:11 +02002294#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002295 c == SET_MAX ? SSL_set_max_proto_version(ssl, TLS1_3_VERSION)
2296 : SSL_set_min_proto_version(ssl, TLS1_3_VERSION);
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002297#endif
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002298}
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002299#endif
2300static void ctx_set_None_func(SSL_CTX *ctx, set_context_func c) { }
2301static void ssl_set_None_func(SSL *ssl, set_context_func c) { }
Emmanuel Hocdetecb0e232017-05-18 11:56:58 +02002302
William Lallemand7fd8b452020-05-07 15:20:43 +02002303struct methodVersions methodVersions[] = {
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02002304 {0, 0, ctx_set_None_func, ssl_set_None_func, "NONE"}, /* CONF_TLSV_NONE */
2305 {SSL_OP_NO_SSLv3, MC_SSL_O_NO_SSLV3, ctx_set_SSLv3_func, ssl_set_SSLv3_func, "SSLv3"}, /* CONF_SSLV3 */
2306 {SSL_OP_NO_TLSv1, MC_SSL_O_NO_TLSV10, ctx_set_TLSv10_func, ssl_set_TLSv10_func, "TLSv1.0"}, /* CONF_TLSV10 */
2307 {SSL_OP_NO_TLSv1_1, MC_SSL_O_NO_TLSV11, ctx_set_TLSv11_func, ssl_set_TLSv11_func, "TLSv1.1"}, /* CONF_TLSV11 */
2308 {SSL_OP_NO_TLSv1_2, MC_SSL_O_NO_TLSV12, ctx_set_TLSv12_func, ssl_set_TLSv12_func, "TLSv1.2"}, /* CONF_TLSV12 */
2309 {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 +02002310};
2311
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002312static void ssl_sock_switchctx_set(SSL *ssl, SSL_CTX *ctx)
2313{
2314 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx), ssl_sock_bind_verifycbk);
2315 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(SSL_CTX_get_client_CA_list(ctx)));
2316 SSL_set_SSL_CTX(ssl, ctx);
2317}
2318
Ilya Shipitsin1fc44d42021-01-23 00:09:14 +05002319#ifdef HAVE_SSL_CLIENT_HELLO_CB
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002320
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002321int ssl_sock_switchctx_err_cbk(SSL *ssl, int *al, void *priv)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002322{
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002323 struct bind_conf *s = priv;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002324 (void)al; /* shut gcc stupid warning */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002325
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002326 if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) || s->generate_certs)
2327 return SSL_TLSEXT_ERR_OK;
2328 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002329}
2330
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002331#ifdef OPENSSL_IS_BORINGSSL
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002332int ssl_sock_switchctx_cbk(const struct ssl_early_callback_ctx *ctx)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002333{
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002334 SSL *ssl = ctx->ssl;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002335#else
Frédéric Lécaille901ee2f2020-11-23 11:19:04 +01002336int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *arg)
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002337{
2338#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002339 struct connection *conn;
2340 struct bind_conf *s;
2341 const uint8_t *extension_data;
2342 size_t extension_len;
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002343 int has_rsa_sig = 0, has_ecdsa_sig = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002344
2345 char *wildp = NULL;
2346 const uint8_t *servername;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002347 size_t servername_len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002348 struct ebmb_node *node, *n, *node_ecdsa = NULL, *node_rsa = NULL, *node_anonymous = NULL;
Olivier Houchardc2aae742017-09-22 18:26:28 +02002349 int allow_early = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002350 int i;
2351
Thierry FOURNIER28962c92018-06-17 21:37:05 +02002352 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Willy Tarreaua8825522018-10-15 13:20:07 +02002353 s = __objt_listener(conn->target)->bind_conf;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002354
Frédéric Lécaillee9473c72020-11-23 15:37:11 +01002355#ifdef USE_QUIC
2356 if (conn->qc) {
2357 /* Look for the QUIC transport parameters. */
2358#ifdef OPENSSL_IS_BORINGSSL
2359 if (!SSL_early_callback_ctx_extension_get(ctx, TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS,
2360 &extension_data, &extension_len))
2361#else
2362 if (!SSL_client_hello_get0_ext(ssl, TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS,
2363 &extension_data, &extension_len))
2364#endif
2365 goto abort;
2366
2367 if (!quic_transport_params_store(conn->qc, 0, extension_data,
2368 extension_data + extension_len))
2369 goto abort;
2370 }
2371#endif
2372
Olivier Houchard9679ac92017-10-27 14:58:08 +02002373 if (s->ssl_conf.early_data)
Olivier Houchardc2aae742017-09-22 18:26:28 +02002374 allow_early = 1;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002375#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002376 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
2377 &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002378#else
2379 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &extension_data, &extension_len)) {
2380#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002381 /*
2382 * The server_name extension was given too much extensibility when it
2383 * was written, so parsing the normal case is a bit complex.
2384 */
2385 size_t len;
2386 if (extension_len <= 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002387 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002388 /* Extract the length of the supplied list of names. */
2389 len = (*extension_data++) << 8;
2390 len |= *extension_data++;
2391 if (len + 2 != extension_len)
2392 goto abort;
2393 /*
2394 * The list in practice only has a single element, so we only consider
2395 * the first one.
2396 */
2397 if (len == 0 || *extension_data++ != TLSEXT_NAMETYPE_host_name)
2398 goto abort;
2399 extension_len = len - 1;
2400 /* Now we can finally pull out the byte array with the actual hostname. */
2401 if (extension_len <= 2)
2402 goto abort;
2403 len = (*extension_data++) << 8;
2404 len |= *extension_data++;
2405 if (len == 0 || len + 2 > extension_len || len > TLSEXT_MAXLEN_host_name
2406 || memchr(extension_data, 0, len) != NULL)
2407 goto abort;
2408 servername = extension_data;
2409 servername_len = len;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002410 } else {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002411#if (!defined SSL_NO_GENERATE_CERTIFICATES)
2412 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02002413 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002414 }
2415#endif
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002416 /* without SNI extension, is the default_ctx (need SSL_TLSEXT_ERR_NOACK) */
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002417 if (!s->strict_sni) {
William Lallemand21724f02019-11-04 17:56:13 +01002418 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002419 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002420 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Olivier Houchardc2aae742017-09-22 18:26:28 +02002421 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002422 }
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002423 goto abort;
2424 }
2425
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05002426 /* extract/check clientHello information */
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002427#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002428 if (SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002429#else
2430 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_signature_algorithms, &extension_data, &extension_len)) {
2431#endif
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002432 uint8_t sign;
2433 size_t len;
2434 if (extension_len < 2)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002435 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002436 len = (*extension_data++) << 8;
2437 len |= *extension_data++;
2438 if (len + 2 != extension_len)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002439 goto abort;
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002440 if (len % 2 != 0)
2441 goto abort;
2442 for (; len > 0; len -= 2) {
2443 extension_data++; /* hash */
2444 sign = *extension_data++;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002445 switch (sign) {
2446 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002447 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002448 break;
2449 case TLSEXT_signature_ecdsa:
2450 has_ecdsa_sig = 1;
2451 break;
2452 default:
2453 continue;
2454 }
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002455 if (has_ecdsa_sig && has_rsa_sig)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002456 break;
2457 }
2458 } else {
Bertrand Jacquina25282b2018-08-14 00:56:13 +01002459 /* without TLSEXT_TYPE_signature_algorithms extension (< TLSv1.2) */
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002460 has_rsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002461 }
2462 if (has_ecdsa_sig) { /* in very rare case: has ecdsa sign but not a ECDSA cipher */
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002463 const SSL_CIPHER *cipher;
2464 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
Emmanuel Hocdet019f9b12017-10-02 17:12:06 +02002482 if (cipher && SSL_CIPHER_get_auth_nid(cipher) == NID_auth_ecdsa) {
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002483 has_ecdsa_sig = 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002484 break;
2485 }
2486 }
2487 }
2488
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002489 for (i = 0; i < trash.size && i < servername_len; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002490 trash.area[i] = tolower(servername[i]);
2491 if (!wildp && (trash.area[i] == '.'))
2492 wildp = &trash.area[i];
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002493 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002494 trash.area[i] = 0;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002495
William Lallemand150bfa82019-09-19 17:12:49 +02002496 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002497
William Lallemand94bd3192020-08-14 14:43:35 +02002498 /* Look for an ECDSA, RSA and DSA certificate, first in the single
2499 * name and if not found in the wildcard */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002500 for (i = 0; i < 2; i++) {
2501 if (i == 0) /* lookup in full qualified names */
2502 node = ebst_lookup(&s->sni_ctx, trash.area);
William Lallemand30f9e092020-08-17 14:31:19 +02002503 else if (i == 1 && wildp) /* lookup in wildcards names */
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002504 node = ebst_lookup(&s->sni_w_ctx, wildp);
2505 else
2506 break;
William Lallemand30f9e092020-08-17 14:31:19 +02002507
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002508 for (n = node; n; n = ebmb_next_dup(n)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002509
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002510 /* lookup a not neg filter */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002511 if (!container_of(n, struct sni_ctx, name)->neg) {
William Lallemand30f9e092020-08-17 14:31:19 +02002512 struct sni_ctx *sni, *sni_tmp;
2513 int skip = 0;
2514
2515 if (i == 1 && wildp) { /* wildcard */
2516 /* If this is a wildcard, look for an exclusion on the same crt-list line */
2517 sni = container_of(n, struct sni_ctx, name);
2518 list_for_each_entry(sni_tmp, &sni->ckch_inst->sni_ctx, by_ckch_inst) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002519 if (sni_tmp->neg && (strcmp((const char *)sni_tmp->name.key, trash.area) == 0)) {
William Lallemand30f9e092020-08-17 14:31:19 +02002520 skip = 1;
2521 break;
2522 }
2523 }
2524 if (skip)
2525 continue;
2526 }
2527
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002528 switch(container_of(n, struct sni_ctx, name)->kinfo.sig) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002529 case TLSEXT_signature_ecdsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002530 if (!node_ecdsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002531 node_ecdsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002532 break;
2533 case TLSEXT_signature_rsa:
Emmanuel Hocdet9f9b0c62018-09-03 16:29:16 +02002534 if (!node_rsa)
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002535 node_rsa = n;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002536 break;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002537 default: /* TLSEXT_signature_anonymous|dsa */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002538 if (!node_anonymous)
2539 node_anonymous = n;
2540 break;
2541 }
2542 }
2543 }
William Lallemand94bd3192020-08-14 14:43:35 +02002544 }
2545 /* Once the certificates are found, select them depending on what is
2546 * supported in the client and by key_signature priority order: EDSA >
2547 * RSA > DSA */
William Lallemand5b1d1f62020-08-14 15:30:13 +02002548 if (has_ecdsa_sig && node_ecdsa)
2549 node = node_ecdsa;
2550 else if (has_rsa_sig && node_rsa)
2551 node = node_rsa;
2552 else if (node_anonymous)
2553 node = node_anonymous;
2554 else if (node_ecdsa)
2555 node = node_ecdsa; /* no ecdsa signature case (< TLSv1.2) */
2556 else
2557 node = node_rsa; /* no rsa signature case (far far away) */
2558
William Lallemand94bd3192020-08-14 14:43:35 +02002559 if (node) {
2560 /* switch ctx */
2561 struct ssl_bind_conf *conf = container_of(node, struct sni_ctx, name)->conf;
2562 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
2563 if (conf) {
2564 methodVersions[conf->ssl_methods.min].ssl_set_version(ssl, SET_MIN);
2565 methodVersions[conf->ssl_methods.max].ssl_set_version(ssl, SET_MAX);
2566 if (conf->early_data)
2567 allow_early = 1;
Emmanuel Hocdet3777e3a2019-11-06 16:05:34 +01002568 }
William Lallemand94bd3192020-08-14 14:43:35 +02002569 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
2570 goto allow_early;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002571 }
William Lallemand150bfa82019-09-19 17:12:49 +02002572
William Lallemand02010472019-10-18 11:02:19 +02002573 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002574#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002575 if (s->generate_certs && ssl_sock_generate_certificate(trash.area, s, ssl)) {
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002576 /* switch ctx done in ssl_sock_generate_certificate */
Olivier Houchardc2aae742017-09-22 18:26:28 +02002577 goto allow_early;
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002578 }
2579#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002580 if (!s->strict_sni) {
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002581 /* no certificate match, is the default_ctx */
William Lallemand21724f02019-11-04 17:56:13 +01002582 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002583 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002584 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
William Lallemand0f2291b2021-11-18 17:46:26 +01002585 goto allow_early;
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002586 }
William Lallemand0f2291b2021-11-18 17:46:26 +01002587
2588 /* other cases fallback on abort, if strict-sni is set but no node was found */
2589
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002590 abort:
2591 /* abort handshake (was SSL_TLSEXT_ERR_ALERT_FATAL) */
2592 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002593#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet48e87552017-08-16 11:28:44 +02002594 return ssl_select_cert_error;
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02002595#else
2596 *al = SSL_AD_UNRECOGNIZED_NAME;
2597 return 0;
2598#endif
William Lallemand0f2291b2021-11-18 17:46:26 +01002599
2600allow_early:
2601#ifdef OPENSSL_IS_BORINGSSL
2602 if (allow_early)
2603 SSL_set_early_data_enabled(ssl, 1);
2604#else
2605 if (!allow_early)
2606 SSL_set_max_early_data(ssl, 0);
2607#endif
2608 return 1;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002609}
2610
William Lallemand0faf5262021-11-18 15:25:16 +01002611#else /* ! HAVE_SSL_CLIENT_HELLO_CB */
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002612
Emeric Brunfc0421f2012-09-07 17:30:07 +02002613/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
2614 * warning when no match is found, which implies the default (first) cert
2615 * will keep being used.
2616 */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002617static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, void *priv)
Emeric Brunfc0421f2012-09-07 17:30:07 +02002618{
2619 const char *servername;
2620 const char *wildp = NULL;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002621 struct ebmb_node *node, *n;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002622 struct bind_conf *s = priv;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002623 int i;
2624 (void)al; /* shut gcc stupid warning */
2625
2626 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002627 if (!servername) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002628#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002629 if (s->generate_certs && ssl_sock_generate_certificate_from_conn(s, ssl))
2630 return SSL_TLSEXT_ERR_OK;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002631#endif
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002632 if (s->strict_sni)
2633 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002634 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002635 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002636 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002637 return SSL_TLSEXT_ERR_NOACK;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002638 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02002639
Willy Tarreau19d14ef2012-10-29 16:51:55 +01002640 for (i = 0; i < trash.size; i++) {
Emeric Brunfc0421f2012-09-07 17:30:07 +02002641 if (!servername[i])
2642 break;
Willy Tarreauf278eec2020-07-05 21:46:32 +02002643 trash.area[i] = tolower((unsigned char)servername[i]);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002644 if (!wildp && (trash.area[i] == '.'))
2645 wildp = &trash.area[i];
Emeric Brunfc0421f2012-09-07 17:30:07 +02002646 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002647 trash.area[i] = 0;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002648
William Lallemand150bfa82019-09-19 17:12:49 +02002649 HA_RWLOCK_RDLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002650 node = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002651 /* lookup in full qualified names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002652 for (n = ebst_lookup(&s->sni_ctx, trash.area); n; n = ebmb_next_dup(n)) {
2653 /* lookup a not neg filter */
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002654 if (!container_of(n, struct sni_ctx, name)->neg) {
2655 node = n;
2656 break;
Emmanuel Hocdet65623372013-01-24 17:17:15 +01002657 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002658 }
2659 if (!node && wildp) {
2660 /* lookup in wildcards names */
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002661 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
2662 /* lookup a not neg filter */
2663 if (!container_of(n, struct sni_ctx, name)->neg) {
2664 node = n;
2665 break;
2666 }
2667 }
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002668 }
Emmanuel Hocdetc5fdf0f2019-11-04 15:49:46 +01002669 if (!node) {
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002670#if (!defined SSL_NO_GENERATE_CERTIFICATES)
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02002671 if (s->generate_certs && ssl_sock_generate_certificate(servername, s, ssl)) {
2672 /* switch ctx done in ssl_sock_generate_certificate */
William Lallemand150bfa82019-09-19 17:12:49 +02002673 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Christopher Faulet31af49d2015-06-09 17:29:50 +02002674 return SSL_TLSEXT_ERR_OK;
2675 }
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01002676#endif
William Lallemand21724f02019-11-04 17:56:13 +01002677 if (s->strict_sni) {
2678 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002679 return SSL_TLSEXT_ERR_ALERT_FATAL;
William Lallemand21724f02019-11-04 17:56:13 +01002680 }
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002681 ssl_sock_switchctx_set(ssl, s->default_ctx);
William Lallemand21724f02019-11-04 17:56:13 +01002682 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01002683 return SSL_TLSEXT_ERR_OK;
Emeric Brunfc0421f2012-09-07 17:30:07 +02002684 }
2685
2686 /* switch ctx */
Emmanuel Hocdet530141f2017-03-01 18:54:56 +01002687 ssl_sock_switchctx_set(ssl, container_of(node, struct sni_ctx, name)->ctx);
William Lallemand150bfa82019-09-19 17:12:49 +02002688 HA_RWLOCK_RDUNLOCK(SNI_LOCK, &s->sni_lock);
Emeric Brunfc0421f2012-09-07 17:30:07 +02002689 return SSL_TLSEXT_ERR_OK;
2690}
Emmanuel Hocdet05942112017-02-20 16:11:50 +01002691#endif /* (!) OPENSSL_IS_BORINGSSL */
Emeric Brunfc0421f2012-09-07 17:30:07 +02002692#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2693
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002694#ifndef OPENSSL_NO_DH
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002695
2696static DH * ssl_get_dh_1024(void)
2697{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002698 static unsigned char dh1024_p[]={
2699 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
2700 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
2701 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
2702 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
2703 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
2704 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
2705 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
2706 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
2707 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
2708 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
2709 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
2710 };
2711 static unsigned char dh1024_g[]={
2712 0x02,
2713 };
2714
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002715 BIGNUM *p;
2716 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002717 DH *dh = DH_new();
2718 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002719 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
2720 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002721
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002722 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002723 DH_free(dh);
2724 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002725 } else {
2726 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002727 }
2728 }
2729 return dh;
2730}
2731
2732static DH *ssl_get_dh_2048(void)
2733{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002734 static unsigned char dh2048_p[]={
2735 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
2736 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
2737 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
2738 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
2739 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
2740 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
2741 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
2742 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
2743 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
2744 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
2745 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
2746 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
2747 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
2748 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
2749 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
2750 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
2751 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
2752 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
2753 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
2754 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
2755 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
2756 0xB7,0x1F,0x77,0xF3,
2757 };
2758 static unsigned char dh2048_g[]={
2759 0x02,
2760 };
2761
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002762 BIGNUM *p;
2763 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002764 DH *dh = DH_new();
2765 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002766 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
2767 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002768
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002769 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002770 DH_free(dh);
2771 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002772 } else {
2773 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002774 }
2775 }
2776 return dh;
2777}
2778
2779static DH *ssl_get_dh_4096(void)
2780{
Remi Gacogned3a341a2015-05-29 16:26:17 +02002781 static unsigned char dh4096_p[]={
2782 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
2783 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
2784 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
2785 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
2786 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
2787 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
2788 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
2789 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
2790 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
2791 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
2792 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
2793 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
2794 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
2795 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
2796 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
2797 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
2798 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
2799 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
2800 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
2801 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
2802 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
2803 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
2804 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
2805 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
2806 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
2807 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
2808 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
2809 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
2810 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
2811 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
2812 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
2813 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
2814 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
2815 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
2816 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
2817 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
2818 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
2819 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
2820 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
2821 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
2822 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
2823 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
2824 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002825 };
Remi Gacogned3a341a2015-05-29 16:26:17 +02002826 static unsigned char dh4096_g[]={
2827 0x02,
2828 };
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002829
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002830 BIGNUM *p;
2831 BIGNUM *g;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002832 DH *dh = DH_new();
2833 if (dh) {
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002834 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
2835 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
Remi Gacogned3a341a2015-05-29 16:26:17 +02002836
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002837 if (!p || !g) {
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002838 DH_free(dh);
2839 dh = NULL;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002840 } else {
2841 DH_set0_pqg(dh, p, NULL, g);
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002842 }
2843 }
2844 return dh;
2845}
2846
2847/* Returns Diffie-Hellman parameters matching the private key length
Willy Tarreauef934602016-12-22 23:12:01 +01002848 but not exceeding global_ssl.default_dh_param */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002849static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen)
2850{
2851 DH *dh = NULL;
2852 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02002853 int type;
2854
2855 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002856
2857 /* The keylen supplied by OpenSSL can only be 512 or 1024.
2858 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
2859 */
2860 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
2861 keylen = EVP_PKEY_bits(pkey);
2862 }
2863
Willy Tarreauef934602016-12-22 23:12:01 +01002864 if (keylen > global_ssl.default_dh_param) {
2865 keylen = global_ssl.default_dh_param;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002866 }
2867
Remi Gacogned3a341a2015-05-29 16:26:17 +02002868 if (keylen >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002869 dh = local_dh_4096;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002870 }
2871 else if (keylen >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02002872 dh = local_dh_2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002873 }
2874 else {
Remi Gacogne8de54152014-07-15 11:36:40 +02002875 dh = local_dh_1024;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02002876 }
2877
2878 return dh;
2879}
2880
Remi Gacogne47783ef2015-05-29 15:53:22 +02002881static DH * ssl_sock_get_dh_from_file(const char *filename)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002882{
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002883 DH *dh = NULL;
Remi Gacogne47783ef2015-05-29 15:53:22 +02002884 BIO *in = BIO_new(BIO_s_file());
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002885
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002886 if (in == NULL)
2887 goto end;
2888
Remi Gacogne47783ef2015-05-29 15:53:22 +02002889 if (BIO_read_filename(in, filename) <= 0)
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002890 goto end;
2891
Remi Gacogne47783ef2015-05-29 15:53:22 +02002892 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
2893
2894end:
2895 if (in)
2896 BIO_free(in);
2897
Emeric Brune1b4ed42018-08-16 15:14:12 +02002898 ERR_clear_error();
2899
Remi Gacogne47783ef2015-05-29 15:53:22 +02002900 return dh;
2901}
2902
2903int ssl_sock_load_global_dh_param_from_file(const char *filename)
2904{
2905 global_dh = ssl_sock_get_dh_from_file(filename);
2906
2907 if (global_dh) {
2908 return 0;
2909 }
2910
2911 return -1;
2912}
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02002913#endif
2914
William Lallemand9117de92019-10-04 00:29:42 +02002915/* This function allocates a sni_ctx and adds it to the ckch_inst */
William Lallemand1d29c742019-10-04 00:53:29 +02002916static int ckch_inst_add_cert_sni(SSL_CTX *ctx, struct ckch_inst *ckch_inst,
William Lallemand9117de92019-10-04 00:29:42 +02002917 struct bind_conf *s, struct ssl_bind_conf *conf,
2918 struct pkey_info kinfo, char *name, int order)
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002919{
2920 struct sni_ctx *sc;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002921 int wild = 0, neg = 0;
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002922
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002923 if (*name == '!') {
2924 neg = 1;
2925 name++;
2926 }
2927 if (*name == '*') {
2928 wild = 1;
2929 name++;
2930 }
2931 /* !* filter is a nop */
2932 if (neg && wild)
2933 return order;
2934 if (*name) {
2935 int j, len;
2936 len = strlen(name);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002937 for (j = 0; j < len && j < trash.size; j++)
Willy Tarreauf278eec2020-07-05 21:46:32 +02002938 trash.area[j] = tolower((unsigned char)name[j]);
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002939 if (j >= trash.size)
William Lallemandfe49bb32019-10-03 23:46:33 +02002940 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002941 trash.area[j] = 0;
Thierry FOURNIER / OZON.IO07c3d782016-10-06 10:56:48 +02002942
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002943 sc = malloc(sizeof(struct sni_ctx) + len + 1);
Thierry FOURNIER / OZON.IO7a3bd3b2016-10-06 10:35:29 +02002944 if (!sc)
William Lallemandfe49bb32019-10-03 23:46:33 +02002945 return -1;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002946 memcpy(sc->name.key, trash.area, len + 1);
William Lallemand02e19a52020-04-08 16:11:26 +02002947 SSL_CTX_up_ref(ctx);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002948 sc->ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01002949 sc->conf = conf;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02002950 sc->kinfo = kinfo;
Emmanuel Hocdet7c41a1b2013-05-07 20:20:06 +02002951 sc->order = order++;
2952 sc->neg = neg;
William Lallemand1d29c742019-10-04 00:53:29 +02002953 sc->wild = wild;
2954 sc->name.node.leaf_p = NULL;
William Lallemandcfca1422020-03-05 10:17:47 +01002955 sc->ckch_inst = ckch_inst;
Willy Tarreau2b718102021-04-21 07:32:39 +02002956 LIST_APPEND(&ckch_inst->sni_ctx, &sc->by_ckch_inst);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01002957 }
2958 return order;
2959}
2960
William Lallemand6af03992019-07-23 15:00:54 +02002961/*
William Lallemand1d29c742019-10-04 00:53:29 +02002962 * Insert the sni_ctxs that are listed in the ckch_inst, in the bind_conf's sni_ctx tree
2963 * This function can't return an error.
2964 *
2965 * *CAUTION*: The caller must lock the sni tree if called in multithreading mode
2966 */
William Lallemandc756bbd2020-05-13 17:23:59 +02002967void ssl_sock_load_cert_sni(struct ckch_inst *ckch_inst, struct bind_conf *bind_conf)
William Lallemand1d29c742019-10-04 00:53:29 +02002968{
2969
2970 struct sni_ctx *sc0, *sc0b, *sc1;
2971 struct ebmb_node *node;
2972
2973 list_for_each_entry_safe(sc0, sc0b, &ckch_inst->sni_ctx, by_ckch_inst) {
2974
2975 /* ignore if sc0 was already inserted in a tree */
2976 if (sc0->name.node.leaf_p)
2977 continue;
2978
2979 /* Check for duplicates. */
2980 if (sc0->wild)
2981 node = ebst_lookup(&bind_conf->sni_w_ctx, (char *)sc0->name.key);
2982 else
2983 node = ebst_lookup(&bind_conf->sni_ctx, (char *)sc0->name.key);
2984
2985 for (; node; node = ebmb_next_dup(node)) {
2986 sc1 = ebmb_entry(node, struct sni_ctx, name);
2987 if (sc1->ctx == sc0->ctx && sc1->conf == sc0->conf
2988 && sc1->neg == sc0->neg && sc1->wild == sc0->wild) {
2989 /* it's a duplicate, we should remove and free it */
Willy Tarreau2b718102021-04-21 07:32:39 +02002990 LIST_DELETE(&sc0->by_ckch_inst);
William Lallemand02e19a52020-04-08 16:11:26 +02002991 SSL_CTX_free(sc0->ctx);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002992 ha_free(&sc0);
William Lallemande15029b2019-10-14 10:46:58 +02002993 break;
William Lallemand1d29c742019-10-04 00:53:29 +02002994 }
2995 }
2996
2997 /* if duplicate, ignore the insertion */
2998 if (!sc0)
2999 continue;
3000
3001 if (sc0->wild)
3002 ebst_insert(&bind_conf->sni_w_ctx, &sc0->name);
3003 else
3004 ebst_insert(&bind_conf->sni_ctx, &sc0->name);
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003005 }
William Lallemand21724f02019-11-04 17:56:13 +01003006
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003007 /* replace the default_ctx if required with the instance's ctx. */
3008 if (ckch_inst->is_default) {
3009 SSL_CTX_free(bind_conf->default_ctx);
3010 SSL_CTX_up_ref(ckch_inst->ctx);
3011 bind_conf->default_ctx = ckch_inst->ctx;
William Lallemand1d29c742019-10-04 00:53:29 +02003012 }
3013}
3014
3015/*
William Lallemande3af8fb2019-10-08 11:36:53 +02003016 * tree used to store the ckchs ordered by filename/bundle name
William Lallemand6af03992019-07-23 15:00:54 +02003017 */
William Lallemande3af8fb2019-10-08 11:36:53 +02003018struct eb_root ckchs_tree = EB_ROOT_UNIQUE;
William Lallemand6af03992019-07-23 15:00:54 +02003019
William Lallemand2954c472020-03-06 21:54:13 +01003020/* tree of crtlist (crt-list/directory) */
William Lallemandc756bbd2020-05-13 17:23:59 +02003021struct eb_root crtlists_tree = EB_ROOT_UNIQUE;
William Lallemandfa892222019-07-23 16:06:08 +02003022
Emeric Brun7a883362019-10-17 13:27:40 +02003023/* Loads Diffie-Hellman parameter from a ckchs to an SSL_CTX.
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05003024 * If there is no DH parameter available in the ckchs, the global
Emeric Brun7a883362019-10-17 13:27:40 +02003025 * DH parameter is loaded into the SSL_CTX and if there is no
3026 * DH parameter available in ckchs nor in global, the default
3027 * DH parameters are applied on the SSL_CTX.
3028 * Returns a bitfield containing the flags:
3029 * ERR_FATAL in any fatal error case
3030 * ERR_ALERT if a reason of the error is availabine in err
3031 * ERR_WARN if a warning is available into err
3032 * The value 0 means there is no error nor warning and
3033 * the operation succeed.
3034 */
William Lallemandfa892222019-07-23 16:06:08 +02003035#ifndef OPENSSL_NO_DH
Emeric Brun7a883362019-10-17 13:27:40 +02003036static int ssl_sock_load_dh_params(SSL_CTX *ctx, const struct cert_key_and_chain *ckch,
3037 const char *path, char **err)
William Lallemandfa892222019-07-23 16:06:08 +02003038{
Emeric Brun7a883362019-10-17 13:27:40 +02003039 int ret = 0;
William Lallemandfa892222019-07-23 16:06:08 +02003040 DH *dh = NULL;
3041
William Lallemanda8c73742019-07-31 18:31:34 +02003042 if (ckch && ckch->dh) {
William Lallemandfa892222019-07-23 16:06:08 +02003043 dh = ckch->dh;
Emeric Bruna9363eb2019-10-17 14:53:03 +02003044 if (!SSL_CTX_set_tmp_dh(ctx, dh)) {
3045 memprintf(err, "%sunable to load the DH parameter specified in '%s'",
3046 err && *err ? *err : "", path);
3047#if defined(SSL_CTX_set_dh_auto)
3048 SSL_CTX_set_dh_auto(ctx, 1);
3049 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3050 err && *err ? *err : "");
3051#else
3052 memprintf(err, "%s, DH ciphers won't be available.\n",
3053 err && *err ? *err : "");
3054#endif
3055 ret |= ERR_WARN;
3056 goto end;
3057 }
William Lallemandfa892222019-07-23 16:06:08 +02003058
3059 if (ssl_dh_ptr_index >= 0) {
3060 /* store a pointer to the DH params to avoid complaining about
3061 ssl-default-dh-param not being set for this SSL_CTX */
3062 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
3063 }
3064 }
3065 else if (global_dh) {
Emeric Bruna9363eb2019-10-17 14:53:03 +02003066 if (!SSL_CTX_set_tmp_dh(ctx, global_dh)) {
3067 memprintf(err, "%sunable to use the global DH parameter for certificate '%s'",
3068 err && *err ? *err : "", path);
3069#if defined(SSL_CTX_set_dh_auto)
3070 SSL_CTX_set_dh_auto(ctx, 1);
3071 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3072 err && *err ? *err : "");
3073#else
3074 memprintf(err, "%s, DH ciphers won't be available.\n",
3075 err && *err ? *err : "");
3076#endif
3077 ret |= ERR_WARN;
3078 goto end;
3079 }
William Lallemandfa892222019-07-23 16:06:08 +02003080 }
3081 else {
3082 /* Clear openssl global errors stack */
3083 ERR_clear_error();
3084
Willy Tarreau6d27a922020-11-05 19:38:05 +01003085 if (global_ssl.default_dh_param && global_ssl.default_dh_param <= 1024) {
William Lallemandfa892222019-07-23 16:06:08 +02003086 /* we are limited to DH parameter of 1024 bits anyway */
3087 if (local_dh_1024 == NULL)
3088 local_dh_1024 = ssl_get_dh_1024();
3089
Emeric Brun7a883362019-10-17 13:27:40 +02003090 if (local_dh_1024 == NULL) {
3091 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3092 err && *err ? *err : "", path);
3093 ret |= ERR_ALERT | ERR_FATAL;
William Lallemandfa892222019-07-23 16:06:08 +02003094 goto end;
Emeric Brun7a883362019-10-17 13:27:40 +02003095 }
William Lallemandfa892222019-07-23 16:06:08 +02003096
Emeric Bruna9363eb2019-10-17 14:53:03 +02003097 if (!SSL_CTX_set_tmp_dh(ctx, local_dh_1024)) {
3098 memprintf(err, "%sunable to load default 1024 bits DH parameter for certificate '%s'.\n",
3099 err && *err ? *err : "", path);
3100#if defined(SSL_CTX_set_dh_auto)
3101 SSL_CTX_set_dh_auto(ctx, 1);
3102 memprintf(err, "%s, SSL library will use an automatically generated DH parameter.\n",
3103 err && *err ? *err : "");
3104#else
3105 memprintf(err, "%s, DH ciphers won't be available.\n",
3106 err && *err ? *err : "");
3107#endif
3108 ret |= ERR_WARN;
3109 goto end;
3110 }
William Lallemandfa892222019-07-23 16:06:08 +02003111 }
3112 else {
3113 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh);
3114 }
William Lallemand8d0f8932019-10-17 18:03:58 +02003115 }
3116
William Lallemandf9568fc2019-10-16 18:27:58 +02003117end:
William Lallemandf9568fc2019-10-16 18:27:58 +02003118 ERR_clear_error();
William Lallemandf9568fc2019-10-16 18:27:58 +02003119 return ret;
3120}
Emmanuel Hocdet54227d82019-07-30 17:04:01 +02003121#endif
William Lallemandfa892222019-07-23 16:06:08 +02003122
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003123
3124/* Load a certificate chain into an SSL context.
Emeric Bruna96b5822019-10-17 13:25:14 +02003125 * Returns a bitfield containing the flags:
3126 * ERR_FATAL in any fatal error case
3127 * ERR_ALERT if the reason of the error is available in err
3128 * ERR_WARN if a warning is available into err
Remi Tricot-Le Bretond417c252022-12-15 15:44:37 +01003129 * The caller is responsible of freeing the newly built or newly refcounted
3130 * find_chain element.
Emeric Bruna96b5822019-10-17 13:25:14 +02003131 * The value 0 means there is no error nor warning and
3132 * the operation succeed.
yanbzhu488a4d22015-12-01 15:16:07 -05003133 */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003134static int ssl_sock_load_cert_chain(const char *path, const struct cert_key_and_chain *ckch,
3135 SSL_CTX *ctx, STACK_OF(X509) **find_chain, char **err)
yanbzhu488a4d22015-12-01 15:16:07 -05003136{
Emeric Bruna96b5822019-10-17 13:25:14 +02003137 int errcode = 0;
3138
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003139 if (find_chain == NULL) {
3140 errcode |= ERR_FATAL;
3141 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003142 }
3143
3144 if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
3145 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
3146 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003147 errcode |= ERR_ALERT | ERR_FATAL;
3148 goto end;
yanbzhu488a4d22015-12-01 15:16:07 -05003149 }
3150
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003151 if (ckch->chain) {
Remi Tricot-Le Bretond417c252022-12-15 15:44:37 +01003152 *find_chain = X509_chain_up_ref(ckch->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003153 } else {
3154 /* Find Certificate Chain in global */
3155 struct issuer_chain *issuer;
Emmanuel Hocdetef87e0a2020-03-23 11:29:11 +01003156 issuer = ssl_get0_issuer_chain(ckch->cert);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003157 if (issuer)
Remi Tricot-Le Bretond417c252022-12-15 15:44:37 +01003158 *find_chain = X509_chain_up_ref(issuer->chain);
Emmanuel Hocdetb90d2cb2020-02-18 15:27:32 +01003159 }
William Lallemand85888572020-02-27 14:48:35 +01003160
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003161 if (!*find_chain) {
William Lallemand935d8292020-08-12 20:02:10 +02003162 /* always put a null chain stack in the SSL_CTX so it does not
3163 * try to build the chain from the verify store */
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003164 *find_chain = sk_X509_new_null();
William Lallemand935d8292020-08-12 20:02:10 +02003165 }
3166
William Lallemandf187ce62020-06-02 18:27:20 +02003167 /* Load all certs in the ckch into the ctx_chain for the ssl_ctx */
William Lallemandf187ce62020-06-02 18:27:20 +02003168#ifdef SSL_CTX_set1_chain
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003169 if (!SSL_CTX_set1_chain(ctx, *find_chain)) {
William Lallemand935d8292020-08-12 20:02:10 +02003170 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'. Make sure you are linking against Openssl >= 1.0.2.\n",
3171 err && *err ? *err : "", path);
3172 errcode |= ERR_ALERT | ERR_FATAL;
3173 goto end;
3174 }
William Lallemandf187ce62020-06-02 18:27:20 +02003175#else
3176 { /* legacy compat (< openssl 1.0.2) */
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003177 X509 *ca;
Remi Tricot-Le Bretond417c252022-12-15 15:44:37 +01003178 while ((ca = sk_X509_shift(*find_chain)))
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003179 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003180 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3181 err && *err ? *err : "", path);
William Lallemandf187ce62020-06-02 18:27:20 +02003182 X509_free(ca);
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003183 errcode |= ERR_ALERT | ERR_FATAL;
3184 goto end;
3185 }
Emmanuel Hocdet4fed93e2020-02-28 16:00:34 +01003186 }
William Lallemandf187ce62020-06-02 18:27:20 +02003187#endif
yanbzhu488a4d22015-12-01 15:16:07 -05003188
William Lallemand9a1d8392020-08-10 17:28:23 +02003189#ifdef SSL_CTX_build_cert_chain
William Lallemandbf298af2020-08-10 16:18:45 +02003190 /* remove the Root CA from the SSL_CTX if the option is activated */
3191 if (global_ssl.skip_self_issued_ca) {
3192 if (!SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT|SSL_BUILD_CHAIN_FLAG_UNTRUSTED|SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR)) {
3193 memprintf(err, "%sunable to load chain certificate into SSL Context '%s'.\n",
3194 err && *err ? *err : "", path);
3195 errcode |= ERR_ALERT | ERR_FATAL;
3196 goto end;
3197 }
3198 }
William Lallemand9a1d8392020-08-10 17:28:23 +02003199#endif
William Lallemandbf298af2020-08-10 16:18:45 +02003200
Remi Tricot-Le Bretonec805a32021-01-25 17:19:42 +01003201end:
3202 return errcode;
3203}
3204
3205
3206/* Loads the info in ckch into ctx
3207 * Returns a bitfield containing the flags:
3208 * ERR_FATAL in any fatal error case
3209 * ERR_ALERT if the reason of the error is available in err
3210 * ERR_WARN if a warning is available into err
3211 * The value 0 means there is no error nor warning and
3212 * the operation succeed.
3213 */
3214static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
3215{
3216 int errcode = 0;
3217 STACK_OF(X509) *find_chain = NULL;
3218
3219 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3220 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3221 err && *err ? *err : "", path);
3222 errcode |= ERR_ALERT | ERR_FATAL;
3223 return errcode;
3224 }
3225
3226 /* Load certificate chain */
3227 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3228 if (errcode & ERR_CODE)
3229 goto end;
3230
William Lallemandfa892222019-07-23 16:06:08 +02003231#ifndef OPENSSL_NO_DH
3232 /* store a NULL pointer to indicate we have not yet loaded
3233 a custom DH param file */
3234 if (ssl_dh_ptr_index >= 0) {
3235 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
3236 }
3237
Emeric Brun7a883362019-10-17 13:27:40 +02003238 errcode |= ssl_sock_load_dh_params(ctx, ckch, path, err);
3239 if (errcode & ERR_CODE) {
William Lallemandfa892222019-07-23 16:06:08 +02003240 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
3241 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003242 goto end;
William Lallemandfa892222019-07-23 16:06:08 +02003243 }
3244#endif
3245
Ilya Shipitsin7bbf5862021-02-06 18:55:27 +05003246#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
William Lallemanda17f4112019-10-10 15:16:44 +02003247 if (sctl_ex_index >= 0 && ckch->sctl) {
3248 if (ssl_sock_load_sctl(ctx, ckch->sctl) < 0) {
3249 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01003250 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003251 errcode |= ERR_ALERT | ERR_FATAL;
3252 goto end;
William Lallemanda17f4112019-10-10 15:16:44 +02003253 }
3254 }
3255#endif
3256
Emmanuel Hocdeta73a2222020-10-26 13:55:30 +01003257#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) || defined OPENSSL_IS_BORINGSSL)
William Lallemand246c0242019-10-11 08:59:13 +02003258 /* Load OCSP Info into context */
3259 if (ckch->ocsp_response) {
Emmanuel Hocdet6f507c72020-02-18 15:56:39 +01003260 if (ssl_sock_load_ocsp(ctx, ckch, find_chain) < 0) {
Tim Duesterhus93128532019-11-23 23:45:10 +01003261 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",
3262 err && *err ? *err : "", path);
Emeric Bruna96b5822019-10-17 13:25:14 +02003263 errcode |= ERR_ALERT | ERR_FATAL;
3264 goto end;
William Lallemand246c0242019-10-11 08:59:13 +02003265 }
3266 }
William Lallemand246c0242019-10-11 08:59:13 +02003267#endif
3268
Emeric Bruna96b5822019-10-17 13:25:14 +02003269 end:
Remi Tricot-Le Bretond417c252022-12-15 15:44:37 +01003270 sk_X509_pop_free(find_chain, X509_free);
Emeric Bruna96b5822019-10-17 13:25:14 +02003271 return errcode;
yanbzhu488a4d22015-12-01 15:16:07 -05003272}
3273
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003274
3275/* Loads the info of a ckch built out of a backend certificate into an SSL ctx
3276 * Returns a bitfield containing the flags:
3277 * ERR_FATAL in any fatal error case
3278 * ERR_ALERT if the reason of the error is available in err
3279 * ERR_WARN if a warning is available into err
3280 * The value 0 means there is no error nor warning and
3281 * the operation succeed.
3282 */
3283static int ssl_sock_put_srv_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch,
3284 SSL_CTX *ctx, char **err)
3285{
3286 int errcode = 0;
3287 STACK_OF(X509) *find_chain = NULL;
3288
3289 /* Load the private key */
3290 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
3291 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
3292 err && *err ? *err : "", path);
3293 errcode |= ERR_ALERT | ERR_FATAL;
3294 }
3295
3296 /* Load certificate chain */
3297 errcode |= ssl_sock_load_cert_chain(path, ckch, ctx, &find_chain, err);
3298 if (errcode & ERR_CODE)
3299 goto end;
3300
3301 if (SSL_CTX_check_private_key(ctx) <= 0) {
3302 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3303 err && *err ? *err : "", path);
3304 errcode |= ERR_ALERT | ERR_FATAL;
3305 }
3306
3307end:
Remi Tricot-Le Bretond417c252022-12-15 15:44:37 +01003308 sk_X509_pop_free(find_chain, X509_free);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003309 return errcode;
3310}
3311
3312
William Lallemand614ca0d2019-10-07 13:52:11 +02003313/*
3314 * This function allocate a ckch_inst and create its snis
Emeric Brun054563d2019-10-17 13:16:58 +02003315 *
3316 * Returns a bitfield containing the flags:
3317 * ERR_FATAL in any fatal error case
3318 * ERR_ALERT if the reason of the error is available in err
3319 * ERR_WARN if a warning is available into err
William Lallemand614ca0d2019-10-07 13:52:11 +02003320 */
William Lallemandc756bbd2020-05-13 17:23:59 +02003321int ckch_inst_new_load_store(const char *path, struct ckch_store *ckchs, struct bind_conf *bind_conf,
Emeric Brun054563d2019-10-17 13:16:58 +02003322 struct ssl_bind_conf *ssl_conf, char **sni_filter, int fcount, struct ckch_inst **ckchi, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003323{
William Lallemandc9402072019-05-15 15:33:54 +02003324 SSL_CTX *ctx;
William Lallemandc9402072019-05-15 15:33:54 +02003325 int i;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003326 int order = 0;
3327 X509_NAME *xname;
3328 char *str;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003329 EVP_PKEY *pkey;
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003330 struct pkey_info kinfo = { .sig = TLSEXT_signature_anonymous, .bits = 0 };
Emeric Brunfc0421f2012-09-07 17:30:07 +02003331#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3332 STACK_OF(GENERAL_NAME) *names;
3333#endif
William Lallemand36b84632019-07-18 19:28:17 +02003334 struct cert_key_and_chain *ckch;
William Lallemand614ca0d2019-10-07 13:52:11 +02003335 struct ckch_inst *ckch_inst = NULL;
Emeric Brun054563d2019-10-17 13:16:58 +02003336 int errcode = 0;
3337
3338 *ckchi = NULL;
William Lallemanda59191b2019-05-15 16:08:56 +02003339
William Lallemande3af8fb2019-10-08 11:36:53 +02003340 if (!ckchs || !ckchs->ckch)
Emeric Brun054563d2019-10-17 13:16:58 +02003341 return ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003342
William Lallemande3af8fb2019-10-08 11:36:53 +02003343 ckch = ckchs->ckch;
William Lallemand36b84632019-07-18 19:28:17 +02003344
William Lallemandc9402072019-05-15 15:33:54 +02003345 ctx = SSL_CTX_new(SSLv23_server_method());
3346 if (!ctx) {
3347 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3348 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003349 errcode |= ERR_ALERT | ERR_FATAL;
3350 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003351 }
3352
Emeric Bruna96b5822019-10-17 13:25:14 +02003353 errcode |= ssl_sock_put_ckch_into_ctx(path, ckch, ctx, err);
3354 if (errcode & ERR_CODE)
William Lallemand614ca0d2019-10-07 13:52:11 +02003355 goto error;
William Lallemand614ca0d2019-10-07 13:52:11 +02003356
3357 ckch_inst = ckch_inst_new();
3358 if (!ckch_inst) {
3359 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3360 err && *err ? *err : "", path);
Emeric Brun054563d2019-10-17 13:16:58 +02003361 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003362 goto error;
William Lallemandc9402072019-05-15 15:33:54 +02003363 }
3364
William Lallemand36b84632019-07-18 19:28:17 +02003365 pkey = X509_get_pubkey(ckch->cert);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003366 if (pkey) {
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003367 kinfo.bits = EVP_PKEY_bits(pkey);
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003368 switch(EVP_PKEY_base_id(pkey)) {
3369 case EVP_PKEY_RSA:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003370 kinfo.sig = TLSEXT_signature_rsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003371 break;
3372 case EVP_PKEY_EC:
Emmanuel Hocdetddc090b2017-10-27 18:43:29 +02003373 kinfo.sig = TLSEXT_signature_ecdsa;
3374 break;
3375 case EVP_PKEY_DSA:
3376 kinfo.sig = TLSEXT_signature_dsa;
Emmanuel Hocdet05942112017-02-20 16:11:50 +01003377 break;
3378 }
3379 EVP_PKEY_free(pkey);
3380 }
3381
Emeric Brun50bcecc2013-04-22 13:05:23 +02003382 if (fcount) {
William Lallemandfe49bb32019-10-03 23:46:33 +02003383 while (fcount--) {
William Lallemand1d29c742019-10-04 00:53:29 +02003384 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 +02003385 if (order < 0) {
3386 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003387 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003388 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003389 }
3390 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003391 }
3392 else {
Emeric Brunfc0421f2012-09-07 17:30:07 +02003393#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
William Lallemand36b84632019-07-18 19:28:17 +02003394 names = X509_get_ext_d2i(ckch->cert, NID_subject_alt_name, NULL, NULL);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003395 if (names) {
3396 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
3397 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
3398 if (name->type == GEN_DNS) {
3399 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003400 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003401 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003402 if (order < 0) {
3403 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003404 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003405 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003406 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003407 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003408 }
3409 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003410 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Emeric Brunfc0421f2012-09-07 17:30:07 +02003411 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003412#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
William Lallemand36b84632019-07-18 19:28:17 +02003413 xname = X509_get_subject_name(ckch->cert);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003414 i = -1;
3415 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
3416 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02003417 ASN1_STRING *value;
3418
3419 value = X509_NAME_ENTRY_get_data(entry);
3420 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
William Lallemand1d29c742019-10-04 00:53:29 +02003421 order = ckch_inst_add_cert_sni(ctx, ckch_inst, bind_conf, ssl_conf, kinfo, str, order);
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003422 OPENSSL_free(str);
William Lallemandfe49bb32019-10-03 23:46:33 +02003423 if (order < 0) {
3424 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003425 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003426 goto error;
William Lallemandfe49bb32019-10-03 23:46:33 +02003427 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003428 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003429 }
3430 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003431 /* we must not free the SSL_CTX anymore below, since it's already in
3432 * the tree, so it will be discovered and cleaned in time.
3433 */
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003434
Emeric Brunfc0421f2012-09-07 17:30:07 +02003435#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003436 if (bind_conf->default_ctx) {
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003437 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
3438 err && *err ? *err : "");
Emeric Brun054563d2019-10-17 13:16:58 +02003439 errcode |= ERR_ALERT | ERR_FATAL;
William Lallemandd9199372019-10-04 15:37:05 +02003440 goto error;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003441 }
3442#endif
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003443 if (!bind_conf->default_ctx) {
Willy Tarreau2a65ff02012-09-13 17:54:29 +02003444 bind_conf->default_ctx = ctx;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003445 bind_conf->default_ssl_conf = ssl_conf;
William Lallemand21724f02019-11-04 17:56:13 +01003446 ckch_inst->is_default = 1;
William Lallemand02e19a52020-04-08 16:11:26 +02003447 SSL_CTX_up_ref(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01003448 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02003449
Remi Tricot-Le Breton8218aed2021-03-17 14:56:54 +01003450 /* Always keep a reference to the newly constructed SSL_CTX in the
3451 * instance. This way if the instance has no SNIs, the SSL_CTX will
3452 * still be linked. */
3453 SSL_CTX_up_ref(ctx);
3454 ckch_inst->ctx = ctx;
3455
William Lallemand9117de92019-10-04 00:29:42 +02003456 /* everything succeed, the ckch instance can be used */
3457 ckch_inst->bind_conf = bind_conf;
William Lallemand150bfa82019-09-19 17:12:49 +02003458 ckch_inst->ssl_conf = ssl_conf;
William Lallemandcfca1422020-03-05 10:17:47 +01003459 ckch_inst->ckch_store = ckchs;
William Lallemand9117de92019-10-04 00:29:42 +02003460
William Lallemand02e19a52020-04-08 16:11:26 +02003461 SSL_CTX_free(ctx); /* we need to free the ctx since we incremented the refcount where it's used */
3462
Emeric Brun054563d2019-10-17 13:16:58 +02003463 *ckchi = ckch_inst;
3464 return errcode;
William Lallemandd9199372019-10-04 15:37:05 +02003465
3466error:
3467 /* free the allocated sni_ctxs */
William Lallemand614ca0d2019-10-07 13:52:11 +02003468 if (ckch_inst) {
William Lallemand02e19a52020-04-08 16:11:26 +02003469 if (ckch_inst->is_default)
3470 SSL_CTX_free(ctx);
3471
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003472 ckch_inst_free(ckch_inst);
William Lallemand614ca0d2019-10-07 13:52:11 +02003473 ckch_inst = NULL;
William Lallemandd9199372019-10-04 15:37:05 +02003474 }
William Lallemandd9199372019-10-04 15:37:05 +02003475 SSL_CTX_free(ctx);
3476
Emeric Brun054563d2019-10-17 13:16:58 +02003477 return errcode;
Emeric Brunfc0421f2012-09-07 17:30:07 +02003478}
3479
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003480
3481/*
3482 * This function allocate a ckch_inst that will be used on the backend side
3483 * (server line)
3484 *
3485 * Returns a bitfield containing the flags:
3486 * ERR_FATAL in any fatal error case
3487 * ERR_ALERT if the reason of the error is available in err
3488 * ERR_WARN if a warning is available into err
3489 */
3490int ckch_inst_new_load_srv_store(const char *path, struct ckch_store *ckchs,
William Lallemand795bd9b2021-01-26 11:27:42 +01003491 struct ckch_inst **ckchi, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003492{
3493 SSL_CTX *ctx;
3494 struct cert_key_and_chain *ckch;
3495 struct ckch_inst *ckch_inst = NULL;
3496 int errcode = 0;
3497
3498 *ckchi = NULL;
3499
3500 if (!ckchs || !ckchs->ckch)
3501 return ERR_FATAL;
3502
3503 ckch = ckchs->ckch;
3504
3505 ctx = SSL_CTX_new(SSLv23_client_method());
3506 if (!ctx) {
3507 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3508 err && *err ? *err : "", path);
3509 errcode |= ERR_ALERT | ERR_FATAL;
3510 goto error;
3511 }
3512
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003513 errcode |= ssl_sock_put_srv_ckch_into_ctx(path, ckch, ctx, err);
3514 if (errcode & ERR_CODE)
3515 goto error;
3516
3517 ckch_inst = ckch_inst_new();
3518 if (!ckch_inst) {
3519 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
3520 err && *err ? *err : "", path);
3521 errcode |= ERR_ALERT | ERR_FATAL;
3522 goto error;
3523 }
3524
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003525 /* everything succeed, the ckch instance can be used */
3526 ckch_inst->bind_conf = NULL;
3527 ckch_inst->ssl_conf = NULL;
3528 ckch_inst->ckch_store = ckchs;
William Lallemand795bd9b2021-01-26 11:27:42 +01003529 ckch_inst->ctx = ctx;
William Lallemanddb26e2b2021-01-26 12:01:46 +01003530 ckch_inst->is_server_instance = 1;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003531
3532 *ckchi = ckch_inst;
3533 return errcode;
3534
3535error:
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003536 SSL_CTX_free(ctx);
3537
3538 return errcode;
3539}
3540
Willy Tarreau8c5414a2019-10-16 17:06:25 +02003541/* Returns a set of ERR_* flags possibly with an error in <err>. */
William Lallemand614ca0d2019-10-07 13:52:11 +02003542static int ssl_sock_load_ckchs(const char *path, struct ckch_store *ckchs,
3543 struct bind_conf *bind_conf, struct ssl_bind_conf *ssl_conf,
William Lallemand24bde432020-03-09 16:48:43 +01003544 char **sni_filter, int fcount, struct ckch_inst **ckch_inst, char **err)
William Lallemand614ca0d2019-10-07 13:52:11 +02003545{
Emeric Brun054563d2019-10-17 13:16:58 +02003546 int errcode = 0;
William Lallemand614ca0d2019-10-07 13:52:11 +02003547
3548 /* we found the ckchs in the tree, we can use it directly */
William Lallemande7eb1fe2020-09-16 16:17:51 +02003549 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 +02003550
Emeric Brun054563d2019-10-17 13:16:58 +02003551 if (errcode & ERR_CODE)
3552 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003553
William Lallemand24bde432020-03-09 16:48:43 +01003554 ssl_sock_load_cert_sni(*ckch_inst, bind_conf);
William Lallemand614ca0d2019-10-07 13:52:11 +02003555
3556 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003557 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Emeric Brun054563d2019-10-17 13:16:58 +02003558 return errcode;
William Lallemand614ca0d2019-10-07 13:52:11 +02003559}
3560
William Lallemanddb26e2b2021-01-26 12:01:46 +01003561/* This function generates a <struct ckch_inst *> for a <struct server *>, and
3562 * fill the SSL_CTX of the server.
3563 *
3564 * Returns a set of ERR_* flags possibly with an error in <err>. */
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003565static int ssl_sock_load_srv_ckchs(const char *path, struct ckch_store *ckchs,
William Lallemanddb26e2b2021-01-26 12:01:46 +01003566 struct server *server, struct ckch_inst **ckch_inst, char **err)
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003567{
3568 int errcode = 0;
3569
3570 /* we found the ckchs in the tree, we can use it directly */
William Lallemand795bd9b2021-01-26 11:27:42 +01003571 errcode |= ckch_inst_new_load_srv_store(path, ckchs, ckch_inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003572
3573 if (errcode & ERR_CODE)
3574 return errcode;
3575
William Lallemanddb26e2b2021-01-26 12:01:46 +01003576 (*ckch_inst)->server = server;
3577 /* Keep the reference to the SSL_CTX in the server. */
3578 SSL_CTX_up_ref((*ckch_inst)->ctx);
3579 server->ssl_ctx.ctx = (*ckch_inst)->ctx;
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003580 /* succeed, add the instance to the ckch_store's list of instance */
Willy Tarreau2b718102021-04-21 07:32:39 +02003581 LIST_APPEND(&ckchs->ckch_inst, &((*ckch_inst)->by_ckchs));
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003582 return errcode;
3583}
3584
William Lallemand6be66ec2020-03-06 22:26:32 +01003585
William Lallemand4c68bba2020-03-30 18:45:10 +02003586
3587
3588/* Make sure openssl opens /dev/urandom before the chroot. The work is only
3589 * done once. Zero is returned if the operation fails. No error is returned
3590 * if the random is said as not implemented, because we expect that openssl
3591 * will use another method once needed.
3592 */
3593static int ssl_initialize_random()
3594{
3595 unsigned char random;
3596 static int random_initialized = 0;
3597
3598 if (!random_initialized && RAND_bytes(&random, 1) != 0)
3599 random_initialized = 1;
3600
3601 return random_initialized;
3602}
3603
William Lallemand2954c472020-03-06 21:54:13 +01003604/* Load a crt-list file, this is done in 2 parts:
3605 * - store the content of the file in a crtlist structure with crtlist_entry structures
3606 * - generate the instances by iterating on entries in the crtlist struct
3607 *
3608 * Nothing is locked there, this function is used in the configuration parser.
3609 *
3610 * Returns a set of ERR_* flags possibly with an error in <err>.
3611 */
William Lallemand6be66ec2020-03-06 22:26:32 +01003612int 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 +01003613{
3614 struct crtlist *crtlist = NULL;
3615 struct ebmb_node *eb;
William Lallemand49398312020-03-30 17:01:33 +02003616 struct crtlist_entry *entry = NULL;
William Lallemand79d31ec2020-03-25 15:10:49 +01003617 struct bind_conf_list *bind_conf_node = NULL;
William Lallemand2954c472020-03-06 21:54:13 +01003618 int cfgerr = 0;
William Lallemand41ca9302020-04-08 13:15:18 +02003619 char *end;
William Lallemand2954c472020-03-06 21:54:13 +01003620
William Lallemand79d31ec2020-03-25 15:10:49 +01003621 bind_conf_node = malloc(sizeof(*bind_conf_node));
3622 if (!bind_conf_node) {
3623 memprintf(err, "%sCan't alloc memory!\n", err && *err ? *err : "");
3624 cfgerr |= ERR_FATAL | ERR_ALERT;
3625 goto error;
3626 }
3627 bind_conf_node->next = NULL;
3628 bind_conf_node->bind_conf = bind_conf;
3629
William Lallemand41ca9302020-04-08 13:15:18 +02003630 /* strip trailing slashes, including first one */
3631 for (end = file + strlen(file) - 1; end >= file && *end == '/'; end--)
3632 *end = 0;
3633
William Lallemand2954c472020-03-06 21:54:13 +01003634 /* look for an existing crtlist or create one */
3635 eb = ebst_lookup(&crtlists_tree, file);
3636 if (eb) {
3637 crtlist = ebmb_entry(eb, struct crtlist, node);
3638 } else {
William Lallemand6be66ec2020-03-06 22:26:32 +01003639 /* load a crt-list OR a directory */
3640 if (dir)
3641 cfgerr |= crtlist_load_cert_dir(file, bind_conf, &crtlist, err);
3642 else
3643 cfgerr |= crtlist_parse_file(file, bind_conf, curproxy, &crtlist, err);
3644
William Lallemand2954c472020-03-06 21:54:13 +01003645 if (!(cfgerr & ERR_CODE))
3646 ebst_insert(&crtlists_tree, &crtlist->node);
3647 }
3648
3649 if (cfgerr & ERR_CODE) {
3650 cfgerr |= ERR_FATAL | ERR_ALERT;
3651 goto error;
3652 }
3653
3654 /* generates ckch instance from the crtlist_entry */
3655 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3656 struct ckch_store *store;
3657 struct ckch_inst *ckch_inst = NULL;
3658
3659 store = entry->node.key;
3660 cfgerr |= ssl_sock_load_ckchs(store->path, store, bind_conf, entry->ssl_conf, entry->filters, entry->fcount, &ckch_inst, err);
3661 if (cfgerr & ERR_CODE) {
3662 memprintf(err, "error processing line %d in file '%s' : %s", entry->linenum, file, *err);
3663 goto error;
3664 }
Willy Tarreau2b718102021-04-21 07:32:39 +02003665 LIST_APPEND(&entry->ckch_inst, &ckch_inst->by_crtlist_entry);
William Lallemandcaa16192020-04-08 16:29:15 +02003666 ckch_inst->crtlist_entry = entry;
William Lallemand2954c472020-03-06 21:54:13 +01003667 }
William Lallemand2954c472020-03-06 21:54:13 +01003668
William Lallemand79d31ec2020-03-25 15:10:49 +01003669 /* add the bind_conf to the list */
3670 bind_conf_node->next = crtlist->bind_conf;
3671 crtlist->bind_conf = bind_conf_node;
3672
William Lallemand2954c472020-03-06 21:54:13 +01003673 return cfgerr;
3674error:
3675 {
William Lallemand49398312020-03-30 17:01:33 +02003676 struct crtlist_entry *lastentry;
William Lallemand2954c472020-03-06 21:54:13 +01003677 struct ckch_inst *inst, *s_inst;
3678
William Lallemand49398312020-03-30 17:01:33 +02003679 lastentry = entry; /* which entry we tried to generate last */
3680 if (lastentry) {
3681 list_for_each_entry(entry, &crtlist->ord_entries, by_crtlist) {
3682 if (entry == lastentry) /* last entry we tried to generate, no need to go further */
3683 break;
3684
3685 list_for_each_entry_safe(inst, s_inst, &entry->ckch_inst, by_crtlist_entry) {
William Lallemand2954c472020-03-06 21:54:13 +01003686
William Lallemand49398312020-03-30 17:01:33 +02003687 /* this was not generated for this bind_conf, skip */
3688 if (inst->bind_conf != bind_conf)
3689 continue;
3690
William Lallemandd9d5d1b2020-04-09 16:31:05 +02003691 /* free the sni_ctx and instance */
3692 ckch_inst_free(inst);
William Lallemand49398312020-03-30 17:01:33 +02003693 }
William Lallemand2954c472020-03-06 21:54:13 +01003694 }
William Lallemand2954c472020-03-06 21:54:13 +01003695 }
William Lallemand79d31ec2020-03-25 15:10:49 +01003696 free(bind_conf_node);
William Lallemand2954c472020-03-06 21:54:13 +01003697 }
Emmanuel Hocdetfe616562013-01-22 15:31:15 +01003698 return cfgerr;
3699}
3700
William Lallemand06b22a82020-03-16 14:45:55 +01003701/* Returns a set of ERR_* flags possibly with an error in <err>. */
3702int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, char **err)
3703{
3704 struct stat buf;
William Lallemand06b22a82020-03-16 14:45:55 +01003705 int cfgerr = 0;
3706 struct ckch_store *ckchs;
William Lallemand24bde432020-03-09 16:48:43 +01003707 struct ckch_inst *ckch_inst = NULL;
William Lallemand06ce84a2020-11-20 15:36:13 +01003708 int found = 0; /* did we found a file to load ? */
William Lallemand06b22a82020-03-16 14:45:55 +01003709
3710 if ((ckchs = ckchs_lookup(path))) {
3711 /* we found the ckchs in the tree, we can use it directly */
William Lallemand06ce84a2020-11-20 15:36:13 +01003712 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3713 found++;
3714 } else if (stat(path, &buf) == 0) {
3715 found++;
William Lallemand06b22a82020-03-16 14:45:55 +01003716 if (S_ISDIR(buf.st_mode) == 0) {
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003717 ckchs = ckchs_load_cert_file(path, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003718 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003719 cfgerr |= ERR_ALERT | ERR_FATAL;
3720 cfgerr |= ssl_sock_load_ckchs(path, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003721 } else {
William Lallemand06ce84a2020-11-20 15:36:13 +01003722 cfgerr |= ssl_sock_load_cert_list_file(path, 1, bind_conf, bind_conf->frontend, err);
William Lallemand06b22a82020-03-16 14:45:55 +01003723 }
3724 } else {
3725 /* stat failed, could be a bundle */
3726 if (global_ssl.extra_files & SSL_GF_BUNDLE) {
William Lallemanddfa93be2020-09-16 14:48:52 +02003727 char fp[MAXPATHLEN+1] = {0};
3728 int n = 0;
3729
3730 /* Load all possible certs and keys in separate ckch_store */
3731 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
3732 struct stat buf;
3733 int ret;
3734
3735 ret = snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
3736 if (ret > sizeof(fp))
3737 continue;
3738
3739 if ((ckchs = ckchs_lookup(fp))) {
3740 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
William Lallemand06ce84a2020-11-20 15:36:13 +01003741 found++;
William Lallemanddfa93be2020-09-16 14:48:52 +02003742 } else {
3743 if (stat(fp, &buf) == 0) {
William Lallemand06ce84a2020-11-20 15:36:13 +01003744 found++;
William Lallemandbd8e6ed2020-09-16 16:08:08 +02003745 ckchs = ckchs_load_cert_file(fp, err);
William Lallemanddfa93be2020-09-16 14:48:52 +02003746 if (!ckchs)
William Lallemand06ce84a2020-11-20 15:36:13 +01003747 cfgerr |= ERR_ALERT | ERR_FATAL;
William Lallemanddfa93be2020-09-16 14:48:52 +02003748 cfgerr |= ssl_sock_load_ckchs(fp, ckchs, bind_conf, NULL, NULL, 0, &ckch_inst, err);
3749 }
3750 }
3751 }
William Lallemandb7fdfdf2020-12-04 15:45:02 +01003752#if HA_OPENSSL_VERSION_NUMBER < 0x10101000L
3753 if (found) {
3754 memprintf(err, "%sCan't load '%s'. Loading a multi certificates bundle requires OpenSSL >= 1.1.1\n",
3755 err && *err ? *err : "", path);
3756 cfgerr |= ERR_ALERT | ERR_FATAL;
3757 }
3758#endif
William Lallemand06b22a82020-03-16 14:45:55 +01003759 }
3760 }
William Lallemand06ce84a2020-11-20 15:36:13 +01003761 if (!found) {
3762 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3763 err && *err ? *err : "", path, strerror(errno));
3764 cfgerr |= ERR_ALERT | ERR_FATAL;
3765 }
William Lallemand06b22a82020-03-16 14:45:55 +01003766
3767 return cfgerr;
3768}
3769
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003770
3771/* Create a full ssl context and ckch instance that will be used for a specific
3772 * backend server (server configuration line).
3773 * Returns a set of ERR_* flags possibly with an error in <err>.
3774 */
3775int ssl_sock_load_srv_cert(char *path, struct server *server, char **err)
3776{
3777 struct stat buf;
3778 int cfgerr = 0;
3779 struct ckch_store *ckchs;
3780 int found = 0; /* did we found a file to load ? */
3781
3782 if ((ckchs = ckchs_lookup(path))) {
3783 /* we found the ckchs in the tree, we can use it directly */
William Lallemanddb26e2b2021-01-26 12:01:46 +01003784 cfgerr |= ssl_sock_load_srv_ckchs(path, ckchs, server, &server->ssl_ctx.inst, err);
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01003785 found++;
3786 } else if (stat(path, &buf) == 0) {
3787 /* We do not manage directories on backend side. */
3788 if (S_ISDIR(buf.st_mode) == 0) {
3789 ++found;
3790 ckchs = ckchs_load_cert_file(path, err);
3791 if (!ckchs)
3792 cfgerr |= ERR_ALERT | ERR_FATAL;
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 }
3795 }
3796 if (!found) {
3797 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
3798 err && *err ? *err : "", path, strerror(errno));
3799 cfgerr |= ERR_ALERT | ERR_FATAL;
3800 }
3801
3802 return cfgerr;
3803}
3804
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003805/* Create an initial CTX used to start the SSL connection before switchctx */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003806static int
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003807ssl_sock_initial_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02003808{
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003809 SSL_CTX *ctx = NULL;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003810 long options =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003811 SSL_OP_ALL | /* all known workarounds for bugs */
3812 SSL_OP_NO_SSLv2 |
3813 SSL_OP_NO_COMPRESSION |
Emeric Bruna4bcd9a2012-09-20 16:19:02 +02003814 SSL_OP_SINGLE_DH_USE |
Emeric Brun2b58d042012-09-20 17:10:03 +02003815 SSL_OP_SINGLE_ECDH_USE |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003816 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
Lukas Tribus926594f2018-05-18 17:55:57 +02003817 SSL_OP_PRIORITIZE_CHACHA |
Emeric Brun3c4bc6e2012-10-04 18:44:19 +02003818 SSL_OP_CIPHER_SERVER_PREFERENCE;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003819 long mode =
Emeric Brunfc0421f2012-09-07 17:30:07 +02003820 SSL_MODE_ENABLE_PARTIAL_WRITE |
3821 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
Willy Tarreau396a1862014-11-13 14:06:52 +01003822 SSL_MODE_RELEASE_BUFFERS |
3823 SSL_MODE_SMALL_BUFFERS;
Emmanuel Hocdet43664762017-08-09 18:26:20 +02003824 struct tls_version_filter *conf_ssl_methods = &bind_conf->ssl_conf.ssl_methods;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003825 int i, min, max, hole;
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003826 int flags = MC_SSL_O_ALL;
3827 int cfgerr = 0;
William Lallemand50df1cb2020-06-02 10:52:24 +02003828 const int default_min_ver = CONF_TLSV12;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003829
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003830 ctx = SSL_CTX_new(SSLv23_server_method());
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003831 bind_conf->initial_ctx = ctx;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003832
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003833 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01003834 ha_warning("Proxy '%s': no-sslv3/no-tlsv1x are ignored for bind '%s' at [%s:%d]. "
3835 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3836 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003837 else
3838 flags = conf_ssl_methods->flags;
3839
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003840 min = conf_ssl_methods->min;
3841 max = conf_ssl_methods->max;
William Lallemand50df1cb2020-06-02 10:52:24 +02003842
3843 /* default minimum is TLSV12, */
3844 if (!min) {
3845 if (!max || (max >= default_min_ver)) {
3846 min = default_min_ver;
3847 } else {
3848 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). "
3849 "Setting the ssl-min-ver to %s. Use 'ssl-min-ver' to fix this.\n",
3850 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line, methodVersions[default_min_ver].name, methodVersions[max].name);
3851 min = max;
3852 }
3853 }
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003854 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdetbd695fe2017-05-15 15:53:41 +02003855 if (min)
3856 flags |= (methodVersions[min].flag - 1);
3857 if (max)
3858 flags |= ~((methodVersions[max].flag << 1) - 1);
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003859 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003860 min = max = CONF_TLSV_NONE;
3861 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003862 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003863 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003864 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003865 if (min) {
3866 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003867 ha_warning("Proxy '%s': SSL/TLS versions range not contiguous for bind '%s' at [%s:%d]. "
3868 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
3869 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line,
3870 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003871 hole = 0;
3872 }
3873 max = i;
3874 }
3875 else {
3876 min = max = i;
3877 }
3878 }
3879 else {
3880 if (min)
3881 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003882 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003883 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003884 ha_alert("Proxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
3885 bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003886 cfgerr += 1;
3887 }
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02003888 /* save real min/max in bind_conf */
3889 conf_ssl_methods->min = min;
3890 conf_ssl_methods->max = max;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003891
Willy Tarreau9a1ab082019-05-09 13:26:41 +02003892#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003893 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08003894 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003895 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003896 methodVersions[min].ctx_set_version(ctx, SET_SERVER);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003897 else
William Lallemandd0712f32020-06-11 17:34:00 +02003898 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++) {
3899 /* clear every version flags in case SSL_CTX_new()
3900 * returns an SSL_CTX with disabled versions */
3901 SSL_CTX_clear_options(ctx, methodVersions[i].option);
3902
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003903 if (flags & methodVersions[i].flag)
3904 options |= methodVersions[i].option;
William Lallemandd0712f32020-06-11 17:34:00 +02003905
3906 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003907#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02003908 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02003909 methodVersions[min].ctx_set_version(ctx, SET_MIN);
3910 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emeric Brunfa5c5c82017-04-28 16:19:51 +02003911#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003912
3913 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
3914 options |= SSL_OP_NO_TICKET;
3915 if (bind_conf->ssl_options & BC_SSL_O_PREF_CLIE_CIPH)
3916 options &= ~SSL_OP_CIPHER_SERVER_PREFERENCE;
Dirkjan Bussink526894f2019-01-21 09:35:03 -08003917
3918#ifdef SSL_OP_NO_RENEGOTIATION
3919 options |= SSL_OP_NO_RENEGOTIATION;
3920#endif
3921
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003922 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003923
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05003924#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00003925 if (global_ssl.async)
3926 mode |= SSL_MODE_ASYNC;
3927#endif
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02003928 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003929 if (global_ssl.life_time)
3930 SSL_CTX_set_timeout(ctx, global_ssl.life_time);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003931
3932#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3933#ifdef OPENSSL_IS_BORINGSSL
3934 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
3935 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Ilya Shipitsine9ff8992020-01-19 12:20:14 +05003936#elif defined(SSL_OP_NO_ANTI_REPLAY)
Olivier Houchard545989f2019-12-17 15:39:54 +01003937 if (bind_conf->ssl_conf.early_data)
Olivier Houchard51088ce2019-01-02 18:46:41 +01003938 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
Emmanuel Hocdet84e417d2017-08-16 11:33:17 +02003939 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
3940 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003941#else
3942 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003943#endif
Emmanuel Hocdet253c62b2017-08-14 11:01:25 +02003944 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01003945#endif
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02003946 return cfgerr;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01003947}
3948
William Lallemand4f45bb92017-10-30 20:08:51 +01003949
3950static inline void sh_ssl_sess_free_blocks(struct shared_block *first, struct shared_block *block)
3951{
3952 if (first == block) {
3953 struct sh_ssl_sess_hdr *sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3954 if (first->len > 0)
3955 sh_ssl_sess_tree_delete(sh_ssl_sess);
3956 }
3957}
3958
3959/* return first block from sh_ssl_sess */
3960static inline struct shared_block *sh_ssl_sess_first_block(struct sh_ssl_sess_hdr *sh_ssl_sess)
3961{
3962 return (struct shared_block *)((unsigned char *)sh_ssl_sess - ((struct shared_block *)NULL)->data);
3963
3964}
3965
3966/* store a session into the cache
3967 * s_id : session id padded with zero to SSL_MAX_SSL_SESSION_ID_LENGTH
3968 * data: asn1 encoded session
3969 * data_len: asn1 encoded session length
3970 * Returns 1 id session was stored (else 0)
3971 */
3972static int sh_ssl_sess_store(unsigned char *s_id, unsigned char *data, int data_len)
3973{
3974 struct shared_block *first;
3975 struct sh_ssl_sess_hdr *sh_ssl_sess, *oldsh_ssl_sess;
3976
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02003977 first = shctx_row_reserve_hot(ssl_shctx, NULL, data_len + sizeof(struct sh_ssl_sess_hdr));
William Lallemand4f45bb92017-10-30 20:08:51 +01003978 if (!first) {
3979 /* Could not retrieve enough free blocks to store that session */
3980 return 0;
3981 }
3982
3983 /* STORE the key in the first elem */
3984 sh_ssl_sess = (struct sh_ssl_sess_hdr *)first->data;
3985 memcpy(sh_ssl_sess->key_data, s_id, SSL_MAX_SSL_SESSION_ID_LENGTH);
3986 first->len = sizeof(struct sh_ssl_sess_hdr);
3987
3988 /* it returns the already existing node
3989 or current node if none, never returns null */
3990 oldsh_ssl_sess = sh_ssl_sess_tree_insert(sh_ssl_sess);
3991 if (oldsh_ssl_sess != sh_ssl_sess) {
3992 /* NOTE: Row couldn't be in use because we lock read & write function */
3993 /* release the reserved row */
William Lallemand52a61cc2023-01-31 14:12:28 +01003994 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 +01003995 shctx_row_dec_hot(ssl_shctx, first);
3996 /* replace the previous session already in the tree */
3997 sh_ssl_sess = oldsh_ssl_sess;
3998 /* ignore the previous session data, only use the header */
3999 first = sh_ssl_sess_first_block(sh_ssl_sess);
4000 shctx_row_inc_hot(ssl_shctx, first);
4001 first->len = sizeof(struct sh_ssl_sess_hdr);
4002 }
4003
Frédéric Lécaille0bec8072018-10-22 17:55:57 +02004004 if (shctx_row_data_append(ssl_shctx, first, NULL, data, data_len) < 0) {
William Lallemand99b90af2018-01-03 19:15:51 +01004005 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004006 return 0;
William Lallemand99b90af2018-01-03 19:15:51 +01004007 }
4008
4009 shctx_row_dec_hot(ssl_shctx, first);
William Lallemand4f45bb92017-10-30 20:08:51 +01004010
4011 return 1;
4012}
William Lallemanded0b5ad2017-10-30 19:36:36 +01004013
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004014/* SSL callback used when a new session is created while connecting to a server */
4015static int ssl_sess_new_srv_cb(SSL *ssl, SSL_SESSION *sess)
4016{
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004017 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004018 struct server *s;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004019
Willy Tarreau07d94e42018-09-20 10:57:52 +02004020 s = __objt_server(conn->target);
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004021
William Lallemand3ce6eed2021-02-08 10:43:44 +01004022 /* RWLOCK: only read lock the SSL cache even when writing in it because there is
4023 * one cache per thread, it only prevents to flush it from the CLI in
4024 * another thread */
4025
Olivier Houcharde6060c52017-11-16 17:42:52 +01004026 if (!(s->ssl_ctx.options & SRV_SSL_O_NO_REUSE)) {
4027 int len;
4028 unsigned char *ptr;
William Lallemandc78ac5a2021-11-17 02:59:21 +01004029 const char *sni;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004030
Olivier Houcharde6060c52017-11-16 17:42:52 +01004031 len = i2d_SSL_SESSION(sess, NULL);
William Lallemandc78ac5a2021-11-17 02:59:21 +01004032 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004033 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004034 if (s->ssl_ctx.reused_sess[tid].ptr && s->ssl_ctx.reused_sess[tid].allocated_size >= len) {
4035 ptr = s->ssl_ctx.reused_sess[tid].ptr;
4036 } else {
Willy Tarreau3bda3f42021-02-26 21:05:08 +01004037 ptr = realloc(s->ssl_ctx.reused_sess[tid].ptr, len);
4038 s->ssl_ctx.reused_sess[tid].ptr = ptr;
Olivier Houcharde6060c52017-11-16 17:42:52 +01004039 s->ssl_ctx.reused_sess[tid].allocated_size = len;
4040 }
4041 if (s->ssl_ctx.reused_sess[tid].ptr) {
4042 s->ssl_ctx.reused_sess[tid].size = i2d_SSL_SESSION(sess,
4043 &ptr);
4044 }
William Lallemandc78ac5a2021-11-17 02:59:21 +01004045
4046 if (s->ssl_ctx.reused_sess[tid].sni) {
4047 /* if the new sni is empty or isn' t the same as the old one */
4048 if ((!sni) || strcmp(s->ssl_ctx.reused_sess[tid].sni, sni) != 0) {
4049 ha_free(&s->ssl_ctx.reused_sess[tid].sni);
4050 if (sni)
4051 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4052 }
4053 } else if (sni) {
4054 /* if there wasn't an old sni but there is a new one */
4055 s->ssl_ctx.reused_sess[tid].sni = strdup(sni);
4056 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01004057 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004058 } else {
William Lallemand3ce6eed2021-02-08 10:43:44 +01004059 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004060 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01004061 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Olivier Houcharde6060c52017-11-16 17:42:52 +01004062 }
4063
4064 return 0;
Olivier Houchardbd84ac82017-11-03 13:43:35 +01004065}
4066
Olivier Houcharde6060c52017-11-16 17:42:52 +01004067
William Lallemanded0b5ad2017-10-30 19:36:36 +01004068/* SSL callback used on new session creation */
William Lallemand4f45bb92017-10-30 20:08:51 +01004069int sh_ssl_sess_new_cb(SSL *ssl, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004070{
4071 unsigned char encsess[SHSESS_MAX_DATA_LEN]; /* encoded session */
4072 unsigned char encid[SSL_MAX_SSL_SESSION_ID_LENGTH]; /* encoded id */
4073 unsigned char *p;
4074 int data_len;
Emeric Bruneb469652019-10-08 18:27:37 +02004075 unsigned int sid_length;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004076 const unsigned char *sid_data;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004077
4078 /* Session id is already stored in to key and session id is known
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05004079 * so we don't store it to keep size.
Emeric Bruneb469652019-10-08 18:27:37 +02004080 * note: SSL_SESSION_set1_id is using
4081 * a memcpy so we need to use a different pointer
4082 * than sid_data or sid_ctx_data to avoid valgrind
4083 * complaining.
William Lallemanded0b5ad2017-10-30 19:36:36 +01004084 */
4085
4086 sid_data = SSL_SESSION_get_id(sess, &sid_length);
Emeric Bruneb469652019-10-08 18:27:37 +02004087
4088 /* copy value in an other buffer */
4089 memcpy(encid, sid_data, sid_length);
4090
4091 /* pad with 0 */
4092 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH)
4093 memset(encid + sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH-sid_length);
4094
4095 /* force length to zero to avoid ASN1 encoding */
4096 SSL_SESSION_set1_id(sess, encid, 0);
4097
4098 /* force length to zero to avoid ASN1 encoding */
4099 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, 0);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004100
4101 /* check if buffer is large enough for the ASN1 encoded session */
4102 data_len = i2d_SSL_SESSION(sess, NULL);
4103 if (data_len > SHSESS_MAX_DATA_LEN)
4104 goto err;
4105
4106 p = encsess;
4107
4108 /* process ASN1 session encoding before the lock */
4109 i2d_SSL_SESSION(sess, &p);
4110
William Lallemanded0b5ad2017-10-30 19:36:36 +01004111
William Lallemanda3c77cf2017-10-30 23:44:40 +01004112 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004113 /* store to cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004114 sh_ssl_sess_store(encid, encsess, data_len);
William Lallemanda3c77cf2017-10-30 23:44:40 +01004115 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004116err:
4117 /* reset original length values */
Emeric Bruneb469652019-10-08 18:27:37 +02004118 SSL_SESSION_set1_id(sess, encid, sid_length);
4119 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004120
4121 return 0; /* do not increment session reference count */
4122}
4123
4124/* SSL callback used on lookup an existing session cause none found in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004125SSL_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 +01004126{
William Lallemand4f45bb92017-10-30 20:08:51 +01004127 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004128 unsigned char data[SHSESS_MAX_DATA_LEN], *p;
4129 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
William Lallemanded0b5ad2017-10-30 19:36:36 +01004130 SSL_SESSION *sess;
William Lallemand4f45bb92017-10-30 20:08:51 +01004131 struct shared_block *first;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004132
Willy Tarreau37d69392021-06-15 16:39:22 +02004133 _HA_ATOMIC_INC(&global.shctx_lookups);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004134
4135 /* allow the session to be freed automatically by openssl */
4136 *do_copy = 0;
4137
4138 /* tree key is zeros padded sessionid */
4139 if (key_len < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4140 memcpy(tmpkey, key, key_len);
4141 memset(tmpkey + key_len, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - key_len);
4142 key = tmpkey;
4143 }
4144
4145 /* lock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004146 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004147
4148 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004149 sh_ssl_sess = sh_ssl_sess_tree_lookup(key);
4150 if (!sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004151 /* no session found: unlock cache and exit */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004152 shctx_unlock(ssl_shctx);
Willy Tarreau37d69392021-06-15 16:39:22 +02004153 _HA_ATOMIC_INC(&global.shctx_misses);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004154 return NULL;
4155 }
4156
William Lallemand4f45bb92017-10-30 20:08:51 +01004157 /* sh_ssl_sess (shared_block->data) is at the end of shared_block */
4158 first = sh_ssl_sess_first_block(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004159
William Lallemand4f45bb92017-10-30 20:08:51 +01004160 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 +01004161
William Lallemanda3c77cf2017-10-30 23:44:40 +01004162 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004163
4164 /* decode ASN1 session */
4165 p = data;
William Lallemand4f45bb92017-10-30 20:08:51 +01004166 sess = d2i_SSL_SESSION(NULL, (const unsigned char **)&p, first->len-sizeof(struct sh_ssl_sess_hdr));
William Lallemanded0b5ad2017-10-30 19:36:36 +01004167 /* Reset session id and session id contenxt */
4168 if (sess) {
4169 SSL_SESSION_set1_id(sess, key, key_len);
4170 SSL_SESSION_set1_id_context(sess, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4171 }
4172
4173 return sess;
4174}
4175
William Lallemand4f45bb92017-10-30 20:08:51 +01004176
William Lallemanded0b5ad2017-10-30 19:36:36 +01004177/* SSL callback used to signal session is no more used in internal cache */
William Lallemand4f45bb92017-10-30 20:08:51 +01004178void sh_ssl_sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004179{
William Lallemand4f45bb92017-10-30 20:08:51 +01004180 struct sh_ssl_sess_hdr *sh_ssl_sess;
William Lallemanded0b5ad2017-10-30 19:36:36 +01004181 unsigned char tmpkey[SSL_MAX_SSL_SESSION_ID_LENGTH];
4182 unsigned int sid_length;
4183 const unsigned char *sid_data;
4184 (void)ctx;
4185
4186 sid_data = SSL_SESSION_get_id(sess, &sid_length);
4187 /* tree key is zeros padded sessionid */
4188 if (sid_length < SSL_MAX_SSL_SESSION_ID_LENGTH) {
4189 memcpy(tmpkey, sid_data, sid_length);
4190 memset(tmpkey+sid_length, 0, SSL_MAX_SSL_SESSION_ID_LENGTH - sid_length);
4191 sid_data = tmpkey;
4192 }
4193
William Lallemanda3c77cf2017-10-30 23:44:40 +01004194 shctx_lock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004195
4196 /* lookup for session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004197 sh_ssl_sess = sh_ssl_sess_tree_lookup(sid_data);
4198 if (sh_ssl_sess) {
William Lallemanded0b5ad2017-10-30 19:36:36 +01004199 /* free session */
William Lallemand4f45bb92017-10-30 20:08:51 +01004200 sh_ssl_sess_tree_delete(sh_ssl_sess);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004201 }
4202
4203 /* unlock cache */
William Lallemanda3c77cf2017-10-30 23:44:40 +01004204 shctx_unlock(ssl_shctx);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004205}
4206
4207/* Set session cache mode to server and disable openssl internal cache.
4208 * Set shared cache callbacks on an ssl context.
4209 * Shared context MUST be firstly initialized */
William Lallemand4f45bb92017-10-30 20:08:51 +01004210void ssl_set_shctx(SSL_CTX *ctx)
William Lallemanded0b5ad2017-10-30 19:36:36 +01004211{
4212 SSL_CTX_set_session_id_context(ctx, (const unsigned char *)SHCTX_APPNAME, strlen(SHCTX_APPNAME));
4213
4214 if (!ssl_shctx) {
4215 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
4216 return;
4217 }
4218
4219 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER |
4220 SSL_SESS_CACHE_NO_INTERNAL |
4221 SSL_SESS_CACHE_NO_AUTO_CLEAR);
4222
4223 /* Set callbacks */
William Lallemand4f45bb92017-10-30 20:08:51 +01004224 SSL_CTX_sess_set_new_cb(ctx, sh_ssl_sess_new_cb);
4225 SSL_CTX_sess_set_get_cb(ctx, sh_ssl_sess_get_cb);
4226 SSL_CTX_sess_set_remove_cb(ctx, sh_ssl_sess_remove_cb);
William Lallemanded0b5ad2017-10-30 19:36:36 +01004227}
William Lallemand7d42ef52020-07-06 11:41:30 +02004228
4229/*
4230 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
4231 *
4232 * The format is:
4233 * * <Label> <space> <ClientRandom> <space> <Secret>
4234 * We only need to copy the secret as there is a sample fetch for the ClientRandom
4235 */
4236
William Lallemandca5cf0a2021-06-09 16:46:12 +02004237#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02004238void SSL_CTX_keylog(const SSL *ssl, const char *line)
4239{
4240 struct ssl_keylog *keylog;
4241 char *lastarg = NULL;
4242 char *dst = NULL;
4243
4244 keylog = SSL_get_ex_data(ssl, ssl_keylog_index);
4245 if (!keylog)
4246 return;
4247
4248 lastarg = strrchr(line, ' ');
4249 if (lastarg == NULL || ++lastarg == NULL)
4250 return;
4251
4252 dst = pool_alloc(pool_head_ssl_keylog_str);
4253 if (!dst)
4254 return;
4255
4256 strncpy(dst, lastarg, SSL_KEYLOG_MAX_SECRET_SIZE-1);
4257 dst[SSL_KEYLOG_MAX_SECRET_SIZE-1] = '\0';
4258
4259 if (strncmp(line, "CLIENT_RANDOM ", strlen("CLIENT RANDOM ")) == 0) {
4260 if (keylog->client_random)
4261 goto error;
4262 keylog->client_random = dst;
4263
4264 } else if (strncmp(line, "CLIENT_EARLY_TRAFFIC_SECRET ", strlen("CLIENT_EARLY_TRAFFIC_SECRET ")) == 0) {
4265 if (keylog->client_early_traffic_secret)
4266 goto error;
4267 keylog->client_early_traffic_secret = dst;
4268
4269 } else if (strncmp(line, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ", strlen("CLIENT_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4270 if(keylog->client_handshake_traffic_secret)
4271 goto error;
4272 keylog->client_handshake_traffic_secret = dst;
4273
4274 } else if (strncmp(line, "SERVER_HANDSHAKE_TRAFFIC_SECRET ", strlen("SERVER_HANDSHAKE_TRAFFIC_SECRET ")) == 0) {
4275 if (keylog->server_handshake_traffic_secret)
4276 goto error;
4277 keylog->server_handshake_traffic_secret = dst;
4278
4279 } else if (strncmp(line, "CLIENT_TRAFFIC_SECRET_0 ", strlen("CLIENT_TRAFFIC_SECRET_0 ")) == 0) {
4280 if (keylog->client_traffic_secret_0)
4281 goto error;
4282 keylog->client_traffic_secret_0 = dst;
4283
4284 } else if (strncmp(line, "SERVER_TRAFFIC_SECRET_0 ", strlen("SERVER_TRAFFIC_SECRET_0 ")) == 0) {
4285 if (keylog->server_traffic_secret_0)
4286 goto error;
4287 keylog->server_traffic_secret_0 = dst;
4288
4289 } else if (strncmp(line, "EARLY_EXPORTER_SECRET ", strlen("EARLY_EXPORTER_SECRET ")) == 0) {
4290 if (keylog->early_exporter_secret)
4291 goto error;
4292 keylog->early_exporter_secret = dst;
4293
4294 } else if (strncmp(line, "EXPORTER_SECRET ", strlen("EXPORTER_SECRET ")) == 0) {
4295 if (keylog->exporter_secret)
4296 goto error;
4297 keylog->exporter_secret = dst;
4298 } else {
4299 goto error;
4300 }
4301
4302 return;
4303
4304error:
4305 pool_free(pool_head_ssl_keylog_str, dst);
4306
4307 return;
4308}
4309#endif
William Lallemanded0b5ad2017-10-30 19:36:36 +01004310
William Lallemand8b453912019-11-21 15:48:10 +01004311/*
4312 * This function applies the SSL configuration on a SSL_CTX
4313 * It returns an error code and fills the <err> buffer
4314 */
4315int 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 +01004316{
4317 struct proxy *curproxy = bind_conf->frontend;
4318 int cfgerr = 0;
4319 int verify = SSL_VERIFY_NONE;
Willy Tarreau5d4cafb2018-01-04 18:55:19 +01004320 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004321 const char *conf_ciphers;
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004322#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004323 const char *conf_ciphersuites;
4324#endif
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004325 const char *conf_curves = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004326
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004327 if (ssl_conf) {
4328 struct tls_version_filter *conf_ssl_methods = &ssl_conf->ssl_methods;
4329 int i, min, max;
4330 int flags = MC_SSL_O_ALL;
4331
4332 /* Real min and max should be determinate with configuration and openssl's capabilities */
Emmanuel Hocdet43664762017-08-09 18:26:20 +02004333 min = conf_ssl_methods->min ? conf_ssl_methods->min : bind_conf->ssl_conf.ssl_methods.min;
4334 max = conf_ssl_methods->max ? conf_ssl_methods->max : bind_conf->ssl_conf.ssl_methods.max;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004335 if (min)
4336 flags |= (methodVersions[min].flag - 1);
4337 if (max)
4338 flags |= ~((methodVersions[max].flag << 1) - 1);
4339 min = max = CONF_TLSV_NONE;
4340 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4341 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
4342 if (min)
4343 max = i;
4344 else
4345 min = max = i;
4346 }
4347 /* save real min/max */
4348 conf_ssl_methods->min = min;
4349 conf_ssl_methods->max = max;
4350 if (!min) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004351 memprintf(err, "%sProxy '%s': all SSL/TLS versions are disabled for bind '%s' at [%s:%d].\n",
4352 err && *err ? *err : "", bind_conf->frontend->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004353 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdetdf701a22017-05-18 12:46:50 +02004354 }
4355 }
4356
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004357 switch ((ssl_conf && ssl_conf->verify) ? ssl_conf->verify : bind_conf->ssl_conf.verify) {
Emeric Brun850efd52014-01-29 12:24:34 +01004358 case SSL_SOCK_VERIFY_NONE:
4359 verify = SSL_VERIFY_NONE;
4360 break;
4361 case SSL_SOCK_VERIFY_OPTIONAL:
4362 verify = SSL_VERIFY_PEER;
4363 break;
4364 case SSL_SOCK_VERIFY_REQUIRED:
4365 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
4366 break;
4367 }
4368 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
4369 if (verify & SSL_VERIFY_PEER) {
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004370 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 +01004371 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 +01004372 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 +01004373 if (ca_file || ca_verify_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004374 /* set CAfile to verify */
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004375 if (ca_file && !ssl_set_verify_locations_file(ctx, ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004376 memprintf(err, "%sProxy '%s': unable to set CA file '%s' for bind '%s' at [%s:%d].\n",
Tim Duesterhus93128532019-11-23 23:45:10 +01004377 err && *err ? *err : "", curproxy->id, ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004378 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004379 }
Emmanuel Hocdet842e94e2019-12-16 16:39:17 +01004380 if (ca_verify_file && !ssl_set_verify_locations_file(ctx, ca_verify_file)) {
4381 memprintf(err, "%sProxy '%s': unable to set CA-no-names file '%s' for bind '%s' at [%s:%d].\n",
4382 err && *err ? *err : "", curproxy->id, ca_verify_file, bind_conf->arg, bind_conf->file, bind_conf->line);
4383 cfgerr |= ERR_ALERT | ERR_FATAL;
4384 }
4385 if (ca_file && !((ssl_conf && ssl_conf->no_ca_names) || bind_conf->ssl_conf.no_ca_names)) {
Emmanuel Hocdet174dfe52017-07-28 15:01:05 +02004386 /* set CA names for client cert request, function returns void */
Emmanuel Hocdet129d3282019-10-24 18:08:51 +02004387 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 +02004388 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004389 }
Emeric Brun850efd52014-01-29 12:24:34 +01004390 else {
Tim Duesterhus93128532019-11-23 23:45:10 +01004391 memprintf(err, "%sProxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
4392 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004393 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun850efd52014-01-29 12:24:34 +01004394 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004395#ifdef X509_V_FLAG_CRL_CHECK
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004396 if (crl_file) {
Emeric Brund94b3fe2012-09-20 18:23:56 +02004397 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
4398
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004399 if (!ssl_set_cert_crl_file(store, crl_file)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004400 memprintf(err, "%sProxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
4401 err && *err ? *err : "", curproxy->id, crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004402 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brund94b3fe2012-09-20 18:23:56 +02004403 }
Emeric Brun561e5742012-10-02 15:20:55 +02004404 else {
4405 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4406 }
Emeric Brund94b3fe2012-09-20 18:23:56 +02004407 }
Emeric Brun051cdab2012-10-02 19:25:50 +02004408#endif
Emeric Brun644cde02012-12-14 11:21:13 +01004409 ERR_clear_error();
Emeric Brund94b3fe2012-09-20 18:23:56 +02004410 }
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004411#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Nenad Merdanovic146defa2015-05-09 08:46:00 +02004412 if(bind_conf->keys_ref) {
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004413 if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, ssl_tlsext_ticket_key_cb)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004414 memprintf(err, "%sProxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
4415 err && *err ? *err : "", curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004416 cfgerr |= ERR_ALERT | ERR_FATAL;
Nenad Merdanovic05552d42015-02-27 19:56:49 +01004417 }
4418 }
4419#endif
4420
William Lallemand4f45bb92017-10-30 20:08:51 +01004421 ssl_set_shctx(ctx);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004422 conf_ciphers = (ssl_conf && ssl_conf->ciphers) ? ssl_conf->ciphers : bind_conf->ssl_conf.ciphers;
4423 if (conf_ciphers &&
4424 !SSL_CTX_set_cipher_list(ctx, conf_ciphers)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004425 memprintf(err, "%sProxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
4426 err && *err ? *err : "", curproxy->id, conf_ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004427 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004428 }
4429
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004430#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004431 conf_ciphersuites = (ssl_conf && ssl_conf->ciphersuites) ? ssl_conf->ciphersuites : bind_conf->ssl_conf.ciphersuites;
4432 if (conf_ciphersuites &&
4433 !SSL_CTX_set_ciphersuites(ctx, conf_ciphersuites)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004434 memprintf(err, "%sProxy '%s': unable to set TLS 1.3 cipher suites to '%s' for bind '%s' at [%s:%d].\n",
4435 err && *err ? *err : "", curproxy->id, conf_ciphersuites, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004436 cfgerr |= ERR_ALERT | ERR_FATAL;
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004437 }
4438#endif
4439
Emmanuel Hocdetcc6c2a22017-03-03 17:04:14 +01004440#ifndef OPENSSL_NO_DH
Remi Gacogne47783ef2015-05-29 15:53:22 +02004441 /* If tune.ssl.default-dh-param has not been set,
4442 neither has ssl-default-dh-file and no static DH
4443 params were in the certificate file. */
Willy Tarreauef934602016-12-22 23:12:01 +01004444 if (global_ssl.default_dh_param == 0 &&
Remi Gacogne47783ef2015-05-29 15:53:22 +02004445 global_dh == NULL &&
Remi Gacogne4f902b82015-05-28 16:23:00 +02004446 (ssl_dh_ptr_index == -1 ||
4447 SSL_CTX_get_ex_data(ctx, ssl_dh_ptr_index) == NULL)) {
Willy Tarreau3ba77d22020-05-08 09:31:18 +02004448 /* default to dh-param 2048 */
4449 global_ssl.default_dh_param = 2048;
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004450 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004451
Willy Tarreauef934602016-12-22 23:12:01 +01004452 if (global_ssl.default_dh_param >= 1024) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004453 if (local_dh_1024 == NULL) {
4454 local_dh_1024 = ssl_get_dh_1024();
4455 }
Willy Tarreauef934602016-12-22 23:12:01 +01004456 if (global_ssl.default_dh_param >= 2048) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004457 if (local_dh_2048 == NULL) {
4458 local_dh_2048 = ssl_get_dh_2048();
4459 }
Willy Tarreauef934602016-12-22 23:12:01 +01004460 if (global_ssl.default_dh_param >= 4096) {
Remi Gacogne8de54152014-07-15 11:36:40 +02004461 if (local_dh_4096 == NULL) {
4462 local_dh_4096 = ssl_get_dh_4096();
4463 }
Remi Gacogne8de54152014-07-15 11:36:40 +02004464 }
4465 }
4466 }
4467#endif /* OPENSSL_NO_DH */
Remi Gacognef46cd6e2014-06-12 14:58:40 +02004468
Emeric Brunfc0421f2012-09-07 17:30:07 +02004469 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
Ilya Shipitsin7ff77472021-02-08 16:55:06 +05004470#ifdef SSL_CTRL_SET_MSG_CALLBACK
Emeric Brun29f037d2014-04-25 19:05:36 +02004471 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
Willy Tarreau5cbe4ef2014-05-08 22:45:11 +02004472#endif
William Lallemandca5cf0a2021-06-09 16:46:12 +02004473#ifdef HAVE_SSL_KEYLOG
William Lallemand2cb86e72022-11-18 15:00:15 +01004474 /* only activate the keylog callback if it was required to prevent performance loss */
4475 if (global_ssl.keylog > 0)
4476 SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog);
William Lallemand7d42ef52020-07-06 11:41:30 +02004477#endif
Emeric Brun29f037d2014-04-25 19:05:36 +02004478
Bernard Spil13c53f82018-02-15 13:34:58 +01004479#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004480 ssl_conf_cur = NULL;
4481 if (ssl_conf && ssl_conf->npn_str)
4482 ssl_conf_cur = ssl_conf;
4483 else if (bind_conf->ssl_conf.npn_str)
4484 ssl_conf_cur = &bind_conf->ssl_conf;
4485 if (ssl_conf_cur)
4486 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, ssl_conf_cur);
Willy Tarreau6c9a3d52012-10-18 18:57:14 +02004487#endif
Dirkjan Bussink48f1c4e2014-02-13 12:29:42 +01004488#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004489 ssl_conf_cur = NULL;
4490 if (ssl_conf && ssl_conf->alpn_str)
4491 ssl_conf_cur = ssl_conf;
4492 else if (bind_conf->ssl_conf.alpn_str)
4493 ssl_conf_cur = &bind_conf->ssl_conf;
4494 if (ssl_conf_cur)
4495 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, ssl_conf_cur);
Willy Tarreauab861d32013-04-02 02:30:41 +02004496#endif
Ilya Shipitsin0aa8c292020-11-04 00:39:07 +05004497#if defined(SSL_CTX_set1_curves_list)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004498 conf_curves = (ssl_conf && ssl_conf->curves) ? ssl_conf->curves : bind_conf->ssl_conf.curves;
4499 if (conf_curves) {
4500 if (!SSL_CTX_set1_curves_list(ctx, conf_curves)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004501 memprintf(err, "%sProxy '%s': unable to set SSL curves list to '%s' for bind '%s' at [%s:%d].\n",
4502 err && *err ? *err : "", curproxy->id, conf_curves, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004503 cfgerr |= ERR_ALERT | ERR_FATAL;
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004504 }
Emmanuel Hocdeta52bb152017-03-20 11:11:49 +01004505 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004506 }
4507#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004508#if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
Emmanuel Hocdete7f2b732017-01-09 16:15:54 +01004509 if (!conf_curves) {
Emeric Brun2b58d042012-09-20 17:10:03 +02004510 int i;
4511 EC_KEY *ecdh;
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004512#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004513 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
Olivier Houchardc2aae742017-09-22 18:26:28 +02004514 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4515 NULL);
4516
4517 if (ecdhe == NULL) {
Eric Salama3c8bde82019-11-20 11:33:40 +01004518 (void)SSL_CTX_set_ecdh_auto(ctx, 1);
Olivier Houchardc2aae742017-09-22 18:26:28 +02004519 return cfgerr;
4520 }
4521#else
4522 const char *ecdhe = (ssl_conf && ssl_conf->ecdhe) ? ssl_conf->ecdhe :
4523 (bind_conf->ssl_conf.ecdhe ? bind_conf->ssl_conf.ecdhe :
4524 ECDHE_DEFAULT_CURVE);
4525#endif
Emeric Brun2b58d042012-09-20 17:10:03 +02004526
Emmanuel Hocdet98263292016-12-29 18:26:15 +01004527 i = OBJ_sn2nid(ecdhe);
Emeric Brun2b58d042012-09-20 17:10:03 +02004528 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
Tim Duesterhus93128532019-11-23 23:45:10 +01004529 memprintf(err, "%sProxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
4530 err && *err ? *err : "", curproxy->id, ecdhe, bind_conf->arg, bind_conf->file, bind_conf->line);
William Lallemand8b453912019-11-21 15:48:10 +01004531 cfgerr |= ERR_ALERT | ERR_FATAL;
Emeric Brun2b58d042012-09-20 17:10:03 +02004532 }
4533 else {
4534 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
4535 EC_KEY_free(ecdh);
4536 }
4537 }
4538#endif
4539
Emeric Brunfc0421f2012-09-07 17:30:07 +02004540 return cfgerr;
4541}
4542
Evan Broderbe554312013-06-27 00:05:25 -07004543static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
4544{
4545 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
4546 size_t prefixlen, suffixlen;
4547
4548 /* Trivial case */
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004549 if (strcasecmp(pattern, hostname) == 0)
Evan Broderbe554312013-06-27 00:05:25 -07004550 return 1;
4551
Evan Broderbe554312013-06-27 00:05:25 -07004552 /* The rest of this logic is based on RFC 6125, section 6.4.3
4553 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
4554
Emeric Bruna848dae2013-10-08 11:27:28 +02004555 pattern_wildcard = NULL;
4556 pattern_left_label_end = pattern;
4557 while (*pattern_left_label_end != '.') {
4558 switch (*pattern_left_label_end) {
4559 case 0:
4560 /* End of label not found */
4561 return 0;
4562 case '*':
4563 /* If there is more than one wildcards */
4564 if (pattern_wildcard)
4565 return 0;
4566 pattern_wildcard = pattern_left_label_end;
4567 break;
4568 }
4569 pattern_left_label_end++;
4570 }
4571
4572 /* If it's not trivial and there is no wildcard, it can't
4573 * match */
4574 if (!pattern_wildcard)
Evan Broderbe554312013-06-27 00:05:25 -07004575 return 0;
4576
4577 /* Make sure all labels match except the leftmost */
4578 hostname_left_label_end = strchr(hostname, '.');
4579 if (!hostname_left_label_end
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004580 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
Evan Broderbe554312013-06-27 00:05:25 -07004581 return 0;
4582
4583 /* Make sure the leftmost label of the hostname is long enough
4584 * that the wildcard can match */
Emeric Brun369da852013-10-08 11:39:35 +02004585 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
Evan Broderbe554312013-06-27 00:05:25 -07004586 return 0;
4587
4588 /* Finally compare the string on either side of the
4589 * wildcard */
4590 prefixlen = pattern_wildcard - pattern;
4591 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
William Lallemand2d6fd0a2020-09-14 15:20:10 +02004592 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
4593 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
Evan Broderbe554312013-06-27 00:05:25 -07004594 return 0;
4595
4596 return 1;
4597}
4598
4599static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
4600{
4601 SSL *ssl;
4602 struct connection *conn;
Olivier Houchard66ab4982019-02-26 18:37:15 +01004603 struct ssl_sock_ctx *ssl_ctx;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004604 const char *servername;
Willy Tarreau71d058c2017-07-26 20:09:56 +02004605 const char *sni;
Evan Broderbe554312013-06-27 00:05:25 -07004606
4607 int depth;
4608 X509 *cert;
4609 STACK_OF(GENERAL_NAME) *alt_names;
4610 int i;
4611 X509_NAME *cert_subject;
4612 char *str;
4613
4614 if (ok == 0)
4615 return ok;
4616
4617 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Thierry FOURNIER28962c92018-06-17 21:37:05 +02004618 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
Olivier Houchard66ab4982019-02-26 18:37:15 +01004619 ssl_ctx = conn->xprt_ctx;
Evan Broderbe554312013-06-27 00:05:25 -07004620
Willy Tarreauad92a9a2017-07-28 11:38:41 +02004621 /* We're checking if the provided hostnames match the desired one. The
4622 * desired hostname comes from the SNI we presented if any, or if not
4623 * provided then it may have been explicitly stated using a "verifyhost"
4624 * directive. If neither is set, we don't care about the name so the
4625 * verification is OK.
Willy Tarreau2ab88672017-07-05 18:23:03 +02004626 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01004627 servername = SSL_get_servername(ssl_ctx->ssl, TLSEXT_NAMETYPE_host_name);
Willy Tarreau71d058c2017-07-26 20:09:56 +02004628 sni = servername;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004629 if (!servername) {
Willy Tarreau07d94e42018-09-20 10:57:52 +02004630 servername = __objt_server(conn->target)->ssl_ctx.verify_host;
Willy Tarreau2ab88672017-07-05 18:23:03 +02004631 if (!servername)
4632 return ok;
4633 }
Evan Broderbe554312013-06-27 00:05:25 -07004634
4635 /* We only need to verify the CN on the actual server cert,
4636 * not the indirect CAs */
4637 depth = X509_STORE_CTX_get_error_depth(ctx);
4638 if (depth != 0)
4639 return ok;
4640
4641 /* At this point, the cert is *not* OK unless we can find a
4642 * hostname match */
4643 ok = 0;
4644
4645 cert = X509_STORE_CTX_get_current_cert(ctx);
4646 /* It seems like this might happen if verify peer isn't set */
4647 if (!cert)
4648 return ok;
4649
4650 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
4651 if (alt_names) {
4652 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
4653 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
4654 if (name->type == GEN_DNS) {
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004655#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Emeric Bruna33410c2013-09-17 15:47:48 +02004656 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
4657#else
Evan Broderbe554312013-06-27 00:05:25 -07004658 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
Emeric Bruna33410c2013-09-17 15:47:48 +02004659#endif
Evan Broderbe554312013-06-27 00:05:25 -07004660 ok = ssl_sock_srv_hostcheck(str, servername);
4661 OPENSSL_free(str);
4662 }
4663 }
4664 }
Emeric Brun4ad50a42013-09-17 15:19:54 +02004665 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
Evan Broderbe554312013-06-27 00:05:25 -07004666 }
4667
4668 cert_subject = X509_get_subject_name(cert);
4669 i = -1;
4670 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
4671 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02004672 ASN1_STRING *value;
4673 value = X509_NAME_ENTRY_get_data(entry);
4674 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
Evan Broderbe554312013-06-27 00:05:25 -07004675 ok = ssl_sock_srv_hostcheck(str, servername);
4676 OPENSSL_free(str);
4677 }
4678 }
4679
Willy Tarreau71d058c2017-07-26 20:09:56 +02004680 /* report the mismatch and indicate if SNI was used or not */
4681 if (!ok && !conn->err_code)
4682 conn->err_code = sni ? CO_ER_SSL_MISMATCH_SNI : CO_ER_SSL_MISMATCH;
Evan Broderbe554312013-06-27 00:05:25 -07004683 return ok;
4684}
4685
Emeric Brun94324a42012-10-11 14:00:19 +02004686/* prepare ssl context from servers options. Returns an error count */
Willy Tarreau03209342016-12-22 17:08:28 +01004687int ssl_sock_prepare_srv_ctx(struct server *srv)
Emeric Brun94324a42012-10-11 14:00:19 +02004688{
Willy Tarreau03209342016-12-22 17:08:28 +01004689 struct proxy *curproxy = srv->proxy;
Emeric Brun94324a42012-10-11 14:00:19 +02004690 int cfgerr = 0;
William Lallemand6338b7d2021-12-28 18:47:17 +01004691 SSL_CTX *ctx;
Emeric Brun94324a42012-10-11 14:00:19 +02004692
Thierry Fournier383085f2013-01-24 14:15:43 +01004693 /* Make sure openssl opens /dev/urandom before the chroot */
4694 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004695 ha_alert("OpenSSL random data generator initialization failed.\n");
Thierry Fournier383085f2013-01-24 14:15:43 +01004696 cfgerr++;
4697 }
4698
Willy Tarreaufce03112015-01-15 21:32:40 +01004699 /* Automatic memory computations need to know we use SSL there */
4700 global.ssl_used_backend = 1;
4701
4702 /* Initiate SSL context for current server */
Emeric Brun821bb9b2017-06-15 16:37:39 +02004703 if (!srv->ssl_ctx.reused_sess) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01004704 if ((srv->ssl_ctx.reused_sess = calloc(1, global.nbthread*sizeof(*srv->ssl_ctx.reused_sess))) == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004705 ha_alert("Proxy '%s', server '%s' [%s:%d] out of memory.\n",
4706 curproxy->id, srv->id,
4707 srv->conf.file, srv->conf.line);
Emeric Brun821bb9b2017-06-15 16:37:39 +02004708 cfgerr++;
4709 return cfgerr;
4710 }
4711 }
Christopher Fauletf61f33a2020-03-27 18:55:49 +01004712 if (srv->use_ssl == 1)
Emeric Brun94324a42012-10-11 14:00:19 +02004713 srv->xprt = &ssl_sock;
Emeric Brun94324a42012-10-11 14:00:19 +02004714
William Lallemand6338b7d2021-12-28 18:47:17 +01004715 if (srv->ssl_ctx.client_crt) {
4716 char *err = NULL;
4717 int err_code = 0;
4718
4719 /* If there is a crt keyword there, the SSL_CTX will be created here. */
4720 err_code = ssl_sock_load_srv_cert(srv->ssl_ctx.client_crt, srv, &err);
4721 if (err_code != ERR_NONE) {
4722 if ((err_code & ERR_WARN) && !(err_code & ERR_ALERT))
4723 ha_warning("%s", err);
4724 else
4725 ha_alert("%s", err);
4726
4727 if (err_code & (ERR_FATAL|ERR_ABORT))
4728 cfgerr++;
4729 }
4730 ha_free(&err);
4731 }
4732
4733 ctx = srv->ssl_ctx.ctx;
4734
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004735 /* The context will be uninitialized if there wasn't any "cert" option
4736 * in the server line. */
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004737 if (!ctx) {
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004738 ctx = SSL_CTX_new(SSLv23_client_method());
4739 if (!ctx) {
4740 ha_alert("config : %s '%s', server '%s': unable to allocate ssl context.\n",
4741 proxy_type_str(curproxy), curproxy->id,
4742 srv->id);
4743 cfgerr++;
4744 return cfgerr;
4745 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004746
Remi Tricot-Le Bretond817dc72021-01-25 17:19:43 +01004747 srv->ssl_ctx.ctx = ctx;
4748 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004749
4750 cfgerr += ssl_sock_prepare_srv_ssl_ctx(srv, srv->ssl_ctx.ctx);
4751
4752 return cfgerr;
4753}
4754
4755
4756/* Initialize an SSL context that will be used on the backend side.
4757 * Returns an error count.
4758 */
4759int ssl_sock_prepare_srv_ssl_ctx(const struct server *srv, SSL_CTX *ctx)
4760{
4761 struct proxy *curproxy = srv->proxy;
4762 int cfgerr = 0;
4763 long options =
4764 SSL_OP_ALL | /* all known workarounds for bugs */
4765 SSL_OP_NO_SSLv2 |
4766 SSL_OP_NO_COMPRESSION;
4767 long mode =
4768 SSL_MODE_ENABLE_PARTIAL_WRITE |
4769 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
4770 SSL_MODE_RELEASE_BUFFERS |
4771 SSL_MODE_SMALL_BUFFERS;
4772 int verify = SSL_VERIFY_NONE;
4773 const struct tls_version_filter *conf_ssl_methods = &srv->ssl_ctx.methods;
4774 int i, min, max, hole;
4775 int flags = MC_SSL_O_ALL;
4776
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004777 if (conf_ssl_methods->flags && (conf_ssl_methods->min || conf_ssl_methods->max))
Christopher Faulet767a84b2017-11-24 16:50:31 +01004778 ha_warning("config : %s '%s': no-sslv3/no-tlsv1x are ignored for server '%s'. "
4779 "Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4780 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004781 else
4782 flags = conf_ssl_methods->flags;
4783
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004784 /* Real min and max should be determinate with configuration and openssl's capabilities */
4785 if (conf_ssl_methods->min)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004786 flags |= (methodVersions[conf_ssl_methods->min].flag - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004787 if (conf_ssl_methods->max)
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004788 flags |= ~((methodVersions[conf_ssl_methods->max].flag << 1) - 1);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004789
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004790 /* find min, max and holes */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004791 min = max = CONF_TLSV_NONE;
4792 hole = 0;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004793 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004794 /* version is in openssl && version not disable in configuration */
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004795 if (methodVersions[i].option && !(flags & methodVersions[i].flag)) {
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004796 if (min) {
4797 if (hole) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004798 ha_warning("config : %s '%s': SSL/TLS versions range not contiguous for server '%s'. "
4799 "Hole find for %s. Use only 'ssl-min-ver' and 'ssl-max-ver' to fix.\n",
4800 proxy_type_str(curproxy), curproxy->id, srv->id,
4801 methodVersions[hole].name);
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004802 hole = 0;
4803 }
4804 max = i;
4805 }
4806 else {
4807 min = max = i;
4808 }
4809 }
4810 else {
4811 if (min)
4812 hole = i;
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004813 }
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004814 if (!min) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004815 ha_alert("config : %s '%s': all SSL/TLS versions are disabled for server '%s'.\n",
4816 proxy_type_str(curproxy), curproxy->id, srv->id);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004817 cfgerr += 1;
4818 }
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004819
Willy Tarreau9a1ab082019-05-09 13:26:41 +02004820#if (HA_OPENSSL_VERSION_NUMBER < 0x1010000fL)
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004821 /* Keep force-xxx implementation as it is in older haproxy. It's a
Joseph Herlant017b3da2018-11-15 09:07:59 -08004822 precautionary measure to avoid any surprise with older openssl version. */
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004823 if (min == max)
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004824 methodVersions[min].ctx_set_version(ctx, SET_CLIENT);
Emmanuel Hocdetabd32332017-05-05 18:06:12 +02004825 else
4826 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
4827 if (flags & methodVersions[i].flag)
4828 options |= methodVersions[i].option;
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004829#else /* openssl >= 1.1.0 */
Emmanuel Hocdetb4e9ba42017-03-30 19:25:07 +02004830 /* set the max_version is required to cap TLS version or activate new TLS (v1.3) */
Emmanuel Hocdet4aa615f2017-05-18 12:33:19 +02004831 methodVersions[min].ctx_set_version(ctx, SET_MIN);
4832 methodVersions[max].ctx_set_version(ctx, SET_MAX);
Emmanuel Hocdet5db33cb2017-03-30 19:19:37 +02004833#endif
4834
4835 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
4836 options |= SSL_OP_NO_TICKET;
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004837 SSL_CTX_set_options(ctx, options);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004838
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004839#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00004840 if (global_ssl.async)
4841 mode |= SSL_MODE_ASYNC;
4842#endif
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004843 SSL_CTX_set_mode(ctx, mode);
Emmanuel Hocdet4de1ff12017-03-03 12:21:32 +01004844
Emeric Brun850efd52014-01-29 12:24:34 +01004845 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
4846 verify = SSL_VERIFY_PEER;
Emeric Brun850efd52014-01-29 12:24:34 +01004847 switch (srv->ssl_ctx.verify) {
4848 case SSL_SOCK_VERIFY_NONE:
4849 verify = SSL_VERIFY_NONE;
4850 break;
4851 case SSL_SOCK_VERIFY_REQUIRED:
4852 verify = SSL_VERIFY_PEER;
4853 break;
4854 }
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004855 SSL_CTX_set_verify(ctx, verify,
Willy Tarreau2ab88672017-07-05 18:23:03 +02004856 (srv->ssl_ctx.verify_host || (verify & SSL_VERIFY_PEER)) ? ssl_sock_srv_verifycbk : NULL);
Emeric Brun850efd52014-01-29 12:24:34 +01004857 if (verify & SSL_VERIFY_PEER) {
Emeric Brunef42d922012-10-11 16:11:36 +02004858 if (srv->ssl_ctx.ca_file) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004859 /* set CAfile to verify */
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004860 if (!ssl_set_verify_locations_file(ctx, srv->ssl_ctx.ca_file)) {
Emmanuel Hocdetd4f9a602019-10-24 11:32:47 +02004861 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to set CA file '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01004862 curproxy->id, srv->id,
4863 srv->conf.file, srv->conf.line, srv->ssl_ctx.ca_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004864 cfgerr++;
4865 }
4866 }
Emeric Brun850efd52014-01-29 12:24:34 +01004867 else {
4868 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
Christopher Faulet767a84b2017-11-24 16:50:31 +01004869 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",
4870 curproxy->id, srv->id,
4871 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004872 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01004873 ha_alert("Proxy '%s', server '%s' [%s:%d] verify is enabled but no CA file specified.\n",
4874 curproxy->id, srv->id,
4875 srv->conf.file, srv->conf.line);
Emeric Brun850efd52014-01-29 12:24:34 +01004876 cfgerr++;
4877 }
Emeric Brunef42d922012-10-11 16:11:36 +02004878#ifdef X509_V_FLAG_CRL_CHECK
4879 if (srv->ssl_ctx.crl_file) {
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004880 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
Emeric Brunef42d922012-10-11 16:11:36 +02004881
Emmanuel Hocdetb270e812019-11-21 19:09:31 +01004882 if (!ssl_set_cert_crl_file(store, srv->ssl_ctx.crl_file)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004883 ha_alert("Proxy '%s', server '%s' [%s:%d] unable to configure CRL file '%s'.\n",
4884 curproxy->id, srv->id,
4885 srv->conf.file, srv->conf.line, srv->ssl_ctx.crl_file);
Emeric Brunef42d922012-10-11 16:11:36 +02004886 cfgerr++;
4887 }
4888 else {
4889 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4890 }
4891 }
4892#endif
4893 }
4894
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004895 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
4896 SSL_CTX_sess_set_new_cb(ctx, ssl_sess_new_srv_cb);
Emeric Brun94324a42012-10-11 14:00:19 +02004897 if (srv->ssl_ctx.ciphers &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004898 !SSL_CTX_set_cipher_list(ctx, srv->ssl_ctx.ciphers)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004899 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set SSL cipher list to '%s'.\n",
4900 curproxy->id, srv->id,
4901 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphers);
Emeric Brun94324a42012-10-11 14:00:19 +02004902 cfgerr++;
4903 }
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004904
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05004905#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004906 if (srv->ssl_ctx.ciphersuites &&
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004907 !SSL_CTX_set_ciphersuites(ctx, srv->ssl_ctx.ciphersuites)) {
Dirkjan Bussink415150f2018-09-14 11:14:21 +02004908 ha_alert("Proxy '%s', server '%s' [%s:%d] : unable to set TLS 1.3 cipher suites to '%s'.\n",
4909 curproxy->id, srv->id,
4910 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphersuites);
4911 cfgerr++;
4912 }
4913#endif
Olivier Houchardc7566002018-11-20 23:33:50 +01004914#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
4915 if (srv->ssl_ctx.npn_str)
Remi Tricot-Le Breton442b7f22021-01-25 17:19:41 +01004916 SSL_CTX_set_next_proto_select_cb(ctx, ssl_sock_srv_select_protos, (struct server*)srv);
Olivier Houchardc7566002018-11-20 23:33:50 +01004917#endif
4918#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4919 if (srv->ssl_ctx.alpn_str)
4920 SSL_CTX_set_alpn_protos(ctx, (unsigned char *)srv->ssl_ctx.alpn_str, srv->ssl_ctx.alpn_len);
4921#endif
4922
Emeric Brun94324a42012-10-11 14:00:19 +02004923
4924 return cfgerr;
4925}
4926
Frédéric Lécailleec216522020-11-23 14:33:30 +01004927/*
4928 * Create an initial CTX used to start the SSL connections.
4929 * May be used by QUIC xprt which makes usage of SSL sessions initialized from SSL_CTXs.
4930 * Returns 0 if succeeded, or something >0 if not.
4931 */
4932#ifdef USE_QUIC
4933static int ssl_initial_ctx(struct bind_conf *bind_conf)
4934{
4935 if (bind_conf->xprt == xprt_get(XPRT_QUIC))
4936 return ssl_quic_initial_ctx(bind_conf);
4937 else
4938 return ssl_sock_initial_ctx(bind_conf);
4939}
4940#else
4941static int ssl_initial_ctx(struct bind_conf *bind_conf)
4942{
4943 return ssl_sock_initial_ctx(bind_conf);
4944}
4945#endif
4946
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004947/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02004948 * be NULL, in which case nothing is done. Returns the number of errors
4949 * encountered.
4950 */
Willy Tarreau03209342016-12-22 17:08:28 +01004951int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02004952{
4953 struct ebmb_node *node;
4954 struct sni_ctx *sni;
4955 int err = 0;
William Lallemand8b453912019-11-21 15:48:10 +01004956 int errcode = 0;
4957 char *errmsg = NULL;
Emeric Brunfc0421f2012-09-07 17:30:07 +02004958
Willy Tarreaufce03112015-01-15 21:32:40 +01004959 /* Automatic memory computations need to know we use SSL there */
4960 global.ssl_used_frontend = 1;
4961
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004962 /* Make sure openssl opens /dev/urandom before the chroot */
4963 if (!ssl_initialize_random()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01004964 ha_alert("OpenSSL random data generator initialization failed.\n");
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004965 err++;
4966 }
4967 /* Create initial_ctx used to start the ssl connection before do switchctx */
4968 if (!bind_conf->initial_ctx) {
Frédéric Lécailleec216522020-11-23 14:33:30 +01004969 err += ssl_initial_ctx(bind_conf);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004970 /* It should not be necessary to call this function, but it's
4971 necessary first to check and move all initialisation related
Frédéric Lécailleec216522020-11-23 14:33:30 +01004972 to initial_ctx in ssl_initial_ctx. */
William Lallemand8b453912019-11-21 15:48:10 +01004973 errcode |= ssl_sock_prepare_ctx(bind_conf, NULL, bind_conf->initial_ctx, &errmsg);
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01004974 }
Emeric Brun0bed9942014-10-30 19:25:24 +01004975 if (bind_conf->default_ctx)
William Lallemand8b453912019-11-21 15:48:10 +01004976 errcode |= ssl_sock_prepare_ctx(bind_conf, bind_conf->default_ssl_conf, bind_conf->default_ctx, &errmsg);
Emeric Brun0bed9942014-10-30 19:25:24 +01004977
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004978 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004979 while (node) {
4980 sni = ebmb_entry(node, struct sni_ctx, name);
Emeric Brun0bed9942014-10-30 19:25:24 +01004981 if (!sni->order && sni->ctx != bind_conf->default_ctx)
4982 /* only initialize the CTX on its first occurrence and
4983 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004984 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004985 node = ebmb_next(node);
4986 }
4987
Willy Tarreau2a65ff02012-09-13 17:54:29 +02004988 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02004989 while (node) {
4990 sni = ebmb_entry(node, struct sni_ctx, name);
William Lallemand8b453912019-11-21 15:48:10 +01004991 if (!sni->order && sni->ctx != bind_conf->default_ctx) {
Emeric Brun0bed9942014-10-30 19:25:24 +01004992 /* only initialize the CTX on its first occurrence and
4993 if it is not the default_ctx */
William Lallemand8b453912019-11-21 15:48:10 +01004994 errcode |= ssl_sock_prepare_ctx(bind_conf, sni->conf, sni->ctx, &errmsg);
4995 }
Emeric Brunfc0421f2012-09-07 17:30:07 +02004996 node = ebmb_next(node);
4997 }
William Lallemand8b453912019-11-21 15:48:10 +01004998
4999 if (errcode & ERR_WARN) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005000 ha_warning("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005001 } else if (errcode & ERR_CODE) {
Tim Duesterhusc0e820c2019-11-23 23:52:30 +01005002 ha_alert("%s", errmsg);
William Lallemand8b453912019-11-21 15:48:10 +01005003 err++;
5004 }
5005
5006 free(errmsg);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005007 return err;
5008}
5009
Willy Tarreau55d37912016-12-21 23:38:39 +01005010/* Prepares all the contexts for a bind_conf and allocates the shared SSL
5011 * context if needed. Returns < 0 on error, 0 on success. The warnings and
5012 * alerts are directly emitted since the rest of the stack does it below.
5013 */
5014int ssl_sock_prepare_bind_conf(struct bind_conf *bind_conf)
5015{
5016 struct proxy *px = bind_conf->frontend;
5017 int alloc_ctx;
5018 int err;
5019
5020 if (!bind_conf->is_ssl) {
5021 if (bind_conf->default_ctx) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005022 ha_warning("Proxy '%s': A certificate was specified but SSL was not enabled on bind '%s' at [%s:%d] (use 'ssl').\n",
5023 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Willy Tarreau55d37912016-12-21 23:38:39 +01005024 }
5025 return 0;
5026 }
5027 if (!bind_conf->default_ctx) {
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005028 if (bind_conf->strict_sni && !bind_conf->generate_certs) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005029 ha_warning("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d], ssl connections will fail (use 'crt').\n",
5030 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005031 }
5032 else {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005033 ha_alert("Proxy '%s': no SSL certificate specified for bind '%s' at [%s:%d] (use 'crt').\n",
5034 px->id, bind_conf->arg, bind_conf->file, bind_conf->line);
Emmanuel Hocdetaa0d6372017-08-09 11:24:25 +02005035 return -1;
5036 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005037 }
William Lallemandc61c0b32017-12-04 18:46:39 +01005038 if (!ssl_shctx && global.tune.sslcachesize) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005039 alloc_ctx = shctx_init(&ssl_shctx, global.tune.sslcachesize,
Frédéric Lécailleb7838af2018-10-22 16:21:39 +02005040 sizeof(struct sh_ssl_sess_hdr) + SHSESS_BLOCK_MIN_SIZE, -1,
William Lallemandc3cd35f2017-11-28 11:04:43 +01005041 sizeof(*sh_ssl_sess_tree),
5042 ((global.nbthread > 1) || (!global_ssl.private_cache && (global.nbproc > 1))) ? 1 : 0);
Frédéric Lécaille4c8aa112018-10-25 20:22:46 +02005043 if (alloc_ctx <= 0) {
William Lallemandc3cd35f2017-11-28 11:04:43 +01005044 if (alloc_ctx == SHCTX_E_INIT_LOCK)
5045 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");
5046 else
5047 ha_alert("Unable to allocate SSL session cache.\n");
5048 return -1;
5049 }
5050 /* free block callback */
5051 ssl_shctx->free_block = sh_ssl_sess_free_blocks;
5052 /* init the root tree within the extra space */
5053 sh_ssl_sess_tree = (void *)ssl_shctx + sizeof(struct shared_context);
5054 *sh_ssl_sess_tree = EB_ROOT_UNIQUE;
Willy Tarreau55d37912016-12-21 23:38:39 +01005055 }
Willy Tarreau55d37912016-12-21 23:38:39 +01005056 err = 0;
5057 /* initialize all certificate contexts */
5058 err += ssl_sock_prepare_all_ctx(bind_conf);
5059
5060 /* initialize CA variables if the certificates generation is enabled */
5061 err += ssl_sock_load_ca(bind_conf);
5062
5063 return -err;
5064}
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005065
William Lallemand9d118682021-12-30 11:25:43 +01005066/* release ssl context allocated for servers. Most of the field free here
5067 * must also be allocated in srv_ssl_settings_cpy() */
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005068void ssl_sock_free_srv_ctx(struct server *srv)
5069{
Olivier Houchardc7566002018-11-20 23:33:50 +01005070#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
William Lallemand9d118682021-12-30 11:25:43 +01005071 ha_free(&srv->ssl_ctx.alpn_str);
Olivier Houchardc7566002018-11-20 23:33:50 +01005072#endif
Lukas Tribusda95fd92018-11-25 13:21:27 +01005073#ifdef OPENSSL_NPN_NEGOTIATED
William Lallemand9d118682021-12-30 11:25:43 +01005074 ha_free(&srv->ssl_ctx.npn_str);
Lukas Tribus7706b852018-11-26 22:57:17 +01005075#endif
Christopher Faulet58feb492020-10-07 13:20:23 +02005076 if (srv->ssl_ctx.reused_sess) {
5077 int i;
5078
William Lallemandc78ac5a2021-11-17 02:59:21 +01005079 for (i = 0; i < global.nbthread; i++) {
Willy Tarreaue709e822021-02-26 21:06:32 +01005080 ha_free(&srv->ssl_ctx.reused_sess[i].ptr);
William Lallemandc78ac5a2021-11-17 02:59:21 +01005081 ha_free(&srv->ssl_ctx.reused_sess[i].sni);
5082 }
Willy Tarreaue709e822021-02-26 21:06:32 +01005083 ha_free(&srv->ssl_ctx.reused_sess);
Christopher Faulet58feb492020-10-07 13:20:23 +02005084 }
5085
Willy Tarreaue709e822021-02-26 21:06:32 +01005086 if (srv->ssl_ctx.ctx) {
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005087 SSL_CTX_free(srv->ssl_ctx.ctx);
Willy Tarreaue709e822021-02-26 21:06:32 +01005088 srv->ssl_ctx.ctx = NULL;
5089 }
William Lallemand9d118682021-12-30 11:25:43 +01005090
5091 ha_free(&srv->ssl_ctx.ca_file);
5092 ha_free(&srv->ssl_ctx.crl_file);
5093 ha_free(&srv->ssl_ctx.client_crt);
5094 ha_free(&srv->ssl_ctx.verify_host);
5095#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5096 ha_free(&srv->sni_expr);
William Lallemand17d0caa2022-03-16 17:48:19 +01005097 release_sample_expr(srv->ssl_ctx.sni);
5098 srv->ssl_ctx.sni = NULL;
William Lallemand9d118682021-12-30 11:25:43 +01005099#endif
5100 ha_free(&srv->ssl_ctx.ciphers);
5101#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
5102 ha_free(&srv->ssl_ctx.ciphersuites);
5103#endif
William Lallemandec3d2d62021-12-30 14:45:19 +01005104 /* If there is a certificate we must unlink the ckch instance */
5105 ckch_inst_free(srv->ssl_ctx.inst);
Christopher Faulet77fe80c2015-07-29 13:02:40 +02005106}
5107
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005108/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +02005109 * be NULL, in which case nothing is done. The default_ctx is nullified too.
5110 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005111void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +02005112{
5113 struct ebmb_node *node, *back;
5114 struct sni_ctx *sni;
5115
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005116 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005117 while (node) {
5118 sni = ebmb_entry(node, struct sni_ctx, name);
5119 back = ebmb_next(node);
5120 ebmb_delete(node);
William Lallemand02e19a52020-04-08 16:11:26 +02005121 SSL_CTX_free(sni->ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02005122 LIST_DELETE(&sni->by_ckch_inst);
Emeric Brunfc0421f2012-09-07 17:30:07 +02005123 free(sni);
5124 node = back;
5125 }
5126
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005127 node = ebmb_first(&bind_conf->sni_w_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 }
William Lallemandb2408692020-06-24 09:54:29 +02005137
Emmanuel Hocdetf6b37c62017-03-06 15:34:44 +01005138 SSL_CTX_free(bind_conf->initial_ctx);
5139 bind_conf->initial_ctx = NULL;
William Lallemand02e19a52020-04-08 16:11:26 +02005140 SSL_CTX_free(bind_conf->default_ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +02005141 bind_conf->default_ctx = NULL;
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005142 bind_conf->default_ssl_conf = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +02005143}
William Lallemandb2408692020-06-24 09:54:29 +02005144
5145
5146void ssl_sock_deinit()
5147{
5148 crtlist_deinit(); /* must be free'd before the ckchs */
5149 ckch_deinit();
5150}
5151REGISTER_POST_DEINIT(ssl_sock_deinit);
Emeric Brune1f38db2012-09-03 20:36:47 +02005152
Willy Tarreau795cdab2016-12-22 17:30:54 +01005153/* Destroys all the contexts for a bind_conf. This is used during deinit(). */
5154void ssl_sock_destroy_bind_conf(struct bind_conf *bind_conf)
5155{
5156 ssl_sock_free_ca(bind_conf);
5157 ssl_sock_free_all_ctx(bind_conf);
Emmanuel Hocdet98263292016-12-29 18:26:15 +01005158 ssl_sock_free_ssl_conf(&bind_conf->ssl_conf);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005159 free(bind_conf->ca_sign_file);
5160 free(bind_conf->ca_sign_pass);
Willy Tarreau17b4aa12018-07-17 10:05:32 +02005161 if (bind_conf->keys_ref && !--bind_conf->keys_ref->refcount) {
Willy Tarreau795cdab2016-12-22 17:30:54 +01005162 free(bind_conf->keys_ref->filename);
5163 free(bind_conf->keys_ref->tlskeys);
Willy Tarreau2b718102021-04-21 07:32:39 +02005164 LIST_DELETE(&bind_conf->keys_ref->list);
Willy Tarreau795cdab2016-12-22 17:30:54 +01005165 free(bind_conf->keys_ref);
5166 }
5167 bind_conf->keys_ref = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005168 bind_conf->ca_sign_pass = NULL;
5169 bind_conf->ca_sign_file = NULL;
Willy Tarreau795cdab2016-12-22 17:30:54 +01005170}
5171
Christopher Faulet31af49d2015-06-09 17:29:50 +02005172/* Load CA cert file and private key used to generate certificates */
5173int
Willy Tarreau03209342016-12-22 17:08:28 +01005174ssl_sock_load_ca(struct bind_conf *bind_conf)
Christopher Faulet31af49d2015-06-09 17:29:50 +02005175{
Willy Tarreau03209342016-12-22 17:08:28 +01005176 struct proxy *px = bind_conf->frontend;
Shimi Gersner5846c492020-08-23 13:58:12 +03005177 struct cert_key_and_chain *ckch = NULL;
5178 int ret = 0;
5179 char *err = NULL;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005180
Christopher Fauletf8bb0ce2017-09-15 09:52:49 +02005181 if (!bind_conf->generate_certs)
Shimi Gersner5846c492020-08-23 13:58:12 +03005182 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005183
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005184#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02005185 if (global_ssl.ctx_cache) {
Willy Tarreauef934602016-12-22 23:12:01 +01005186 ssl_ctx_lru_tree = lru64_new(global_ssl.ctx_cache);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005187 }
Christopher Fauletd2cab922015-07-28 16:03:47 +02005188 ssl_ctx_lru_seed = (unsigned int)time(NULL);
Emeric Brun821bb9b2017-06-15 16:37:39 +02005189 ssl_ctx_serial = now_ms;
Willy Tarreaua84c2672015-10-09 12:10:13 +02005190#endif
Christopher Fauletd2cab922015-07-28 16:03:47 +02005191
Christopher Faulet31af49d2015-06-09 17:29:50 +02005192 if (!bind_conf->ca_sign_file) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01005193 ha_alert("Proxy '%s': cannot enable certificate generation, "
5194 "no CA certificate File configured at [%s:%d].\n",
5195 px->id, bind_conf->file, bind_conf->line);
Shimi Gersner5846c492020-08-23 13:58:12 +03005196 goto failed;
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005197 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005198
Shimi Gersner5846c492020-08-23 13:58:12 +03005199 /* Allocate cert structure */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02005200 ckch = calloc(1, sizeof(*ckch));
Shimi Gersner5846c492020-08-23 13:58:12 +03005201 if (!ckch) {
5202 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain allocation failure\n",
5203 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5204 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005205 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005206
5207 /* Try to parse file */
5208 if (ssl_sock_load_files_into_ckch(bind_conf->ca_sign_file, ckch, &err)) {
5209 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain loading failed: %s\n",
5210 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line, err);
Willy Tarreau01acf562021-02-26 21:12:15 +01005211 free(err);
Shimi Gersner5846c492020-08-23 13:58:12 +03005212 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005213 }
Shimi Gersner5846c492020-08-23 13:58:12 +03005214
5215 /* Fail if missing cert or pkey */
5216 if ((!ckch->cert) || (!ckch->key)) {
5217 ha_alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d]. Chain missing certificate or private key\n",
5218 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
5219 goto failed;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005220 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005221
Shimi Gersner5846c492020-08-23 13:58:12 +03005222 /* Final assignment to bind */
5223 bind_conf->ca_sign_ckch = ckch;
5224 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005225
Shimi Gersner5846c492020-08-23 13:58:12 +03005226 failed:
5227 if (ckch) {
5228 ssl_sock_free_cert_key_and_chain_contents(ckch);
5229 free(ckch);
5230 }
5231
Christopher Fauletc6f02fb2015-10-09 10:53:31 +02005232 bind_conf->generate_certs = 0;
Shimi Gersner5846c492020-08-23 13:58:12 +03005233 ret++;
5234 return ret;
Christopher Faulet31af49d2015-06-09 17:29:50 +02005235}
5236
5237/* Release CA cert and private key used to generate certificated */
5238void
5239ssl_sock_free_ca(struct bind_conf *bind_conf)
5240{
Shimi Gersner5846c492020-08-23 13:58:12 +03005241 if (bind_conf->ca_sign_ckch) {
5242 ssl_sock_free_cert_key_and_chain_contents(bind_conf->ca_sign_ckch);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005243 ha_free(&bind_conf->ca_sign_ckch);
Shimi Gersner5846c492020-08-23 13:58:12 +03005244 }
Christopher Faulet31af49d2015-06-09 17:29:50 +02005245}
5246
Emeric Brun46591952012-05-18 15:47:34 +02005247/*
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005248 * Try to allocate the BIO and SSL session objects of <conn> connection with <bio> and
5249 * <ssl> as addresses, <bio_meth> as BIO method and <ssl_ctx> as SSL context inherited settings.
5250 * Connect the allocated BIO to the allocated SSL session. Also set <ctx> as address of custom
5251 * data for the BIO and store <conn> as user data of the SSL session object.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05005252 * 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 +01005253 * as parameters to this function.
5254 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <conn> to
5255 * CO_ER_SSL_NO_MEM.
5256 */
5257int ssl_bio_and_sess_init(struct connection *conn, SSL_CTX *ssl_ctx,
5258 SSL **ssl, BIO **bio, BIO_METHOD *bio_meth, void *ctx)
5259{
5260 int retry = 1;
5261
5262 retry:
5263 /* Alloc a new SSL session. */
5264 *ssl = SSL_new(ssl_ctx);
5265 if (!*ssl) {
5266 if (!retry--)
5267 goto err;
5268
5269 pool_gc(NULL);
5270 goto retry;
5271 }
5272
5273 *bio = BIO_new(bio_meth);
5274 if (!*bio) {
5275 SSL_free(*ssl);
5276 *ssl = NULL;
5277 if (!retry--)
5278 goto err;
5279
5280 pool_gc(NULL);
5281 goto retry;
5282 }
5283
5284 BIO_set_data(*bio, ctx);
5285 SSL_set_bio(*ssl, *bio, *bio);
5286
5287 /* set connection pointer. */
5288 if (!SSL_set_ex_data(*ssl, ssl_app_data_index, conn)) {
5289 SSL_free(*ssl);
5290 *ssl = NULL;
5291 if (!retry--)
5292 goto err;
5293
5294 pool_gc(NULL);
5295 goto retry;
5296 }
5297
5298 return 0;
5299
5300 err:
5301 conn->err_code = CO_ER_SSL_NO_MEM;
5302 return -1;
5303}
5304
Olivier Houchardbc5ce922021-03-05 23:47:00 +01005305/* This function is called when all the XPRT have been initialized. We can
5306 * now attempt to start the SSL handshake.
5307 */
5308static int ssl_sock_start(struct connection *conn, void *xprt_ctx)
5309{
5310 struct ssl_sock_ctx *ctx = xprt_ctx;
5311
5312 if (ctx->xprt->start) {
5313 int ret;
5314
5315 ret = ctx->xprt->start(conn, ctx->xprt_ctx);
5316 if (ret < 0)
5317 return ret;
5318 }
5319 tasklet_wakeup(ctx->wait_event.tasklet);
5320
5321 return 0;
5322}
5323
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005324/*
Emeric Brun46591952012-05-18 15:47:34 +02005325 * This function is called if SSL * context is not yet allocated. The function
5326 * is designed to be called before any other data-layer operation and sets the
5327 * handshake flag on the connection. It is safe to call it multiple times.
5328 * It returns 0 on success and -1 in error case.
5329 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005330static int ssl_sock_init(struct connection *conn, void **xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005331{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005332 struct ssl_sock_ctx *ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005333 /* already initialized */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005334 if (*xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005335 return 0;
5336
Olivier Houchard66ab4982019-02-26 18:37:15 +01005337 ctx = pool_alloc(ssl_sock_ctx_pool);
5338 if (!ctx) {
5339 conn->err_code = CO_ER_SSL_NO_MEM;
5340 return -1;
5341 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005342 ctx->wait_event.tasklet = tasklet_new();
5343 if (!ctx->wait_event.tasklet) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005344 conn->err_code = CO_ER_SSL_NO_MEM;
5345 pool_free(ssl_sock_ctx_pool, ctx);
5346 return -1;
5347 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005348 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5349 ctx->wait_event.tasklet->context = ctx;
Willy Tarreau9205ab32021-02-25 15:31:00 +01005350 ctx->wait_event.tasklet->state |= TASK_HEAVY; // assign it to the bulk queue during handshake
Olivier Houchardea8dd942019-05-20 14:02:16 +02005351 ctx->wait_event.events = 0;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005352 ctx->sent_early_data = 0;
Olivier Houchard54907bb2019-12-19 15:02:39 +01005353 ctx->early_buf = BUF_NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005354 ctx->conn = conn;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005355 ctx->subs = NULL;
Emeric Brun5762a0d2019-09-06 15:36:02 +02005356 ctx->xprt_st = 0;
5357 ctx->xprt_ctx = NULL;
Olivier Houcharda8955d52019-04-07 22:00:38 +02005358
5359 /* Only work with sockets for now, this should be adapted when we'll
5360 * add QUIC support.
5361 */
5362 ctx->xprt = xprt_get(XPRT_RAW);
Olivier Houchard19afb272019-05-23 18:24:07 +02005363 if (ctx->xprt->init) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005364 if (ctx->xprt->init(conn, &ctx->xprt_ctx) != 0)
5365 goto err;
Olivier Houchard19afb272019-05-23 18:24:07 +02005366 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005367
Willy Tarreau20879a02012-12-03 16:32:10 +01005368 if (global.maxsslconn && sslconns >= global.maxsslconn) {
5369 conn->err_code = CO_ER_SSL_TOO_MANY;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005370 goto err;
Willy Tarreau20879a02012-12-03 16:32:10 +01005371 }
Willy Tarreau403edff2012-09-06 11:58:37 +02005372
Emeric Brun46591952012-05-18 15:47:34 +02005373 /* If it is in client mode initiate SSL session
5374 in connect state otherwise accept state */
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005375 if (objt_server(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005376 if (ssl_bio_and_sess_init(conn, __objt_server(conn->target)->ssl_ctx.ctx,
5377 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005378 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005379
Olivier Houchard66ab4982019-02-26 18:37:15 +01005380 SSL_set_connect_state(ctx->ssl);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005381 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Willy Tarreau07d94e42018-09-20 10:57:52 +02005382 if (__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr) {
5383 const unsigned char *ptr = __objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr;
5384 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 +01005385 if (sess && !SSL_set_session(ctx->ssl, sess)) {
Olivier Houcharde6060c52017-11-16 17:42:52 +01005386 SSL_SESSION_free(sess);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005387 ha_free(&__objt_server(conn->target)->ssl_ctx.reused_sess[tid].ptr);
Olivier Houcharde6060c52017-11-16 17:42:52 +01005388 } else if (sess) {
5389 SSL_SESSION_free(sess);
Emeric Brun55476152014-11-12 17:35:37 +01005390 }
5391 }
William Lallemand3ce6eed2021-02-08 10:43:44 +01005392 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &(__objt_server(conn->target)->ssl_ctx.lock));
Evan Broderbe554312013-06-27 00:05:25 -07005393
Emeric Brun46591952012-05-18 15:47:34 +02005394 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005395 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +02005396
Willy Tarreau4781b152021-04-06 13:53:36 +02005397 _HA_ATOMIC_INC(&sslconns);
5398 _HA_ATOMIC_INC(&totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005399 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005400 return 0;
5401 }
Willy Tarreau3fdb3662012-11-12 00:42:33 +01005402 else if (objt_listener(conn->target)) {
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005403 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
Willy Tarreaufba03cd2014-11-13 13:48:58 +01005404
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005405 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
5406 &ctx->ssl, &ctx->bio, ha_meth, ctx) == -1)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005407 goto err;
Emeric Brun55476152014-11-12 17:35:37 +01005408
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005409#ifdef SSL_READ_EARLY_DATA_SUCCESS
Frédéric Lécaille5aa92412020-11-09 15:59:23 +01005410 if (bc->ssl_conf.early_data) {
Frédéric Lécaille3139c1b2020-01-24 14:56:18 +01005411 b_alloc(&ctx->early_buf);
5412 SSL_set_max_early_data(ctx->ssl,
5413 /* Only allow early data if we managed to allocate
5414 * a buffer.
5415 */
5416 (!b_is_null(&ctx->early_buf)) ?
5417 global.tune.bufsize - global.tune.maxrewrite : 0);
5418 }
5419#endif
5420
Olivier Houchard66ab4982019-02-26 18:37:15 +01005421 SSL_set_accept_state(ctx->ssl);
Emeric Brune1f38db2012-09-03 20:36:47 +02005422
Emeric Brun46591952012-05-18 15:47:34 +02005423 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +02005424 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005425#ifdef SSL_READ_EARLY_DATA_SUCCESS
Willy Tarreaua84986a2021-02-03 11:21:38 +01005426 if (bc->ssl_conf.early_data)
5427 conn->flags |= CO_FL_EARLY_SSL_HS;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005428#endif
Willy Tarreau403edff2012-09-06 11:58:37 +02005429
Willy Tarreau4781b152021-04-06 13:53:36 +02005430 _HA_ATOMIC_INC(&sslconns);
5431 _HA_ATOMIC_INC(&totalsslconns);
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005432 *xprt_ctx = ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005433 return 0;
5434 }
5435 /* don't know how to handle such a target */
Willy Tarreau20879a02012-12-03 16:32:10 +01005436 conn->err_code = CO_ER_SSL_NO_TARGET;
Olivier Houchard66ab4982019-02-26 18:37:15 +01005437err:
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02005438 if (ctx && ctx->wait_event.tasklet)
5439 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01005440 pool_free(ssl_sock_ctx_pool, ctx);
Emeric Brun46591952012-05-18 15:47:34 +02005441 return -1;
5442}
5443
5444
5445/* This is the callback which is used when an SSL handshake is pending. It
5446 * updates the FD status if it wants some polling before being called again.
5447 * It returns 0 if it fails in a fatal way or needs to poll to go further,
5448 * otherwise it returns non-zero and removes itself from the connection's
5449 * flags (the bit is provided in <flag> by the caller).
5450 */
Olivier Houchard000694c2019-05-23 14:45:12 +02005451static int ssl_sock_handshake(struct connection *conn, unsigned int flag)
Emeric Brun46591952012-05-18 15:47:34 +02005452{
Olivier Houchard66ab4982019-02-26 18:37:15 +01005453 struct ssl_sock_ctx *ctx = conn->xprt_ctx;
Emeric Brun46591952012-05-18 15:47:34 +02005454 int ret;
Willy Tarreau42995282020-11-06 13:19:18 +01005455 struct ssl_counters *counters = NULL;
5456 struct ssl_counters *counters_px = NULL;
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005457 struct listener *li;
5458 struct server *srv;
Willy Tarreau06300382021-02-02 15:42:25 +01005459 socklen_t lskerr;
5460 int skerr;
5461
Emeric Brun46591952012-05-18 15:47:34 +02005462
Willy Tarreau3c728722014-01-23 13:50:42 +01005463 if (!conn_ctrl_ready(conn))
Willy Tarreauf79c8172013-10-21 16:30:56 +02005464 return 0;
5465
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005466 /* get counters */
5467 switch (obj_type(conn->target)) {
5468 case OBJ_TYPE_LISTENER:
5469 li = objt_listener(conn->target);
5470 counters = EXTRA_COUNTERS_GET(li->extra_counters, &ssl_stats_module);
5471 counters_px = EXTRA_COUNTERS_GET(li->bind_conf->frontend->extra_counters_fe,
5472 &ssl_stats_module);
5473 break;
5474
5475 case OBJ_TYPE_SERVER:
5476 srv = objt_server(conn->target);
5477 counters = EXTRA_COUNTERS_GET(srv->extra_counters, &ssl_stats_module);
5478 counters_px = EXTRA_COUNTERS_GET(srv->proxy->extra_counters_be,
5479 &ssl_stats_module);
5480 break;
5481
5482 default:
5483 break;
5484 }
5485
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02005486 if (!conn->xprt_ctx)
Emeric Brun46591952012-05-18 15:47:34 +02005487 goto out_error;
5488
Willy Tarreau06300382021-02-02 15:42:25 +01005489 /* don't start calculating a handshake on a dead connection */
5490 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH))
5491 goto out_error;
5492
5493 /* FIXME/WT: for now we don't have a clear way to inspect the connection
5494 * status from the lower layers, so let's check the FD directly. Ideally
5495 * the xprt layers should provide some status indicating their knowledge
5496 * of shutdowns or error.
5497 */
5498 skerr = 0;
5499 lskerr = sizeof(skerr);
5500 if ((getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) < 0) ||
5501 skerr != 0)
5502 goto out_error;
5503
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005504#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02005505 /*
5506 * Check if we have early data. If we do, we have to read them
5507 * before SSL_do_handshake() is called, And there's no way to
5508 * detect early data, except to try to read them
5509 */
5510 if (conn->flags & CO_FL_EARLY_SSL_HS) {
Olivier Houchard54907bb2019-12-19 15:02:39 +01005511 size_t read_data = 0;
Olivier Houchardc2aae742017-09-22 18:26:28 +02005512
Olivier Houchard54907bb2019-12-19 15:02:39 +01005513 while (1) {
5514 ret = SSL_read_early_data(ctx->ssl,
5515 b_tail(&ctx->early_buf), b_room(&ctx->early_buf),
5516 &read_data);
5517 if (ret == SSL_READ_EARLY_DATA_ERROR)
5518 goto check_error;
5519 if (read_data > 0) {
5520 conn->flags |= CO_FL_EARLY_DATA;
5521 b_add(&ctx->early_buf, read_data);
5522 }
5523 if (ret == SSL_READ_EARLY_DATA_FINISH) {
5524 conn->flags &= ~CO_FL_EARLY_SSL_HS;
5525 if (!b_data(&ctx->early_buf))
5526 b_free(&ctx->early_buf);
5527 break;
5528 }
5529 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02005530 }
5531#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005532 /* If we use SSL_do_handshake to process a reneg initiated by
5533 * the remote peer, it sometimes returns SSL_ERROR_SSL.
5534 * Usually SSL_write and SSL_read are used and process implicitly
5535 * the reneg handshake.
5536 * Here we use SSL_peek as a workaround for reneg.
5537 */
Willy Tarreauc192b0a2020-01-23 09:11:58 +01005538 if (!(conn->flags & CO_FL_WAIT_L6_CONN) && SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005539 char c;
5540
Olivier Houchard66ab4982019-02-26 18:37:15 +01005541 ret = SSL_peek(ctx->ssl, &c, 1);
Emeric Brun674b7432012-11-08 19:21:55 +01005542 if (ret <= 0) {
5543 /* handshake may have not been completed, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005544 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005545
Emeric Brun674b7432012-11-08 19:21:55 +01005546 if (ret == SSL_ERROR_WANT_WRITE) {
5547 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005548 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005549 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005550 return 0;
5551 }
5552 else if (ret == SSL_ERROR_WANT_READ) {
5553 /* handshake may have been completed but we have
5554 * no more data to read.
5555 */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005556 if (!SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun674b7432012-11-08 19:21:55 +01005557 ret = 1;
5558 goto reneg_ok;
5559 }
5560 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005561 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005562 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun674b7432012-11-08 19:21:55 +01005563 return 0;
5564 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005565#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005566 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005567 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005568 return 0;
5569 }
5570#endif
Emeric Brun674b7432012-11-08 19:21:55 +01005571 else if (ret == SSL_ERROR_SYSCALL) {
5572 /* if errno is null, then connection was successfully established */
5573 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5574 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Willy Tarreau20879a02012-12-03 16:32:10 +01005575 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005576#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5577 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005578 conn->err_code = CO_ER_SSL_HANDSHAKE;
5579#else
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005580 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005581#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005582 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005583 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)ctx->ssl);
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005584 empty_handshake = state == TLS_ST_BEFORE;
5585#else
Lukas Tribus49799162019-07-08 14:29:15 +02005586 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5587 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005588#endif
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005589 if (empty_handshake) {
Emeric Brun29f037d2014-04-25 19:05:36 +02005590 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005591 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005592 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5593 else
5594 conn->err_code = CO_ER_SSL_EMPTY;
5595 }
5596 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005597 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005598 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5599 else
5600 conn->err_code = CO_ER_SSL_ABORT;
5601 }
5602 }
5603 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005604 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005605 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
Willy Tarreau20879a02012-12-03 16:32:10 +01005606 else
Emeric Brun29f037d2014-04-25 19:05:36 +02005607 conn->err_code = CO_ER_SSL_HANDSHAKE;
5608 }
Lukas Tribus49799162019-07-08 14:29:15 +02005609#endif /* BoringSSL or LibreSSL */
Willy Tarreau20879a02012-12-03 16:32:10 +01005610 }
Emeric Brun674b7432012-11-08 19:21:55 +01005611 goto out_error;
5612 }
5613 else {
5614 /* Fail on all other handshake errors */
5615 /* Note: OpenSSL may leave unread bytes in the socket's
5616 * buffer, causing an RST to be emitted upon close() on
5617 * TCP sockets. We first try to drain possibly pending
5618 * data to avoid this as much as possible.
5619 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005620 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005621 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005622 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005623 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun674b7432012-11-08 19:21:55 +01005624 goto out_error;
5625 }
5626 }
5627 /* read some data: consider handshake completed */
5628 goto reneg_ok;
5629 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01005630 ret = SSL_do_handshake(ctx->ssl);
Olivier Houchardc2aae742017-09-22 18:26:28 +02005631check_error:
Emeric Brun46591952012-05-18 15:47:34 +02005632 if (ret != 1) {
5633 /* handshake did not complete, let's find why */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005634 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02005635
5636 if (ret == SSL_ERROR_WANT_WRITE) {
5637 /* SSL handshake needs to write, L4 connection may not be ready */
Olivier Houchard03abf2d2019-05-28 10:12:02 +02005638 if (!(ctx->wait_event.events & SUB_RETRY_SEND))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005639 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005640 return 0;
5641 }
5642 else if (ret == SSL_ERROR_WANT_READ) {
5643 /* SSL handshake needs to read, L4 connection is ready */
Olivier Houchardea8dd942019-05-20 14:02:16 +02005644 if (!(ctx->wait_event.events & SUB_RETRY_RECV))
Olivier Houchardea8dd942019-05-20 14:02:16 +02005645 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
5646 SUB_RETRY_RECV, &ctx->wait_event);
Emeric Brun46591952012-05-18 15:47:34 +02005647 return 0;
5648 }
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005649#ifdef SSL_MODE_ASYNC
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005650 else if (ret == SSL_ERROR_WANT_ASYNC) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005651 ssl_async_process_fds(ctx);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00005652 return 0;
5653 }
5654#endif
Willy Tarreau89230192012-09-28 20:22:13 +02005655 else if (ret == SSL_ERROR_SYSCALL) {
5656 /* if errno is null, then connection was successfully established */
5657 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
5658 conn->flags &= ~CO_FL_WAIT_L4_CONN;
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005659 if (!conn->err_code) {
Lukas Tribus49799162019-07-08 14:29:15 +02005660#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
5661 /* do not handle empty handshakes in BoringSSL or LibreSSL */
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005662 conn->err_code = CO_ER_SSL_HANDSHAKE;
5663#else
5664 int empty_handshake;
Willy Tarreau5db847a2019-05-09 14:13:35 +02005665#if (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL)
Lukas Tribus49799162019-07-08 14:29:15 +02005666 /* use SSL_get_state() in OpenSSL >= 1.1.0; SSL_state() is broken */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005667 OSSL_HANDSHAKE_STATE state = SSL_get_state(ctx->ssl);
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005668 empty_handshake = state == TLS_ST_BEFORE;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005669#else
Lukas Tribus49799162019-07-08 14:29:15 +02005670 /* access packet_length directly in OpenSSL <= 1.0.2; SSL_state() is broken */
5671 empty_handshake = !ctx->ssl->packet_length;
Dirkjan Bussink1866d6d2016-08-29 13:26:37 +02005672#endif
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005673 if (empty_handshake) {
5674 if (!errno) {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005675 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005676 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5677 else
5678 conn->err_code = CO_ER_SSL_EMPTY;
5679 }
5680 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005681 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005682 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5683 else
5684 conn->err_code = CO_ER_SSL_ABORT;
5685 }
Emeric Brun29f037d2014-04-25 19:05:36 +02005686 }
5687 else {
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005688 if (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
Emeric Brun29f037d2014-04-25 19:05:36 +02005689 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
5690 else
Emmanuel Hocdetfdec7892017-01-13 17:48:18 +01005691 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun29f037d2014-04-25 19:05:36 +02005692 }
Lukas Tribus49799162019-07-08 14:29:15 +02005693#endif /* BoringSSL or LibreSSL */
Emeric Brun29f037d2014-04-25 19:05:36 +02005694 }
Willy Tarreau89230192012-09-28 20:22:13 +02005695 goto out_error;
5696 }
Emeric Brun46591952012-05-18 15:47:34 +02005697 else {
5698 /* Fail on all other handshake errors */
Willy Tarreau566dc552012-10-19 20:52:18 +02005699 /* Note: OpenSSL may leave unread bytes in the socket's
5700 * buffer, causing an RST to be emitted upon close() on
5701 * TCP sockets. We first try to drain possibly pending
5702 * data to avoid this as much as possible.
5703 */
Willy Tarreau2ded48d2020-12-11 16:20:34 +01005704 conn_ctrl_drain(conn);
Willy Tarreau20879a02012-12-03 16:32:10 +01005705 if (!conn->err_code)
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01005706 conn->err_code = (ctx->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
Willy Tarreauf51c6982014-04-25 20:02:39 +02005707 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005708 goto out_error;
5709 }
5710 }
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05005711#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard522eea72017-11-03 16:27:47 +01005712 else {
5713 /*
5714 * If the server refused the early data, we have to send a
5715 * 425 to the client, as we no longer have the data to sent
5716 * them again.
5717 */
5718 if ((conn->flags & CO_FL_EARLY_DATA) && (objt_server(conn->target))) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01005719 if (SSL_get_early_data_status(ctx->ssl) == SSL_EARLY_DATA_REJECTED) {
Olivier Houchard522eea72017-11-03 16:27:47 +01005720 conn->err_code = CO_ER_SSL_EARLY_FAILED;
5721 goto out_error;
5722 }
5723 }
5724 }
5725#endif
5726
Emeric Brun46591952012-05-18 15:47:34 +02005727
Emeric Brun674b7432012-11-08 19:21:55 +01005728reneg_ok:
Emeric Brunb5e42a82017-06-06 12:35:14 +00005729
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005730#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00005731 /* ASYNC engine API doesn't support moving read/write
5732 * buffers. So we disable ASYNC mode right after
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05005733 * the handshake to avoid buffer overflow.
Emeric Brunb5e42a82017-06-06 12:35:14 +00005734 */
5735 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01005736 SSL_clear_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00005737#endif
Emeric Brun46591952012-05-18 15:47:34 +02005738 /* Handshake succeeded */
Olivier Houchard66ab4982019-02-26 18:37:15 +01005739 if (!SSL_session_reused(ctx->ssl)) {
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005740 if (objt_server(conn->target)) {
5741 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
5742 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
5743 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
Emeric Brun46591952012-05-18 15:47:34 +02005744 }
Willy Tarreau0c9c2722014-05-28 12:28:58 +02005745 else {
5746 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
5747 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
5748 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
5749 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005750
Willy Tarreau42995282020-11-06 13:19:18 +01005751 if (counters) {
Willy Tarreau41736ab2021-11-22 17:46:13 +01005752 HA_ATOMIC_INC(&counters->sess);
5753 HA_ATOMIC_INC(&counters_px->sess);
Willy Tarreau42995282020-11-06 13:19:18 +01005754 }
Amaury Denoyelled0447a72020-11-03 17:10:02 +01005755 }
Willy Tarreau42995282020-11-06 13:19:18 +01005756 else if (counters) {
Willy Tarreau41736ab2021-11-22 17:46:13 +01005757 HA_ATOMIC_INC(&counters->reused_sess);
5758 HA_ATOMIC_INC(&counters_px->reused_sess);
Emeric Brun46591952012-05-18 15:47:34 +02005759 }
5760
5761 /* The connection is now established at both layers, it's time to leave */
5762 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
5763 return 1;
5764
5765 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01005766 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02005767 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01005768 ERR_clear_error();
5769
Emeric Brun9fa89732012-10-04 17:09:56 +02005770 /* free resumed session if exists */
William Lallemand3ce6eed2021-02-08 10:43:44 +01005771 if (objt_server(conn->target)) {
5772 struct server *s = __objt_server(conn->target);
5773 /* RWLOCK: only rdlock the SSL cache even when writing in it because there is
5774 * one cache per thread, it only prevents to flush it from the CLI in
5775 * another thread */
5776
5777 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01005778 if (s->ssl_ctx.reused_sess[tid].ptr)
5779 ha_free(&s->ssl_ctx.reused_sess[tid].ptr);
William Lallemand3ce6eed2021-02-08 10:43:44 +01005780 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Emeric Brun9fa89732012-10-04 17:09:56 +02005781 }
5782
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005783 if (counters) {
Willy Tarreau41736ab2021-11-22 17:46:13 +01005784 HA_ATOMIC_INC(&counters->failed_handshake);
5785 HA_ATOMIC_INC(&counters_px->failed_handshake);
Amaury Denoyelle034c1622020-11-13 16:05:00 +01005786 }
5787
Emeric Brun46591952012-05-18 15:47:34 +02005788 /* Fail on all other handshake errors */
5789 conn->flags |= CO_FL_ERROR;
Willy Tarreau20879a02012-12-03 16:32:10 +01005790 if (!conn->err_code)
5791 conn->err_code = CO_ER_SSL_HANDSHAKE;
Emeric Brun46591952012-05-18 15:47:34 +02005792 return 0;
5793}
5794
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005795/* Called from the upper layer, to subscribe <es> to events <event_type>. The
5796 * event subscriber <es> is not allowed to change from a previous call as long
5797 * as at least one event is still subscribed. The <event_type> must only be a
5798 * combination of SUB_RETRY_RECV and SUB_RETRY_SEND. It always returns 0,
5799 * unless the transport layer was already released.
5800 */
5801static int ssl_subscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005802{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005803 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005804
Olivier Houchard0ff28652019-06-24 18:57:39 +02005805 if (!ctx)
5806 return -1;
5807
Willy Tarreau113d52b2020-01-10 09:20:26 +01005808 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005809 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005810
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005811 ctx->subs = es;
5812 es->events |= event_type;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005813
5814 /* we may have to subscribe to lower layers for new events */
5815 event_type &= ~ctx->wait_event.events;
5816 if (event_type && !(conn->flags & CO_FL_SSL_WAIT_HS))
5817 ctx->xprt->subscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005818 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005819}
5820
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005821/* Called from the upper layer, to unsubscribe <es> from events <event_type>.
5822 * The <es> pointer is not allowed to differ from the one passed to the
5823 * subscribe() call. It always returns zero.
5824 */
5825static int ssl_unsubscribe(struct connection *conn, void *xprt_ctx, int event_type, struct wait_event *es)
Olivier Houcharddf357842019-03-21 16:30:07 +01005826{
Olivier Houchardea8dd942019-05-20 14:02:16 +02005827 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houcharde179d0e2019-03-21 18:27:17 +01005828
Willy Tarreau113d52b2020-01-10 09:20:26 +01005829 BUG_ON(event_type & ~(SUB_RETRY_SEND|SUB_RETRY_RECV));
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005830 BUG_ON(ctx->subs && ctx->subs != es);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005831
Willy Tarreauee1a6fc2020-01-17 07:52:13 +01005832 es->events &= ~event_type;
5833 if (!es->events)
Willy Tarreau113d52b2020-01-10 09:20:26 +01005834 ctx->subs = NULL;
5835
5836 /* If we subscribed, and we're not doing the handshake,
5837 * then we subscribed because the upper layer asked for it,
5838 * as the upper layer is no longer interested, we can
5839 * unsubscribe too.
5840 */
5841 event_type &= ctx->wait_event.events;
5842 if (event_type && !(ctx->conn->flags & CO_FL_SSL_WAIT_HS))
5843 conn_unsubscribe(conn, ctx->xprt_ctx, event_type, &ctx->wait_event);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005844
5845 return 0;
Olivier Houcharddf357842019-03-21 16:30:07 +01005846}
5847
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005848/* The connection has been taken over, so destroy the old tasklet and create
5849 * a new one. The original thread ID must be passed into orig_tid
5850 * It should be called with the takeover lock for the old thread held.
5851 * Returns 0 on success, and -1 on failure
5852 */
5853static int ssl_takeover(struct connection *conn, void *xprt_ctx, int orig_tid)
5854{
5855 struct ssl_sock_ctx *ctx = xprt_ctx;
5856 struct tasklet *tl = tasklet_new();
5857
5858 if (!tl)
5859 return -1;
5860
5861 ctx->wait_event.tasklet->context = NULL;
5862 tasklet_wakeup_on(ctx->wait_event.tasklet, orig_tid);
5863 ctx->wait_event.tasklet = tl;
5864 ctx->wait_event.tasklet->process = ssl_sock_io_cb;
5865 ctx->wait_event.tasklet->context = ctx;
5866 return 0;
5867}
5868
Willy Tarreau41491682021-03-02 17:29:56 +01005869/* notify the next xprt that the connection is about to become idle and that it
5870 * may be stolen at any time after the function returns and that any tasklet in
5871 * the chain must be careful before dereferencing its context.
5872 */
5873static void ssl_set_idle(struct connection *conn, void *xprt_ctx)
5874{
5875 struct ssl_sock_ctx *ctx = xprt_ctx;
5876
5877 if (!ctx || !ctx->wait_event.tasklet)
5878 return;
5879
5880 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
5881 if (ctx->xprt)
5882 xprt_set_idle(conn, ctx->xprt, ctx->xprt_ctx);
5883}
5884
5885/* notify the next xprt that the connection is not idle anymore and that it may
5886 * not be stolen before the next xprt_set_idle().
5887 */
5888static void ssl_set_used(struct connection *conn, void *xprt_ctx)
5889{
5890 struct ssl_sock_ctx *ctx = xprt_ctx;
5891
5892 if (!ctx || !ctx->wait_event.tasklet)
5893 return;
5894
5895 HA_ATOMIC_OR(&ctx->wait_event.tasklet->state, TASK_F_USR1);
5896 if (ctx->xprt)
5897 xprt_set_used(conn, ctx->xprt, ctx->xprt_ctx);
5898}
5899
Olivier Houchard2e055482019-05-27 19:50:12 +02005900/* Use the provided XPRT as an underlying XPRT, and provide the old one.
5901 * Returns 0 on success, and non-zero on failure.
5902 */
5903static 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)
5904{
5905 struct ssl_sock_ctx *ctx = xprt_ctx;
5906
5907 if (oldxprt_ops != NULL)
5908 *oldxprt_ops = ctx->xprt;
5909 if (oldxprt_ctx != NULL)
5910 *oldxprt_ctx = ctx->xprt_ctx;
5911 ctx->xprt = toadd_ops;
5912 ctx->xprt_ctx = toadd_ctx;
5913 return 0;
5914}
5915
Olivier Houchard5149b592019-05-23 17:47:36 +02005916/* Remove the specified xprt. If if it our underlying XPRT, remove it and
5917 * return 0, otherwise just call the remove_xprt method from the underlying
5918 * XPRT.
5919 */
5920static int ssl_remove_xprt(struct connection *conn, void *xprt_ctx, void *toremove_ctx, const struct xprt_ops *newops, void *newctx)
5921{
5922 struct ssl_sock_ctx *ctx = xprt_ctx;
5923
5924 if (ctx->xprt_ctx == toremove_ctx) {
5925 ctx->xprt_ctx = newctx;
5926 ctx->xprt = newops;
5927 return 0;
5928 }
5929 return (ctx->xprt->remove_xprt(conn, ctx->xprt_ctx, toremove_ctx, newops, newctx));
5930}
5931
Willy Tarreau144f84a2021-03-02 16:09:26 +01005932struct task *ssl_sock_io_cb(struct task *t, void *context, unsigned int state)
Olivier Houchardea8dd942019-05-20 14:02:16 +02005933{
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005934 struct tasklet *tl = (struct tasklet *)t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005935 struct ssl_sock_ctx *ctx = context;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005936 struct connection *conn;
5937 int conn_in_list;
5938 int ret = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005939
Willy Tarreau41491682021-03-02 17:29:56 +01005940 if (state & TASK_F_USR1) {
5941 /* the tasklet was idling on an idle connection, it might have
5942 * been stolen, let's be careful!
5943 */
5944 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
5945 if (tl->context == NULL) {
5946 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
5947 tasklet_free(tl);
5948 return NULL;
5949 }
5950 conn = ctx->conn;
Christopher Fauletc5fd15d2023-03-16 11:43:05 +01005951 conn_in_list = conn_get_idle_flag(conn);
Willy Tarreau41491682021-03-02 17:29:56 +01005952 if (conn_in_list)
5953 conn_delete_from_tree(&conn->hash_node->node);
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01005954 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Willy Tarreau41491682021-03-02 17:29:56 +01005955 } else {
5956 conn = ctx->conn;
5957 conn_in_list = 0;
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005958 }
Willy Tarreau41491682021-03-02 17:29:56 +01005959
Olivier Houchardea8dd942019-05-20 14:02:16 +02005960 /* First if we're doing an handshake, try that */
Willy Tarreau9205ab32021-02-25 15:31:00 +01005961 if (ctx->conn->flags & CO_FL_SSL_WAIT_HS) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005962 ssl_sock_handshake(ctx->conn, CO_FL_SSL_WAIT_HS);
Willy Tarreau9205ab32021-02-25 15:31:00 +01005963 if (!(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
5964 /* handshake completed, leave the bulk queue */
Willy Tarreau4c48edb2021-03-09 17:58:02 +01005965 _HA_ATOMIC_AND(&tl->state, ~TASK_HEAVY);
Willy Tarreau9205ab32021-02-25 15:31:00 +01005966 }
5967 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02005968 /* If we had an error, or the handshake is done and I/O is available,
5969 * let the upper layer know.
Olivier Houchard477902b2020-01-22 18:08:48 +01005970 * If no mux was set up yet, then call conn_create_mux()
Olivier Houchardea8dd942019-05-20 14:02:16 +02005971 * we can't be sure conn_fd_handler() will be called again.
5972 */
5973 if ((ctx->conn->flags & CO_FL_ERROR) ||
5974 !(ctx->conn->flags & CO_FL_SSL_WAIT_HS)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02005975 int woke = 0;
5976
5977 /* On error, wake any waiter */
Willy Tarreau113d52b2020-01-10 09:20:26 +01005978 if (ctx->subs) {
5979 tasklet_wakeup(ctx->subs->tasklet);
5980 ctx->subs->events = 0;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005981 woke = 1;
Willy Tarreau113d52b2020-01-10 09:20:26 +01005982 ctx->subs = NULL;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005983 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01005984
Olivier Houchardea8dd942019-05-20 14:02:16 +02005985 /* If we're the first xprt for the connection, let the
Olivier Houchard477902b2020-01-22 18:08:48 +01005986 * upper layers know. If we have no mux, create it,
5987 * and once we have a mux, call its wake method if we didn't
5988 * woke a tasklet already.
Olivier Houchardea8dd942019-05-20 14:02:16 +02005989 */
5990 if (ctx->conn->xprt_ctx == ctx) {
Olivier Houchard477902b2020-01-22 18:08:48 +01005991 if (!ctx->conn->mux)
5992 ret = conn_create_mux(ctx->conn);
Olivier Houchardea8dd942019-05-20 14:02:16 +02005993 if (ret >= 0 && !woke && ctx->conn->mux && ctx->conn->mux->wake)
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02005994 ret = ctx->conn->mux->wake(ctx->conn);
5995 goto leave;
Olivier Houchardea8dd942019-05-20 14:02:16 +02005996 }
5997 }
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05005998#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01005999 /* If we have early data and somebody wants to receive, let them */
Willy Tarreau113d52b2020-01-10 09:20:26 +01006000 else if (b_data(&ctx->early_buf) && ctx->subs &&
6001 ctx->subs->events & SUB_RETRY_RECV) {
6002 tasklet_wakeup(ctx->subs->tasklet);
6003 ctx->subs->events &= ~SUB_RETRY_RECV;
6004 if (!ctx->subs->events)
6005 ctx->subs = NULL;
Olivier Houchard54907bb2019-12-19 15:02:39 +01006006 }
6007#endif
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006008leave:
6009 if (!ret && conn_in_list) {
6010 struct server *srv = objt_server(conn->target);
6011
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006012 HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006013 if (conn_in_list == CO_FL_SAFE_LIST)
Willy Tarreau430bf4a2021-03-04 09:45:32 +01006014 ebmb_insert(&srv->per_thr[tid].safe_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006015 else
Willy Tarreau430bf4a2021-03-04 09:45:32 +01006016 ebmb_insert(&srv->per_thr[tid].idle_conns, &conn->hash_node->node, sizeof(conn->hash_node->hash));
Amaury Denoyelle5c7086f2021-01-11 09:21:52 +01006017 HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02006018 }
Willy Tarreau74163142021-03-13 11:30:19 +01006019 return t;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006020}
6021
Emeric Brun46591952012-05-18 15:47:34 +02006022/* Receive up to <count> bytes from connection <conn>'s socket and store them
Willy Tarreauabf08d92014-01-14 11:31:27 +01006023 * into buffer <buf>. Only one call to recv() is performed, unless the
Emeric Brun46591952012-05-18 15:47:34 +02006024 * buffer wraps, in which case a second call may be performed. The connection's
6025 * flags are updated with whatever special event is detected (error, read0,
6026 * empty). The caller is responsible for taking care of those events and
6027 * avoiding the call if inappropriate. The function does not call the
6028 * connection's polling update function, so the caller is responsible for this.
6029 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006030static 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 +02006031{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006032 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreaubfc4d772018-07-18 11:22:03 +02006033 ssize_t ret;
6034 size_t try, done = 0;
Emeric Brun46591952012-05-18 15:47:34 +02006035
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006036 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006037 goto out_error;
6038
Ilya Shipitsin761d64c2021-01-07 11:59:58 +05006039#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard54907bb2019-12-19 15:02:39 +01006040 if (b_data(&ctx->early_buf)) {
6041 try = b_contig_space(buf);
6042 if (try > b_data(&ctx->early_buf))
6043 try = b_data(&ctx->early_buf);
6044 memcpy(b_tail(buf), b_head(&ctx->early_buf), try);
6045 b_add(buf, try);
6046 b_del(&ctx->early_buf, try);
6047 if (b_data(&ctx->early_buf) == 0)
6048 b_free(&ctx->early_buf);
6049 return try;
6050 }
6051#endif
6052
Willy Tarreau911db9b2020-01-23 16:27:54 +01006053 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006054 /* a handshake was requested */
6055 return 0;
6056
Emeric Brun46591952012-05-18 15:47:34 +02006057 /* read the largest possible block. For this, we perform only one call
6058 * to recv() unless the buffer wraps and we exactly fill the first hunk,
6059 * in which case we accept to do it once again. A new attempt is made on
6060 * EINTR too.
6061 */
Willy Tarreau00b0fb92014-01-17 11:09:40 +01006062 while (count > 0) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006063
Willy Tarreau591d4452018-06-15 17:21:00 +02006064 try = b_contig_space(buf);
6065 if (!try)
6066 break;
6067
Willy Tarreauabf08d92014-01-14 11:31:27 +01006068 if (try > count)
6069 try = count;
Willy Tarreau591d4452018-06-15 17:21:00 +02006070
Olivier Houchard66ab4982019-02-26 18:37:15 +01006071 ret = SSL_read(ctx->ssl, b_tail(buf), try);
Emmanuel Hocdetf967c312019-08-05 18:04:16 +02006072
Emeric Brune1f38db2012-09-03 20:36:47 +02006073 if (conn->flags & CO_FL_ERROR) {
6074 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006075 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006076 }
Emeric Brun46591952012-05-18 15:47:34 +02006077 if (ret > 0) {
Olivier Houchardacd14032018-06-28 18:17:23 +02006078 b_add(buf, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006079 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006080 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006081 }
Emeric Brun46591952012-05-18 15:47:34 +02006082 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006083 ret = SSL_get_error(ctx->ssl, ret);
Emeric Brun46591952012-05-18 15:47:34 +02006084 if (ret == SSL_ERROR_WANT_WRITE) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006085 /* handshake is running, and it needs to enable write */
Emeric Brun46591952012-05-18 15:47:34 +02006086 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006087 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006088#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006089 /* Async mode can be re-enabled, because we're leaving data state.*/
6090 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006091 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006092#endif
Emeric Brun46591952012-05-18 15:47:34 +02006093 break;
6094 }
6095 else if (ret == SSL_ERROR_WANT_READ) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006096 if (SSL_renegotiate_pending(ctx->ssl)) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006097 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6098 SUB_RETRY_RECV,
6099 &ctx->wait_event);
Emeric Brun282a76a2012-11-08 18:02:56 +01006100 /* handshake is running, and it may need to re-enable read */
6101 conn->flags |= CO_FL_SSL_WAIT_HS;
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006102#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006103 /* Async mode can be re-enabled, because we're leaving data state.*/
6104 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006105 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006106#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006107 break;
6108 }
Emeric Brun46591952012-05-18 15:47:34 +02006109 break;
Olivier Houchardc2aae742017-09-22 18:26:28 +02006110 } else if (ret == SSL_ERROR_ZERO_RETURN)
6111 goto read0;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006112 /* For SSL_ERROR_SYSCALL, make sure to clear the error
6113 * stack before shutting down the connection for
6114 * reading. */
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006115 if (ret == SSL_ERROR_SYSCALL && (!errno || errno == EAGAIN))
6116 goto clear_ssl_error;
Emeric Brun46591952012-05-18 15:47:34 +02006117 /* otherwise it's a real error */
6118 goto out_error;
6119 }
6120 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006121 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006122 return done;
6123
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006124 clear_ssl_error:
6125 /* Clear openssl global errors stack */
6126 ssl_sock_dump_errors(conn);
6127 ERR_clear_error();
Emeric Brun46591952012-05-18 15:47:34 +02006128 read0:
6129 conn_sock_read0(conn);
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006130 goto leave;
Christopher Faulet4ac77a92018-02-19 14:25:15 +01006131
Emeric Brun46591952012-05-18 15:47:34 +02006132 out_error:
Olivier Houchard7e2e5052018-02-13 15:17:23 +01006133 conn->flags |= CO_FL_ERROR;
Emeric Brun644cde02012-12-14 11:21:13 +01006134 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006135 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006136 ERR_clear_error();
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006137 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006138}
6139
6140
Willy Tarreau787db9a2018-06-14 18:31:46 +02006141/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
6142 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
6143 * other pending data for example, but this flag is ignored at the moment.
Emeric Brun46591952012-05-18 15:47:34 +02006144 * Only one call to send() is performed, unless the buffer wraps, in which case
6145 * a second call may be performed. The connection's flags are updated with
6146 * whatever special event is detected (error, empty). The caller is responsible
6147 * for taking care of those events and avoiding the call if inappropriate. The
6148 * function does not call the connection's polling update function, so the caller
Willy Tarreau787db9a2018-06-14 18:31:46 +02006149 * is responsible for this. The buffer's output is not adjusted, it's up to the
6150 * caller to take care of this. It's up to the caller to update the buffer's
6151 * contents based on the return value.
Emeric Brun46591952012-05-18 15:47:34 +02006152 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006153static 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 +02006154{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006155 struct ssl_sock_ctx *ctx = xprt_ctx;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006156 ssize_t ret;
6157 size_t try, done;
Emeric Brun46591952012-05-18 15:47:34 +02006158
6159 done = 0;
6160
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006161 if (!ctx)
Emeric Brun46591952012-05-18 15:47:34 +02006162 goto out_error;
6163
Willy Tarreau911db9b2020-01-23 16:27:54 +01006164 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS | CO_FL_EARLY_SSL_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006165 /* a handshake was requested */
6166 return 0;
6167
6168 /* send the largest possible block. For this we perform only one call
6169 * to send() unless the buffer wraps and we exactly fill the first hunk,
6170 * in which case we accept to do it once again.
6171 */
Willy Tarreau787db9a2018-06-14 18:31:46 +02006172 while (count) {
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006173#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchardc2aae742017-09-22 18:26:28 +02006174 size_t written_data;
6175#endif
6176
Willy Tarreau787db9a2018-06-14 18:31:46 +02006177 try = b_contig_data(buf, done);
6178 if (try > count)
6179 try = count;
Willy Tarreaubfd59462013-02-21 07:46:09 +01006180
Willy Tarreau7bed9452014-02-02 02:00:24 +01006181 if (!(flags & CO_SFL_STREAMER) &&
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006182 !(ctx->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
Willy Tarreauef934602016-12-22 23:12:01 +01006183 global_ssl.max_record && try > global_ssl.max_record) {
6184 try = global_ssl.max_record;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006185 }
6186 else {
6187 /* we need to keep the information about the fact that
6188 * we're not limiting the upcoming send(), because if it
6189 * fails, we'll have to retry with at least as many data.
6190 */
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006191 ctx->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau518cedd2014-02-17 15:43:01 +01006192 }
Willy Tarreaubfd59462013-02-21 07:46:09 +01006193
Ilya Shipitsinb9b84a42020-10-24 23:42:30 +05006194#ifdef SSL_READ_EARLY_DATA_SUCCESS
Olivier Houchard010941f2019-05-03 20:56:19 +02006195 if (!SSL_is_init_finished(ctx->ssl) && conn_is_back(conn)) {
Olivier Houchardc2aae742017-09-22 18:26:28 +02006196 unsigned int max_early;
6197
Olivier Houchard522eea72017-11-03 16:27:47 +01006198 if (objt_listener(conn->target))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006199 max_early = SSL_get_max_early_data(ctx->ssl);
Olivier Houchard522eea72017-11-03 16:27:47 +01006200 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006201 if (SSL_get0_session(ctx->ssl))
6202 max_early = SSL_SESSION_get_max_early_data(SSL_get0_session(ctx->ssl));
Olivier Houchard522eea72017-11-03 16:27:47 +01006203 else
6204 max_early = 0;
6205 }
6206
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006207 if (try + ctx->sent_early_data > max_early) {
6208 try -= (try + ctx->sent_early_data) - max_early;
Olivier Houchard522eea72017-11-03 16:27:47 +01006209 if (try <= 0) {
Olivier Houchard010941f2019-05-03 20:56:19 +02006210 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006211 tasklet_wakeup(ctx->wait_event.tasklet);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006212 break;
Olivier Houchard522eea72017-11-03 16:27:47 +01006213 }
Olivier Houchardc2aae742017-09-22 18:26:28 +02006214 }
Olivier Houchard66ab4982019-02-26 18:37:15 +01006215 ret = SSL_write_early_data(ctx->ssl, b_peek(buf, done), try, &written_data);
Olivier Houchardc2aae742017-09-22 18:26:28 +02006216 if (ret == 1) {
6217 ret = written_data;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006218 ctx->sent_early_data += ret;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006219 if (objt_server(conn->target)) {
Olivier Houchard522eea72017-11-03 16:27:47 +01006220 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN | CO_FL_EARLY_DATA;
Olivier Houchard965e84e2019-06-15 20:59:30 +02006221 /* Initiate the handshake, now */
6222 tasklet_wakeup(ctx->wait_event.tasklet);
6223 }
Olivier Houchard522eea72017-11-03 16:27:47 +01006224
Olivier Houchardc2aae742017-09-22 18:26:28 +02006225 }
6226
6227 } else
6228#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006229 ret = SSL_write(ctx->ssl, b_peek(buf, done), try);
Willy Tarreau518cedd2014-02-17 15:43:01 +01006230
Emeric Brune1f38db2012-09-03 20:36:47 +02006231 if (conn->flags & CO_FL_ERROR) {
6232 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
Emeric Brun644cde02012-12-14 11:21:13 +01006233 goto out_error;
Emeric Brune1f38db2012-09-03 20:36:47 +02006234 }
Emeric Brun46591952012-05-18 15:47:34 +02006235 if (ret > 0) {
Willy Tarreauc192b0a2020-01-23 09:11:58 +01006236 /* A send succeeded, so we can consider ourself connected */
6237 conn->flags &= ~CO_FL_WAIT_L4L6;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006238 ctx->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
Willy Tarreau787db9a2018-06-14 18:31:46 +02006239 count -= ret;
Emeric Brun46591952012-05-18 15:47:34 +02006240 done += ret;
Emeric Brun46591952012-05-18 15:47:34 +02006241 }
6242 else {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006243 ret = SSL_get_error(ctx->ssl, ret);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006244
Emeric Brun46591952012-05-18 15:47:34 +02006245 if (ret == SSL_ERROR_WANT_WRITE) {
Olivier Houchard66ab4982019-02-26 18:37:15 +01006246 if (SSL_renegotiate_pending(ctx->ssl)) {
Emeric Brun282a76a2012-11-08 18:02:56 +01006247 /* handshake is running, and it may need to re-enable write */
6248 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006249 ctx->xprt->subscribe(conn, ctx->xprt_ctx, SUB_RETRY_SEND, &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006250#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006251 /* Async mode can be re-enabled, because we're leaving data state.*/
6252 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006253 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006254#endif
Emeric Brun282a76a2012-11-08 18:02:56 +01006255 break;
6256 }
Olivier Houchardea8dd942019-05-20 14:02:16 +02006257
Emeric Brun46591952012-05-18 15:47:34 +02006258 break;
6259 }
6260 else if (ret == SSL_ERROR_WANT_READ) {
Emeric Brun8af8dd12012-11-08 17:56:20 +01006261 /* handshake is running, and it needs to enable read */
Emeric Brun46591952012-05-18 15:47:34 +02006262 conn->flags |= CO_FL_SSL_WAIT_HS;
Olivier Houchardea8dd942019-05-20 14:02:16 +02006263 ctx->xprt->subscribe(conn, ctx->xprt_ctx,
6264 SUB_RETRY_RECV,
6265 &ctx->wait_event);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006266#ifdef SSL_MODE_ASYNC
Emeric Brunb5e42a82017-06-06 12:35:14 +00006267 /* Async mode can be re-enabled, because we're leaving data state.*/
6268 if (global_ssl.async)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006269 SSL_set_mode(ctx->ssl, SSL_MODE_ASYNC);
Emeric Brunb5e42a82017-06-06 12:35:14 +00006270#endif
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006271 break;
6272 }
Emeric Brun46591952012-05-18 15:47:34 +02006273 goto out_error;
6274 }
6275 }
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006276 leave:
Emeric Brun46591952012-05-18 15:47:34 +02006277 return done;
6278
6279 out_error:
Emeric Brun644cde02012-12-14 11:21:13 +01006280 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006281 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006282 ERR_clear_error();
6283
Emeric Brun46591952012-05-18 15:47:34 +02006284 conn->flags |= CO_FL_ERROR;
Willy Tarreau31d4dbe2017-10-25 09:32:15 +02006285 goto leave;
Emeric Brun46591952012-05-18 15:47:34 +02006286}
6287
Willy Tarreau832e2422021-05-13 10:11:03 +02006288void ssl_sock_close(struct connection *conn, void *xprt_ctx) {
Emeric Brun46591952012-05-18 15:47:34 +02006289
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006290 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006291
Olivier Houchardea8dd942019-05-20 14:02:16 +02006292
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006293 if (ctx) {
Olivier Houchardea8dd942019-05-20 14:02:16 +02006294 if (ctx->wait_event.events != 0)
6295 ctx->xprt->unsubscribe(ctx->conn, ctx->xprt_ctx,
6296 ctx->wait_event.events,
6297 &ctx->wait_event);
Willy Tarreau113d52b2020-01-10 09:20:26 +01006298 if (ctx->subs) {
6299 ctx->subs->events = 0;
6300 tasklet_wakeup(ctx->subs->tasklet);
Olivier Houchardea8dd942019-05-20 14:02:16 +02006301 }
Willy Tarreau113d52b2020-01-10 09:20:26 +01006302
Olivier Houchard692c1d02019-05-23 18:41:47 +02006303 if (ctx->xprt->close)
6304 ctx->xprt->close(conn, ctx->xprt_ctx);
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05006305#ifdef SSL_MODE_ASYNC
Emeric Brun3854e012017-05-17 20:42:48 +02006306 if (global_ssl.async) {
6307 OSSL_ASYNC_FD all_fd[32], afd;
6308 size_t num_all_fds = 0;
6309 int i;
6310
Olivier Houchard66ab4982019-02-26 18:37:15 +01006311 SSL_get_all_async_fds(ctx->ssl, NULL, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006312 if (num_all_fds > 32) {
6313 send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
6314 return;
6315 }
6316
Olivier Houchard66ab4982019-02-26 18:37:15 +01006317 SSL_get_all_async_fds(ctx->ssl, all_fd, &num_all_fds);
Emeric Brun3854e012017-05-17 20:42:48 +02006318
6319 /* If an async job is pending, we must try to
6320 to catch the end using polling before calling
6321 SSL_free */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006322 if (num_all_fds && SSL_waiting_for_async(ctx->ssl)) {
Emeric Brun3854e012017-05-17 20:42:48 +02006323 for (i=0 ; i < num_all_fds ; i++) {
6324 /* switch on an handler designed to
6325 * handle the SSL_free
6326 */
6327 afd = all_fd[i];
6328 fdtab[afd].iocb = ssl_async_fd_free;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006329 fdtab[afd].owner = ctx->ssl;
Emeric Brun3854e012017-05-17 20:42:48 +02006330 fd_want_recv(afd);
Emeric Brunce9e01c2017-05-31 10:02:53 +00006331 /* To ensure that the fd cache won't be used
6332 * and we'll catch a real RD event.
6333 */
6334 fd_cant_recv(afd);
Emeric Brun3854e012017-05-17 20:42:48 +02006335 }
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006336 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006337 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006338 _HA_ATOMIC_INC(&jobs);
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006339 return;
6340 }
Emeric Brun3854e012017-05-17 20:42:48 +02006341 /* Else we can remove the fds from the fdtab
6342 * and call SSL_free.
Willy Tarreau67672452020-08-26 11:44:17 +02006343 * note: we do a fd_stop_both and not a delete
Emeric Brun3854e012017-05-17 20:42:48 +02006344 * because the fd is owned by the engine.
6345 * the engine is responsible to close
6346 */
Emeric Brun64ff81b2022-07-01 17:36:50 +02006347 for (i=0 ; i < num_all_fds ; i++) {
6348 /* We want to remove the fd from the fdtab
6349 * but we flag it to disown because the
6350 * close is performed by the engine itself
6351 */
6352 fdtab[all_fd[i]].state |= FD_DISOWN;
6353 fd_delete(all_fd[i]);
6354 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006355 }
6356#endif
Olivier Houchard66ab4982019-02-26 18:37:15 +01006357 SSL_free(ctx->ssl);
Olivier Houchard54907bb2019-12-19 15:02:39 +01006358 b_free(&ctx->early_buf);
Willy Tarreau3c39a7d2019-06-14 14:42:29 +02006359 tasklet_free(ctx->wait_event.tasklet);
Olivier Houchard66ab4982019-02-26 18:37:15 +01006360 pool_free(ssl_sock_ctx_pool, ctx);
Willy Tarreau4781b152021-04-06 13:53:36 +02006361 _HA_ATOMIC_DEC(&sslconns);
Emeric Brun46591952012-05-18 15:47:34 +02006362 }
Emeric Brun46591952012-05-18 15:47:34 +02006363}
6364
6365/* This function tries to perform a clean shutdown on an SSL connection, and in
6366 * any case, flags the connection as reusable if no handshake was in progress.
6367 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006368static void ssl_sock_shutw(struct connection *conn, void *xprt_ctx, int clean)
Emeric Brun46591952012-05-18 15:47:34 +02006369{
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006370 struct ssl_sock_ctx *ctx = xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006371
Willy Tarreau911db9b2020-01-23 16:27:54 +01006372 if (conn->flags & (CO_FL_WAIT_XPRT | CO_FL_SSL_WAIT_HS))
Emeric Brun46591952012-05-18 15:47:34 +02006373 return;
Emmanuel Hocdet405ff312017-01-08 14:07:39 +01006374 if (!clean)
6375 /* don't sent notify on SSL_shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006376 SSL_set_quiet_shutdown(ctx->ssl, 1);
Emeric Brun46591952012-05-18 15:47:34 +02006377 /* no handshake was in progress, try a clean ssl shutdown */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006378 if (SSL_shutdown(ctx->ssl) <= 0) {
Emeric Brun644cde02012-12-14 11:21:13 +01006379 /* Clear openssl global errors stack */
Thierry FOURNIER / OZON.IO8b068c22016-10-10 11:59:50 +02006380 ssl_sock_dump_errors(conn);
Emeric Brun644cde02012-12-14 11:21:13 +01006381 ERR_clear_error();
6382 }
Emeric Brun46591952012-05-18 15:47:34 +02006383}
6384
Emmanuel Hocdet96b78342017-10-31 15:46:07 +01006385
Ilya Shipitsin77e3b4a2020-03-10 12:06:11 +05006386/* used for ppv2 pkey algo (can be used for logging) */
William Lallemandd4f946c2019-12-05 10:26:40 +01006387int ssl_sock_get_pkey_algo(struct connection *conn, struct buffer *out)
6388{
6389 struct ssl_sock_ctx *ctx;
6390 X509 *crt;
6391
6392 if (!ssl_sock_is_ssl(conn))
6393 return 0;
6394
6395 ctx = conn->xprt_ctx;
6396
6397 crt = SSL_get_certificate(ctx->ssl);
6398 if (!crt)
6399 return 0;
6400
6401 return cert_get_pkey_algo(crt, out);
6402}
6403
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006404/* used for ppv2 cert signature (can be used for logging) */
6405const char *ssl_sock_get_cert_sig(struct connection *conn)
6406{
Christopher Faulet82004142019-09-10 10:12:03 +02006407 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006408
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006409 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
6410 X509 *crt;
6411
6412 if (!ssl_sock_is_ssl(conn))
6413 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006414 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006415 crt = SSL_get_certificate(ctx->ssl);
Emmanuel Hocdet283e0042017-11-02 14:05:23 +01006416 if (!crt)
6417 return NULL;
6418 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
6419 return OBJ_nid2sn(OBJ_obj2nid(algorithm));
6420}
6421
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006422/* used for ppv2 authority */
6423const char *ssl_sock_get_sni(struct connection *conn)
6424{
6425#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006426 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006427
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006428 if (!ssl_sock_is_ssl(conn))
6429 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006430 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006431 return SSL_get_servername(ctx->ssl, TLSEXT_NAMETYPE_host_name);
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006432#else
Olivier Houchard66ab4982019-02-26 18:37:15 +01006433 return NULL;
Emmanuel Hocdet253c3b72018-02-01 18:29:59 +01006434#endif
6435}
6436
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006437/* used for logging/ppv2, may be changed for a sample fetch later */
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006438const char *ssl_sock_get_cipher_name(struct connection *conn)
6439{
Christopher Faulet82004142019-09-10 10:12:03 +02006440 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006441
Emmanuel Hocdet01da5712017-10-13 16:59:49 +02006442 if (!ssl_sock_is_ssl(conn))
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006443 return NULL;
Christopher Faulet82004142019-09-10 10:12:03 +02006444 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006445 return SSL_get_cipher_name(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006446}
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_proto_version(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_version(ctx->ssl);
Willy Tarreauffc3fcd2012-10-12 20:17:54 +02006457}
6458
Olivier Houchardab28a322018-12-21 19:45:40 +01006459void ssl_sock_set_alpn(struct connection *conn, const unsigned char *alpn, int len)
6460{
6461#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christopher Faulet82004142019-09-10 10:12:03 +02006462 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006463
Olivier Houcharde488ea82019-06-28 14:10:33 +02006464 if (!ssl_sock_is_ssl(conn))
6465 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006466 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006467 SSL_set_alpn_protos(ctx->ssl, alpn, len);
Olivier Houchardab28a322018-12-21 19:45:40 +01006468#endif
6469}
6470
Willy Tarreau119a4082016-12-22 21:58:38 +01006471/* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
6472 * to disable SNI.
6473 */
Willy Tarreau63076412015-07-10 11:33:32 +02006474void ssl_sock_set_servername(struct connection *conn, const char *hostname)
6475{
6476#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
Christopher Faulet82004142019-09-10 10:12:03 +02006477 struct ssl_sock_ctx *ctx;
William Lallemandc78ac5a2021-11-17 02:59:21 +01006478 struct server *s;
Willy Tarreau119a4082016-12-22 21:58:38 +01006479 char *prev_name;
6480
Willy Tarreau63076412015-07-10 11:33:32 +02006481 if (!ssl_sock_is_ssl(conn))
6482 return;
Christopher Faulet82004142019-09-10 10:12:03 +02006483 ctx = conn->xprt_ctx;
William Lallemandc78ac5a2021-11-17 02:59:21 +01006484 s = __objt_server(conn->target);
Willy Tarreau63076412015-07-10 11:33:32 +02006485
Willy Tarreau119a4082016-12-22 21:58:38 +01006486 /* if the SNI changes, we must destroy the reusable context so that a
William Lallemandc78ac5a2021-11-17 02:59:21 +01006487 * new connection will present a new SNI. compare with the SNI
6488 * previously stored in the reused_sess */
6489 /* the RWLOCK is used to ensure that we are not trying to flush the
6490 * cache from the CLI */
6491
6492 HA_RWLOCK_RDLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
6493 prev_name = s->ssl_ctx.reused_sess[tid].sni;
Willy Tarreau119a4082016-12-22 21:58:38 +01006494 if ((!prev_name && hostname) ||
6495 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
Olivier Houchard66ab4982019-02-26 18:37:15 +01006496 SSL_set_session(ctx->ssl, NULL);
William Lallemandc78ac5a2021-11-17 02:59:21 +01006497 HA_RWLOCK_RDUNLOCK(SSL_SERVER_LOCK, &s->ssl_ctx.lock);
Willy Tarreau119a4082016-12-22 21:58:38 +01006498
Olivier Houchard66ab4982019-02-26 18:37:15 +01006499 SSL_set_tlsext_host_name(ctx->ssl, hostname);
Willy Tarreau63076412015-07-10 11:33:32 +02006500#endif
6501}
6502
Emeric Brun0abf8362014-06-24 18:26:41 +02006503/* Extract peer certificate's common name into the chunk dest
6504 * Returns
6505 * the len of the extracted common name
6506 * or 0 if no CN found in DN
6507 * or -1 on error case (i.e. no peer certificate)
6508 */
Willy Tarreau83061a82018-07-13 11:56:34 +02006509int ssl_sock_get_remote_common_name(struct connection *conn,
6510 struct buffer *dest)
David Safb76832014-05-08 23:42:08 -04006511{
Christopher Faulet82004142019-09-10 10:12:03 +02006512 struct ssl_sock_ctx *ctx;
David Safb76832014-05-08 23:42:08 -04006513 X509 *crt = NULL;
6514 X509_NAME *name;
David Safb76832014-05-08 23:42:08 -04006515 const char find_cn[] = "CN";
Willy Tarreau83061a82018-07-13 11:56:34 +02006516 const struct buffer find_cn_chunk = {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02006517 .area = (char *)&find_cn,
6518 .data = sizeof(find_cn)-1
David Safb76832014-05-08 23:42:08 -04006519 };
Emeric Brun0abf8362014-06-24 18:26:41 +02006520 int result = -1;
David Safb76832014-05-08 23:42:08 -04006521
6522 if (!ssl_sock_is_ssl(conn))
Emeric Brun0abf8362014-06-24 18:26:41 +02006523 goto out;
Christopher Faulet82004142019-09-10 10:12:03 +02006524 ctx = conn->xprt_ctx;
David Safb76832014-05-08 23:42:08 -04006525
6526 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006527 crt = SSL_get_peer_certificate(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006528 if (!crt)
6529 goto out;
6530
6531 name = X509_get_subject_name(crt);
6532 if (!name)
6533 goto out;
David Safb76832014-05-08 23:42:08 -04006534
Emeric Brun0abf8362014-06-24 18:26:41 +02006535 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
6536out:
David Safb76832014-05-08 23:42:08 -04006537 if (crt)
6538 X509_free(crt);
6539
6540 return result;
6541}
6542
Dave McCowan328fb582014-07-30 10:39:13 -04006543/* returns 1 if client passed a certificate for this session, 0 if not */
6544int ssl_sock_get_cert_used_sess(struct connection *conn)
6545{
Christopher Faulet82004142019-09-10 10:12:03 +02006546 struct ssl_sock_ctx *ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006547 X509 *crt = NULL;
6548
6549 if (!ssl_sock_is_ssl(conn))
6550 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006551 ctx = conn->xprt_ctx;
Dave McCowan328fb582014-07-30 10:39:13 -04006552
6553 /* SSL_get_peer_certificate, it increase X509 * ref count */
Olivier Houchard66ab4982019-02-26 18:37:15 +01006554 crt = SSL_get_peer_certificate(ctx->ssl);
Dave McCowan328fb582014-07-30 10:39:13 -04006555 if (!crt)
6556 return 0;
6557
6558 X509_free(crt);
6559 return 1;
6560}
6561
6562/* returns 1 if client passed a certificate for this connection, 0 if not */
6563int ssl_sock_get_cert_used_conn(struct connection *conn)
David Safb76832014-05-08 23:42:08 -04006564{
Christopher Faulet82004142019-09-10 10:12:03 +02006565 struct ssl_sock_ctx *ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006566
David Safb76832014-05-08 23:42:08 -04006567 if (!ssl_sock_is_ssl(conn))
6568 return 0;
Christopher Faulet82004142019-09-10 10:12:03 +02006569 ctx = conn->xprt_ctx;
Olivier Houchard7b5fd1e2019-02-28 18:10:45 +01006570 return SSL_SOCK_ST_FL_VERIFY_DONE & ctx->xprt_st ? 1 : 0;
David Safb76832014-05-08 23:42:08 -04006571}
6572
6573/* returns result from SSL verify */
6574unsigned int ssl_sock_get_verify_result(struct connection *conn)
6575{
Christopher Faulet82004142019-09-10 10:12:03 +02006576 struct ssl_sock_ctx *ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006577
David Safb76832014-05-08 23:42:08 -04006578 if (!ssl_sock_is_ssl(conn))
6579 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
Christopher Faulet82004142019-09-10 10:12:03 +02006580 ctx = conn->xprt_ctx;
Olivier Houchard66ab4982019-02-26 18:37:15 +01006581 return (unsigned int)SSL_get_verify_result(ctx->ssl);
David Safb76832014-05-08 23:42:08 -04006582}
6583
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006584/* Returns the application layer protocol name in <str> and <len> when known.
6585 * Zero is returned if the protocol name was not found, otherwise non-zero is
6586 * returned. The string is allocated in the SSL context and doesn't have to be
6587 * freed by the caller. NPN is also checked if available since older versions
6588 * of openssl (1.0.1) which are more common in field only support this one.
6589 */
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006590static int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx, const char **str, int *len)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006591{
Olivier Houchard66ab4982019-02-26 18:37:15 +01006592#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation) || \
6593 defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006594 struct ssl_sock_ctx *ctx = xprt_ctx;
6595 if (!ctx)
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006596 return 0;
6597
6598 *str = NULL;
6599
6600#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Olivier Houchard66ab4982019-02-26 18:37:15 +01006601 SSL_get0_alpn_selected(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006602 if (*str)
6603 return 1;
6604#endif
Bernard Spil13c53f82018-02-15 13:34:58 +01006605#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Olivier Houchard66ab4982019-02-26 18:37:15 +01006606 SSL_get0_next_proto_negotiated(ctx->ssl, (const unsigned char **)str, (unsigned *)len);
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006607 if (*str)
6608 return 1;
6609#endif
Olivier Houcharde179d0e2019-03-21 18:27:17 +01006610#endif
Willy Tarreau8743f7e2016-12-04 18:44:29 +01006611 return 0;
6612}
6613
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006614/* "issuers-chain-path" load chain certificate in global */
William Lallemanddad31052020-05-14 17:47:32 +02006615int ssl_load_global_issuer_from_BIO(BIO *in, char *fp, char **err)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006616{
6617 X509 *ca;
6618 X509_NAME *name = NULL;
6619 ASN1_OCTET_STRING *skid = NULL;
6620 STACK_OF(X509) *chain = NULL;
6621 struct issuer_chain *issuer;
6622 struct eb64_node *node;
6623 char *path;
6624 u64 key;
6625 int ret = 0;
6626
6627 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
6628 if (chain == NULL) {
6629 chain = sk_X509_new_null();
6630 skid = X509_get_ext_d2i(ca, NID_subject_key_identifier, NULL, NULL);
6631 name = X509_get_subject_name(ca);
6632 }
6633 if (!sk_X509_push(chain, ca)) {
6634 X509_free(ca);
6635 goto end;
6636 }
6637 }
6638 if (!chain) {
6639 memprintf(err, "unable to load issuers-chain %s : pem certificate not found.\n", fp);
6640 goto end;
6641 }
6642 if (!skid) {
6643 memprintf(err, "unable to load issuers-chain %s : SubjectKeyIdentifier not found.\n", fp);
6644 goto end;
6645 }
6646 if (!name) {
6647 memprintf(err, "unable to load issuers-chain %s : SubjectName not found.\n", fp);
6648 goto end;
6649 }
Dragan Dosen967e7e72020-12-22 13:22:34 +01006650 key = XXH3(ASN1_STRING_get0_data(skid), ASN1_STRING_length(skid), 0);
William Lallemande0f3fd52020-02-25 14:53:06 +01006651 for (node = eb64_lookup(&cert_issuer_tree, key); node; node = eb64_next(node)) {
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006652 issuer = container_of(node, typeof(*issuer), node);
6653 if (!X509_NAME_cmp(name, X509_get_subject_name(sk_X509_value(issuer->chain, 0)))) {
6654 memprintf(err, "duplicate issuers-chain %s: %s already in store\n", fp, issuer->path);
6655 goto end;
6656 }
6657 }
6658 issuer = calloc(1, sizeof *issuer);
6659 path = strdup(fp);
6660 if (!issuer || !path) {
6661 free(issuer);
6662 free(path);
6663 goto end;
6664 }
6665 issuer->node.key = key;
6666 issuer->path = path;
6667 issuer->chain = chain;
6668 chain = NULL;
William Lallemande0f3fd52020-02-25 14:53:06 +01006669 eb64_insert(&cert_issuer_tree, &issuer->node);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006670 ret = 1;
6671 end:
6672 if (skid)
6673 ASN1_OCTET_STRING_free(skid);
6674 if (chain)
6675 sk_X509_pop_free(chain, X509_free);
6676 return ret;
6677}
6678
William Lallemandda8584c2020-05-14 10:14:37 +02006679 struct issuer_chain* ssl_get0_issuer_chain(X509 *cert)
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006680{
6681 AUTHORITY_KEYID *akid;
6682 struct issuer_chain *issuer = NULL;
6683
6684 akid = X509_get_ext_d2i(cert, NID_authority_key_identifier, NULL, NULL);
William Lallemandf69cd682020-11-19 16:24:13 +01006685 if (akid && akid->keyid) {
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006686 struct eb64_node *node;
6687 u64 hk;
Dragan Dosen967e7e72020-12-22 13:22:34 +01006688 hk = XXH3(ASN1_STRING_get0_data(akid->keyid), ASN1_STRING_length(akid->keyid), 0);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006689 for (node = eb64_lookup(&cert_issuer_tree, hk); node; node = eb64_next(node)) {
6690 struct issuer_chain *ti = container_of(node, typeof(*issuer), node);
6691 if (X509_check_issued(sk_X509_value(ti->chain, 0), cert) == X509_V_OK) {
6692 issuer = ti;
6693 break;
6694 }
6695 }
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006696 }
Remi Tricot-Le Breton172da592022-11-03 15:16:48 +01006697 AUTHORITY_KEYID_free(akid);
Emmanuel Hocdet75a7aa12020-02-18 15:19:24 +01006698 return issuer;
6699}
6700
William Lallemanddad31052020-05-14 17:47:32 +02006701void ssl_free_global_issuers(void)
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006702{
6703 struct eb64_node *node, *back;
6704 struct issuer_chain *issuer;
6705
William Lallemande0f3fd52020-02-25 14:53:06 +01006706 node = eb64_first(&cert_issuer_tree);
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01006707 while (node) {
6708 issuer = container_of(node, typeof(*issuer), node);
6709 back = eb64_next(node);
6710 eb64_delete(node);
6711 free(issuer->path);
6712 sk_X509_pop_free(issuer->chain, X509_free);
6713 free(issuer);
6714 node = back;
6715 }
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006716}
6717
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02006718#ifndef OPENSSL_NO_ENGINE
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006719static int ssl_check_async_engine_count(void) {
Christopher Fauletfc633b62020-11-06 15:24:23 +01006720 int err_code = ERR_NONE;
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006721
Emeric Brun3854e012017-05-17 20:42:48 +02006722 if (global_ssl.async && (openssl_engines_initialized > 32)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01006723 ha_alert("ssl-mode-async only supports a maximum of 32 engines.\n");
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00006724 err_code = ERR_ABORT;
6725 }
6726 return err_code;
Willy Tarreau8c3b0fd2016-12-21 22:44:46 +01006727}
Willy Tarreau9ceda382016-12-21 23:13:03 +01006728#endif
6729
Willy Tarreaude5675a2021-01-20 14:41:29 +01006730/* "show fd" helper to dump ssl internals. Warning: the output buffer is often
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006731 * the common trash! It returns non-zero if the connection entry looks suspicious.
Willy Tarreaude5675a2021-01-20 14:41:29 +01006732 */
Willy Tarreau8050efe2021-01-21 08:26:06 +01006733static int ssl_sock_show_fd(struct buffer *buf, const struct connection *conn, const void *ctx)
Willy Tarreaude5675a2021-01-20 14:41:29 +01006734{
6735 const struct ssl_sock_ctx *sctx = ctx;
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006736 int ret = 0;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006737
6738 if (!sctx)
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006739 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006740
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006741 if (sctx->conn != conn) {
6742 chunk_appendf(&trash, " xctx.conn=%p(BOGUS)", sctx->conn);
6743 ret = 1;
6744 }
Willy Tarreaude5675a2021-01-20 14:41:29 +01006745 chunk_appendf(&trash, " xctx.st=%d", sctx->xprt_st);
6746
6747 if (sctx->xprt) {
6748 chunk_appendf(&trash, " .xprt=%s", sctx->xprt->name);
6749 if (sctx->xprt_ctx)
6750 chunk_appendf(&trash, " .xctx=%p", sctx->xprt_ctx);
6751 }
6752
6753 chunk_appendf(&trash, " .wait.ev=%d", sctx->wait_event.events);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006754
6755 /* as soon as a shutdown is reported the lower layer unregisters its
6756 * subscriber, so the situations below are transient and rare enough to
6757 * be reported as suspicious. In any case they shouldn't last.
6758 */
6759 if ((sctx->wait_event.events & 1) && (conn->flags & (CO_FL_SOCK_RD_SH|CO_FL_ERROR)))
6760 ret = 1;
6761 if ((sctx->wait_event.events & 2) && (conn->flags & (CO_FL_SOCK_WR_SH|CO_FL_ERROR)))
6762 ret = 1;
6763
Willy Tarreaude5675a2021-01-20 14:41:29 +01006764 chunk_appendf(&trash, " .subs=%p", sctx->subs);
6765 if (sctx->subs) {
6766 chunk_appendf(&trash, "(ev=%d tl=%p", sctx->subs->events, sctx->subs->tasklet);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006767 if (sctx->subs->tasklet->calls >= 1000000)
6768 ret = 1;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006769 chunk_appendf(&trash, " tl.calls=%d tl.ctx=%p tl.fct=",
6770 sctx->subs->tasklet->calls,
6771 sctx->subs->tasklet->context);
6772 resolve_sym_name(&trash, NULL, sctx->subs->tasklet->process);
6773 chunk_appendf(&trash, ")");
6774 }
6775 chunk_appendf(&trash, " .sent_early=%d", sctx->sent_early_data);
6776 chunk_appendf(&trash, " .early_in=%d", (int)sctx->early_buf.data);
Willy Tarreau4bd5d632021-01-21 08:53:50 +01006777 return ret;
Willy Tarreaude5675a2021-01-20 14:41:29 +01006778}
6779
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006780#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
William Lallemand32af2032016-10-29 18:09:35 +02006781/* This function is used with TLS ticket keys management. It permits to browse
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006782 * each reference. The variable <ref> must point to the current node's list
6783 * element (which starts by the root), and <end> must point to the root node.
William Lallemand32af2032016-10-29 18:09:35 +02006784 */
William Lallemand32af2032016-10-29 18:09:35 +02006785static inline
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006786struct tls_keys_ref *tlskeys_list_get_next(struct list *ref, struct list *end)
William Lallemand32af2032016-10-29 18:09:35 +02006787{
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006788 /* Get next list entry. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006789 ref = ref->n;
William Lallemand32af2032016-10-29 18:09:35 +02006790
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006791 /* If the entry is the last of the list, return NULL. */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006792 if (ref == end)
Tim Duesterhus2c7bb332021-01-03 01:29:55 +01006793 return NULL;
William Lallemand32af2032016-10-29 18:09:35 +02006794
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006795 return LIST_ELEM(ref, struct tls_keys_ref *, list);
William Lallemand32af2032016-10-29 18:09:35 +02006796}
6797
6798static inline
6799struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
6800{
6801 int id;
6802 char *error;
6803
6804 /* If the reference starts by a '#', this is numeric id. */
6805 if (reference[0] == '#') {
6806 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
6807 id = strtol(reference + 1, &error, 10);
6808 if (*error != '\0')
6809 return NULL;
6810
6811 /* Perform the unique id lookup. */
6812 return tlskeys_ref_lookupid(id);
6813 }
6814
6815 /* Perform the string lookup. */
6816 return tlskeys_ref_lookup(reference);
6817}
6818#endif
6819
6820
6821#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6822
6823static int cli_io_handler_tlskeys_files(struct appctx *appctx);
6824
6825static inline int cli_io_handler_tlskeys_entries(struct appctx *appctx) {
6826 return cli_io_handler_tlskeys_files(appctx);
6827}
6828
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006829/* dumps all tls keys. Relies on cli.i0 (non-null = only list file names), cli.i1
6830 * (next index to be dumped), and cli.p0 (next key reference).
6831 */
William Lallemand32af2032016-10-29 18:09:35 +02006832static int cli_io_handler_tlskeys_files(struct appctx *appctx) {
6833
6834 struct stream_interface *si = appctx->owner;
6835
6836 switch (appctx->st2) {
6837 case STAT_ST_INIT:
6838 /* Display the column headers. If the message cannot be sent,
Joseph Herlant017b3da2018-11-15 09:07:59 -08006839 * quit the function with returning 0. The function is called
William Lallemand32af2032016-10-29 18:09:35 +02006840 * later and restart at the state "STAT_ST_INIT".
6841 */
6842 chunk_reset(&trash);
6843
6844 if (appctx->io_handler == cli_io_handler_tlskeys_entries)
6845 chunk_appendf(&trash, "# id secret\n");
6846 else
6847 chunk_appendf(&trash, "# id (file)\n");
6848
Willy Tarreau06d80a92017-10-19 14:32:15 +02006849 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01006850 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006851 return 0;
6852 }
6853
William Lallemand32af2032016-10-29 18:09:35 +02006854 /* Now, we start the browsing of the references lists.
6855 * Note that the following call to LIST_ELEM return bad pointer. The only
6856 * available field of this pointer is <list>. It is used with the function
6857 * tlskeys_list_get_next() for retruning the first available entry
6858 */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006859 if (appctx->ctx.cli.p0 == NULL)
6860 appctx->ctx.cli.p0 = tlskeys_list_get_next(&tlskeys_reference, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006861
6862 appctx->st2 = STAT_ST_LIST;
6863 /* fall through */
6864
6865 case STAT_ST_LIST:
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006866 while (appctx->ctx.cli.p0) {
6867 struct tls_keys_ref *ref = appctx->ctx.cli.p0;
William Lallemand32af2032016-10-29 18:09:35 +02006868
6869 chunk_reset(&trash);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006870 if (appctx->io_handler == cli_io_handler_tlskeys_entries && appctx->ctx.cli.i1 == 0)
William Lallemand32af2032016-10-29 18:09:35 +02006871 chunk_appendf(&trash, "# ");
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006872
6873 if (appctx->ctx.cli.i1 == 0)
6874 chunk_appendf(&trash, "%d (%s)\n", ref->unique_id, ref->filename);
6875
William Lallemand32af2032016-10-29 18:09:35 +02006876 if (appctx->io_handler == cli_io_handler_tlskeys_entries) {
Christopher Faulet16f45c82018-02-16 11:23:49 +01006877 int head;
6878
6879 HA_RWLOCK_RDLOCK(TLSKEYS_REF_LOCK, &ref->lock);
6880 head = ref->tls_ticket_enc_index;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006881 while (appctx->ctx.cli.i1 < TLS_TICKETS_NO) {
Willy Tarreau83061a82018-07-13 11:56:34 +02006882 struct buffer *t2 = get_trash_chunk();
William Lallemand32af2032016-10-29 18:09:35 +02006883
6884 chunk_reset(t2);
6885 /* should never fail here because we dump only a key in the t2 buffer */
Emeric Brun9e754772019-01-10 17:51:55 +01006886 if (ref->key_size_bits == 128) {
6887 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6888 sizeof(struct tls_sess_key_128),
6889 t2->area, t2->size);
6890 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6891 t2->area);
6892 }
6893 else if (ref->key_size_bits == 256) {
6894 t2->data = a2base64((char *)(ref->tlskeys + (head + 2 + appctx->ctx.cli.i1) % TLS_TICKETS_NO),
6895 sizeof(struct tls_sess_key_256),
6896 t2->area, t2->size);
6897 chunk_appendf(&trash, "%d.%d %s\n", ref->unique_id, appctx->ctx.cli.i1,
6898 t2->area);
6899 }
6900 else {
6901 /* This case should never happen */
6902 chunk_appendf(&trash, "%d.%d <unknown>\n", ref->unique_id, appctx->ctx.cli.i1);
6903 }
William Lallemand32af2032016-10-29 18:09:35 +02006904
Willy Tarreau06d80a92017-10-19 14:32:15 +02006905 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006906 /* let's try again later from this stream. We add ourselves into
6907 * this stream's users so that it can remove us upon termination.
6908 */
Christopher Faulet16f45c82018-02-16 11:23:49 +01006909 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreaudb398432018-11-15 11:08:52 +01006910 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006911 return 0;
6912 }
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006913 appctx->ctx.cli.i1++;
William Lallemand32af2032016-10-29 18:09:35 +02006914 }
Christopher Faulet16f45c82018-02-16 11:23:49 +01006915 HA_RWLOCK_RDUNLOCK(TLSKEYS_REF_LOCK, &ref->lock);
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006916 appctx->ctx.cli.i1 = 0;
William Lallemand32af2032016-10-29 18:09:35 +02006917 }
Willy Tarreau06d80a92017-10-19 14:32:15 +02006918 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand32af2032016-10-29 18:09:35 +02006919 /* let's try again later from this stream. We add ourselves into
6920 * this stream's users so that it can remove us upon termination.
6921 */
Willy Tarreaudb398432018-11-15 11:08:52 +01006922 si_rx_room_blk(si);
William Lallemand32af2032016-10-29 18:09:35 +02006923 return 0;
6924 }
6925
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006926 if (appctx->ctx.cli.i0 == 0) /* don't display everything if not necessary */
William Lallemand32af2032016-10-29 18:09:35 +02006927 break;
6928
6929 /* get next list entry and check the end of the list */
Willy Tarreaub6fc5242021-01-05 10:44:30 +01006930 appctx->ctx.cli.p0 = tlskeys_list_get_next(&ref->list, &tlskeys_reference);
William Lallemand32af2032016-10-29 18:09:35 +02006931 }
6932
6933 appctx->st2 = STAT_ST_FIN;
6934 /* fall through */
6935
6936 default:
6937 appctx->st2 = STAT_ST_FIN;
6938 return 1;
6939 }
6940 return 0;
6941}
6942
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006943/* sets cli.i0 to non-zero if only file lists should be dumped */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006944static int cli_parse_show_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006945{
William Lallemand32af2032016-10-29 18:09:35 +02006946 /* no parameter, shows only file list */
6947 if (!*args[2]) {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006948 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006949 appctx->io_handler = cli_io_handler_tlskeys_files;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006950 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006951 }
6952
6953 if (args[2][0] == '*') {
6954 /* list every TLS ticket keys */
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006955 appctx->ctx.cli.i0 = 1;
William Lallemand32af2032016-10-29 18:09:35 +02006956 } else {
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006957 appctx->ctx.cli.p0 = tlskeys_ref_lookup_ref(args[2]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006958 if (!appctx->ctx.cli.p0)
6959 return cli_err(appctx, "'show tls-keys' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006960 }
William Lallemand32af2032016-10-29 18:09:35 +02006961 appctx->io_handler = cli_io_handler_tlskeys_entries;
Willy Tarreau3067bfa2016-12-05 14:50:15 +01006962 return 0;
William Lallemand32af2032016-10-29 18:09:35 +02006963}
6964
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006965static int cli_parse_set_tlskeys(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006966{
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006967 struct tls_keys_ref *ref;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006968 int ret;
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006969
William Lallemand32af2032016-10-29 18:09:35 +02006970 /* Expect two parameters: the filename and the new new TLS key in encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02006971 if (!*args[3] || !*args[4])
6972 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 +02006973
Willy Tarreauf5f26e82016-12-16 18:47:27 +01006974 ref = tlskeys_ref_lookup_ref(args[3]);
Willy Tarreau9d008692019-08-09 11:21:01 +02006975 if (!ref)
6976 return cli_err(appctx, "'set ssl tls-key' unable to locate referenced filename\n");
William Lallemand32af2032016-10-29 18:09:35 +02006977
Willy Tarreau1c913e42018-08-22 05:26:57 +02006978 ret = base64dec(args[4], strlen(args[4]), trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02006979 if (ret < 0)
6980 return cli_err(appctx, "'set ssl tls-key' received invalid base64 encoded TLS key.\n");
Emeric Brun9e754772019-01-10 17:51:55 +01006981
Willy Tarreau1c913e42018-08-22 05:26:57 +02006982 trash.data = ret;
Willy Tarreau9d008692019-08-09 11:21:01 +02006983 if (ssl_sock_update_tlskey_ref(ref, &trash) < 0)
6984 return cli_err(appctx, "'set ssl tls-key' received a key of wrong size.\n");
William Lallemand32af2032016-10-29 18:09:35 +02006985
Willy Tarreau9d008692019-08-09 11:21:01 +02006986 return cli_msg(appctx, LOG_INFO, "TLS ticket key updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02006987}
William Lallemandd4f946c2019-12-05 10:26:40 +01006988#endif
William Lallemand419e6342020-04-08 12:05:39 +02006989
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006990static int cli_parse_set_ocspresponse(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand32af2032016-10-29 18:09:35 +02006991{
6992#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
6993 char *err = NULL;
Willy Tarreau1c913e42018-08-22 05:26:57 +02006994 int i, j, ret;
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02006995
6996 if (!payload)
6997 payload = args[3];
William Lallemand32af2032016-10-29 18:09:35 +02006998
6999 /* Expect one parameter: the new response in base64 encoding */
Willy Tarreau9d008692019-08-09 11:21:01 +02007000 if (!*payload)
7001 return cli_err(appctx, "'set ssl ocsp-response' expects response in base64 encoding.\n");
Aurélien Nephtali1e0867c2018-04-18 14:04:58 +02007002
7003 /* remove \r and \n from the payload */
7004 for (i = 0, j = 0; payload[i]; i++) {
7005 if (payload[i] == '\r' || payload[i] == '\n')
7006 continue;
7007 payload[j++] = payload[i];
7008 }
7009 payload[j] = 0;
William Lallemand32af2032016-10-29 18:09:35 +02007010
Willy Tarreau1c913e42018-08-22 05:26:57 +02007011 ret = base64dec(payload, j, trash.area, trash.size);
Willy Tarreau9d008692019-08-09 11:21:01 +02007012 if (ret < 0)
7013 return cli_err(appctx, "'set ssl ocsp-response' received invalid base64 encoded response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007014
Willy Tarreau1c913e42018-08-22 05:26:57 +02007015 trash.data = ret;
William Lallemand32af2032016-10-29 18:09:35 +02007016 if (ssl_sock_update_ocsp_response(&trash, &err)) {
Willy Tarreau9d008692019-08-09 11:21:01 +02007017 if (err)
7018 return cli_dynerr(appctx, memprintf(&err, "%s.\n", err));
7019 else
7020 return cli_err(appctx, "Failed to update OCSP response.\n");
William Lallemand32af2032016-10-29 18:09:35 +02007021 }
Willy Tarreau9d008692019-08-09 11:21:01 +02007022
7023 return cli_msg(appctx, LOG_INFO, "OCSP Response updated!\n");
William Lallemand32af2032016-10-29 18:09:35 +02007024#else
Willy Tarreau9d008692019-08-09 11:21:01 +02007025 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 +02007026#endif
7027
Elliot Otchet71f82972020-01-15 08:12:14 -05007028}
7029
William Lallemand32af2032016-10-29 18:09:35 +02007030/* register cli keywords */
7031static struct cli_kw_list cli_kws = {{ },{
7032#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
Willy Tarreaub205bfd2021-05-07 11:38:37 +02007033 { { "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 },
7034 { { "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 +02007035#endif
Willy Tarreaub205bfd2021-05-07 11:38:37 +02007036 { { "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 +02007037 { { NULL }, NULL, NULL, NULL }
7038}};
7039
Willy Tarreau0108d902018-11-25 19:14:37 +01007040INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand32af2032016-10-29 18:09:35 +02007041
Willy Tarreauf7bc57c2012-10-03 00:19:48 +02007042/* transport-layer operations for SSL sockets */
William Lallemanddad31052020-05-14 17:47:32 +02007043struct xprt_ops ssl_sock = {
Emeric Brun46591952012-05-18 15:47:34 +02007044 .snd_buf = ssl_sock_from_buf,
7045 .rcv_buf = ssl_sock_to_buf,
Olivier Houcharddf357842019-03-21 16:30:07 +01007046 .subscribe = ssl_subscribe,
7047 .unsubscribe = ssl_unsubscribe,
Olivier Houchard5149b592019-05-23 17:47:36 +02007048 .remove_xprt = ssl_remove_xprt,
Olivier Houchard2e055482019-05-27 19:50:12 +02007049 .add_xprt = ssl_add_xprt,
Emeric Brun46591952012-05-18 15:47:34 +02007050 .rcv_pipe = NULL,
7051 .snd_pipe = NULL,
7052 .shutr = NULL,
7053 .shutw = ssl_sock_shutw,
7054 .close = ssl_sock_close,
7055 .init = ssl_sock_init,
Olivier Houchardbc5ce922021-03-05 23:47:00 +01007056 .start = ssl_sock_start,
Willy Tarreau55d37912016-12-21 23:38:39 +01007057 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
Willy Tarreau795cdab2016-12-22 17:30:54 +01007058 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
Willy Tarreau17d45382016-12-22 21:16:08 +01007059 .prepare_srv = ssl_sock_prepare_srv_ctx,
7060 .destroy_srv = ssl_sock_free_srv_ctx,
Willy Tarreau8743f7e2016-12-04 18:44:29 +01007061 .get_alpn = ssl_sock_get_alpn,
Olivier Houcharda74bb7e2020-07-03 14:01:21 +02007062 .takeover = ssl_takeover,
Willy Tarreau41491682021-03-02 17:29:56 +01007063 .set_idle = ssl_set_idle,
7064 .set_used = ssl_set_used,
Willy Tarreau8e0bb0a2016-11-24 16:58:12 +01007065 .name = "SSL",
Willy Tarreaude5675a2021-01-20 14:41:29 +01007066 .show_fd = ssl_sock_show_fd,
Emeric Brun46591952012-05-18 15:47:34 +02007067};
7068
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007069enum act_return ssl_action_wait_for_hs(struct act_rule *rule, struct proxy *px,
7070 struct session *sess, struct stream *s, int flags)
7071{
7072 struct connection *conn;
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007073 struct conn_stream *cs;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007074
7075 conn = objt_conn(sess->origin);
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007076 cs = objt_cs(s->si[0].end);
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007077
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007078 if (conn && cs) {
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007079 if (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS)) {
Olivier Houchard6fa63d92017-11-27 18:41:32 +01007080 cs->flags |= CS_FL_WAIT_FOR_HS;
Olivier Houchardccaa7de2017-10-02 11:51:03 +02007081 s->req.flags |= CF_READ_NULL;
7082 return ACT_RET_YIELD;
7083 }
7084 }
7085 return (ACT_RET_CONT);
7086}
7087
7088static enum act_parse_ret ssl_parse_wait_for_hs(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
7089{
7090 rule->action_ptr = ssl_action_wait_for_hs;
7091
7092 return ACT_RET_PRS_OK;
7093}
7094
7095static struct action_kw_list http_req_actions = {ILH, {
7096 { "wait-for-handshake", ssl_parse_wait_for_hs },
7097 { /* END */ }
7098}};
7099
Willy Tarreau0108d902018-11-25 19:14:37 +01007100INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
7101
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007102#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007103
7104static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7105{
7106 if (ptr) {
7107 chunk_destroy(ptr);
7108 free(ptr);
7109 }
7110}
7111
7112#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007113
7114#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7115static void ssl_sock_ocsp_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7116{
7117 struct ocsp_cbk_arg *ocsp_arg;
7118
7119 if (ptr) {
7120 ocsp_arg = ptr;
7121
7122 if (ocsp_arg->is_single) {
7123 ssl_sock_free_ocsp(ocsp_arg->s_ocsp);
7124 ocsp_arg->s_ocsp = NULL;
7125 } else {
7126 int i;
7127
7128 for (i = 0; i < SSL_SOCK_NUM_KEYTYPES; i++) {
7129 ssl_sock_free_ocsp(ocsp_arg->m_ocsp[i]);
7130 ocsp_arg->m_ocsp[i] = NULL;
7131 }
7132 }
7133 free(ocsp_arg);
7134 }
7135}
7136#endif
7137
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007138static void ssl_sock_capture_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7139{
Willy Tarreaubafbe012017-11-24 17:34:44 +01007140 pool_free(pool_head_ssl_capture, ptr);
Emmanuel Hocdetaaee7502017-03-07 18:34:58 +01007141}
William Lallemand7d42ef52020-07-06 11:41:30 +02007142
William Lallemandca5cf0a2021-06-09 16:46:12 +02007143#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007144static void ssl_sock_keylog_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
7145{
7146 struct ssl_keylog *keylog;
7147
7148 if (!ptr)
7149 return;
7150
7151 keylog = ptr;
7152
7153 pool_free(pool_head_ssl_keylog_str, keylog->client_random);
7154 pool_free(pool_head_ssl_keylog_str, keylog->client_early_traffic_secret);
7155 pool_free(pool_head_ssl_keylog_str, keylog->client_handshake_traffic_secret);
7156 pool_free(pool_head_ssl_keylog_str, keylog->server_handshake_traffic_secret);
7157 pool_free(pool_head_ssl_keylog_str, keylog->client_traffic_secret_0);
7158 pool_free(pool_head_ssl_keylog_str, keylog->server_traffic_secret_0);
7159 pool_free(pool_head_ssl_keylog_str, keylog->exporter_secret);
7160 pool_free(pool_head_ssl_keylog_str, keylog->early_exporter_secret);
7161
7162 pool_free(pool_head_ssl_keylog, ptr);
7163}
7164#endif
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007165
Emeric Brun46591952012-05-18 15:47:34 +02007166__attribute__((constructor))
Willy Tarreau92faadf2012-10-10 23:04:25 +02007167static void __ssl_sock_init(void)
7168{
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007169#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007170 STACK_OF(SSL_COMP)* cm;
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007171 int n;
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007172#endif
Emeric Brun46591952012-05-18 15:47:34 +02007173
Willy Tarreauef934602016-12-22 23:12:01 +01007174 if (global_ssl.listen_default_ciphers)
7175 global_ssl.listen_default_ciphers = strdup(global_ssl.listen_default_ciphers);
7176 if (global_ssl.connect_default_ciphers)
7177 global_ssl.connect_default_ciphers = strdup(global_ssl.connect_default_ciphers);
Ilya Shipitsinf34ed0b2020-11-21 14:37:34 +05007178#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
Dirkjan Bussink415150f2018-09-14 11:14:21 +02007179 if (global_ssl.listen_default_ciphersuites)
7180 global_ssl.listen_default_ciphersuites = strdup(global_ssl.listen_default_ciphersuites);
7181 if (global_ssl.connect_default_ciphersuites)
7182 global_ssl.connect_default_ciphersuites = strdup(global_ssl.connect_default_ciphersuites);
7183#endif
Willy Tarreau610f04b2014-02-13 11:36:41 +01007184
Willy Tarreau13e14102016-12-22 20:25:26 +01007185 xprt_register(XPRT_SSL, &ssl_sock);
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007186#if HA_OPENSSL_VERSION_NUMBER < 0x10100000L
Emeric Brun46591952012-05-18 15:47:34 +02007187 SSL_library_init();
Rosen Penev68185952018-12-14 08:47:02 -08007188#endif
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007189#if (!defined(OPENSSL_NO_COMP) && !defined(SSL_OP_NO_COMPRESSION))
Emeric Brun46591952012-05-18 15:47:34 +02007190 cm = SSL_COMP_get_compression_methods();
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007191 n = sk_SSL_COMP_num(cm);
7192 while (n--) {
7193 (void) sk_SSL_COMP_pop(cm);
7194 }
Ilya Shipitsin0590f442019-05-25 19:30:50 +05007195#endif
Ilya Shipitsine242f3d2019-05-25 03:38:14 +05007196
Willy Tarreau5db847a2019-05-09 14:13:35 +02007197#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007198 ssl_locking_init();
7199#endif
Ilya Shipitsinf00cdb12021-02-06 18:59:22 +05007200#ifdef HAVE_SSL_CTX_ADD_SERVER_CUSTOM_EXT
Janusz Dziemidowicz2c701b52015-03-07 23:03:59 +01007201 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
7202#endif
William Lallemand76b4a122020-08-04 17:41:39 +02007203
7204#if ((defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP) && !defined OPENSSL_IS_BORINGSSL)
7205 ocsp_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_ocsp_free_func);
7206#endif
7207
Thierry FOURNIER28962c92018-06-17 21:37:05 +02007208 ssl_app_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
Thierry FOURNIER16ff0502018-06-17 21:33:01 +02007209 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 +02007210#ifdef HAVE_SSL_KEYLOG
William Lallemand7d42ef52020-07-06 11:41:30 +02007211 ssl_keylog_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_keylog_free_func);
7212#endif
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007213#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00007214 ENGINE_load_builtin_engines();
Grant Zhangfa6c7ee2017-01-14 01:42:15 +00007215 hap_register_post_check(ssl_check_async_engine_count);
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007216#endif
Willy Tarreaud1c57502016-12-22 22:46:15 +01007217#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
7218 hap_register_post_check(tlskeys_finalize_config);
7219#endif
Willy Tarreau80713382018-11-26 10:19:54 +01007220
7221 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
7222 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
7223
Emmanuel Hocdet70df7bf2019-01-04 11:08:20 +01007224 hap_register_post_deinit(ssl_free_global_issuers);
7225
Willy Tarreau80713382018-11-26 10:19:54 +01007226#ifndef OPENSSL_NO_DH
7227 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
7228 hap_register_post_deinit(ssl_free_dh);
7229#endif
7230#ifndef OPENSSL_NO_ENGINE
7231 hap_register_post_deinit(ssl_free_engines);
7232#endif
7233 /* Load SSL string for the verbose & debug mode. */
7234 ERR_load_SSL_strings();
Olivier Houcharda8955d52019-04-07 22:00:38 +02007235 ha_meth = BIO_meth_new(0x666, "ha methods");
7236 BIO_meth_set_write(ha_meth, ha_ssl_write);
7237 BIO_meth_set_read(ha_meth, ha_ssl_read);
7238 BIO_meth_set_ctrl(ha_meth, ha_ssl_ctrl);
7239 BIO_meth_set_create(ha_meth, ha_ssl_new);
7240 BIO_meth_set_destroy(ha_meth, ha_ssl_free);
7241 BIO_meth_set_puts(ha_meth, ha_ssl_puts);
7242 BIO_meth_set_gets(ha_meth, ha_ssl_gets);
William Lallemand150bfa82019-09-19 17:12:49 +02007243
7244 HA_SPIN_INIT(&ckch_lock);
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007245
Dragan Dosen9ac98092020-05-11 15:51:45 +02007246 /* Try to register dedicated SSL/TLS protocol message callbacks for
7247 * heartbleed attack (CVE-2014-0160) and clienthello.
7248 */
7249 hap_register_post_check(ssl_sock_register_msg_callbacks);
7250
Dragan Dosen1e7ed042020-05-08 18:30:00 +02007251 /* Try to free all callbacks that were registered by using
7252 * ssl_sock_register_msg_callback().
7253 */
7254 hap_register_post_deinit(ssl_sock_unregister_msg_callbacks);
Willy Tarreau80713382018-11-26 10:19:54 +01007255}
Willy Tarreaud92aa5c2015-01-15 21:34:39 +01007256
Willy Tarreau80713382018-11-26 10:19:54 +01007257/* Compute and register the version string */
7258static void ssl_register_build_options()
7259{
7260 char *ptr = NULL;
7261 int i;
7262
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007263 memprintf(&ptr, "Built with OpenSSL version : "
7264#ifdef OPENSSL_IS_BORINGSSL
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007265 "BoringSSL");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007266#else /* OPENSSL_IS_BORINGSSL */
7267 OPENSSL_VERSION_TEXT
7268 "\nRunning on OpenSSL version : %s%s",
Rosen Penev68185952018-12-14 08:47:02 -08007269 OpenSSL_version(OPENSSL_VERSION),
Willy Tarreau1d158ab2019-05-09 13:41:45 +02007270 ((OPENSSL_VERSION_NUMBER ^ OpenSSL_version_num()) >> 8) ? " (VERSIONS DIFFER!)" : "");
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007271#endif
7272 memprintf(&ptr, "%s\nOpenSSL library supports TLS extensions : "
Willy Tarreau9a1ab082019-05-09 13:26:41 +02007273#if HA_OPENSSL_VERSION_NUMBER < 0x00907000L
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007274 "no (library version too old)"
7275#elif defined(OPENSSL_NO_TLSEXT)
7276 "no (disabled via OPENSSL_NO_TLSEXT)"
7277#else
7278 "yes"
7279#endif
7280 "", ptr);
7281
7282 memprintf(&ptr, "%s\nOpenSSL library supports SNI : "
7283#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
7284 "yes"
7285#else
7286#ifdef OPENSSL_NO_TLSEXT
7287 "no (because of OPENSSL_NO_TLSEXT)"
7288#else
7289 "no (version might be too old, 0.9.8f min needed)"
7290#endif
7291#endif
7292 "", ptr);
7293
Emmanuel Hocdetf80bc242017-07-12 14:25:38 +02007294 memprintf(&ptr, "%s\nOpenSSL library supports :", ptr);
7295 for (i = CONF_TLSV_MIN; i <= CONF_TLSV_MAX; i++)
7296 if (methodVersions[i].option)
7297 memprintf(&ptr, "%s %s", ptr, methodVersions[i].name);
Emmanuel Hocdet50e25e12017-03-24 15:20:03 +01007298
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007299 hap_register_build_opts(ptr, 1);
Willy Tarreau80713382018-11-26 10:19:54 +01007300}
Willy Tarreauc2c0b612016-12-21 19:23:20 +01007301
Willy Tarreau80713382018-11-26 10:19:54 +01007302INITCALL0(STG_REGISTER, ssl_register_build_options);
Remi Gacogne4f902b82015-05-28 16:23:00 +02007303
Emeric Brun46591952012-05-18 15:47:34 +02007304
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007305#ifndef OPENSSL_NO_ENGINE
Grant Zhang872f9c22017-01-21 01:10:18 +00007306void ssl_free_engines(void) {
7307 struct ssl_engine_list *wl, *wlb;
7308 /* free up engine list */
7309 list_for_each_entry_safe(wl, wlb, &openssl_engines, list) {
7310 ENGINE_finish(wl->e);
7311 ENGINE_free(wl->e);
Willy Tarreau2b718102021-04-21 07:32:39 +02007312 LIST_DELETE(&wl->list);
Grant Zhang872f9c22017-01-21 01:10:18 +00007313 free(wl);
7314 }
7315}
Emmanuel Hocdet9ac143b2017-05-29 14:36:20 +02007316#endif
Christopher Faulet31af49d2015-06-09 17:29:50 +02007317
Remi Gacogned3a23c32015-05-28 16:39:47 +02007318#ifndef OPENSSL_NO_DH
Grant Zhang872f9c22017-01-21 01:10:18 +00007319void ssl_free_dh(void) {
7320 if (local_dh_1024) {
7321 DH_free(local_dh_1024);
7322 local_dh_1024 = NULL;
7323 }
7324 if (local_dh_2048) {
7325 DH_free(local_dh_2048);
7326 local_dh_2048 = NULL;
7327 }
7328 if (local_dh_4096) {
7329 DH_free(local_dh_4096);
7330 local_dh_4096 = NULL;
7331 }
Remi Gacogne47783ef2015-05-29 15:53:22 +02007332 if (global_dh) {
7333 DH_free(global_dh);
7334 global_dh = NULL;
7335 }
Grant Zhang872f9c22017-01-21 01:10:18 +00007336}
7337#endif
7338
7339__attribute__((destructor))
7340static void __ssl_sock_deinit(void)
7341{
7342#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
Emeric Brun821bb9b2017-06-15 16:37:39 +02007343 if (ssl_ctx_lru_tree) {
7344 lru64_destroy(ssl_ctx_lru_tree);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007345 HA_RWLOCK_DESTROY(&ssl_ctx_lru_rwlock);
Emeric Brun821bb9b2017-06-15 16:37:39 +02007346 }
Remi Gacogned3a23c32015-05-28 16:39:47 +02007347#endif
7348
Willy Tarreau5db847a2019-05-09 14:13:35 +02007349#if (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007350 ERR_remove_state(0);
7351 ERR_free_strings();
7352
7353 EVP_cleanup();
Rosen Penev68185952018-12-14 08:47:02 -08007354#endif
Remi Gacogned3a23c32015-05-28 16:39:47 +02007355
Willy Tarreau5db847a2019-05-09 14:13:35 +02007356#if (HA_OPENSSL_VERSION_NUMBER >= 0x00907000L) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
Remi Gacogned3a23c32015-05-28 16:39:47 +02007357 CRYPTO_cleanup_all_ex_data();
7358#endif
Olivier Houcharda8955d52019-04-07 22:00:38 +02007359 BIO_meth_free(ha_meth);
Remi Gacogned3a23c32015-05-28 16:39:47 +02007360}
7361
William Dauchyf6370442020-11-14 19:25:33 +01007362/* Activate ssl on server <s>.
7363 * do nothing if there is no change to apply
7364 *
7365 * Must be called with the server lock held.
7366 */
7367void ssl_sock_set_srv(struct server *s, signed char use_ssl)
7368{
7369 if (s->use_ssl == use_ssl)
7370 return;
7371
7372 s->use_ssl = use_ssl;
7373 if (s->use_ssl == 1)
7374 s->xprt = &ssl_sock;
7375 else
William Dauchyf5186442022-01-06 16:57:15 +01007376 s->xprt = xprt_get(XPRT_RAW);
William Dauchyf6370442020-11-14 19:25:33 +01007377}
7378
Emeric Brun46591952012-05-18 15:47:34 +02007379/*
7380 * Local variables:
7381 * c-indent-level: 8
7382 * c-basic-offset: 8
7383 * End:
7384 */